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

toolOutput.ts

350 lines12.2 KB

1import {
2 isProviderSendTurnSupportedImageMimeType,
3 PROVIDER_SEND_TURN_MAX_IMAGE_BYTES,
4} from "@t3tools/contracts";
5import * as Predicate from "effect/Predicate";
6​
7import {
8 HTML_RENDER_TOOL_NAME,
9 readHtmlRenderReference,
10 type HtmlRenderReference,
11} from "./htmlRender.ts";
12import {
13 claudeMcpToolName,
14 MCP_APP_OUTPUT_KEY,
15 readMcpAppReference,
16 type McpAppReference,
17} from "./mcpApp.ts";
18import { resolveT3McpToolId } from "./t3McpToolPresentation.ts";
19​
20export const SEND_TO_USER_TOOL_NAME = "send_to_user";
21// 4,000 UTF-16 units stay inside MAX_PARSED_BYTES even as 3-byte characters.
22export const SEND_TO_USER_MAX_LENGTH = 4_000;
23​
24const MAX_PARSED_BYTES = 16_384;
25const MAX_METADATA_BYTES = 8_192;
26const MAX_ID_LENGTH = 256;
27const MAX_THREADS = 100;
28const MAX_CONTENT_BLOCKS = 32;
29const MAX_ENVELOPE_DEPTH = 4;
30const MAX_ENVELOPE_NODES = 128;
31const encoder = new TextEncoder();
32​
33interface ResultReadBudget {
34 remainingBytes: number;
35 remainingNodes: number;
36 exceeded: boolean;
38​
39interface ResultEnvelope {
40 data?: Record<PropertyKey, unknown>;
41 failed: boolean;
43​
44interface CompactToolOutput {
45 isError?: true;
46 threadId?: string;
47 messageId?: string;
48 taskId?: string;
49 scheduledTaskId?: string;
50 status?: "rolled_back";
51 htmlRender?: HtmlRenderReference;
52 [MCP_APP_OUTPUT_KEY]?: McpAppReference;
53 thread?: { threadId: string };
54 threads?: Array<{ threadId?: string; status?: "rolled_back" }>;
55 linkedCount?: number;
56 unlinkedCount?: number;
57 sentMessage?: string;
59​
60function readResult(value: unknown, budget: ResultReadBudget, depth = 0): ResultEnvelope {
61 if (depth > MAX_ENVELOPE_DEPTH || budget.remainingNodes-- <= 0) {
62 budget.exceeded = true;
63 return { failed: false };
64 }
65 if (typeof value === "string") {
66 if (value.length > budget.remainingBytes) {
67 budget.exceeded = true;
68 return { failed: false };
69 }
70 const bytes = encoder.encode(value).byteLength;
71 if (bytes > budget.remainingBytes) {
72 budget.exceeded = true;
73 return { failed: false };
74 }
75 budget.remainingBytes -= bytes;
76 try {
77 return readResult(JSON.parse(value), budget, depth + 1);
78 } catch {
79 return { failed: false };
80 }
81 }
82 if (Array.isArray(value)) {
83 if (value.length > MAX_CONTENT_BLOCKS) {
84 budget.exceeded = true;
85 return { failed: false };
86 }
87 let data: ResultEnvelope["data"];
88 let failed = false;
89 for (const block of value) {
90 const text = Predicate.isObject(block) ? block.text : undefined;
91 const result = readResult(
92 Predicate.isObject(text) ? (text.text ?? text) : text,
93 budget,
94 depth + 1,
95 );
96 data ??= result.data;
97 failed ||= result.failed;
98 if (budget.exceeded) break;
99 }
100 return { ...(data === undefined ? {} : { data }), failed };
101 }
102 if (!Predicate.isObject(value)) return { failed: false };
103 const failed =
104 value.isError === true ||
105 value.is_error === true ||
106 value._tag === "OrchestratorMcpFailure" ||
107 value.error != null;
108 const content = value.structuredContent ?? value.content;
109 if (content !== undefined) {
110 const nested = readResult(content, budget, depth + 1);
111 return { ...nested, failed: failed || nested.failed };
112 }
113 return { data: value, failed };
115​
116function boundedId(value: unknown): string | undefined {
117 if (typeof value !== "string" || value.length > MAX_ID_LENGTH || value.trim() === "") {
118 return undefined;
119 }
120 return Array.from(value).join("");
122​
123export function compactDynamicToolOutput(value: unknown): CompactToolOutput | undefined {
124 const budget: ResultReadBudget = {
125 remainingBytes: MAX_PARSED_BYTES,
126 remainingNodes: MAX_ENVELOPE_NODES,
127 exceeded: false,
128 };
129 const result = readResult(value, budget);
130 const output: CompactToolOutput = result.failed ? { isError: true } : {};
131 const data = budget.exceeded ? undefined : result.data;
132 if (data !== undefined) {
133 for (const key of ["threadId", "messageId", "taskId", "scheduledTaskId"] as const) {
134 const id = boundedId(data[key]);
135 if (id !== undefined) output[key] = id;
136 }
137 if (data.status === "rolled_back") output.status = "rolled_back";
138 for (const key of ["linkedCount", "unlinkedCount"] as const) {
139 const count = data[key];
140 if (typeof count === "number" && Number.isSafeInteger(count)) output[key] = count;
141 }
142 if (
143 typeof data.sentMessage === "string" &&
144 data.sentMessage.trim() !== "" &&
145 data.sentMessage.length <= SEND_TO_USER_MAX_LENGTH
146 ) {
147 output.sentMessage = data.sentMessage;
148 }
149 const htmlRender = readHtmlRenderReference(data.htmlRender);
150 if (htmlRender !== undefined) output.htmlRender = htmlRender;
151 const mcpApp = readMcpAppReference(data[MCP_APP_OUTPUT_KEY]);
152 if (mcpApp !== undefined) output[MCP_APP_OUTPUT_KEY] = mcpApp;
153 const nestedThreadId = Predicate.isObject(data.thread)
154 ? boundedId(data.thread.threadId)
155 : undefined;
156 if (nestedThreadId !== undefined) output.thread = { threadId: nestedThreadId };
157​
158 if (Array.isArray(data.threads)) {
159 let complete = data.threads.length <= MAX_THREADS;
160 const threads: NonNullable<CompactToolOutput["threads"]> = [];
161 if (complete) {
162 for (const entry of data.threads) {
163 if (!Predicate.isObject(entry)) {
164 complete = false;
165 break;
166 }
167 const threadId = boundedId(entry.threadId);
168 const rolledBack = entry.status === "rolled_back";
169 if (threadId === undefined && !rolledBack) {
170 complete = false;
171 break;
172 }
173 threads.push({
174 ...(threadId === undefined ? {} : { threadId }),
175 ...(rolledBack ? { status: "rolled_back" as const } : {}),
176 });
177 }
178 }
179 if (complete) output.threads = threads;
180 else {
181 // Partial batches or top-level ids make the summary parser report a false creation count.
182 delete output.threadId;
183 delete output.status;
184 }
185 }
186 }
187 const oversized = () => encoder.encode(JSON.stringify(output)).byteLength > MAX_METADATA_BYTES;
188 if (oversized()) {
189 delete output.threads;
190 delete output.threadId;
191 delete output.status;
192 }
193 const app = output[MCP_APP_OUTPUT_KEY];
194 if (app?.csp !== undefined && oversized()) {
195 const { csp: _csp, ...rest } = app;
196 output[MCP_APP_OUTPUT_KEY] = rest;
197 }
198 if (oversized()) delete output[MCP_APP_OUTPUT_KEY];
199 return Object.keys(output).length === 0 ? undefined : output;
201​
202// OpenCode 2 Code Mode reports a script's nested T3 tool calls as one item with the script's result.
203const OPENCODE_CODE_MODE_TOOL_NAME = "execute";
204​
205export function htmlRenderFromToolItem(item: {
206 readonly toolName: string | null | undefined;
207 readonly output?: unknown;
208}): HtmlRenderReference | undefined {
209 if (
210 item.toolName !== OPENCODE_CODE_MODE_TOOL_NAME &&
211 resolveT3McpToolId(item.toolName) !== HTML_RENDER_TOOL_NAME
212 ) {
213 return undefined;
214 }
215 const output = compactDynamicToolOutput(item.output);
216 return output?.isError ? undefined : output?.htmlRender;
218​
219/** The text `send_to_user` showed the user, which clients render as the agent's own words. */
220export function sentMessageFromToolItem(item: {
221 readonly toolName: string | null | undefined;
222 readonly output?: unknown;
223}): string | undefined {
224 if (
225 item.toolName !== OPENCODE_CODE_MODE_TOOL_NAME &&
226 resolveT3McpToolId(item.toolName) !== SEND_TO_USER_TOOL_NAME
227 ) {
228 return undefined;
229 }
230 const output = compactDynamicToolOutput(item.output);
231 return output?.isError ? undefined : output?.sentMessage;
233​
234/** The thread-owned file `preview_recording_stop` stored for the agent. */
235export function previewRecordingIdFromToolItem(item: {
236 readonly toolName: string | null | undefined;
237 readonly output?: unknown;
238}): string | undefined {
239 if (resolveT3McpToolId(item.toolName) !== "preview_recording_stop") return undefined;
240 const budget: ResultReadBudget = {
241 remainingBytes: MAX_PARSED_BYTES,
242 remainingNodes: MAX_ENVELOPE_NODES,
243 exceeded: false,
244 };
245 const result = readResult(item.output, budget);
246 return result.failed || budget.exceeded ? undefined : boundedId(result.data?.id);
248​
249/** Accept app references only when server and tool match the item, so tools cannot impersonate another app source. */
250export function mcpAppFromToolItem(item: {
251 readonly toolName: string | null | undefined;
252 readonly output?: unknown;
253}): McpAppReference | undefined {
254 const app = compactDynamicToolOutput(item.output)?.[MCP_APP_OUTPUT_KEY];
255 return app !== undefined &&
256 (item.toolName === `${app.server}.${app.tool}` ||
257 item.toolName === claudeMcpToolName(app.server, app.tool))
258 ? app
259 : undefined;
261​
262// A superset of every needle below, so most outputs are rejected by this single scan.
263const FAILURE_HINT =
264 /enoent|no such|no files found|not found|commandnotfound|not recognized|cannot (?:find path|be found)|exit/i;
265​
266/** Some providers report completion even when command output describes a failure. */
267export function toolOutputIndicatesFailure(text: string): boolean {
268 return (
269 FAILURE_HINT.test(text) &&
270 (/file not found|no files found|enoent|no such file|commandnotfoundexception|command not found|is not recognized as the name of a cmdlet|a parameter cannot be found that matches parameter name/i.test(
271 text,
272 ) ||
273 (/cannot find path/i.test(text) && /because it does not exist/i.test(text)) ||
274 (/is not recognized/i.test(text) && /the term '/i.test(text)) ||
275 /exit(?:ed)? with exit code\s+[1-9]\d*/i.test(text) ||
276 /exit code\s*[:\s]\s*[1-9]\d*\b/i.test(text))
277 );
279​
280export interface ToolOutputImage {
281 readonly mimeType: string;
282 readonly data?: string;
284​
285/** Raster types only, so agent SVG/HTML cannot be served inline. */
286export function readToolOutputImage(block: unknown): ToolOutputImage | null {
287 if (!Predicate.isObject(block) || block.type !== "image") return null;
288 const source = Predicate.isObject(block.source) ? block.source : undefined;
289 if (source !== undefined && source.type !== "base64") return null;
290 const mimeType = source === undefined ? block.mimeType : source.media_type;
291 const data = source === undefined ? block.data : source.data;
292 if (typeof mimeType !== "string" || !isProviderSendTurnSupportedImageMimeType(mimeType)) {
293 return null;
294 }
295 const image = { mimeType: mimeType.toLowerCase() };
296 return typeof data === "string" ? { ...image, data } : image;
298​
299function outputBlocks(value: unknown): ReadonlyArray<unknown> {
300 if (Array.isArray(value)) return value;
301 if (Predicate.isObject(value) && Array.isArray(value.content)) return value.content;
302 return [value];
304​
305export const MAX_TOOL_OUTPUT_IMAGES = 8;
306​
307export const MAX_TOOL_OUTPUT_IMAGE_BASE64_LENGTH =
308 Math.ceil(PROVIDER_SEND_TURN_MAX_IMAGE_BYTES / 3) * 4;
309​
310export function toolOutputImageBlocks(value: unknown): ReadonlyArray<unknown> {
311 const blocks: unknown[] = [];
312 for (const block of outputBlocks(value)) {
313 if (readToolOutputImage(block) === null) continue;
314 blocks.push(block);
315 if (blocks.length === MAX_TOOL_OUTPUT_IMAGES) break;
316 }
317 return blocks;
319​
320/** Order defines the shared tool-output-image asset index. */
321export function toolOutputImages(value: unknown): ReadonlyArray<ToolOutputImage> {
322 return toolOutputImageBlocks(value).flatMap((block) => readToolOutputImage(block) ?? []);
324​
325export function mcpToolResultOutput(result: {
326 readonly content?: unknown;
327 readonly structuredContent?: unknown;
328}): unknown {
329 const structuredContent =
330 (Array.isArray(result.structuredContent) || Predicate.isObject(result.structuredContent)) &&
331 Object.keys(result.structuredContent).length === 0
332 ? undefined
333 : result.structuredContent;
334 if (structuredContent != null && toolOutputImages(result.content).length > 0) {
335 return { content: result.content, structuredContent };
336 }
337 return structuredContent ?? result.content;
339​
340export function omitToolOutputImageData(value: unknown): unknown {
341 const omit = (block: unknown) => {
342 const image = readToolOutputImage(block);
343 return image?.data === undefined ? block : { type: "image", mimeType: image.mimeType };
344 };
345 if (Array.isArray(value)) return value.map(omit);
346 if (Predicate.isObject(value) && Array.isArray(value.content)) {
347 return { ...value, content: value.content.map(omit) };
348 }
349 return omit(value);