Skip to content
Source
Sign inSign up
pingdotgg/t3code
Open History to see the last commit

toolActivity.ts

471 lines12.8 KB

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