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

toolActivity.ts

433 lines11.7 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​
17/** CUA's `title` describes the action shown in the activity log. */
18export function computerUseToolTitle(
19 toolName: string | null | undefined,
20 input: unknown,
21): string | undefined {
22 if (toolName !== "cua_repl.js") return undefined;
23 return asTrimmedString(asRecord(input)?.title);
25​
26function recordHasKeys(
27 value: Record<string, unknown> | undefined,
28): value is Record<string, unknown> {
29 return value !== undefined && Object.keys(value).length > 0;
31​
32function normalizeCommandValue(value: unknown): string | undefined {
33 const direct = asTrimmedString(value);
34 if (direct) {
35 return direct;
36 }
37 if (!Array.isArray(value)) {
38 return undefined;
39 }
40 const parts: string[] = [];
41 for (const entry of value) {
42 const part = asTrimmedString(entry);
43 if (part !== undefined) {
44 parts.push(part);
45 }
46 }
47 return parts.length > 0 ? parts.join(" ") : undefined;
49​
50function stripTrailingExitCode(value: string | undefined): string | undefined {
51 const trimmed = value?.trim();
52 if (!trimmed) {
53 return undefined;
54 }
55 const match = /^(?<output>[\s\S]*?)(?:\s*<exited with exit code \d+>)\s*$/iu.exec(trimmed);
56 const output = match?.groups?.output?.trim() ?? trimmed;
57 return output.length > 0 ? output : undefined;
59​
60function extractCommandFromTitle(title: string | undefined): string | undefined {
61 if (!title) {
62 return undefined;
63 }
64 const backtickMatch = /`([^`]+)`/u.exec(title);
65 return backtickMatch?.[1]?.trim() || undefined;
67​
68function extractToolCommand(data: Record<string, unknown> | undefined, title: string | undefined) {
69 const item = asRecord(data?.item);
70 const itemInput = asRecord(item?.input);
71 const itemResult = asRecord(item?.result);
72 const rawInput = asRecord(data?.rawInput);
73 const candidates = [
74 normalizeCommandValue(item?.command),
75 normalizeCommandValue(itemInput?.command),
76 normalizeCommandValue(itemResult?.command),
77 normalizeCommandValue(data?.command),
78 normalizeCommandValue(rawInput?.command),
79 ];
80 const direct = candidates.find((candidate) => candidate !== undefined);
81 if (direct) {
82 return direct;
83 }
84 const executable = asTrimmedString(rawInput?.executable);
85 const args = normalizeCommandValue(rawInput?.args);
86 if (executable && args) {
87 return `${executable} ${args}`;
88 }
89 if (executable) {
90 return executable;
91 }
92 return extractCommandFromTitle(title);
94​
95const PATH_KEYS = [
96 "path",
97 "filePath",
98 "file_path",
99 "relativePath",
100 "filename",
101 "fileName",
102 "newPath",
103 "oldPath",
104] as const;
105​
106function collectPaths(value: unknown, paths: string[], seen: Set<string>, depth: number): void {
107 if (depth > 4 || paths.length >= 8) {
108 return;
109 }
110 if (Array.isArray(value)) {
111 for (const entry of value) {
112 collectPaths(entry, paths, seen, depth + 1);
113 if (paths.length >= 8) {
114 return;
115 }
116 }
117 return;
118 }
119 const record = asRecord(value);
120 if (!record) {
121 return;
122 }
123 for (const key of PATH_KEYS) {
124 const candidate = asTrimmedString(record[key]);
125 if (!candidate || seen.has(candidate)) {
126 continue;
127 }
128 seen.add(candidate);
129 paths.push(candidate);
130 if (paths.length >= 8) {
131 return;
132 }
133 }
134 for (const nestedKey of ["locations", "item", "input", "result", "rawInput", "data", "changes"]) {
135 if (!(nestedKey in record)) {
136 continue;
137 }
138 collectPaths(record[nestedKey], paths, seen, depth + 1);
139 if (paths.length >= 8) {
140 return;
141 }
142 }
144​
145/** Structured paths from tool input, never file-body text. */
146export function collectToolFilePaths(data: unknown): string[] {
147 const paths: string[] = [];
148 collectPaths(data, paths, new Set<string>(), 0);
149 return paths;
151​
152function extractPrimaryPath(data: Record<string, unknown> | undefined): string | undefined {
153 return collectToolFilePaths(data)[0];
155​
156/**
157 * Later ACP updates often resend `rawInput: {}`. Keep the first object that
158 * actually carried keys so a parsed path is not wiped out.
159 */
160export function mergeToolActivityData(
161 previous: unknown,
162 next: unknown,
163): Record<string, unknown> | undefined {
164 const previousRecord = asRecord(previous);
165 const nextRecord = asRecord(next);
166 if (!nextRecord) {
167 return previousRecord;
168 }
169 if (!previousRecord) {
170 return nextRecord;
171 }
172 const previousInput = asRecord(previousRecord.rawInput);
173 const nextInput = asRecord(nextRecord.rawInput);
174 const rawInput = recordHasKeys(nextInput)
175 ? { ...previousInput, ...nextInput }
176 : (previousInput ?? nextInput);
177 const merged = { ...previousRecord, ...nextRecord };
178 if (recordHasKeys(rawInput)) {
179 merged.rawInput = rawInput;
180 } else {
181 delete merged.rawInput;
182 }
183 return merged;
185​
186function normalizeEquivalentValue(value: string | undefined): string | undefined {
187 const trimmed = asTrimmedString(value);
188 if (!trimmed) {
189 return undefined;
190 }
191 return trimmed
192 .replace(/\s+/gu, " ")
193 .replace(/\s+(?:complete|completed|started)\s*$/iu, "")
194 .trim();
196​
197function isEquivalent(left: string | undefined, right: string | undefined): boolean {
198 const normalizedLeft = normalizeEquivalentValue(left)?.toLowerCase();
199 const normalizedRight = normalizeEquivalentValue(right)?.toLowerCase();
200 return normalizedLeft !== undefined && normalizedLeft === normalizedRight;
202​
203export type ToolActivityAction = "command" | "read" | "file_change" | "search" | "other";
204​
205function toolNameToken(value: string | undefined): string | undefined {
206 const trimmed = asTrimmedString(value);
207 // Server-prefixed MCP names (`github.read_file`, `mcp__db__find`) are not local reads or searches.
208 if (!trimmed || /__|[./]/u.test(trimmed)) {
209 return undefined;
210 }
211 return trimmed.replace(/[_\s-]/gu, "").toLowerCase();
213​
214export function classifyToolActivity(input: {
215 readonly itemType?: ToolLifecycleItemType | string | null | undefined;
216 readonly requestKind?: string | null | undefined;
217 readonly title?: string | undefined;
218 readonly data?: Record<string, unknown> | undefined;
219}): ToolActivityAction {
220 const itemType = input.itemType ?? undefined;
221 const requestKind = asTrimmedString(input.requestKind)?.toLowerCase();
222 const kind = asTrimmedString(input.data?.kind)?.toLowerCase();
223 const toolName = toolNameToken(
224 asTrimmedString(input.data?.toolName) ?? asTrimmedString(asRecord(input.data?.item)?.tool),
225 );
226​
227 if (itemType === "command_execution") {
228 return "command";
229 }
230 if (itemType === "image_view") {
231 return "read";
232 }
233 if (itemType === "file_change") {
234 return "file_change";
235 }
236 if (itemType === "web_search") {
237 return "search";
238 }
239 if (requestKind === "command" || kind === "execute") {
240 return "command";
241 }
242 if (
243 requestKind === "file-change" ||
244 kind === "edit" ||
245 kind === "move" ||
246 kind === "delete" ||
247 kind === "write"
248 ) {
249 return "file_change";
250 }
251 if (
252 kind === "search" ||
253 toolName === "find" ||
254 toolName === "grep" ||
255 toolName === "glob" ||
256 toolName === "rg" ||
257 toolName === "ls"
258 ) {
259 return "search";
260 }
261 if (requestKind === "file-read" || kind === "read") {
262 return "read";
263 }
264 if (toolName === "terminal" || toolName === "bash" || toolName === "shell") {
265 return "command";
266 }
267 if (toolName === "read" || toolName === "readfile") {
268 return "read";
269 }
270 return "other";
272​
273const SEARCH_QUERY_KEYS = ["pattern", "query", "searchTerm", "regex", "grep", "needle"] as const;
274const SEARCH_GLOB_KEYS = [
275 "glob",
276 "globPattern",
277 "glob_pattern",
278 "include",
279 "filePattern",
280 "file_pattern",
281] as const;
282const SEARCH_TARGET_KEYS = [
283 "path",
284 "target_directory",
285 "targetDirectory",
286 "directory",
287 "cwd",
288 "root",
289] as const;
290​
291function firstInputString(
292 record: Record<string, unknown> | undefined,
293 keys: readonly string[],
294): string | undefined {
295 if (!record) {
296 return undefined;
297 }
298 for (const key of keys) {
299 const value = asTrimmedString(record[key]);
300 if (value) {
301 return value;
302 }
303 }
304 return undefined;
306​
307function searchInputRecord(
308 data: Record<string, unknown> | undefined,
309): Record<string, unknown> | undefined {
310 return (
311 [data?.rawInput, data?.input, asRecord(data?.item)?.input]
312 .map(asRecord)
313 .find((record) => recordHasKeys(record ?? undefined)) ?? data
314 );
316​
317function searchTargetName(value: string | undefined): string | undefined {
318 if (!value) {
319 return undefined;
320 }
321 return value.split(/[\\/]/u).findLast((part) => part.length > 0 && part !== ".");
323​
324/** Cursor-style row: "Searched files *.{ts,tsx} in t3chat-new". */
325export function formatSearchToolLabel(
326 data: Record<string, unknown> | undefined,
327): string | undefined {
328 const input = searchInputRecord(data);
329 const query = firstInputString(input, SEARCH_QUERY_KEYS);
330 const glob = firstInputString(input, SEARCH_GLOB_KEYS);
331 const target = searchTargetName(firstInputString(input, SEARCH_TARGET_KEYS));
332 if (query && target) {
333 return `Searched ${query} in ${target}`;
334 }
335 if (glob && target) {
336 return `Searched files ${glob} in ${target}`;
337 }
338 if (glob) {
339 return `Searched files ${glob}`;
340 }
341 if (query) {
342 return `Searched ${query}`;
343 }
344 if (target) {
345 return `Searched in ${target}`;
346 }
347 return undefined;
349​
350/** Work-log heading for a file read: verb plus the structured path, never the path alone. */
351export function formatReadToolLabel(path: string, extraCount = 0): string {
352 const trimmed = path.trim();
353 const suffix = extraCount > 0 ? ` +${extraCount} more` : "";
354 if (!trimmed) {
355 return `Read file${suffix}`;
356 }
357 return `Read ${trimmed}${suffix}`;
359​
360export interface ToolActivityPresentationInput {
361 readonly itemType?: ToolLifecycleItemType | null | undefined;
362 readonly title?: string | null | undefined;
363 readonly detail?: string | null | undefined;
364 readonly data?: unknown;
365 readonly fallbackSummary?: string | null | undefined;
367​
368export interface ToolActivityPresentation {
369 readonly summary: string;
370 readonly detail?: string | undefined;
372​
373export function deriveToolActivityPresentation(
374 input: ToolActivityPresentationInput,
375): ToolActivityPresentation {
376 const title = asTrimmedString(input.title);
377 const detail = stripTrailingExitCode(asTrimmedString(input.detail));
378 const fallbackSummary = asTrimmedString(input.fallbackSummary) ?? "Tool";
379 const data = asRecord(input.data);
380 const command = extractToolCommand(data, title);
381 const primaryPath = extractPrimaryPath(data);
382 const action = classifyToolActivity({
383 itemType: input.itemType,
384 title,
385 data,
386 });
387​
388 if (action === "command") {
389 return {
390 summary: "Ran command",
391 ...(command ? { detail: command } : {}),
392 };
393 }
394​
395 if (action === "read") {
396 if (primaryPath) {
397 return {
398 summary: formatReadToolLabel(primaryPath),
399 };
400 }
401 return {
402 summary: "Read file",
403 };
404 }
405​
406 if (action === "file_change") {
407 return {
408 summary: "Changed files",
409 ...(primaryPath ? { detail: primaryPath } : {}),
410 };
411 }
412​
413 if (action === "search") {
414 const searchLabel = formatSearchToolLabel(data);
415 if (searchLabel) {
416 return { summary: searchLabel };
417 }
418 return {
419 summary: "Searched files",
420 };
421 }
422​
423 if (detail && !isEquivalent(detail, title) && !isEquivalent(detail, fallbackSummary)) {
424 return {
425 summary: title ?? fallbackSummary,
426 detail,
427 };
428 }
429​
430 return {
431 summary: title ?? fallbackSummary,
432 };