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

toolActivity.ts

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