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

toolOutput.ts

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