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

toolOutput.ts

255 lines9.0 KB

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