@devries-cameron20 / t3code Mirror · read-only
Fork 0

The best way to control Claude Code, Codex and more from any computer or phone

Mirrored from https://github.com/Camo67/t3code.git

Synced Nov 21, 03:37 UTC

main
ts 370 lines 13.1 KB
Raw
1 import {
2 isProviderSendTurnSupportedImageMimeType,
3 PROVIDER_SEND_TURN_MAX_IMAGE_BYTES,
4 } from "@t3tools/contracts";
5 import * as Predicate from "effect/Predicate";
6
7 import {
8 HTML_RENDER_TOOL_NAME,
9 readHtmlRenderReference,
10 type HtmlRenderReference,
11 } from "./htmlRender.ts";
12 import {
13 claudeMcpToolName,
14 MCP_APP_OUTPUT_KEY,
15 readMcpAppReference,
16 type McpAppReference,
17 } from "./mcpApp.ts";
18 import { resolveT3McpToolId } from "./t3McpToolPresentation.ts";
19
20 export const SEND_TO_USER_TOOL_NAME = "send_to_user";
21 // 4,000 UTF-16 units stay inside MAX_PARSED_BYTES even as 3-byte characters.
22 export const SEND_TO_USER_MAX_LENGTH = 4_000;
23
24 const MAX_PARSED_BYTES = 16_384;
25 const MAX_METADATA_BYTES = 8_192;
26 const MAX_ID_LENGTH = 256;
27 const MAX_THREADS = 100;
28 const MAX_CONTENT_BLOCKS = 32;
29 const MAX_ENVELOPE_DEPTH = 4;
30 const MAX_ENVELOPE_NODES = 128;
31 const encoder = new TextEncoder();
32 // Antigravity's terminal tool prefixes an `acp-mcp-call` result's stdout with timestamps and exit status.
33 const TERMINAL_OUTPUT_MARKER = "\nCommand output:\n";
34
35 interface ResultReadBudget {
36 remainingBytes: number;
37 remainingNodes: number;
38 exceeded: boolean;
39 }
40
41 interface ResultEnvelope {
42 data?: Record<PropertyKey, unknown>;
43 failed: boolean;
44 }
45
46 interface CompactToolOutput {
47 isError?: true;
48 threadId?: string;
49 messageId?: string;
50 taskId?: string;
51 scheduledTaskId?: string;
52 status?: "rolled_back";
53 htmlRender?: HtmlRenderReference;
54 [MCP_APP_OUTPUT_KEY]?: McpAppReference;
55 thread?: { threadId: string };
56 threads?: Array<{ threadId?: string; status?: "rolled_back" }>;
57 linkedCount?: number;
58 unlinkedCount?: number;
59 sentMessage?: string;
60 }
61
62 function readResult(value: unknown, budget: ResultReadBudget, depth = 0): ResultEnvelope {
63 if (depth > MAX_ENVELOPE_DEPTH || budget.remainingNodes-- <= 0) {
64 budget.exceeded = true;
65 return { failed: false };
66 }
67 if (typeof value === "string") {
68 if (value.length > budget.remainingBytes) {
69 budget.exceeded = true;
70 return { failed: false };
71 }
72 const bytes = encoder.encode(value).byteLength;
73 if (bytes > budget.remainingBytes) {
74 budget.exceeded = true;
75 return { failed: false };
76 }
77 budget.remainingBytes -= bytes;
78 try {
79 return readResult(JSON.parse(value), budget, depth + 1);
80 } catch {
81 return { failed: false };
82 }
83 }
84 if (Array.isArray(value)) {
85 if (value.length > MAX_CONTENT_BLOCKS) {
86 budget.exceeded = true;
87 return { failed: false };
88 }
89 let data: ResultEnvelope["data"];
90 let failed = false;
91 for (const block of value) {
92 const text = Predicate.isObject(block) ? block.text : undefined;
93 const result = readResult(
94 Predicate.isObject(text) ? (text.text ?? text) : text,
95 budget,
96 depth + 1,
97 );
98 data ??= result.data;
99 failed ||= result.failed;
100 if (budget.exceeded) break;
101 }
102 return { ...(data === undefined ? {} : { data }), failed };
103 }
104 if (!Predicate.isObject(value)) return { failed: false };
105 const failed =
106 value.isError === true ||
107 value.is_error === true ||
108 value._tag === "OrchestratorMcpFailure" ||
109 value.error != null;
110 const terminal = typeof value.output === "string" ? value.output : "";
111 const marker = terminal.indexOf(TERMINAL_OUTPUT_MARKER);
112 const content =
113 value.structuredContent ??
114 value.content ??
115 (marker === -1 ? undefined : terminal.slice(marker + TERMINAL_OUTPUT_MARKER.length));
116 if (content !== undefined) {
117 const nested = readResult(content, budget, depth + 1);
118 return { ...nested, failed: failed || nested.failed };
119 }
120 return { data: value, failed };
121 }
122
123 function boundedId(value: unknown): string | undefined {
124 if (typeof value !== "string" || value.length > MAX_ID_LENGTH || value.trim() === "") {
125 return undefined;
126 }
127 return Array.from(value).join("");
128 }
129
130 export function compactDynamicToolOutput(value: unknown): CompactToolOutput | undefined {
131 const budget: ResultReadBudget = {
132 remainingBytes: MAX_PARSED_BYTES,
133 remainingNodes: MAX_ENVELOPE_NODES,
134 exceeded: false,
135 };
136 const result = readResult(value, budget);
137 const output: CompactToolOutput = result.failed ? { isError: true } : {};
138 const data = budget.exceeded ? undefined : result.data;
139 if (data !== undefined) {
140 for (const key of ["threadId", "messageId", "taskId", "scheduledTaskId"] as const) {
141 const id = boundedId(data[key]);
142 if (id !== undefined) output[key] = id;
143 }
144 if (data.status === "rolled_back") output.status = "rolled_back";
145 for (const key of ["linkedCount", "unlinkedCount"] as const) {
146 const count = data[key];
147 if (typeof count === "number" && Number.isSafeInteger(count)) output[key] = count;
148 }
149 if (
150 typeof data.sentMessage === "string" &&
151 data.sentMessage.trim() !== "" &&
152 data.sentMessage.length <= SEND_TO_USER_MAX_LENGTH
153 ) {
154 output.sentMessage = data.sentMessage;
155 }
156 const htmlRender = readHtmlRenderReference(data.htmlRender);
157 if (htmlRender !== undefined) output.htmlRender = htmlRender;
158 const mcpApp = readMcpAppReference(data[MCP_APP_OUTPUT_KEY]);
159 if (mcpApp !== undefined) output[MCP_APP_OUTPUT_KEY] = mcpApp;
160 const nestedThreadId = Predicate.isObject(data.thread)
161 ? boundedId(data.thread.threadId)
162 : undefined;
163 if (nestedThreadId !== undefined) output.thread = { threadId: nestedThreadId };
164
165 if (Array.isArray(data.threads)) {
166 let complete = data.threads.length <= MAX_THREADS;
167 const threads: NonNullable<CompactToolOutput["threads"]> = [];
168 if (complete) {
169 for (const entry of data.threads) {
170 if (!Predicate.isObject(entry)) {
171 complete = false;
172 break;
173 }
174 const threadId = boundedId(entry.threadId);
175 const rolledBack = entry.status === "rolled_back";
176 if (threadId === undefined && !rolledBack) {
177 complete = false;
178 break;
179 }
180 threads.push({
181 ...(threadId === undefined ? {} : { threadId }),
182 ...(rolledBack ? { status: "rolled_back" as const } : {}),
183 });
184 }
185 }
186 if (complete) output.threads = threads;
187 else {
188 // Partial batches or top-level ids make the summary parser report a false creation count.
189 delete output.threadId;
190 delete output.status;
191 }
192 }
193 }
194 const oversized = () => encoder.encode(JSON.stringify(output)).byteLength > MAX_METADATA_BYTES;
195 if (oversized()) {
196 delete output.threads;
197 delete output.threadId;
198 delete output.status;
199 }
200 const app = output[MCP_APP_OUTPUT_KEY];
201 if (app?.csp !== undefined && oversized()) {
202 const { csp: _csp, ...rest } = app;
203 output[MCP_APP_OUTPUT_KEY] = rest;
204 }
205 if (oversized()) delete output[MCP_APP_OUTPUT_KEY];
206 return Object.keys(output).length === 0 ? undefined : output;
207 }
208
209 // OpenCode 2 Code Mode reports a script's nested T3 tool calls as one item with the script's result.
210 const OPENCODE_CODE_MODE_TOOL_NAME = "execute";
211
212 export function htmlRenderFromToolItem(item: {
213 readonly toolName: string | null | undefined;
214 readonly output?: unknown;
215 }): HtmlRenderReference | undefined {
216 if (
217 item.toolName !== OPENCODE_CODE_MODE_TOOL_NAME &&
218 resolveT3McpToolId(item.toolName) !== HTML_RENDER_TOOL_NAME
219 ) {
220 return undefined;
221 }
222 const output = compactDynamicToolOutput(item.output);
223 return output?.isError ? undefined : output?.htmlRender;
224 }
225
226 /** The text `send_to_user` showed the user, which clients render as the agent's own words. */
227 export function sentMessageFromToolItem(item: {
228 readonly toolName: string | null | undefined;
229 readonly output?: unknown;
230 }): string | undefined {
231 if (
232 item.toolName !== OPENCODE_CODE_MODE_TOOL_NAME &&
233 resolveT3McpToolId(item.toolName) !== SEND_TO_USER_TOOL_NAME
234 ) {
235 return undefined;
236 }
237 const output = compactDynamicToolOutput(item.output);
238 return output?.isError ? undefined : output?.sentMessage;
239 }
240
241 /** The thread-owned file `preview_recording_stop` stored for the agent. */
242 export function previewRecordingIdFromToolItem(item: {
243 readonly toolName: string | null | undefined;
244 readonly output?: unknown;
245 }): string | undefined {
246 if (resolveT3McpToolId(item.toolName) !== "preview_recording_stop") return undefined;
247 const budget: ResultReadBudget = {
248 remainingBytes: MAX_PARSED_BYTES,
249 remainingNodes: MAX_ENVELOPE_NODES,
250 exceeded: false,
251 };
252 const result = readResult(item.output, budget);
253 return result.failed || budget.exceeded ? undefined : boundedId(result.data?.id);
254 }
255
256 /** Accept app references only when server and tool match the item, so tools cannot impersonate another app source. */
257 export function mcpAppFromToolItem(item: {
258 readonly toolName: string | null | undefined;
259 readonly output?: unknown;
260 }): McpAppReference | undefined {
261 const app = compactDynamicToolOutput(item.output)?.[MCP_APP_OUTPUT_KEY];
262 return app !== undefined &&
263 (item.toolName === `${app.server}.${app.tool}` ||
264 item.toolName === claudeMcpToolName(app.server, app.tool))
265 ? app
266 : undefined;
267 }
268
269 // A superset of every needle below, so most outputs are rejected by this single scan.
270 const FAILURE_HINT =
271 /enoent|no such|no files found|not found|commandnotfound|not recognized|cannot (?:find path|be found)|exit/i;
272
273 /** Some providers report completion even when command output describes a failure. */
274 export function toolOutputIndicatesFailure(text: string): boolean {
275 return (
276 FAILURE_HINT.test(text) &&
277 (/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(
278 text,
279 ) ||
280 (/cannot find path/i.test(text) && /because it does not exist/i.test(text)) ||
281 (/is not recognized/i.test(text) && /the term '/i.test(text)) ||
282 /exit(?:ed)? with exit code\s+[1-9]\d*/i.test(text) ||
283 /exit code\s*[:\s]\s*[1-9]\d*\b/i.test(text))
284 );
285 }
286
287 /** Whether a command failed. A reported exit code outranks text in its output. */
288 export function commandIndicatesFailure(command: {
289 readonly exitCode?: number | undefined;
290 readonly outputIndicatesFailure?: boolean | undefined;
291 readonly output?: string | undefined;
292 }): boolean {
293 if (command.exitCode !== undefined) return command.exitCode !== 0;
294 return (
295 command.outputIndicatesFailure === true ||
296 (command.output !== undefined && toolOutputIndicatesFailure(command.output.slice(0, 32_768)))
297 );
298 }
299
300 export interface ToolOutputImage {
301 readonly mimeType: string;
302 readonly data?: string;
303 }
304
305 /** Raster types only, so agent SVG/HTML cannot be served inline. */
306 export function readToolOutputImage(block: unknown): ToolOutputImage | null {
307 if (!Predicate.isObject(block) || block.type !== "image") return null;
308 const source = Predicate.isObject(block.source) ? block.source : undefined;
309 if (source !== undefined && source.type !== "base64") return null;
310 const mimeType = source === undefined ? block.mimeType : source.media_type;
311 const data = source === undefined ? block.data : source.data;
312 if (typeof mimeType !== "string" || !isProviderSendTurnSupportedImageMimeType(mimeType)) {
313 return null;
314 }
315 const image = { mimeType: mimeType.toLowerCase() };
316 return typeof data === "string" ? { ...image, data } : image;
317 }
318
319 function outputBlocks(value: unknown): ReadonlyArray<unknown> {
320 if (Array.isArray(value)) return value;
321 if (Predicate.isObject(value) && Array.isArray(value.content)) return value.content;
322 return [value];
323 }
324
325 export const MAX_TOOL_OUTPUT_IMAGES = 8;
326
327 export const MAX_TOOL_OUTPUT_IMAGE_BASE64_LENGTH =
328 Math.ceil(PROVIDER_SEND_TURN_MAX_IMAGE_BYTES / 3) * 4;
329
330 export function toolOutputImageBlocks(value: unknown): ReadonlyArray<unknown> {
331 const blocks: unknown[] = [];
332 for (const block of outputBlocks(value)) {
333 if (readToolOutputImage(block) === null) continue;
334 blocks.push(block);
335 if (blocks.length === MAX_TOOL_OUTPUT_IMAGES) break;
336 }
337 return blocks;
338 }
339
340 /** Order defines the shared tool-output-image asset index. */
341 export function toolOutputImages(value: unknown): ReadonlyArray<ToolOutputImage> {
342 return toolOutputImageBlocks(value).flatMap((block) => readToolOutputImage(block) ?? []);
343 }
344
345 export function mcpToolResultOutput(result: {
346 readonly content?: unknown;
347 readonly structuredContent?: unknown;
348 }): unknown {
349 const structuredContent =
350 (Array.isArray(result.structuredContent) || Predicate.isObject(result.structuredContent)) &&
351 Object.keys(result.structuredContent).length === 0
352 ? undefined
353 : result.structuredContent;
354 if (structuredContent != null && toolOutputImages(result.content).length > 0) {
355 return { content: result.content, structuredContent };
356 }
357 return structuredContent ?? result.content;
358 }
359
360 export function omitToolOutputImageData(value: unknown): unknown {
361 const omit = (block: unknown) => {
362 const image = readToolOutputImage(block);
363 return image?.data === undefined ? block : { type: "image", mimeType: image.mimeType };
364 };
365 if (Array.isArray(value)) return value.map(omit);
366 if (Predicate.isObject(value) && Array.isArray(value.content)) {
367 return { ...value, content: value.content.map(omit) };
368 }
369 return omit(value);
370 }