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

toolOutput.ts

287 lines10.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 { 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" }>;
46 linkedCount?: number;
47 unlinkedCount?: number;
49​
50function readResult(value: unknown, budget: ResultReadBudget, depth = 0): ResultEnvelope {
51 if (depth > MAX_ENVELOPE_DEPTH || budget.remainingNodes-- <= 0) {
52 budget.exceeded = true;
53 return { failed: false };
54 }
55 if (typeof value === "string") {
56 if (value.length > budget.remainingBytes) {
57 budget.exceeded = true;
58 return { failed: false };
59 }
60 const bytes = encoder.encode(value).byteLength;
61 if (bytes > budget.remainingBytes) {
62 budget.exceeded = true;
63 return { failed: false };
64 }
65 budget.remainingBytes -= bytes;
66 try {
67 return readResult(JSON.parse(value), budget, depth + 1);
68 } catch {
69 return { failed: false };
70 }
71 }
72 if (Array.isArray(value)) {
73 if (value.length > MAX_CONTENT_BLOCKS) {
74 budget.exceeded = true;
75 return { failed: false };
76 }
77 let data: ResultEnvelope["data"];
78 let failed = false;
79 for (const block of value) {
80 const text = Predicate.isObject(block) ? block.text : undefined;
81 const result = readResult(
82 Predicate.isObject(text) ? (text.text ?? text) : text,
83 budget,
84 depth + 1,
85 );
86 data ??= result.data;
87 failed ||= result.failed;
88 if (budget.exceeded) break;
89 }
90 return { ...(data === undefined ? {} : { data }), failed };
91 }
92 if (!Predicate.isObject(value)) return { failed: false };
93 const failed =
94 value.isError === true ||
95 value.is_error === true ||
96 value._tag === "OrchestratorMcpFailure" ||
97 value.error != null;
98 const content = value.structuredContent ?? value.content;
99 if (content !== undefined) {
100 const nested = readResult(content, budget, depth + 1);
101 return { ...nested, failed: failed || nested.failed };
102 }
103 return { data: value, failed };
105​
106function boundedId(value: unknown): string | undefined {
107 if (typeof value !== "string" || value.length > MAX_ID_LENGTH || value.trim() === "") {
108 return undefined;
109 }
110 return Array.from(value).join("");
112​
113export function compactDynamicToolOutput(value: unknown): CompactToolOutput | undefined {
114 const budget: ResultReadBudget = {
115 remainingBytes: MAX_PARSED_BYTES,
116 remainingNodes: MAX_ENVELOPE_NODES,
117 exceeded: false,
118 };
119 const result = readResult(value, budget);
120 const output: CompactToolOutput = result.failed ? { isError: true } : {};
121 const data = budget.exceeded ? undefined : result.data;
122 if (data !== undefined) {
123 for (const key of ["threadId", "messageId", "taskId", "scheduledTaskId"] as const) {
124 const id = boundedId(data[key]);
125 if (id !== undefined) output[key] = id;
126 }
127 if (data.status === "rolled_back") output.status = "rolled_back";
128 for (const key of ["linkedCount", "unlinkedCount"] as const) {
129 const count = data[key];
130 if (typeof count === "number" && Number.isSafeInteger(count)) output[key] = count;
131 }
132 const htmlRender = readHtmlRenderReference(data.htmlRender);
133 if (htmlRender !== undefined) output.htmlRender = htmlRender;
134 const mcpApp = readMcpAppReference(data[MCP_APP_OUTPUT_KEY]);
135 if (mcpApp !== undefined) output[MCP_APP_OUTPUT_KEY] = mcpApp;
136 const nestedThreadId = Predicate.isObject(data.thread)
137 ? boundedId(data.thread.threadId)
138 : undefined;
139 if (nestedThreadId !== undefined) output.thread = { threadId: nestedThreadId };
140​
141 if (Array.isArray(data.threads)) {
142 let complete = data.threads.length <= MAX_THREADS;
143 const threads: NonNullable<CompactToolOutput["threads"]> = [];
144 if (complete) {
145 for (const entry of data.threads) {
146 if (!Predicate.isObject(entry)) {
147 complete = false;
148 break;
149 }
150 const threadId = boundedId(entry.threadId);
151 const rolledBack = entry.status === "rolled_back";
152 if (threadId === undefined && !rolledBack) {
153 complete = false;
154 break;
155 }
156 threads.push({
157 ...(threadId === undefined ? {} : { threadId }),
158 ...(rolledBack ? { status: "rolled_back" as const } : {}),
159 });
160 }
161 }
162 if (complete) output.threads = threads;
163 else {
164 // Partial batches or top-level ids make the summary parser report a false creation count.
165 delete output.threadId;
166 delete output.status;
167 }
168 }
169 }
170 const oversized = () => encoder.encode(JSON.stringify(output)).byteLength > MAX_METADATA_BYTES;
171 if (oversized()) {
172 delete output.threads;
173 delete output.threadId;
174 delete output.status;
175 }
176 const app = output[MCP_APP_OUTPUT_KEY];
177 if (app?.csp !== undefined && oversized()) {
178 const { csp: _csp, ...rest } = app;
179 output[MCP_APP_OUTPUT_KEY] = rest;
180 }
181 if (oversized()) delete output[MCP_APP_OUTPUT_KEY];
182 return Object.keys(output).length === 0 ? undefined : output;
184​
185export function htmlRenderFromToolItem(item: {
186 readonly toolName: string | null | undefined;
187 readonly output?: unknown;
188}): HtmlRenderReference | undefined {
189 if (resolveT3McpToolId(item.toolName) !== HTML_RENDER_TOOL_NAME) return undefined;
190 const output = compactDynamicToolOutput(item.output);
191 return output?.isError ? undefined : output?.htmlRender;
193​
194/** The thread-owned file `preview_recording_stop` stored for the agent. */
195export function previewRecordingIdFromToolItem(item: {
196 readonly toolName: string | null | undefined;
197 readonly output?: unknown;
198}): string | undefined {
199 if (resolveT3McpToolId(item.toolName) !== "preview_recording_stop") return undefined;
200 const budget: ResultReadBudget = {
201 remainingBytes: MAX_PARSED_BYTES,
202 remainingNodes: MAX_ENVELOPE_NODES,
203 exceeded: false,
204 };
205 const result = readResult(item.output, budget);
206 return result.failed || budget.exceeded ? undefined : boundedId(result.data?.id);
208​
209/** Accept app references only when server and tool match the item, so tools cannot impersonate another app source. */
210export function mcpAppFromToolItem(item: {
211 readonly toolName: string | null | undefined;
212 readonly output?: unknown;
213}): McpAppReference | undefined {
214 const app = compactDynamicToolOutput(item.output)?.[MCP_APP_OUTPUT_KEY];
215 return app !== undefined && item.toolName === `${app.server}.${app.tool}` ? app : undefined;
217​
218/** Some providers report completion even when command output describes a failure. */
219export function toolOutputIndicatesFailure(text: string): boolean {
220 return (
221 /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(
222 text,
223 ) ||
224 (/cannot find path/i.test(text) && /because it does not exist/i.test(text)) ||
225 (/is not recognized/i.test(text) && /the term '/i.test(text)) ||
226 /<exited with exit code\s+[1-9]\d*\s*>/i.test(text) ||
227 /exit(?:ed)? with exit code\s+[1-9]\d*/i.test(text) ||
228 /exit code\s*[:\s]\s*[1-9]\d*\b/i.test(text)
229 );
231​
232export interface ToolOutputImage {
233 readonly mimeType: string;
234 readonly data?: string;
236​
237/** Raster types only, so agent SVG/HTML cannot be served inline. */
238export function readToolOutputImage(block: unknown): ToolOutputImage | null {
239 if (!Predicate.isObject(block) || block.type !== "image") return null;
240 const source = Predicate.isObject(block.source) ? block.source : undefined;
241 if (source !== undefined && source.type !== "base64") return null;
242 const mimeType = source === undefined ? block.mimeType : source.media_type;
243 const data = source === undefined ? block.data : source.data;
244 if (typeof mimeType !== "string" || !isProviderSendTurnSupportedImageMimeType(mimeType)) {
245 return null;
246 }
247 const image = { mimeType: mimeType.toLowerCase() };
248 return typeof data === "string" ? { ...image, data } : image;
250​
251function outputBlocks(value: unknown): ReadonlyArray<unknown> {
252 if (Array.isArray(value)) return value;
253 if (Predicate.isObject(value) && Array.isArray(value.content)) return value.content;
254 return [value];
256​
257export const MAX_TOOL_OUTPUT_IMAGES = 8;
258​
259export const MAX_TOOL_OUTPUT_IMAGE_BASE64_LENGTH =
260 Math.ceil(PROVIDER_SEND_TURN_MAX_IMAGE_BYTES / 3) * 4;
261​
262export function toolOutputImageBlocks(value: unknown): ReadonlyArray<unknown> {
263 const blocks: unknown[] = [];
264 for (const block of outputBlocks(value)) {
265 if (readToolOutputImage(block) === null) continue;
266 blocks.push(block);
267 if (blocks.length === MAX_TOOL_OUTPUT_IMAGES) break;
268 }
269 return blocks;
271​
272/** Order defines the shared tool-output-image asset index. */
273export function toolOutputImages(value: unknown): ReadonlyArray<ToolOutputImage> {
274 return toolOutputImageBlocks(value).flatMap((block) => readToolOutputImage(block) ?? []);
276​
277export function omitToolOutputImageData(value: unknown): unknown {
278 const omit = (block: unknown) => {
279 const image = readToolOutputImage(block);
280 return image?.data === undefined ? block : { type: "image", mimeType: image.mimeType };
281 };
282 if (Array.isArray(value)) return value.map(omit);
283 if (Predicate.isObject(value) && Array.isArray(value.content)) {
284 return { ...value, content: value.content.map(omit) };
285 }
286 return omit(value);