Open History to see the last commit
1import type { OrchestrationV2Notification, ToolLifecycleItemType } from "@t3tools/contracts";
2
3export function truncatedCommandNotificationPrefix(
4 notification: Pick<OrchestrationV2Notification, "source" | "summary">,
5): string | undefined {
6 if (notification.source.kind !== "command") return undefined;
7 // Match the single-command summary written by backgroundWorkNotification.
8 return /^Command "(.+)…" (?:finished|failed|was stopped|updated)(?: \(exit -?\d+\))?$/u.exec(
9 notification.summary,
10 )?.[1];
11}
12
13function asRecord(value: unknown): Record<string, unknown> | undefined {
14 return value !== null && typeof value === "object" && !Array.isArray(value)
15 ? (value as Record<string, unknown>)
16 : undefined;
17}
18
19function asTrimmedString(value: unknown): string | undefined {
20 if (typeof value !== "string") {
21 return undefined;
22 }
23 const trimmed = value.trim();
24 return trimmed.length > 0 ? trimmed : undefined;
25}
26
27export function claudeSkillInvocation(
28 toolName: string | null | undefined,
29 input: unknown,
30): { readonly name: string; readonly args: string | undefined } | undefined {
31 if (toolName !== "Skill") return undefined;
32 const record = asRecord(input);
33 const name = asTrimmedString(record?.skill);
34 return name === undefined ? undefined : { name, args: asTrimmedString(record?.args) };
35}
36
37export function isJavaScriptReplTool(toolName: string | null | undefined): boolean {
38 return toolName === "js" || toolName === "cua_repl.js" || toolName === "node_repl.js";
39}
40
41export const COMPUTER_USE_TOOL_SOURCE = {
42 key: "computer-use",
43 name: "Computer Use",
44 kind: "computer",
45} as const;
46
47export function dynamicToolSurface(toolName: string | null | undefined, input: unknown) {
48 if (toolName === "cua_repl.js") return "computer" as const;
49 const code = asRecord(input)?.code;
50 return isJavaScriptReplTool(toolName) &&
51 typeof code === "string" &&
52 (/\bsky\s*\./u.test(code) || /["']@oai\/sky["']/u.test(code))
53 ? ("computer" as const)
54 : undefined;
55}
56
57export type DynamicToolTitle =
58 | { readonly kind: "title"; readonly title: string }
59 | { readonly kind: "computer-use" }
60 | { readonly kind: "run-javascript" }
61 | { readonly kind: "skill"; readonly name: string };
62
63export function describeDynamicToolTitle(
64 toolName: string | null | undefined,
65 input: unknown,
66 retainedTitle?: string | null,
67): DynamicToolTitle | undefined {
68 if (isJavaScriptReplTool(toolName)) {
69 const title = asTrimmedString(retainedTitle);
70 const meaningfulTitle =
71 title && title.toLowerCase() !== "js" && title.toLowerCase() !== toolName?.toLowerCase()
72 ? title
73 : undefined;
74 const shown = asTrimmedString(asRecord(input)?.title) ?? meaningfulTitle;
75 if (shown) return { kind: "title", title: shown };
76 return dynamicToolSurface(toolName, input) === "computer"
77 ? { kind: "computer-use" }
78 : { kind: "run-javascript" };
79 }
80 const skill = claudeSkillInvocation(toolName, input);
81 return skill === undefined ? undefined : { kind: "skill", name: skill.name };
82}
83
84export function dynamicToolTitle(
85 toolName: string | null | undefined,
86 input: unknown,
87 retainedTitle?: string | null,
88): string | undefined {
89 const title = describeDynamicToolTitle(toolName, input, retainedTitle);
90 switch (title?.kind) {
91 case undefined:
92 return undefined;
93 case "title":
94 return title.title;
95 case "computer-use":
96 return "Computer use";
97 case "run-javascript":
98 return "Run JavaScript";
99 case "skill":
100 return `Skill: ${title.name}`;
101 }
102}
103
104function recordHasKeys(
105 value: Record<string, unknown> | undefined,
106): value is Record<string, unknown> {
107 return value !== undefined && Object.keys(value).length > 0;
108}
109
110function normalizeCommandValue(value: unknown): string | undefined {
111 const direct = asTrimmedString(value);
112 if (direct) {
113 return direct;
114 }
115 if (!Array.isArray(value)) {
116 return undefined;
117 }
118 const parts: string[] = [];
119 for (const entry of value) {
120 const part = asTrimmedString(entry);
121 if (part !== undefined) {
122 parts.push(part);
123 }
124 }
125 return parts.length > 0 ? parts.join(" ") : undefined;
126}
127
128function stripTrailingExitCode(value: string | undefined): string | undefined {
129 const trimmed = value?.trim();
130 if (!trimmed) {
131 return undefined;
132 }
133 const match = /^(?<output>[\s\S]*?)(?:\s*<exited with exit code \d+>)\s*$/iu.exec(trimmed);
134 const output = match?.groups?.output?.trim() ?? trimmed;
135 return output.length > 0 ? output : undefined;
136}
137
138function extractCommandFromTitle(title: string | undefined): string | undefined {
139 if (!title) {
140 return undefined;
141 }
142 const backtickMatch = /`([^`]+)`/u.exec(title);
143 return backtickMatch?.[1]?.trim() || undefined;
144}
145
146function extractToolCommand(data: Record<string, unknown> | undefined, title: string | undefined) {
147 const item = asRecord(data?.item);
148 const itemInput = asRecord(item?.input);
149 const itemResult = asRecord(item?.result);
150 const rawInput = asRecord(data?.rawInput);
151 const candidates = [
152 normalizeCommandValue(item?.command),
153 normalizeCommandValue(itemInput?.command),
154 normalizeCommandValue(itemResult?.command),
155 normalizeCommandValue(data?.command),
156 normalizeCommandValue(rawInput?.command),
157 ];
158 const direct = candidates.find((candidate) => candidate !== undefined);
159 if (direct) {
160 return direct;
161 }
162 const executable = asTrimmedString(rawInput?.executable);
163 const args = normalizeCommandValue(rawInput?.args);
164 if (executable && args) {
165 return `${executable} ${args}`;
166 }
167 if (executable) {
168 return executable;
169 }
170 return extractCommandFromTitle(title);
171}
172
173const PATH_KEYS = [
174 "path",
175 "filePath",
176 "file_path",
177 "relativePath",
178 "filename",
179 "fileName",
180 "newPath",
181 "oldPath",
182] as const;
183
184function collectPaths(value: unknown, paths: string[], seen: Set<string>, depth: number): void {
185 if (depth > 4 || paths.length >= 8) {
186 return;
187 }
188 if (Array.isArray(value)) {
189 for (const entry of value) {
190 collectPaths(entry, paths, seen, depth + 1);
191 if (paths.length >= 8) {
192 return;
193 }
194 }
195 return;
196 }
197 const record = asRecord(value);
198 if (!record) {
199 return;
200 }
201 for (const key of PATH_KEYS) {
202 const candidate = record[key];
203 if (typeof candidate !== "string" || !candidate.trim() || seen.has(candidate)) {
204 continue;
205 }
206 seen.add(candidate);
207 paths.push(candidate);
208 if (paths.length >= 8) {
209 return;
210 }
211 }
212 for (const nestedKey of ["locations", "item", "input", "result", "rawInput", "data", "changes"]) {
213 if (!(nestedKey in record)) {
214 continue;
215 }
216 collectPaths(record[nestedKey], paths, seen, depth + 1);
217 if (paths.length >= 8) {
218 return;
219 }
220 }
221}
222
223export function collectToolFilePaths(data: unknown): string[] {
224 const paths: string[] = [];
225 collectPaths(data, paths, new Set<string>(), 0);
226 return paths;
227}
228
229function extractPrimaryPath(data: Record<string, unknown> | undefined): string | undefined {
230 return collectToolFilePaths(data)[0];
231}
232
233/**
234 * A null field clears it (ACP v2) and a nonempty rawInput replaces the previous one.
235 * An empty rawInput keeps the previous one; later ACP updates often resend an empty object.
236 */
237export function mergeToolActivityData(
238 previous: unknown,
239 next: unknown,
240): Record<string, unknown> | undefined {
241 const previousRecord = asRecord(previous);
242 const nextRecord = asRecord(next);
243 if (!nextRecord) {
244 return previousRecord;
245 }
246 const merged = { ...previousRecord, ...nextRecord };
247 for (const [key, value] of Object.entries(merged)) {
248 if (value === null) {
249 delete merged[key];
250 }
251 }
252 if (!previousRecord || nextRecord.rawInput === null) {
253 return merged;
254 }
255 const previousInput = asRecord(previousRecord.rawInput);
256 const nextInput = asRecord(nextRecord.rawInput);
257 const rawInput = recordHasKeys(nextInput) ? nextInput : (previousInput ?? nextInput);
258 if (recordHasKeys(rawInput)) {
259 merged.rawInput = rawInput;
260 } else {
261 delete merged.rawInput;
262 }
263 return merged;
264}
265
266function normalizeEquivalentValue(value: string | undefined): string | undefined {
267 const trimmed = asTrimmedString(value);
268 if (!trimmed) {
269 return undefined;
270 }
271 return trimmed
272 .replace(/\s+/gu, " ")
273 .replace(/\s+(?:complete|completed|started)\s*$/iu, "")
274 .trim();
275}
276
277function isEquivalent(left: string | undefined, right: string | undefined): boolean {
278 const normalizedLeft = normalizeEquivalentValue(left)?.toLowerCase();
279 const normalizedRight = normalizeEquivalentValue(right)?.toLowerCase();
280 return normalizedLeft !== undefined && normalizedLeft === normalizedRight;
281}
282
283export type ToolActivityAction = "command" | "read" | "file_change" | "search" | "other";
284
285function toolNameToken(value: string | undefined): string | undefined {
286 const trimmed = asTrimmedString(value);
287 if (!trimmed || /__|[./]/u.test(trimmed)) {
288 return undefined;
289 }
290 return trimmed.replace(/[_\s-]/gu, "").toLowerCase();
291}
292
293export function classifyToolActivity(input: {
294 readonly itemType?: ToolLifecycleItemType | string | null | undefined;
295 readonly requestKind?: string | null | undefined;
296 readonly title?: string | undefined;
297 readonly data?: Record<string, unknown> | undefined;
298}): ToolActivityAction {
299 const itemType = input.itemType ?? undefined;
300 const requestKind = asTrimmedString(input.requestKind)?.toLowerCase();
301 const kind = asTrimmedString(input.data?.kind)?.toLowerCase();
302 const toolName = toolNameToken(
303 asTrimmedString(input.data?.toolName) ?? asTrimmedString(asRecord(input.data?.item)?.tool),
304 );
305
306 if (itemType === "command_execution") {
307 return "command";
308 }
309 if (itemType === "image_view") {
310 return "read";
311 }
312 if (itemType === "file_change") {
313 return "file_change";
314 }
315 if (itemType === "web_search") {
316 return "search";
317 }
318 if (requestKind === "command" || kind === "execute") {
319 return "command";
320 }
321 if (
322 requestKind === "file-change" ||
323 kind === "edit" ||
324 kind === "move" ||
325 kind === "delete" ||
326 kind === "write"
327 ) {
328 return "file_change";
329 }
330 if (
331 kind === "search" ||
332 toolName === "find" ||
333 toolName === "grep" ||
334 toolName === "glob" ||
335 toolName === "rg" ||
336 toolName === "ls"
337 ) {
338 return "search";
339 }
340 if (requestKind === "file-read" || kind === "read") {
341 return "read";
342 }
343 if (toolName === "terminal" || toolName === "bash" || toolName === "shell") {
344 return "command";
345 }
346 if (toolName === "read" || toolName === "readfile") {
347 return "read";
348 }
349 return "other";
350}
351
352const SEARCH_QUERY_KEYS = ["pattern", "query", "searchTerm", "regex", "grep", "needle"] as const;
353const SEARCH_GLOB_KEYS = [
354 "glob",
355 "globPattern",
356 "glob_pattern",
357 "include",
358 "filePattern",
359 "file_pattern",
360] as const;
361const SEARCH_TARGET_KEYS = [
362 "path",
363 "target_directory",
364 "targetDirectory",
365 "directory",
366 "cwd",
367 "root",
368] as const;
369
370function firstInputString(
371 record: Record<string, unknown> | undefined,
372 keys: readonly string[],
373): string | undefined {
374 if (!record) {
375 return undefined;
376 }
377 for (const key of keys) {
378 const value = asTrimmedString(record[key]);
379 if (value) {
380 return value;
381 }
382 }
383 return undefined;
384}
385
386function searchInputRecord(
387 data: Record<string, unknown> | undefined,
388): Record<string, unknown> | undefined {
389 return (
390 [data?.rawInput, data?.input, asRecord(data?.item)?.input]
391 .map(asRecord)
392 .find((record) => recordHasKeys(record ?? undefined)) ?? data
393 );
394}
395
396function searchTargetName(value: string | undefined): string | undefined {
397 if (!value) {
398 return undefined;
399 }
400 return value.split(/[\\/]/u).findLast((part) => part.length > 0 && part !== ".");
401}
402
403export function searchToolLabelParts(data: Record<string, unknown> | undefined) {
404 const input = searchInputRecord(data);
405 return {
406 query: firstInputString(input, SEARCH_QUERY_KEYS),
407 glob: firstInputString(input, SEARCH_GLOB_KEYS),
408 target: searchTargetName(firstInputString(input, SEARCH_TARGET_KEYS)),
409 };
410}
411
412export function formatSearchToolLabel(
413 data: Record<string, unknown> | undefined,
414): string | undefined {
415 const { query, glob, target } = searchToolLabelParts(data);
416 if (query && target) {
417 return `Searched ${query} in ${target}`;
418 }
419 if (glob && target) {
420 return `Searched files ${glob} in ${target}`;
421 }
422 if (glob) {
423 return `Searched files ${glob}`;
424 }
425 if (query) {
426 return `Searched ${query}`;
427 }
428 if (target) {
429 return `Searched in ${target}`;
430 }
431 return undefined;
432}
433
434export function formatReadToolLabel(path: string, extraCount = 0): string {
435 const trimmed = path.trim();
436 const suffix = extraCount > 0 ? ` +${extraCount} more` : "";
437 if (!trimmed) {
438 return `Read file${suffix}`;
439 }
440 return `Read ${trimmed}${suffix}`;
441}
442
443export interface ToolActivityPresentationInput {
444 readonly itemType?: ToolLifecycleItemType | null | undefined;
445 readonly title?: string | null | undefined;
446 readonly detail?: string | null | undefined;
447 readonly data?: unknown;
448 readonly fallbackSummary?: string | null | undefined;
449}
450
451export interface ToolActivityPresentation {
452 readonly summary: string;
453 readonly detail?: string | undefined;
454}
455
456export function deriveToolActivityPresentation(
457 input: ToolActivityPresentationInput,
458): ToolActivityPresentation {
459 const title = asTrimmedString(input.title);
460 const detail = stripTrailingExitCode(asTrimmedString(input.detail));
461 const fallbackSummary = asTrimmedString(input.fallbackSummary) ?? "Tool";
462 const data = asRecord(input.data);
463 const command = extractToolCommand(data, title);
464 const primaryPath = extractPrimaryPath(data);
465 const action = classifyToolActivity({
466 itemType: input.itemType,
467 title,
468 data,
469 });
470
471 if (action === "command") {
472 return {
473 summary: "Ran command",
474 ...(command ? { detail: command } : {}),
475 };
476 }
477
478 if (action === "read") {
479 if (primaryPath) {
480 return {
481 summary: formatReadToolLabel(primaryPath),
482 };
483 }
484 return {
485 summary: "Read file",
486 };
487 }
488
489 if (action === "file_change") {
490 return {
491 summary: "Changed files",
492 ...(primaryPath ? { detail: primaryPath } : {}),
493 };
494 }
495
496 if (action === "search") {
497 const searchLabel = formatSearchToolLabel(data);
498 if (searchLabel) {
499 return { summary: searchLabel };
500 }
501 return {
502 summary: "Searched files",
503 };
504 }
505
506 if (detail && !isEquivalent(detail, title) && !isEquivalent(detail, fallbackSummary)) {
507 return {
508 summary: title ?? fallbackSummary,
509 detail,
510 };
511 }
512
513 return {
514 summary: title ?? fallbackSummary,
515 };
516}