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

toolOutput.ts

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