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

toolOutput.ts

266 lines9.4 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 { 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;
29​
30interface ResultEnvelope {
31 data?: Record<PropertyKey, unknown>;
32 failed: boolean;
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" }>;
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 };
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("");
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 // Partial batches or top-level ids make the summary parser report a false creation count.
159 delete output.threadId;
160 delete output.status;
161 }
162 }
163 }
164 const oversized = () => encoder.encode(JSON.stringify(output)).byteLength > MAX_METADATA_BYTES;
165 if (oversized()) {
166 delete output.threads;
167 delete output.threadId;
168 delete output.status;
169 }
170 const app = output[MCP_APP_OUTPUT_KEY];
171 if (app?.csp !== undefined && oversized()) {
172 const { csp: _csp, ...rest } = app;
173 output[MCP_APP_OUTPUT_KEY] = rest;
174 }
175 if (oversized()) delete output[MCP_APP_OUTPUT_KEY];
176 return Object.keys(output).length === 0 ? undefined : output;
178​
179export function htmlRenderFromToolItem(item: {
180 readonly toolName: string | null | undefined;
181 readonly output?: unknown;
182}): HtmlRenderReference | undefined {
183 if (resolveT3McpToolId(item.toolName) !== HTML_RENDER_TOOL_NAME) return undefined;
184 const output = compactDynamicToolOutput(item.output);
185 return output?.isError ? undefined : output?.htmlRender;
187​
188/** Accept app references only when server and tool match the item, so tools cannot impersonate another app source. */
189export function mcpAppFromToolItem(item: {
190 readonly toolName: string | null | undefined;
191 readonly output?: unknown;
192}): McpAppReference | undefined {
193 const app = compactDynamicToolOutput(item.output)?.[MCP_APP_OUTPUT_KEY];
194 return app !== undefined && item.toolName === `${app.server}.${app.tool}` ? app : undefined;
196​
197/** Some providers report completion even when command output describes a failure. */
198export function toolOutputIndicatesFailure(text: string): boolean {
199 return (
200 /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(
201 text,
202 ) ||
203 (/cannot find path/i.test(text) && /because it does not exist/i.test(text)) ||
204 (/is not recognized/i.test(text) && /the term '/i.test(text)) ||
205 /<exited with exit code\s+[1-9]\d*\s*>/i.test(text) ||
206 /exit(?:ed)? with exit code\s+[1-9]\d*/i.test(text) ||
207 /exit code\s*[:\s]\s*[1-9]\d*\b/i.test(text)
208 );
210​
211export interface ToolOutputImage {
212 readonly mimeType: string;
213 readonly data?: string;
215​
216/** Raster types only, so agent SVG/HTML cannot be served inline. */
217export function readToolOutputImage(block: unknown): ToolOutputImage | null {
218 if (!Predicate.isObject(block) || block.type !== "image") return null;
219 const source = Predicate.isObject(block.source) ? block.source : undefined;
220 if (source !== undefined && source.type !== "base64") return null;
221 const mimeType = source === undefined ? block.mimeType : source.media_type;
222 const data = source === undefined ? block.data : source.data;
223 if (typeof mimeType !== "string" || !isProviderSendTurnSupportedImageMimeType(mimeType)) {
224 return null;
225 }
226 const image = { mimeType: mimeType.toLowerCase() };
227 return typeof data === "string" ? { ...image, data } : image;
229​
230function outputBlocks(value: unknown): ReadonlyArray<unknown> {
231 if (Array.isArray(value)) return value;
232 if (Predicate.isObject(value) && Array.isArray(value.content)) return value.content;
233 return [value];
235​
236export const MAX_TOOL_OUTPUT_IMAGES = 8;
237​
238export const MAX_TOOL_OUTPUT_IMAGE_BASE64_LENGTH =
239 Math.ceil(PROVIDER_SEND_TURN_MAX_IMAGE_BYTES / 3) * 4;
240​
241export function toolOutputImageBlocks(value: unknown): ReadonlyArray<unknown> {
242 const blocks: unknown[] = [];
243 for (const block of outputBlocks(value)) {
244 if (readToolOutputImage(block) === null) continue;
245 blocks.push(block);
246 if (blocks.length === MAX_TOOL_OUTPUT_IMAGES) break;
247 }
248 return blocks;
250​
251/** Order defines the shared tool-output-image asset index. */
252export function toolOutputImages(value: unknown): ReadonlyArray<ToolOutputImage> {
253 return toolOutputImageBlocks(value).flatMap((block) => readToolOutputImage(block) ?? []);
255​
256export function omitToolOutputImageData(value: unknown): unknown {
257 const omit = (block: unknown) => {
258 const image = readToolOutputImage(block);
259 return image?.data === undefined ? block : { type: "image", mimeType: image.mimeType };
260 };
261 if (Array.isArray(value)) return value.map(omit);
262 if (Predicate.isObject(value) && Array.isArray(value.content)) {
263 return { ...value, content: value.content.map(omit) };
264 }
265 return omit(value);