@devries-cameron20 / t3code Mirror · read-only
Fork 0

The best way to control Claude Code, Codex and more from any computer or phone

Mirrored from https://github.com/Camo67/t3code.git

Synced Nov 21, 04:45 UTC

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