Open History to see the last commit
1import type { OrchestrationV2TurnItem } from "@t3tools/contracts";
2import { resolveT3McpToolId } from "@t3tools/shared/t3McpToolPresentation";
3import { formatReadToolLabel, formatSearchToolLabel } from "@t3tools/shared/toolActivity";
4import {
5 MAX_TOOL_OUTPUT_IMAGES,
6 readToolOutputImage,
7 type ToolOutputImage,
8} from "@t3tools/shared/toolOutput";
9
10export function openCodeToolOutput(
11 output: string | undefined,
12 files: ReadonlyArray<{ readonly uri: string; readonly mime: string }> = [],
13) {
14 const images: Array<ToolOutputImage & { type: "image" }> = [];
15 for (const file of files) {
16 const match = /^data:(image\/[a-z0-9.+-]+);base64,([A-Za-z0-9+/]+={0,2})$/i.exec(file.uri);
17 if (match?.[1]?.toLowerCase() !== file.mime.toLowerCase()) continue;
18 const image = readToolOutputImage({ type: "image", mimeType: file.mime, data: match?.[2] });
19 if (image === null) continue;
20 images.push({ type: "image", ...image });
21 if (images.length === MAX_TOOL_OUTPUT_IMAGES) break;
22 }
23 return images.length === 0
24 ? output
25 : { content: [...(output ? [{ type: "text", text: output }] : []), ...images] };
26}
27
28// Search results stay on the timeline wire, so keep their text a preview.
29const SEARCH_PREVIEW_MAX_CHARS = 8_000;
30
31type ToolItemBase = Omit<
32 Extract<OrchestrationV2TurnItem, { type: "dynamic_tool" }>,
33 "type" | "toolName" | "input" | "output"
34>;
35
36function openCodeToolProjectionKind(
37 toolName: string,
38): "command_execution" | "file_change" | "file_search" | "web_search" | "dynamic_tool" {
39 if (toolName.startsWith("mcp__") || resolveT3McpToolId(toolName) !== null) return "dynamic_tool";
40 const normalized = toolName.toLowerCase();
41 if (normalized === "todowrite") {
42 return "dynamic_tool";
43 }
44 if (normalized.includes("bash") || normalized.includes("shell")) {
45 return "command_execution";
46 }
47 if (normalized.includes("edit") || normalized.includes("write") || normalized.includes("patch")) {
48 return "file_change";
49 }
50 if (normalized.includes("web") || normalized === "codesearch" || normalized === "code_search") {
51 return "web_search";
52 }
53 if (normalized === "read") {
54 return "dynamic_tool";
55 }
56 if (
57 normalized.includes("glob") ||
58 normalized.includes("grep") ||
59 normalized.includes("search") ||
60 normalized.includes("lsp")
61 ) {
62 return "file_search";
63 }
64 return "dynamic_tool";
65}
66
67function recordString(input: unknown, ...keys: ReadonlyArray<string>): string | undefined {
68 if (typeof input !== "object" || input === null) return undefined;
69 for (const key of keys) {
70 const value = (input as Record<string, unknown>)[key];
71 if (typeof value === "string" && value.trim().length > 0) return value;
72 }
73 return undefined;
74}
75
76function recordNumber(input: unknown, ...keys: ReadonlyArray<string>): number | undefined {
77 if (typeof input !== "object" || input === null) return undefined;
78 for (const key of keys) {
79 const value = (input as Record<string, unknown>)[key];
80 if (typeof value === "number" && Number.isFinite(value)) return value;
81 }
82 return undefined;
83}
84
85function stableJson(value: unknown): string {
86 if (typeof value === "string") return value;
87 try {
88 return JSON.stringify(value, null, 2);
89 } catch {
90 return String(value);
91 }
92}
93
94function nativeReadOutput(output: string): string {
95 const header = /^<path>[^\r\n]+<\/path>\r?\n<type>(directory|file)<\/type>\r?\n/.exec(output);
96 if (header === null) return output;
97 const body = output.slice(header[0].length);
98 // File lines are numbered; only a closing tag on its own line ends the envelope.
99 const envelope =
100 header[1] === "directory"
101 ? /^<entries>\r?\n([\s\S]*?)\r?\n<\/entries>(?=\r?\n|$)/.exec(body)
102 : /^<content>(?:\r?\n)?([\s\S]*?)\r?\n<\/content>(?=\r?\n|$)/.exec(body);
103 // OpenCode can append instructions after the envelope; keep that suffix verbatim.
104 return envelope === null ? output : envelope[1] + body.slice(envelope[0].length);
105}
106
107/** OpenCode's shell tool succeeds when the command exits non-zero. */
108export function openCodeCommandFailed(toolName: string, completedMetadata: unknown): boolean {
109 const exitCode = recordNumber(completedMetadata, "exit", "exitCode");
110 return (
111 openCodeToolProjectionKind(toolName) === "command_execution" &&
112 exitCode !== undefined &&
113 exitCode !== 0
114 );
115}
116
117export function openCodeToolTurnItem(
118 base: ToolItemBase,
119 tool: {
120 readonly name: string;
121 readonly input: Record<string, unknown>;
122 readonly output: string | undefined;
123 readonly completedMetadata: unknown;
124 readonly files?: ReadonlyArray<{ readonly uri: string; readonly mime: string }> | undefined;
125 },
126): OrchestrationV2TurnItem {
127 const { input, output } = tool;
128 switch (openCodeToolProjectionKind(tool.name)) {
129 case "command_execution": {
130 const exitCode = recordNumber(tool.completedMetadata, "exit", "exitCode");
131 return {
132 ...base,
133 type: "command_execution",
134 input: recordString(input, "command", "cmd") ?? stableJson(input),
135 ...(output === undefined ? {} : { output }),
136 ...(exitCode === undefined ? {} : { exitCode }),
137 };
138 }
139 case "file_change": {
140 const oldStr = recordString(input, "oldString", "oldText");
141 const newStr = recordString(input, "newString", "content", "newText");
142 const diffStr =
143 recordString(tool.completedMetadata, "diff", "patch") ??
144 (base.status === "failed" && output?.trim() ? output : undefined);
145 return {
146 ...base,
147 type: "file_change",
148 fileName: recordString(input, "filePath", "path", "file") ?? tool.name,
149 ...(oldStr === undefined ? {} : { oldStr }),
150 ...(newStr === undefined ? {} : { newStr }),
151 ...(diffStr === undefined ? {} : { diffStr }),
152 };
153 }
154 case "file_search": {
155 const pattern = recordString(input, "pattern", "query", "path", "filePath");
156 const searchRoot = (recordString(input, "path", "filePath") ?? pattern)?.trim();
157 return {
158 ...base,
159 title:
160 formatSearchToolLabel({ input, ...(pattern === undefined ? {} : { pattern }) }) ??
161 base.title,
162 type: "file_search",
163 ...(pattern === undefined ? {} : { pattern }),
164 ...(!output?.trim() || searchRoot === undefined
165 ? {}
166 : {
167 results: [
168 { fileName: searchRoot, preview: output.slice(0, SEARCH_PREVIEW_MAX_CHARS) },
169 ],
170 }),
171 };
172 }
173 case "web_search": {
174 const pattern = recordString(input, "query", "url", "pattern");
175 const url = recordString(input, "url")?.trim();
176 return {
177 ...base,
178 type: "web_search",
179 ...(pattern === undefined ? {} : { patterns: [pattern] }),
180 ...(!output?.trim()
181 ? {}
182 : {
183 results: [
184 {
185 ...(url === undefined ? {} : { url }),
186 snippet: output.slice(0, SEARCH_PREVIEW_MAX_CHARS),
187 },
188 ],
189 }),
190 };
191 }
192 case "dynamic_tool": {
193 const readPath = recordString(input, "filePath", "path", "file");
194 const cleanedOutput =
195 tool.name === "read" && output !== undefined ? nativeReadOutput(output) : output;
196 return {
197 ...base,
198 title:
199 tool.name.toLowerCase() === "read" && readPath !== undefined
200 ? formatReadToolLabel(readPath)
201 : base.title,
202 type: "dynamic_tool",
203 toolName: tool.name,
204 input,
205 ...(cleanedOutput === undefined && !tool.files?.length
206 ? {}
207 : { output: openCodeToolOutput(cleanedOutput, tool.files) }),
208 };
209 }
210 }
211}