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

toolItems.ts

362 lines13.4 KB

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