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/** Preserve the first nonempty rawInput; later ACP updates often resend an empty object. */
198export function mergeToolActivityData(
199 previous: unknown,
200 next: unknown,
201): Record<string, unknown> | undefined {
202 const previousRecord = asRecord(previous);
203 const nextRecord = asRecord(next);
204 if (!nextRecord) {
205 return previousRecord;
206 }
207 if (!previousRecord) {
208 return nextRecord;
209 }
210 const previousInput = asRecord(previousRecord.rawInput);
211 const nextInput = asRecord(nextRecord.rawInput);
212 const rawInput = recordHasKeys(nextInput)
213 ? { ...previousInput, ...nextInput }
214 : (previousInput ?? nextInput);
215 const merged = { ...previousRecord, ...nextRecord };
216 if (recordHasKeys(rawInput)) {
217 merged.rawInput = rawInput;
218 } else {
219 delete merged.rawInput;
220 }
221 return merged;
222}
223
224function normalizeEquivalentValue(value: string | undefined): string | undefined {
225 const trimmed = asTrimmedString(value);
226 if (!trimmed) {
227 return undefined;
228 }
229 return trimmed
230 .replace(/\s+/gu, " ")
231 .replace(/\s+(?:complete|completed|started)\s*$/iu, "")
232 .trim();
233}
234
235function isEquivalent(left: string | undefined, right: string | undefined): boolean {
236 const normalizedLeft = normalizeEquivalentValue(left)?.toLowerCase();
237 const normalizedRight = normalizeEquivalentValue(right)?.toLowerCase();
238 return normalizedLeft !== undefined && normalizedLeft === normalizedRight;
239}
240
241export type ToolActivityAction = "command" | "read" | "file_change" | "search" | "other";
242
243function toolNameToken(value: string | undefined): string | undefined {
244 const trimmed = asTrimmedString(value);
245 if (!trimmed || /__|[./]/u.test(trimmed)) {
246 return undefined;
247 }
248 return trimmed.replace(/[_\s-]/gu, "").toLowerCase();
249}
250
251export function classifyToolActivity(input: {
252 readonly itemType?: ToolLifecycleItemType | string | null | undefined;
253 readonly requestKind?: string | null | undefined;
254 readonly title?: string | undefined;
255 readonly data?: Record<string, unknown> | undefined;
256}): ToolActivityAction {
257 const itemType = input.itemType ?? undefined;
258 const requestKind = asTrimmedString(input.requestKind)?.toLowerCase();
259 const kind = asTrimmedString(input.data?.kind)?.toLowerCase();
260 const toolName = toolNameToken(
261 asTrimmedString(input.data?.toolName) ?? asTrimmedString(asRecord(input.data?.item)?.tool),
262 );
263
264 if (itemType === "command_execution") {
265 return "command";
266 }
267 if (itemType === "image_view") {
268 return "read";
269 }
270 if (itemType === "file_change") {
271 return "file_change";
272 }
273 if (itemType === "web_search") {
274 return "search";
275 }
276 if (requestKind === "command" || kind === "execute") {
277 return "command";
278 }
279 if (
280 requestKind === "file-change" ||
281 kind === "edit" ||
282 kind === "move" ||
283 kind === "delete" ||
284 kind === "write"
285 ) {
286 return "file_change";
287 }
288 if (
289 kind === "search" ||
290 toolName === "find" ||
291 toolName === "grep" ||
292 toolName === "glob" ||
293 toolName === "rg" ||
294 toolName === "ls"
295 ) {
296 return "search";
297 }
298 if (requestKind === "file-read" || kind === "read") {
299 return "read";
300 }
301 if (toolName === "terminal" || toolName === "bash" || toolName === "shell") {
302 return "command";
303 }
304 if (toolName === "read" || toolName === "readfile") {
305 return "read";
306 }
307 return "other";
308}
309
310const SEARCH_QUERY_KEYS = ["pattern", "query", "searchTerm", "regex", "grep", "needle"] as const;
311const SEARCH_GLOB_KEYS = [
312 "glob",
313 "globPattern",
314 "glob_pattern",
315 "include",
316 "filePattern",
317 "file_pattern",
318] as const;
319const SEARCH_TARGET_KEYS = [
320 "path",
321 "target_directory",
322 "targetDirectory",
323 "directory",
324 "cwd",
325 "root",
326] as const;
327
328function firstInputString(
329 record: Record<string, unknown> | undefined,
330 keys: readonly string[],
331): string | undefined {
332 if (!record) {
333 return undefined;
334 }
335 for (const key of keys) {
336 const value = asTrimmedString(record[key]);
337 if (value) {
338 return value;
339 }
340 }
341 return undefined;
342}
343
344function searchInputRecord(
345 data: Record<string, unknown> | undefined,
346): Record<string, unknown> | undefined {
347 return (
348 [data?.rawInput, data?.input, asRecord(data?.item)?.input]
349 .map(asRecord)
350 .find((record) => recordHasKeys(record ?? undefined)) ?? data
351 );
352}
353
354function searchTargetName(value: string | undefined): string | undefined {
355 if (!value) {
356 return undefined;
357 }
358 return value.split(/[\\/]/u).findLast((part) => part.length > 0 && part !== ".");
359}
360
361export function formatSearchToolLabel(
362 data: Record<string, unknown> | undefined,
363): string | undefined {
364 const input = searchInputRecord(data);
365 const query = firstInputString(input, SEARCH_QUERY_KEYS);
366 const glob = firstInputString(input, SEARCH_GLOB_KEYS);
367 const target = searchTargetName(firstInputString(input, SEARCH_TARGET_KEYS));
368 if (query && target) {
369 return `Searched ${query} in ${target}`;
370 }
371 if (glob && target) {
372 return `Searched files ${glob} in ${target}`;
373 }
374 if (glob) {
375 return `Searched files ${glob}`;
376 }
377 if (query) {
378 return `Searched ${query}`;
379 }
380 if (target) {
381 return `Searched in ${target}`;
382 }
383 return undefined;
384}
385
386export function formatReadToolLabel(path: string, extraCount = 0): string {
387 const trimmed = path.trim();
388 const suffix = extraCount > 0 ? ` +${extraCount} more` : "";
389 if (!trimmed) {
390 return `Read file${suffix}`;
391 }
392 return `Read ${trimmed}${suffix}`;
393}
394
395export interface ToolActivityPresentationInput {
396 readonly itemType?: ToolLifecycleItemType | null | undefined;
397 readonly title?: string | null | undefined;
398 readonly detail?: string | null | undefined;
399 readonly data?: unknown;
400 readonly fallbackSummary?: string | null | undefined;
401}
402
403export interface ToolActivityPresentation {
404 readonly summary: string;
405 readonly detail?: string | undefined;
406}
407
408export function deriveToolActivityPresentation(
409 input: ToolActivityPresentationInput,
410): ToolActivityPresentation {
411 const title = asTrimmedString(input.title);
412 const detail = stripTrailingExitCode(asTrimmedString(input.detail));
413 const fallbackSummary = asTrimmedString(input.fallbackSummary) ?? "Tool";
414 const data = asRecord(input.data);
415 const command = extractToolCommand(data, title);
416 const primaryPath = extractPrimaryPath(data);
417 const action = classifyToolActivity({
418 itemType: input.itemType,
419 title,
420 data,
421 });
422
423 if (action === "command") {
424 return {
425 summary: "Ran command",
426 ...(command ? { detail: command } : {}),
427 };
428 }
429
430 if (action === "read") {
431 if (primaryPath) {
432 return {
433 summary: formatReadToolLabel(primaryPath),
434 };
435 }
436 return {
437 summary: "Read file",
438 };
439 }
440
441 if (action === "file_change") {
442 return {
443 summary: "Changed files",
444 ...(primaryPath ? { detail: primaryPath } : {}),
445 };
446 }
447
448 if (action === "search") {
449 const searchLabel = formatSearchToolLabel(data);
450 if (searchLabel) {
451 return { summary: searchLabel };
452 }
453 return {
454 summary: "Searched files",
455 };
456 }
457
458 if (detail && !isEquivalent(detail, title) && !isEquivalent(detail, fallbackSummary)) {
459 return {
460 summary: title ?? fallbackSummary,
461 detail,
462 };
463 }
464
465 return {
466 summary: title ?? fallbackSummary,
467 };
468}