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