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

toolItems.ts

185 lines6.5 KB

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