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

toolItems.ts

365 lines13.5 KB

1import type { OrchestrationV2TurnItem } from "@t3tools/contracts";
2import { parseGrepOutput } from "@t3tools/shared/grepOutput";
3import { HTML_RENDER_TOOL_NAME } from "@t3tools/shared/htmlRender";
4import { resolveT3McpToolId } from "@t3tools/shared/t3McpToolPresentation";
5import { formatReadToolLabel, formatSearchToolLabel } from "@t3tools/shared/toolActivity";
6import {
7 MAX_TOOL_OUTPUT_IMAGES,
8 readToolOutputImage,
9 SEND_TO_USER_TOOL_NAME,
10 sentMessageFromToolItem,
11 type ToolOutputImage,
12} from "@t3tools/shared/toolOutput";
13​
14export function openCodeToolOutput(
15 output: string | undefined,
16 files: ReadonlyArray<{ readonly uri: string; readonly mime: string }> = [],
17) {
18 const images: Array<ToolOutputImage & { type: "image" }> = [];
19 for (const file of files) {
20 const match = /^data:(image\/[a-z0-9.+-]+);base64,([A-Za-z0-9+/]+={0,2})$/i.exec(file.uri);
21 if (match?.[1]?.toLowerCase() !== file.mime.toLowerCase()) continue;
22 const image = readToolOutputImage({ type: "image", mimeType: file.mime, data: match?.[2] });
23 if (image === null) continue;
24 images.push({ type: "image", ...image });
25 if (images.length === MAX_TOOL_OUTPUT_IMAGES) break;
26 }
27 return images.length === 0
28 ? output
29 : { content: [...(output ? [{ type: "text", text: output }] : []), ...images] };
31​
32// Search results stay on the timeline wire, so keep their text a preview.
33const SEARCH_PREVIEW_MAX_CHARS = 8_000;
34​
35type ToolItemBase = Omit<
36 Extract<OrchestrationV2TurnItem, { type: "dynamic_tool" }>,
37 "type" | "toolName" | "input" | "output"
38>;
39​
40function openCodeToolProjectionKind(
41 toolName: string,
42): "command_execution" | "file_change" | "file_search" | "web_search" | "dynamic_tool" {
43 if (toolName.startsWith("mcp__") || resolveT3McpToolId(toolName) !== null) return "dynamic_tool";
44 const normalized = toolName.toLowerCase();
45 if (normalized === "todowrite") {
46 return "dynamic_tool";
47 }
48 if (normalized.includes("bash") || normalized.includes("shell")) {
49 return "command_execution";
50 }
51 if (normalized.includes("edit") || normalized.includes("write") || normalized.includes("patch")) {
52 return "file_change";
53 }
54 if (normalized.includes("web") || normalized === "codesearch" || normalized === "code_search") {
55 return "web_search";
56 }
57 if (normalized === "read") {
58 return "dynamic_tool";
59 }
60 if (
61 normalized.includes("glob") ||
62 normalized.includes("grep") ||
63 normalized.includes("search") ||
64 normalized.includes("lsp")
65 ) {
66 return "file_search";
67 }
68 return "dynamic_tool";
70​
71function recordString(input: unknown, ...keys: ReadonlyArray<string>): string | undefined {
72 if (typeof input !== "object" || input === null) return undefined;
73 for (const key of keys) {
74 const value = (input as Record<string, unknown>)[key];
75 if (typeof value === "string" && value.trim().length > 0) return value;
76 }
77 return undefined;
79​
80function recordText(input: Record<string, unknown>, ...keys: ReadonlyArray<string>) {
81 for (const key of keys) {
82 const value = input[key];
83 if (typeof value === "string") return value;
84 }
85 return undefined;
87​
88function recordNumber(input: unknown, ...keys: ReadonlyArray<string>): number | undefined {
89 if (typeof input !== "object" || input === null) return undefined;
90 for (const key of keys) {
91 const value = (input as Record<string, unknown>)[key];
92 if (typeof value === "number" && Number.isFinite(value)) return value;
93 }
94 return undefined;
96​
97function stableJson(value: unknown): string {
98 if (typeof value === "string") return value;
99 try {
100 return JSON.stringify(value, null, 2);
101 } catch {
102 return String(value);
103 }
105​
106function nativeReadOutput(output: string): string {
107 const header = /^<path>[^\r\n]+<\/path>\r?\n<type>(directory|file)<\/type>\r?\n/.exec(output);
108 if (header === null) return output;
109 const body = output.slice(header[0].length);
110 // File lines are numbered; only a closing tag on its own line ends the envelope.
111 const envelope =
112 header[1] === "directory"
113 ? /^<entries>\r?\n([\s\S]*?)\r?\n<\/entries>(?=\r?\n|$)/.exec(body)
114 : /^<content>(?:\r?\n)?([\s\S]*?)\r?\n<\/content>(?=\r?\n|$)/.exec(body);
115 // OpenCode can append instructions after the envelope; keep that suffix verbatim.
116 return envelope === null ? output : envelope[1] + body.slice(envelope[0].length);
118​
119/** OpenCode's shell tool succeeds when the command exits non-zero. */
120export function openCodeCommandFailed(toolName: string, completedMetadata: unknown): boolean {
121 const exitCode = recordNumber(completedMetadata, "exit", "exitCode");
122 return (
123 openCodeToolProjectionKind(toolName) === "command_execution" &&
124 exitCode !== undefined &&
125 exitCode !== 0
126 );
128​
129function openCodeCodeModeToolCalls(
130 completedMetadata: unknown,
131 mcpServerName: string,
132 toolName: string,
133): ReadonlyArray<{ readonly index: number; readonly input: Record<string, unknown> }> {
134 if (typeof completedMetadata !== "object" || completedMetadata === null) return [];
135 const toolCalls = (completedMetadata as Record<string, unknown>)["toolCalls"];
136 if (!Array.isArray(toolCalls)) return [];
137 return toolCalls.flatMap((call: unknown, index) => {
138 if (typeof call !== "object" || call === null) return [];
139 const { tool, status, input } = call as Record<string, unknown>;
140 return tool === `${mcpServerName}.${toolName}` &&
141 status === "completed" &&
142 typeof input === "object" &&
143 input !== null
144 ? [{ index, input: input as Record<string, unknown> }]
145 : [];
146 });
148​
149/** Code Mode reports nested calls with their input but no result, so pages are found by input. */
150export function openCodeCodeModeHtmlRenders(
151 completedMetadata: unknown,
152 mcpServerName: string,
153): ReadonlyArray<{ readonly index: number; readonly input: Record<string, unknown> }> {
154 return openCodeCodeModeToolCalls(completedMetadata, mcpServerName, HTML_RENDER_TOOL_NAME);
156​
157/** Code Mode reports nested calls with their input but no result, so sent messages are found by input. */
158export function openCodeCodeModeSentMessages(
159 completedMetadata: unknown,
160 mcpServerName: string,
161): ReadonlyArray<{ readonly index: number; readonly input: Record<string, unknown> }> {
162 return openCodeCodeModeToolCalls(completedMetadata, mcpServerName, SEND_TO_USER_TOOL_NAME);
164​
165const MAX_JSON_STRING_UNWRAP_DEPTH = 4;
166​
167function stripSentMessageFromJsonText(
168 text: string,
169 seen: ReadonlySet<string>,
170 depth = 0,
171): { readonly changed: false } | { readonly changed: true; readonly text: string | undefined } {
172 if (depth >= MAX_JSON_STRING_UNWRAP_DEPTH) return { changed: false };
173 const trimmed = text.trim();
174 if (!trimmed.startsWith("{") && !trimmed.startsWith("[") && !trimmed.startsWith('"')) {
175 return { changed: false };
176 }
177 try {
178 const parsed: unknown = JSON.parse(trimmed);
179 if (typeof parsed === "string") {
180 const inner = stripSentMessageFromJsonText(parsed, seen, depth + 1);
181 if (!inner.changed) return { changed: false };
182 return {
183 changed: true,
184 text: inner.text === undefined ? undefined : JSON.stringify(inner.text),
185 };
186 }
187 const stripped = stripSentMessageFromValue(parsed, seen, depth + 1);
188 if (stripped === parsed) return { changed: false };
189 return {
190 changed: true,
191 text: stripped === undefined ? undefined : JSON.stringify(stripped),
192 };
193 } catch {
194 return { changed: false };
195 }
197​
198function stripSentMessageFromValue(value: unknown, seen: ReadonlySet<string>, depth = 0): unknown {
199 if (typeof value !== "object" || value === null) return value;
200 if (Array.isArray(value)) {
201 const next = value
202 .map((entry) => stripSentMessageFromValue(entry, seen, depth))
203 .filter((entry) => entry !== undefined);
204 if (next.length === value.length && next.every((entry, index) => entry === value[index])) {
205 return value;
206 }
207 return next.length === 0 ? undefined : next;
208 }
209 const record = value as Record<string, unknown>;
210 if (record.type === "text" && typeof record.text === "string") {
211 const strippedText = stripSentMessageFromJsonText(record.text, seen, depth);
212 if (strippedText.changed) {
213 if (strippedText.text !== undefined) {
214 return Object.fromEntries(
215 Object.entries(record).map(([key, entry]) => [
216 key,
217 key === "text" ? strippedText.text : entry,
218 ]),
219 );
220 }
221 const hasSiblings = Object.keys(record).some((key) => key !== "type" && key !== "text");
222 if (!hasSiblings) return undefined;
223 return Object.fromEntries(
224 Object.entries(record).map(([key, entry]) => [key, key === "text" ? "" : entry]),
225 );
226 }
227 return value;
228 }
229 let changed = false;
230 const entries: Array<readonly [string, unknown]> = [];
231 for (const [key, entry] of Object.entries(record)) {
232 if (key === "sentMessage" && typeof entry === "string" && seen.has(entry)) {
233 changed = true;
234 continue;
235 }
236 const isEnvelopeKey = key === "structuredContent" || key === "result" || key === "content";
237 // compactDynamicToolOutput decodes JSON strings under these keys, so suppression must too.
238 const strippedText =
239 isEnvelopeKey && typeof entry === "string"
240 ? stripSentMessageFromJsonText(entry, seen, depth + 1)
241 : undefined;
242 const stripped = strippedText?.changed
243 ? strippedText.text
244 : isEnvelopeKey
245 ? stripSentMessageFromValue(entry, seen, depth)
246 : entry;
247 if (stripped !== entry) changed = true;
248 if (stripped !== undefined) {
249 entries.push([key, stripped]);
250 }
251 }
252 if (!changed) return value;
253 return entries.length === 0 ? undefined : Object.fromEntries(entries);
255​
256/** Remove a duplicate returned sentMessage from Code Mode text output while preserving other fields/images. */
257export function stripOpenCodeReturnedSentMessage(
258 toolName: string,
259 output: string | undefined,
260 seenSentMessages: ReadonlySet<string>,
261): string | undefined {
262 if (output === undefined || seenSentMessages.size === 0) return output;
263 const returned = sentMessageFromToolItem({ toolName, output });
264 if (returned === undefined || !seenSentMessages.has(returned)) return output;
265 const stripped = stripSentMessageFromJsonText(output, seenSentMessages);
266 return stripped.changed ? stripped.text : output;
268​
269export function openCodeToolTurnItem(
270 base: ToolItemBase,
271 tool: {
272 readonly name: string;
273 readonly input: Record<string, unknown>;
274 readonly output: string | undefined;
275 readonly completedMetadata: unknown;
276 readonly files?: ReadonlyArray<{ readonly uri: string; readonly mime: string }> | undefined;
277 },
278): OrchestrationV2TurnItem {
279 const { input, output } = tool;
280 switch (openCodeToolProjectionKind(tool.name)) {
281 case "command_execution": {
282 const exitCode = recordNumber(tool.completedMetadata, "exit", "exitCode");
283 return {
284 ...base,
285 type: "command_execution",
286 input: recordString(input, "command", "cmd") ?? stableJson(input),
287 ...(output === undefined ? {} : { output }),
288 ...(exitCode === undefined ? {} : { exitCode }),
289 };
290 }
291 case "file_change": {
292 const oldStr = recordText(input, "oldString", "oldText");
293 const newStr = recordText(input, "newString", "content", "newText");
294 const diffStr =
295 recordString(tool.completedMetadata, "diff", "patch") ??
296 (base.status === "failed" && output?.trim() ? output : undefined);
297 return {
298 ...base,
299 type: "file_change",
300 fileName: recordString(input, "filePath", "path", "file") ?? tool.name,
301 ...(oldStr === undefined ? {} : { oldStr }),
302 ...(newStr === undefined ? {} : { newStr }),
303 ...(diffStr === undefined ? {} : { diffStr }),
304 };
305 }
306 case "file_search": {
307 const pattern = recordString(input, "pattern", "query", "path", "filePath");
308 const searchRoot = (recordString(input, "path", "filePath") ?? pattern)?.trim();
309 return {
310 ...base,
311 title:
312 formatSearchToolLabel({ input, ...(pattern === undefined ? {} : { pattern }) }) ??
313 base.title,
314 type: "file_search",
315 ...(pattern === undefined ? {} : { pattern }),
316 ...(!output?.trim() || searchRoot === undefined
317 ? {}
318 : {
319 results: [
320 ...(parseGrepOutput(output, searchRoot) ?? [
321 { fileName: searchRoot, preview: output.slice(0, SEARCH_PREVIEW_MAX_CHARS) },
322 ]),
323 ],
324 }),
325 };
326 }
327 case "web_search": {
328 const pattern = recordString(input, "query", "url", "pattern");
329 const url = recordString(input, "url")?.trim();
330 return {
331 ...base,
332 type: "web_search",
333 ...(pattern === undefined ? {} : { patterns: [pattern] }),
334 ...(!output?.trim()
335 ? {}
336 : {
337 results: [
338 {
339 ...(url === undefined ? {} : { url }),
340 snippet: output.slice(0, SEARCH_PREVIEW_MAX_CHARS),
341 },
342 ],
343 }),
344 };
345 }
346 case "dynamic_tool": {
347 const readPath = recordString(input, "filePath", "path", "file");
348 const cleanedOutput =
349 tool.name === "read" && output !== undefined ? nativeReadOutput(output) : output;
350 return {
351 ...base,
352 title:
353 tool.name.toLowerCase() === "read" && readPath !== undefined
354 ? formatReadToolLabel(readPath)
355 : base.title,
356 type: "dynamic_tool",
357 toolName: tool.name,
358 input,
359 ...(cleanedOutput === undefined && !tool.files?.length
360 ? {}
361 : { output: openCodeToolOutput(cleanedOutput, tool.files) }),
362 };
363 }
364 }