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

toolOutput.ts

442 lines16.0 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_PULL_REQUEST_ITEMS = 100;
29const MAX_CONTENT_BLOCKS = 32;
30const MAX_ENVELOPE_DEPTH = 4;
31const MAX_ENVELOPE_NODES = 128;
32const encoder = new TextEncoder();
33// Antigravity's terminal tool prefixes an `acp-mcp-call` result's stdout with timestamps and exit status.
34const TERMINAL_OUTPUT_MARKER = "\nCommand output:\n";
35​
36interface ResultReadBudget {
37 remainingBytes: number;
38 remainingNodes: number;
39 exceeded: boolean;
41​
42interface ResultEnvelope {
43 data?: Record<PropertyKey, unknown>;
44 failed: boolean;
46​
47interface CompactToolOutput {
48 isError?: true;
49 threadId?: string;
50 messageId?: string;
51 taskId?: string;
52 scheduledTaskId?: string;
53 status?: "rolled_back";
54 htmlRender?: HtmlRenderReference;
55 [MCP_APP_OUTPUT_KEY]?: McpAppReference;
56 thread?: { threadId: string; title?: string; link?: string };
57 threads?: Array<{ threadId?: string; status?: "rolled_back" }>;
58 linkedCount?: number;
59 unlinkedCount?: number;
60 created?: boolean;
61 state?: "open" | "closed" | "merged";
62 guides?: Array<{ outcome: "started" | "running" | "failed" }>;
63 checks?: Array<{ rerun: boolean }>;
64 sentMessage?: string;
66​
67function readResult(value: unknown, budget: ResultReadBudget, depth = 0): ResultEnvelope {
68 if (depth > MAX_ENVELOPE_DEPTH || budget.remainingNodes-- <= 0) {
69 budget.exceeded = true;
70 return { failed: false };
71 }
72 if (typeof value === "string") {
73 if (value.length > budget.remainingBytes) {
74 budget.exceeded = true;
75 return { failed: false };
76 }
77 const bytes = encoder.encode(value).byteLength;
78 if (bytes > budget.remainingBytes) {
79 budget.exceeded = true;
80 return { failed: false };
81 }
82 budget.remainingBytes -= bytes;
83 try {
84 return readResult(JSON.parse(value), budget, depth + 1);
85 } catch {
86 return { failed: false };
87 }
88 }
89 if (Array.isArray(value)) {
90 if (value.length > MAX_CONTENT_BLOCKS) {
91 budget.exceeded = true;
92 return { failed: false };
93 }
94 let data: ResultEnvelope["data"];
95 let failed = false;
96 for (const block of value) {
97 const text = Predicate.isObject(block) ? block.text : undefined;
98 const result = readResult(
99 Predicate.isObject(text) ? (text.text ?? text) : text,
100 budget,
101 depth + 1,
102 );
103 data ??= result.data;
104 failed ||= result.failed;
105 if (budget.exceeded) break;
106 }
107 return { ...(data === undefined ? {} : { data }), failed };
108 }
109 if (!Predicate.isObject(value)) return { failed: false };
110 const failed =
111 value.isError === true ||
112 value.is_error === true ||
113 value._tag === "OrchestratorMcpFailure" ||
114 value.error != null;
115 const terminal = typeof value.output === "string" ? value.output : "";
116 const marker = terminal.indexOf(TERMINAL_OUTPUT_MARKER);
117 const content =
118 value.structuredContent ??
119 value.content ??
120 (marker === -1 ? undefined : terminal.slice(marker + TERMINAL_OUTPUT_MARKER.length));
121 if (content !== undefined) {
122 const nested = readResult(content, budget, depth + 1);
123 return { ...nested, failed: failed || nested.failed };
124 }
125 return { data: value, failed };
127​
128function boundedId(value: unknown): string | undefined {
129 if (typeof value !== "string" || value.length > MAX_ID_LENGTH || value.trim() === "") {
130 return undefined;
131 }
132 return Array.from(value).join("");
134​
135// All or nothing: a partial list would make the summary report wrong counts.
136function readEntries<T>(
137 value: unknown,
138 read: (entry: { readonly [key: string]: unknown }) => T | undefined,
139): T[] | undefined {
140 if (!Array.isArray(value) || value.length > MAX_PULL_REQUEST_ITEMS) return undefined;
141 const entries: T[] = [];
142 for (const entry of value) {
143 const compact = Predicate.isObject(entry) ? read(entry) : undefined;
144 if (compact === undefined) return undefined;
145 entries.push(compact);
146 }
147 return entries;
149​
150export function compactDynamicToolOutput(
151 value: unknown,
152 toolName?: string | null,
153): CompactToolOutput | undefined {
154 const readsThread = resolveT3McpToolId(toolName) === "t3_thread_read";
155 const budget: ResultReadBudget = {
156 // Thread-read pages can exceed the generic envelope budget before JSON escaping.
157 remainingBytes: readsThread ? 128 * 1024 : MAX_PARSED_BYTES,
158 remainingNodes: MAX_ENVELOPE_NODES,
159 exceeded: false,
160 };
161 const result = readResult(value, budget);
162 const output: CompactToolOutput = result.failed ? { isError: true } : {};
163 const data = budget.exceeded ? undefined : result.data;
164 if (data !== undefined) {
165 for (const key of ["threadId", "messageId", "taskId", "scheduledTaskId"] as const) {
166 const id = boundedId(data[key]);
167 if (id !== undefined) output[key] = id;
168 }
169 if (data.status === "rolled_back") output.status = "rolled_back";
170 for (const key of ["linkedCount", "unlinkedCount"] as const) {
171 const count = data[key];
172 if (typeof count === "number" && Number.isSafeInteger(count)) output[key] = count;
173 }
174 if (typeof data.created === "boolean") output.created = data.created;
175 if (data.state === "open" || data.state === "closed" || data.state === "merged") {
176 output.state = data.state;
177 }
178 const guides = readEntries(data.guides, (entry) =>
179 entry.outcome === "started" || entry.outcome === "running" || entry.outcome === "failed"
180 ? ({ outcome: entry.outcome } as const)
181 : undefined,
182 );
183 if (guides !== undefined) output.guides = guides;
184 const checks = readEntries(data.checks, (entry) =>
185 typeof entry.rerun === "boolean" ? { rerun: entry.rerun } : undefined,
186 );
187 if (checks !== undefined) output.checks = checks;
188 if (
189 typeof data.sentMessage === "string" &&
190 data.sentMessage.trim() !== "" &&
191 data.sentMessage.length <= SEND_TO_USER_MAX_LENGTH
192 ) {
193 output.sentMessage = data.sentMessage;
194 }
195 const htmlRender = readHtmlRenderReference(data.htmlRender);
196 if (htmlRender !== undefined) output.htmlRender = htmlRender;
197 const mcpApp = readMcpAppReference(data[MCP_APP_OUTPUT_KEY]);
198 if (mcpApp !== undefined) output[MCP_APP_OUTPUT_KEY] = mcpApp;
199 const thread = Predicate.isObject(data.thread) ? data.thread : undefined;
200 const nestedThreadId = boundedId(thread?.threadId);
201 if (nestedThreadId !== undefined) {
202 output.thread = { threadId: nestedThreadId };
203 if (readsThread && !result.failed && thread !== undefined) {
204 const title = typeof thread.title === "string" ? thread.title.trim() : "";
205 if (title.length > 0 && title.length <= 1024) output.thread.title = title;
206 if (typeof thread.link === "string" && thread.link.length <= 2048) {
207 output.thread.link = thread.link;
208 }
209 }
210 }
211​
212 if (Array.isArray(data.threads)) {
213 let complete = data.threads.length <= MAX_THREADS;
214 const threads: NonNullable<CompactToolOutput["threads"]> = [];
215 if (complete) {
216 for (const entry of data.threads) {
217 if (!Predicate.isObject(entry)) {
218 complete = false;
219 break;
220 }
221 const threadId = boundedId(entry.threadId);
222 const rolledBack = entry.status === "rolled_back";
223 if (threadId === undefined && !rolledBack) {
224 complete = false;
225 break;
226 }
227 threads.push({
228 ...(threadId === undefined ? {} : { threadId }),
229 ...(rolledBack ? { status: "rolled_back" as const } : {}),
230 });
231 }
232 }
233 if (complete) output.threads = threads;
234 else {
235 // Partial batches or top-level ids make the summary parser report a false creation count.
236 delete output.threadId;
237 delete output.status;
238 }
239 }
240 }
241 const oversized = () => encoder.encode(JSON.stringify(output)).byteLength > MAX_METADATA_BYTES;
242 if (oversized()) {
243 delete output.threads;
244 delete output.threadId;
245 delete output.status;
246 delete output.guides;
247 delete output.checks;
248 }
249 const app = output[MCP_APP_OUTPUT_KEY];
250 if (app?.csp !== undefined && oversized()) {
251 const { csp: _csp, ...rest } = app;
252 output[MCP_APP_OUTPUT_KEY] = rest;
253 }
254 if (oversized()) delete output[MCP_APP_OUTPUT_KEY];
255 if (readsThread && output.thread && oversized()) {
256 output.thread = { threadId: output.thread.threadId };
257 }
258 return Object.keys(output).length === 0 ? undefined : output;
260​
261// OpenCode 2 Code Mode reports a script's nested T3 tool calls as one item with the script's result.
262const OPENCODE_CODE_MODE_TOOL_NAME = "execute";
263​
264export function htmlRenderFromToolItem(item: {
265 readonly toolName: string | null | undefined;
266 readonly output?: unknown;
267}): HtmlRenderReference | undefined {
268 if (
269 item.toolName !== OPENCODE_CODE_MODE_TOOL_NAME &&
270 resolveT3McpToolId(item.toolName) !== HTML_RENDER_TOOL_NAME
271 ) {
272 return undefined;
273 }
274 const output = compactDynamicToolOutput(item.output);
275 return output?.isError ? undefined : output?.htmlRender;
277​
278/** The text `send_to_user` showed the user, which clients render as the agent's own words. */
279export function sentMessageFromToolItem(item: {
280 readonly toolName: string | null | undefined;
281 readonly output?: unknown;
282}): string | undefined {
283 if (
284 item.toolName !== OPENCODE_CODE_MODE_TOOL_NAME &&
285 resolveT3McpToolId(item.toolName) !== SEND_TO_USER_TOOL_NAME
286 ) {
287 return undefined;
288 }
289 const output = compactDynamicToolOutput(item.output);
290 return output?.isError ? undefined : output?.sentMessage;
292​
293/** The thread-owned file `preview_recording_stop` stored for the agent. */
294export function previewRecordingIdFromToolItem(item: {
295 readonly toolName: string | null | undefined;
296 readonly output?: unknown;
297}): string | undefined {
298 if (resolveT3McpToolId(item.toolName) !== "preview_recording_stop") return undefined;
299 const budget: ResultReadBudget = {
300 remainingBytes: MAX_PARSED_BYTES,
301 remainingNodes: MAX_ENVELOPE_NODES,
302 exceeded: false,
303 };
304 const result = readResult(item.output, budget);
305 return result.failed || budget.exceeded ? undefined : boundedId(result.data?.id);
307​
308/**
309 * Compact structured result a T3 MCP tool carries on its turn item.
310 * Preserves every metadata field clients, summaries, and attachment retention read.
311 */
312export function compactT3McpToolOutput(
313 toolName: string | null | undefined,
314 value: unknown,
315): Record<string, unknown> | undefined {
316 const resolved = resolveT3McpToolId(toolName);
317 if (resolved === null) return undefined;
318 const compact = compactDynamicToolOutput(value, resolved);
319 if (resolved === "preview_recording_stop" && !compact?.isError) {
320 const recordingId = previewRecordingIdFromToolItem({ toolName: resolved, output: value });
321 if (recordingId !== undefined) {
322 return { ...compact, id: recordingId };
323 }
324 }
325 return compact === undefined ? undefined : { ...compact };
327​
328/** Accept app references only when server and tool match the item, so tools cannot impersonate another app source. */
329export function mcpAppFromToolItem(item: {
330 readonly toolName: string | null | undefined;
331 readonly output?: unknown;
332}): McpAppReference | undefined {
333 const app = compactDynamicToolOutput(item.output)?.[MCP_APP_OUTPUT_KEY];
334 return app !== undefined &&
335 (item.toolName === `${app.server}.${app.tool}` ||
336 item.toolName === claudeMcpToolName(app.server, app.tool))
337 ? app
338 : undefined;
340​
341// A superset of every needle below, so most outputs are rejected by this single scan.
342const FAILURE_HINT =
343 /enoent|no such|no files found|not found|commandnotfound|not recognized|cannot (?:find path|be found)|exit/i;
344​
345/** Some providers report completion even when command output describes a failure. */
346export function toolOutputIndicatesFailure(text: string): boolean {
347 return (
348 FAILURE_HINT.test(text) &&
349 (/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(
350 text,
351 ) ||
352 (/cannot find path/i.test(text) && /because it does not exist/i.test(text)) ||
353 (/is not recognized/i.test(text) && /the term '/i.test(text)) ||
354 /exit(?:ed)? with exit code\s+[1-9]\d*/i.test(text) ||
355 /exit code\s*[:\s]\s*[1-9]\d*\b/i.test(text))
356 );
358​
359/** Whether a command failed. A reported exit code outranks text in its output. */
360export function commandIndicatesFailure(command: {
361 readonly exitCode?: number | undefined;
362 readonly outputIndicatesFailure?: boolean | undefined;
363 readonly output?: string | undefined;
364}): boolean {
365 if (command.exitCode !== undefined) return command.exitCode !== 0;
366 return (
367 command.outputIndicatesFailure === true ||
368 (command.output !== undefined && toolOutputIndicatesFailure(command.output.slice(0, 32_768)))
369 );
371​
372export interface ToolOutputImage {
373 readonly mimeType: string;
374 readonly data?: string;
376​
377/** Raster types only, so agent SVG/HTML cannot be served inline. */
378export function readToolOutputImage(block: unknown): ToolOutputImage | null {
379 if (!Predicate.isObject(block) || block.type !== "image") return null;
380 const source = Predicate.isObject(block.source) ? block.source : undefined;
381 if (source !== undefined && source.type !== "base64") return null;
382 const mimeType = source === undefined ? block.mimeType : source.media_type;
383 const data = source === undefined ? block.data : source.data;
384 if (typeof mimeType !== "string" || !isProviderSendTurnSupportedImageMimeType(mimeType)) {
385 return null;
386 }
387 const image = { mimeType: mimeType.toLowerCase() };
388 return typeof data === "string" ? { ...image, data } : image;
390​
391function outputBlocks(value: unknown): ReadonlyArray<unknown> {
392 if (Array.isArray(value)) return value;
393 if (Predicate.isObject(value) && Array.isArray(value.content)) return value.content;
394 return [value];
396​
397export const MAX_TOOL_OUTPUT_IMAGES = 8;
398​
399export const MAX_TOOL_OUTPUT_IMAGE_BASE64_LENGTH =
400 Math.ceil(PROVIDER_SEND_TURN_MAX_IMAGE_BYTES / 3) * 4;
401​
402export function toolOutputImageBlocks(value: unknown): ReadonlyArray<unknown> {
403 const blocks: unknown[] = [];
404 for (const block of outputBlocks(value)) {
405 if (readToolOutputImage(block) === null) continue;
406 blocks.push(block);
407 if (blocks.length === MAX_TOOL_OUTPUT_IMAGES) break;
408 }
409 return blocks;
411​
412/** Order defines the shared tool-output-image asset index. */
413export function toolOutputImages(value: unknown): ReadonlyArray<ToolOutputImage> {
414 return toolOutputImageBlocks(value).flatMap((block) => readToolOutputImage(block) ?? []);
416​
417export function mcpToolResultOutput(result: {
418 readonly content?: unknown;
419 readonly structuredContent?: unknown;
420}): unknown {
421 const structuredContent =
422 (Array.isArray(result.structuredContent) || Predicate.isObject(result.structuredContent)) &&
423 Object.keys(result.structuredContent).length === 0
424 ? undefined
425 : result.structuredContent;
426 if (structuredContent != null && toolOutputImages(result.content).length > 0) {
427 return { content: result.content, structuredContent };
428 }
429 return structuredContent ?? result.content;
431​
432export function omitToolOutputImageData(value: unknown): unknown {
433 const omit = (block: unknown) => {
434 const image = readToolOutputImage(block);
435 return image?.data === undefined ? block : { type: "image", mimeType: image.mimeType };
436 };
437 if (Array.isArray(value)) return value.map(omit);
438 if (Predicate.isObject(value) && Array.isArray(value.content)) {
439 return { ...value, content: value.content.map(omit) };
440 }
441 return omit(value);