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 { MCP_APP_OUTPUT_KEY, readMcpAppReference, type McpAppReference } from "./mcpApp.ts";
13import { resolveT3McpToolId } from "./t3McpToolPresentation.ts";
14
15const MAX_PARSED_BYTES = 16_384;
16const MAX_METADATA_BYTES = 8_192;
17const MAX_ID_LENGTH = 256;
18const MAX_THREADS = 100;
19const MAX_CONTENT_BLOCKS = 32;
20const MAX_ENVELOPE_DEPTH = 4;
21const MAX_ENVELOPE_NODES = 128;
22const encoder = new TextEncoder();
23
24interface ResultReadBudget {
25 remainingBytes: number;
26 remainingNodes: number;
27 exceeded: boolean;
28}
29
30interface ResultEnvelope {
31 data?: Record<PropertyKey, unknown>;
32 failed: boolean;
33}
34
35interface CompactToolOutput {
36 isError?: true;
37 threadId?: string;
38 messageId?: string;
39 taskId?: string;
40 scheduledTaskId?: string;
41 status?: "rolled_back";
42 htmlRender?: HtmlRenderReference;
43 [MCP_APP_OUTPUT_KEY]?: McpAppReference;
44 thread?: { threadId: string };
45 threads?: Array<{ threadId?: string; status?: "rolled_back" }>;
46}
47
48function readResult(value: unknown, budget: ResultReadBudget, depth = 0): ResultEnvelope {
49 if (depth > MAX_ENVELOPE_DEPTH || budget.remainingNodes-- <= 0) {
50 budget.exceeded = true;
51 return { failed: false };
52 }
53 if (typeof value === "string") {
54 if (value.length > budget.remainingBytes) {
55 budget.exceeded = true;
56 return { failed: false };
57 }
58 const bytes = encoder.encode(value).byteLength;
59 if (bytes > budget.remainingBytes) {
60 budget.exceeded = true;
61 return { failed: false };
62 }
63 budget.remainingBytes -= bytes;
64 try {
65 return readResult(JSON.parse(value), budget, depth + 1);
66 } catch {
67 return { failed: false };
68 }
69 }
70 if (Array.isArray(value)) {
71 if (value.length > MAX_CONTENT_BLOCKS) {
72 budget.exceeded = true;
73 return { failed: false };
74 }
75 let data: ResultEnvelope["data"];
76 let failed = false;
77 for (const block of value) {
78 const text = Predicate.isObject(block) ? block.text : undefined;
79 const result = readResult(
80 Predicate.isObject(text) ? (text.text ?? text) : text,
81 budget,
82 depth + 1,
83 );
84 data ??= result.data;
85 failed ||= result.failed;
86 if (budget.exceeded) break;
87 }
88 return { ...(data === undefined ? {} : { data }), failed };
89 }
90 if (!Predicate.isObject(value)) return { failed: false };
91 const failed =
92 value.isError === true ||
93 value.is_error === true ||
94 value._tag === "OrchestratorMcpFailure" ||
95 value.error != null;
96 const content = value.structuredContent ?? value.content;
97 if (content !== undefined) {
98 const nested = readResult(content, budget, depth + 1);
99 return { ...nested, failed: failed || nested.failed };
100 }
101 return { data: value, failed };
102}
103
104function boundedId(value: unknown): string | undefined {
105 if (typeof value !== "string" || value.length > MAX_ID_LENGTH || value.trim() === "") {
106 return undefined;
107 }
108 return Array.from(value).join("");
109}
110
111export function compactDynamicToolOutput(value: unknown): CompactToolOutput | undefined {
112 const budget: ResultReadBudget = {
113 remainingBytes: MAX_PARSED_BYTES,
114 remainingNodes: MAX_ENVELOPE_NODES,
115 exceeded: false,
116 };
117 const result = readResult(value, budget);
118 const output: CompactToolOutput = result.failed ? { isError: true } : {};
119 const data = budget.exceeded ? undefined : result.data;
120 if (data !== undefined) {
121 for (const key of ["threadId", "messageId", "taskId", "scheduledTaskId"] as const) {
122 const id = boundedId(data[key]);
123 if (id !== undefined) output[key] = id;
124 }
125 if (data.status === "rolled_back") output.status = "rolled_back";
126 const htmlRender = readHtmlRenderReference(data.htmlRender);
127 if (htmlRender !== undefined) output.htmlRender = htmlRender;
128 const mcpApp = readMcpAppReference(data[MCP_APP_OUTPUT_KEY]);
129 if (mcpApp !== undefined) output[MCP_APP_OUTPUT_KEY] = mcpApp;
130 const nestedThreadId = Predicate.isObject(data.thread)
131 ? boundedId(data.thread.threadId)
132 : undefined;
133 if (nestedThreadId !== undefined) output.thread = { threadId: nestedThreadId };
134
135 if (Array.isArray(data.threads)) {
136 let complete = data.threads.length <= MAX_THREADS;
137 const threads: NonNullable<CompactToolOutput["threads"]> = [];
138 if (complete) {
139 for (const entry of data.threads) {
140 if (!Predicate.isObject(entry)) {
141 complete = false;
142 break;
143 }
144 const threadId = boundedId(entry.threadId);
145 const rolledBack = entry.status === "rolled_back";
146 if (threadId === undefined && !rolledBack) {
147 complete = false;
148 break;
149 }
150 threads.push({
151 ...(threadId === undefined ? {} : { threadId }),
152 ...(rolledBack ? { status: "rolled_back" as const } : {}),
153 });
154 }
155 }
156 if (complete) output.threads = threads;
157 else {
158 // A partial batch or a top-level ID would turn an unknown creation
159 // count into a confidently wrong one in the existing summary parser.
160 delete output.threadId;
161 delete output.status;
162 }
163 }
164 }
165 const oversized = () => encoder.encode(JSON.stringify(output)).byteLength > MAX_METADATA_BYTES;
166 if (oversized()) {
167 delete output.threads;
168 delete output.threadId;
169 delete output.status;
170 }
171 const app = output[MCP_APP_OUTPUT_KEY];
172 if (app?.csp !== undefined && oversized()) {
173 const { csp: _csp, ...rest } = app;
174 output[MCP_APP_OUTPUT_KEY] = rest;
175 }
176 if (oversized()) delete output[MCP_APP_OUTPUT_KEY];
177 return Object.keys(output).length === 0 ? undefined : output;
178}
179
180export function htmlRenderFromToolItem(item: {
181 readonly toolName: string | null | undefined;
182 readonly output?: unknown;
183}): HtmlRenderReference | undefined {
184 if (resolveT3McpToolId(item.toolName) !== HTML_RENDER_TOOL_NAME) return undefined;
185 const output = compactDynamicToolOutput(item.output);
186 return output?.isError ? undefined : output?.htmlRender;
187}
188
189/**
190 * The MCP App a completed tool call carries, if any. The adapter that captured
191 * it put the reference in the output, beside the tool's own result. A tool's
192 * result can imitate that shape, so the reference only counts when it names
193 * the very server and tool the item records: a server can then only ever
194 * point at an app of its own.
195 */
196export function mcpAppFromToolItem(item: {
197 readonly toolName: string | null | undefined;
198 readonly output?: unknown;
199}): McpAppReference | undefined {
200 const app = compactDynamicToolOutput(item.output)?.[MCP_APP_OUTPUT_KEY];
201 return app !== undefined && item.toolName === `${app.server}.${app.tool}` ? app : undefined;
202}
203
204/** Some providers report completion even when command output describes a failure. */
205export function toolOutputIndicatesFailure(text: string): boolean {
206 return (
207 /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(
208 text,
209 ) ||
210 (/cannot find path/i.test(text) && /because it does not exist/i.test(text)) ||
211 (/is not recognized/i.test(text) && /the term '/i.test(text)) ||
212 /<exited with exit code\s+[1-9]\d*\s*>/i.test(text) ||
213 /exit(?:ed)? with exit code\s+[1-9]\d*/i.test(text) ||
214 /exit code\s*[:\s]\s*[1-9]\d*\b/i.test(text)
215 );
216}
217
218export interface ToolOutputImage {
219 readonly mimeType: string;
220 readonly data?: string;
221}
222
223/**
224 * Only raster types are recognized, so the server never serves an agent's SVG
225 * or HTML inline.
226 */
227export function readToolOutputImage(block: unknown): ToolOutputImage | null {
228 if (!Predicate.isObject(block) || block.type !== "image") return null;
229 const source = Predicate.isObject(block.source) ? block.source : undefined;
230 if (source !== undefined && source.type !== "base64") return null;
231 const mimeType = source === undefined ? block.mimeType : source.media_type;
232 const data = source === undefined ? block.data : source.data;
233 if (typeof mimeType !== "string" || !isProviderSendTurnSupportedImageMimeType(mimeType)) {
234 return null;
235 }
236 const image = { mimeType: mimeType.toLowerCase() };
237 return typeof data === "string" ? { ...image, data } : image;
238}
239
240function outputBlocks(value: unknown): ReadonlyArray<unknown> {
241 if (Array.isArray(value)) return value;
242 if (Predicate.isObject(value) && Array.isArray(value.content)) return value.content;
243 return [value];
244}
245
246export const MAX_TOOL_OUTPUT_IMAGES = 8;
247
248export const MAX_TOOL_OUTPUT_IMAGE_BASE64_LENGTH =
249 Math.ceil(PROVIDER_SEND_TURN_MAX_IMAGE_BYTES / 3) * 4;
250
251export function toolOutputImageBlocks(value: unknown): ReadonlyArray<unknown> {
252 const blocks: unknown[] = [];
253 for (const block of outputBlocks(value)) {
254 if (readToolOutputImage(block) === null) continue;
255 blocks.push(block);
256 if (blocks.length === MAX_TOOL_OUTPUT_IMAGES) break;
257 }
258 return blocks;
259}
260
261/**
262 * The order is the `tool-output-image` asset index, so servers and clients
263 * agree on it.
264 */
265export function toolOutputImages(value: unknown): ReadonlyArray<ToolOutputImage> {
266 return toolOutputImageBlocks(value).flatMap((block) => readToolOutputImage(block) ?? []);
267}
268
269export function omitToolOutputImageData(value: unknown): unknown {
270 const omit = (block: unknown) => {
271 const image = readToolOutputImage(block);
272 return image?.data === undefined ? block : { type: "image", mimeType: image.mimeType };
273 };
274 if (Array.isArray(value)) return value.map(omit);
275 if (Predicate.isObject(value) && Array.isArray(value.content)) {
276 return { ...value, content: value.content.map(omit) };
277 }
278 return omit(value);
279}