Open History to see the last commit
1import * as Predicate from "effect/Predicate";
2
3const MAX_PARSED_BYTES = 16_384;
4const MAX_METADATA_BYTES = 8_192;
5const MAX_ID_LENGTH = 256;
6const MAX_THREADS = 100;
7const MAX_CONTENT_BLOCKS = 32;
8const MAX_ENVELOPE_DEPTH = 4;
9const MAX_ENVELOPE_NODES = 128;
10const encoder = new TextEncoder();
11
12interface ResultReadBudget {
13 remainingBytes: number;
14 remainingNodes: number;
15 exceeded: boolean;
16}
17
18interface ResultEnvelope {
19 data?: Record<PropertyKey, unknown>;
20 failed: boolean;
21}
22
23interface CompactToolOutput {
24 isError?: true;
25 threadId?: string;
26 messageId?: string;
27 taskId?: string;
28 scheduledTaskId?: string;
29 status?: "rolled_back";
30 thread?: { threadId: string };
31 threads?: Array<{ threadId?: string; status?: "rolled_back" }>;
32}
33
34function readResult(value: unknown, budget: ResultReadBudget, depth = 0): ResultEnvelope {
35 if (depth > MAX_ENVELOPE_DEPTH || budget.remainingNodes-- <= 0) {
36 budget.exceeded = true;
37 return { failed: false };
38 }
39 if (typeof value === "string") {
40 if (value.length > budget.remainingBytes) {
41 budget.exceeded = true;
42 return { failed: false };
43 }
44 const bytes = encoder.encode(value).byteLength;
45 if (bytes > budget.remainingBytes) {
46 budget.exceeded = true;
47 return { failed: false };
48 }
49 budget.remainingBytes -= bytes;
50 try {
51 return readResult(JSON.parse(value), budget, depth + 1);
52 } catch {
53 return { failed: false };
54 }
55 }
56 if (Array.isArray(value)) {
57 if (value.length > MAX_CONTENT_BLOCKS) {
58 budget.exceeded = true;
59 return { failed: false };
60 }
61 let data: ResultEnvelope["data"];
62 let failed = false;
63 for (const block of value) {
64 const text = Predicate.isObject(block) ? block.text : undefined;
65 const result = readResult(
66 Predicate.isObject(text) ? (text.text ?? text) : text,
67 budget,
68 depth + 1,
69 );
70 data ??= result.data;
71 failed ||= result.failed;
72 if (budget.exceeded) break;
73 }
74 return { ...(data === undefined ? {} : { data }), failed };
75 }
76 if (!Predicate.isObject(value)) return { failed: false };
77 const failed =
78 value.isError === true ||
79 value.is_error === true ||
80 value._tag === "OrchestratorMcpFailure" ||
81 value.error != null;
82 const content = value.structuredContent ?? value.content;
83 if (content !== undefined) {
84 const nested = readResult(content, budget, depth + 1);
85 return { ...nested, failed: failed || nested.failed };
86 }
87 return { data: value, failed };
88}
89
90function boundedId(value: unknown): string | undefined {
91 if (typeof value !== "string" || value.length > MAX_ID_LENGTH || value.trim() === "") {
92 return undefined;
93 }
94 return Array.from(value).join("");
95}
96
97/** Keeps only IDs and failure metadata used by T3's grouped tool summaries. */
98export function compactDynamicToolOutput(value: unknown): CompactToolOutput | undefined {
99 const budget: ResultReadBudget = {
100 remainingBytes: MAX_PARSED_BYTES,
101 remainingNodes: MAX_ENVELOPE_NODES,
102 exceeded: false,
103 };
104 const result = readResult(value, budget);
105 const output: CompactToolOutput = result.failed ? { isError: true } : {};
106 const data = budget.exceeded ? undefined : result.data;
107 if (data !== undefined) {
108 for (const key of ["threadId", "messageId", "taskId", "scheduledTaskId"] as const) {
109 const id = boundedId(data[key]);
110 if (id !== undefined) output[key] = id;
111 }
112 if (data.status === "rolled_back") output.status = "rolled_back";
113 const nestedThreadId = Predicate.isObject(data.thread)
114 ? boundedId(data.thread.threadId)
115 : undefined;
116 if (nestedThreadId !== undefined) output.thread = { threadId: nestedThreadId };
117
118 if (Array.isArray(data.threads)) {
119 let complete = data.threads.length <= MAX_THREADS;
120 const threads: NonNullable<CompactToolOutput["threads"]> = [];
121 if (complete) {
122 for (const entry of data.threads) {
123 if (!Predicate.isObject(entry)) {
124 complete = false;
125 break;
126 }
127 const threadId = boundedId(entry.threadId);
128 const rolledBack = entry.status === "rolled_back";
129 if (threadId === undefined && !rolledBack) {
130 complete = false;
131 break;
132 }
133 threads.push({
134 ...(threadId === undefined ? {} : { threadId }),
135 ...(rolledBack ? { status: "rolled_back" as const } : {}),
136 });
137 }
138 }
139 if (complete) output.threads = threads;
140 else {
141 // A partial batch or a top-level ID would turn an unknown creation
142 // count into a confidently wrong one in the existing summary parser.
143 delete output.threadId;
144 delete output.status;
145 }
146 }
147 }
148 if (encoder.encode(JSON.stringify(output)).byteLength > MAX_METADATA_BYTES) {
149 delete output.threads;
150 delete output.threadId;
151 delete output.status;
152 }
153 return Object.keys(output).length === 0 ? undefined : output;
154}
155
156/** Some providers report completion even when command output describes a failure. */
157export function toolOutputIndicatesFailure(text: string): boolean {
158 return (
159 /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(
160 text,
161 ) ||
162 (/cannot find path/i.test(text) && /because it does not exist/i.test(text)) ||
163 (/is not recognized/i.test(text) && /the term '/i.test(text)) ||
164 /<exited with exit code\s+[1-9]\d*\s*>/i.test(text) ||
165 /exit(?:ed)? with exit code\s+[1-9]\d*/i.test(text) ||
166 /exit code\s*[:\s]\s*[1-9]\d*\b/i.test(text)
167 );
168}