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
17function normalizeCommandValue(value: unknown): string | undefined {
18 const direct = asTrimmedString(value);
19 if (direct) {
20 return direct;
21 }
22 if (!Array.isArray(value)) {
23 return undefined;
24 }
25 const parts = value
26 .map((entry) => asTrimmedString(entry))
27 .filter((entry): entry is string => entry !== undefined);
28 return parts.length > 0 ? parts.join(" ") : undefined;
29}
30
31function stripTrailingExitCode(value: string | undefined): string | undefined {
32 const trimmed = value?.trim();
33 if (!trimmed) {
34 return undefined;
35 }
36 const match = /^(?<output>[\s\S]*?)(?:\s*<exited with exit code \d+>)\s*$/iu.exec(trimmed);
37 const output = match?.groups?.output?.trim() ?? trimmed;
38 return output.length > 0 ? output : undefined;
39}
40
41function extractCommandFromTitle(title: string | undefined): string | undefined {
42 if (!title) {
43 return undefined;
44 }
45 const backtickMatch = /`([^`]+)`/u.exec(title);
46 return backtickMatch?.[1]?.trim() || undefined;
47}
48
49function extractToolCommand(data: Record<string, unknown> | undefined, title: string | undefined) {
50 const item = asRecord(data?.item);
51 const itemInput = asRecord(item?.input);
52 const itemResult = asRecord(item?.result);
53 const rawInput = asRecord(data?.rawInput);
54 const candidates = [
55 normalizeCommandValue(item?.command),
56 normalizeCommandValue(itemInput?.command),
57 normalizeCommandValue(itemResult?.command),
58 normalizeCommandValue(data?.command),
59 normalizeCommandValue(rawInput?.command),
60 ];
61 const direct = candidates.find((candidate) => candidate !== undefined);
62 if (direct) {
63 return direct;
64 }
65 const executable = asTrimmedString(rawInput?.executable);
66 const args = normalizeCommandValue(rawInput?.args);
67 if (executable && args) {
68 return `${executable} ${args}`;
69 }
70 if (executable) {
71 return executable;
72 }
73 return extractCommandFromTitle(title);
74}
75
76function maybePathLike(value: string | undefined): string | undefined {
77 if (!value) {
78 return undefined;
79 }
80 if (
81 value.includes("/") ||
82 value.includes("\\") ||
83 value.startsWith(".") ||
84 /\.(?:[a-z0-9]{1,12})$/iu.test(value)
85 ) {
86 return value;
87 }
88 return undefined;
89}
90
91function collectPaths(value: unknown, paths: string[], seen: Set<string>, depth: number): void {
92 if (depth > 4 || paths.length >= 8) {
93 return;
94 }
95 if (Array.isArray(value)) {
96 for (const entry of value) {
97 collectPaths(entry, paths, seen, depth + 1);
98 if (paths.length >= 8) {
99 return;
100 }
101 }
102 return;
103 }
104 const record = asRecord(value);
105 if (!record) {
106 return;
107 }
108 for (const key of ["path", "filePath", "relativePath", "filename", "newPath", "oldPath"]) {
109 const candidate = maybePathLike(asTrimmedString(record[key]));
110 if (!candidate || seen.has(candidate)) {
111 continue;
112 }
113 seen.add(candidate);
114 paths.push(candidate);
115 if (paths.length >= 8) {
116 return;
117 }
118 }
119 for (const nestedKey of ["locations", "item", "input", "result", "rawInput", "data", "changes"]) {
120 if (!(nestedKey in record)) {
121 continue;
122 }
123 collectPaths(record[nestedKey], paths, seen, depth + 1);
124 if (paths.length >= 8) {
125 return;
126 }
127 }
128}
129
130function extractPrimaryPath(data: Record<string, unknown> | undefined): string | undefined {
131 const paths: string[] = [];
132 collectPaths(data, paths, new Set<string>(), 0);
133 return paths[0];
134}
135
136function normalizeEquivalentValue(value: string | undefined): string | undefined {
137 const trimmed = asTrimmedString(value);
138 if (!trimmed) {
139 return undefined;
140 }
141 return trimmed
142 .replace(/\s+/gu, " ")
143 .replace(/\s+(?:complete|completed|started)\s*$/iu, "")
144 .trim();
145}
146
147function isEquivalent(left: string | undefined, right: string | undefined): boolean {
148 const normalizedLeft = normalizeEquivalentValue(left)?.toLowerCase();
149 const normalizedRight = normalizeEquivalentValue(right)?.toLowerCase();
150 return normalizedLeft !== undefined && normalizedLeft === normalizedRight;
151}
152
153function classifyToolAction(input: {
154 readonly itemType?: ToolLifecycleItemType | null | undefined;
155 readonly title?: string | undefined;
156 readonly data?: Record<string, unknown> | undefined;
157}): "command" | "read" | "file_change" | "search" | "other" {
158 const itemType = input.itemType ?? undefined;
159 const kind = asTrimmedString(input.data?.kind)?.toLowerCase();
160 const title = asTrimmedString(input.title)?.toLowerCase();
161 if (itemType === "command_execution" || kind === "execute" || title === "terminal") {
162 return "command";
163 }
164 if (kind === "read" || title === "read file") {
165 return "read";
166 }
167 if (
168 itemType === "file_change" ||
169 kind === "edit" ||
170 kind === "move" ||
171 kind === "delete" ||
172 kind === "write"
173 ) {
174 return "file_change";
175 }
176 if (itemType === "web_search" || kind === "search" || title === "find" || title === "grep") {
177 return "search";
178 }
179 return "other";
180}
181
182export interface ToolActivityPresentationInput {
183 readonly itemType?: ToolLifecycleItemType | null | undefined;
184 readonly title?: string | null | undefined;
185 readonly detail?: string | null | undefined;
186 readonly data?: unknown;
187 readonly fallbackSummary?: string | null | undefined;
188}
189
190export interface ToolActivityPresentation {
191 readonly summary: string;
192 readonly detail?: string | undefined;
193}
194
195export function deriveToolActivityPresentation(
196 input: ToolActivityPresentationInput,
197): ToolActivityPresentation {
198 const title = asTrimmedString(input.title);
199 const detail = stripTrailingExitCode(asTrimmedString(input.detail));
200 const fallbackSummary = asTrimmedString(input.fallbackSummary) ?? "Tool";
201 const data = asRecord(input.data);
202 const command = extractToolCommand(data, title);
203 const primaryPath = extractPrimaryPath(data);
204 const action = classifyToolAction({
205 itemType: input.itemType,
206 title,
207 data,
208 });
209
210 if (action === "command") {
211 return {
212 summary: "Ran command",
213 ...(command ? { detail: command } : {}),
214 };
215 }
216
217 if (action === "read") {
218 if (primaryPath) {
219 return {
220 summary: "Read file",
221 detail: primaryPath,
222 };
223 }
224 return {
225 summary: "Read file",
226 };
227 }
228
229 if (action === "file_change") {
230 return {
231 summary: "Changed files",
232 ...(primaryPath ? { detail: primaryPath } : {}),
233 };
234 }
235
236 if (action === "search") {
237 const query =
238 asTrimmedString(asRecord(data?.rawInput)?.query) ??
239 asTrimmedString(asRecord(data?.rawInput)?.pattern) ??
240 asTrimmedString(asRecord(data?.rawInput)?.searchTerm);
241 return {
242 summary: "Searched files",
243 ...(query ? { detail: query } : {}),
244 };
245 }
246
247 if (detail && !isEquivalent(detail, title) && !isEquivalent(detail, fallbackSummary)) {
248 return {
249 summary: title ?? fallbackSummary,
250 detail,
251 };
252 }
253
254 return {
255 summary: title ?? fallbackSummary,
256 };
257}