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