@devries-cameron20 / t3code Mirror · read-only
Fork 0

The best way to control Claude Code, Codex and more from any computer or phone

Mirrored from https://github.com/Camo67/t3code.git

Synced Nov 21, 03:37 UTC

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