Open History to see the last commit
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;
40}
41
42interface ResultEnvelope {
43 data?: Record<PropertyKey, unknown>;
44 failed: boolean;
45}
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 };
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;
65}
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 };
126}
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("");
133}
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;
148}
149
150export function compactDynamicToolOutput(value: unknown): CompactToolOutput | undefined {
151 const budget: ResultReadBudget = {
152 remainingBytes: MAX_PARSED_BYTES,
153 remainingNodes: MAX_ENVELOPE_NODES,
154 exceeded: false,
155 };
156 const result = readResult(value, budget);
157 const output: CompactToolOutput = result.failed ? { isError: true } : {};
158 const data = budget.exceeded ? undefined : result.data;
159 if (data !== undefined) {
160 for (const key of ["threadId", "messageId", "taskId", "scheduledTaskId"] as const) {
161 const id = boundedId(data[key]);
162 if (id !== undefined) output[key] = id;
163 }
164 if (data.status === "rolled_back") output.status = "rolled_back";
165 for (const key of ["linkedCount", "unlinkedCount"] as const) {
166 const count = data[key];
167 if (typeof count === "number" && Number.isSafeInteger(count)) output[key] = count;
168 }
169 if (typeof data.created === "boolean") output.created = data.created;
170 if (data.state === "open" || data.state === "closed" || data.state === "merged") {
171 output.state = data.state;
172 }
173 const guides = readEntries(data.guides, (entry) =>
174 entry.outcome === "started" || entry.outcome === "running" || entry.outcome === "failed"
175 ? ({ outcome: entry.outcome } as const)
176 : undefined,
177 );
178 if (guides !== undefined) output.guides = guides;
179 const checks = readEntries(data.checks, (entry) =>
180 typeof entry.rerun === "boolean" ? { rerun: entry.rerun } : undefined,
181 );
182 if (checks !== undefined) output.checks = checks;
183 if (
184 typeof data.sentMessage === "string" &&
185 data.sentMessage.trim() !== "" &&
186 data.sentMessage.length <= SEND_TO_USER_MAX_LENGTH
187 ) {
188 output.sentMessage = data.sentMessage;
189 }
190 const htmlRender = readHtmlRenderReference(data.htmlRender);
191 if (htmlRender !== undefined) output.htmlRender = htmlRender;
192 const mcpApp = readMcpAppReference(data[MCP_APP_OUTPUT_KEY]);
193 if (mcpApp !== undefined) output[MCP_APP_OUTPUT_KEY] = mcpApp;
194 const nestedThreadId = Predicate.isObject(data.thread)
195 ? boundedId(data.thread.threadId)
196 : undefined;
197 if (nestedThreadId !== undefined) output.thread = { threadId: nestedThreadId };
198
199 if (Array.isArray(data.threads)) {
200 let complete = data.threads.length <= MAX_THREADS;
201 const threads: NonNullable<CompactToolOutput["threads"]> = [];
202 if (complete) {
203 for (const entry of data.threads) {
204 if (!Predicate.isObject(entry)) {
205 complete = false;
206 break;
207 }
208 const threadId = boundedId(entry.threadId);
209 const rolledBack = entry.status === "rolled_back";
210 if (threadId === undefined && !rolledBack) {
211 complete = false;
212 break;
213 }
214 threads.push({
215 ...(threadId === undefined ? {} : { threadId }),
216 ...(rolledBack ? { status: "rolled_back" as const } : {}),
217 });
218 }
219 }
220 if (complete) output.threads = threads;
221 else {
222 // Partial batches or top-level ids make the summary parser report a false creation count.
223 delete output.threadId;
224 delete output.status;
225 }
226 }
227 }
228 const oversized = () => encoder.encode(JSON.stringify(output)).byteLength > MAX_METADATA_BYTES;
229 if (oversized()) {
230 delete output.threads;
231 delete output.threadId;
232 delete output.status;
233 delete output.guides;
234 delete output.checks;
235 }
236 const app = output[MCP_APP_OUTPUT_KEY];
237 if (app?.csp !== undefined && oversized()) {
238 const { csp: _csp, ...rest } = app;
239 output[MCP_APP_OUTPUT_KEY] = rest;
240 }
241 if (oversized()) delete output[MCP_APP_OUTPUT_KEY];
242 return Object.keys(output).length === 0 ? undefined : output;
243}
244
245// OpenCode 2 Code Mode reports a script's nested T3 tool calls as one item with the script's result.
246const OPENCODE_CODE_MODE_TOOL_NAME = "execute";
247
248export function htmlRenderFromToolItem(item: {
249 readonly toolName: string | null | undefined;
250 readonly output?: unknown;
251}): HtmlRenderReference | undefined {
252 if (
253 item.toolName !== OPENCODE_CODE_MODE_TOOL_NAME &&
254 resolveT3McpToolId(item.toolName) !== HTML_RENDER_TOOL_NAME
255 ) {
256 return undefined;
257 }
258 const output = compactDynamicToolOutput(item.output);
259 return output?.isError ? undefined : output?.htmlRender;
260}
261
262/** The text `send_to_user` showed the user, which clients render as the agent's own words. */
263export function sentMessageFromToolItem(item: {
264 readonly toolName: string | null | undefined;
265 readonly output?: unknown;
266}): string | undefined {
267 if (
268 item.toolName !== OPENCODE_CODE_MODE_TOOL_NAME &&
269 resolveT3McpToolId(item.toolName) !== SEND_TO_USER_TOOL_NAME
270 ) {
271 return undefined;
272 }
273 const output = compactDynamicToolOutput(item.output);
274 return output?.isError ? undefined : output?.sentMessage;
275}
276
277/** The thread-owned file `preview_recording_stop` stored for the agent. */
278export function previewRecordingIdFromToolItem(item: {
279 readonly toolName: string | null | undefined;
280 readonly output?: unknown;
281}): string | undefined {
282 if (resolveT3McpToolId(item.toolName) !== "preview_recording_stop") return undefined;
283 const budget: ResultReadBudget = {
284 remainingBytes: MAX_PARSED_BYTES,
285 remainingNodes: MAX_ENVELOPE_NODES,
286 exceeded: false,
287 };
288 const result = readResult(item.output, budget);
289 return result.failed || budget.exceeded ? undefined : boundedId(result.data?.id);
290}
291
292/**
293 * Compact structured result a T3 MCP tool carries on its turn item.
294 * Preserves every metadata field clients, summaries, and attachment retention read.
295 */
296export function compactT3McpToolOutput(
297 toolName: string | null | undefined,
298 value: unknown,
299): Record<string, unknown> | undefined {
300 const resolved = resolveT3McpToolId(toolName);
301 if (resolved === null) return undefined;
302 const compact = compactDynamicToolOutput(value);
303 if (resolved === "preview_recording_stop" && !compact?.isError) {
304 const recordingId = previewRecordingIdFromToolItem({ toolName: resolved, output: value });
305 if (recordingId !== undefined) {
306 return { ...compact, id: recordingId };
307 }
308 }
309 return compact === undefined ? undefined : { ...compact };
310}
311
312/** Accept app references only when server and tool match the item, so tools cannot impersonate another app source. */
313export function mcpAppFromToolItem(item: {
314 readonly toolName: string | null | undefined;
315 readonly output?: unknown;
316}): McpAppReference | undefined {
317 const app = compactDynamicToolOutput(item.output)?.[MCP_APP_OUTPUT_KEY];
318 return app !== undefined &&
319 (item.toolName === `${app.server}.${app.tool}` ||
320 item.toolName === claudeMcpToolName(app.server, app.tool))
321 ? app
322 : undefined;
323}
324
325// A superset of every needle below, so most outputs are rejected by this single scan.
326const FAILURE_HINT =
327 /enoent|no such|no files found|not found|commandnotfound|not recognized|cannot (?:find path|be found)|exit/i;
328
329/** Some providers report completion even when command output describes a failure. */
330export function toolOutputIndicatesFailure(text: string): boolean {
331 return (
332 FAILURE_HINT.test(text) &&
333 (/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(
334 text,
335 ) ||
336 (/cannot find path/i.test(text) && /because it does not exist/i.test(text)) ||
337 (/is not recognized/i.test(text) && /the term '/i.test(text)) ||
338 /exit(?:ed)? with exit code\s+[1-9]\d*/i.test(text) ||
339 /exit code\s*[:\s]\s*[1-9]\d*\b/i.test(text))
340 );
341}
342
343/** Whether a command failed. A reported exit code outranks text in its output. */
344export function commandIndicatesFailure(command: {
345 readonly exitCode?: number | undefined;
346 readonly outputIndicatesFailure?: boolean | undefined;
347 readonly output?: string | undefined;
348}): boolean {
349 if (command.exitCode !== undefined) return command.exitCode !== 0;
350 return (
351 command.outputIndicatesFailure === true ||
352 (command.output !== undefined && toolOutputIndicatesFailure(command.output.slice(0, 32_768)))
353 );
354}
355
356export interface ToolOutputImage {
357 readonly mimeType: string;
358 readonly data?: string;
359}
360
361/** Raster types only, so agent SVG/HTML cannot be served inline. */
362export function readToolOutputImage(block: unknown): ToolOutputImage | null {
363 if (!Predicate.isObject(block) || block.type !== "image") return null;
364 const source = Predicate.isObject(block.source) ? block.source : undefined;
365 if (source !== undefined && source.type !== "base64") return null;
366 const mimeType = source === undefined ? block.mimeType : source.media_type;
367 const data = source === undefined ? block.data : source.data;
368 if (typeof mimeType !== "string" || !isProviderSendTurnSupportedImageMimeType(mimeType)) {
369 return null;
370 }
371 const image = { mimeType: mimeType.toLowerCase() };
372 return typeof data === "string" ? { ...image, data } : image;
373}
374
375function outputBlocks(value: unknown): ReadonlyArray<unknown> {
376 if (Array.isArray(value)) return value;
377 if (Predicate.isObject(value) && Array.isArray(value.content)) return value.content;
378 return [value];
379}
380
381export const MAX_TOOL_OUTPUT_IMAGES = 8;
382
383export const MAX_TOOL_OUTPUT_IMAGE_BASE64_LENGTH =
384 Math.ceil(PROVIDER_SEND_TURN_MAX_IMAGE_BYTES / 3) * 4;
385
386export function toolOutputImageBlocks(value: unknown): ReadonlyArray<unknown> {
387 const blocks: unknown[] = [];
388 for (const block of outputBlocks(value)) {
389 if (readToolOutputImage(block) === null) continue;
390 blocks.push(block);
391 if (blocks.length === MAX_TOOL_OUTPUT_IMAGES) break;
392 }
393 return blocks;
394}
395
396/** Order defines the shared tool-output-image asset index. */
397export function toolOutputImages(value: unknown): ReadonlyArray<ToolOutputImage> {
398 return toolOutputImageBlocks(value).flatMap((block) => readToolOutputImage(block) ?? []);
399}
400
401export function mcpToolResultOutput(result: {
402 readonly content?: unknown;
403 readonly structuredContent?: unknown;
404}): unknown {
405 const structuredContent =
406 (Array.isArray(result.structuredContent) || Predicate.isObject(result.structuredContent)) &&
407 Object.keys(result.structuredContent).length === 0
408 ? undefined
409 : result.structuredContent;
410 if (structuredContent != null && toolOutputImages(result.content).length > 0) {
411 return { content: result.content, structuredContent };
412 }
413 return structuredContent ?? result.content;
414}
415
416export function omitToolOutputImageData(value: unknown): unknown {
417 const omit = (block: unknown) => {
418 const image = readToolOutputImage(block);
419 return image?.data === undefined ? block : { type: "image", mimeType: image.mimeType };
420 };
421 if (Array.isArray(value)) return value.map(omit);
422 if (Predicate.isObject(value) && Array.isArray(value.content)) {
423 return { ...value, content: value.content.map(omit) };
424 }
425 return omit(value);
426}