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