Open History to see the last commit
1import type {
2 OrchestrationV2DomainEvent,
3 OrchestrationV2ContextHandoff,
4 OrchestrationV2ThreadProjection,
5 OrchestrationV2TurnItem,
6} from "@t3tools/contracts";
7import {
8 compactDynamicToolOutput,
9 omitToolOutputImageData,
10 toolOutputImages,
11 toolOutputIndicatesFailure,
12} from "@t3tools/shared/toolOutput";
13
14const MAX_DETAIL_STRING_BYTES = 32_768;
15const MAX_DYNAMIC_VALUE_BYTES = 16_384;
16const MAX_ON_DEMAND_BYTES = 256 * 1024;
17
18function truncateDetail(
19 value: string | undefined,
20 maxBytes = MAX_DETAIL_STRING_BYTES,
21): string | undefined {
22 if (
23 value === undefined ||
24 (value.length <= maxBytes && Buffer.byteLength(value, "utf8") <= maxBytes)
25 ) {
26 return value;
27 }
28 // UTF-8 needs at least one byte per UTF-16 code unit. Only encode the prefix
29 // that could fit, rather than allocating a buffer for the complete output.
30 const prefix = Buffer.from(value.slice(0, maxBytes), "utf8")
31 .subarray(0, maxBytes)
32 .toString("utf8")
33 .replace(/\uFFFD$/u, "");
34 return `${prefix}\n… output truncated for transport`;
35}
36
37/**
38 * Clients never receive more than this (see projectTurnItemForWire), so a full
39 * diff of a large file would only grow the database and the heap that reads it
40 * back.
41 */
42export function boundFileChangeForStorage(item: OrchestrationV2TurnItem): OrchestrationV2TurnItem {
43 if (item.type !== "file_change") return item;
44 const { diffStr, oldStr, newStr } = item;
45 const bounded = {
46 ...item,
47 ...(diffStr === undefined ? {} : { diffStr: truncateDetail(diffStr) }),
48 ...(oldStr === undefined ? {} : { oldStr: truncateDetail(oldStr) }),
49 ...(newStr === undefined ? {} : { newStr: truncateDetail(newStr) }),
50 };
51 return bounded.diffStr === diffStr && bounded.oldStr === oldStr && bounded.newStr === newStr
52 ? item
53 : bounded;
54}
55
56function summarizeDynamicValue(value: unknown): unknown {
57 let serialized: string;
58 try {
59 if (typeof value === "string" && value.length > MAX_DYNAMIC_VALUE_BYTES) {
60 serialized = value;
61 } else {
62 const json = JSON.stringify(value) ?? String(value);
63 if (Buffer.byteLength(json, "utf8") <= MAX_DYNAMIC_VALUE_BYTES) {
64 return value;
65 }
66 serialized = typeof value === "string" ? value : json;
67 }
68 } catch {
69 serialized = "Unserializable tool output";
70 }
71
72 // Splitting and normalizing every line can allocate far more than the input.
73 const start = /\S/u.exec(serialized)?.index;
74 let firstLine = start === undefined ? "Large tool output" : "";
75 let pendingSpace = false;
76 for (let index = start ?? serialized.length; index < serialized.length; index += 1) {
77 const character = serialized[index]!;
78 if (character === "\n") break;
79 if (/\s/u.test(character)) {
80 pendingSpace = true;
81 continue;
82 }
83 if (pendingSpace) firstLine += " ";
84 firstLine += character;
85 pendingSpace = false;
86 if (firstLine.length > 160) break;
87 }
88 return {
89 summary: firstLine.length <= 160 ? firstLine : `${firstLine.slice(0, 159).trimEnd()}…`,
90 truncated: true,
91 };
92}
93
94export function projectTurnItemForWire(item: OrchestrationV2TurnItem): OrchestrationV2TurnItem {
95 switch (item.type) {
96 case "handoff": {
97 const { summary: _summary, ...projected } = item;
98 return projected;
99 }
100 case "command_execution": {
101 const { output, ...projected } = item;
102 const failed =
103 item.outputIndicatesFailure === true ||
104 (item.exitCode !== undefined && item.exitCode !== 0) ||
105 (output !== undefined &&
106 toolOutputIndicatesFailure(output.slice(0, MAX_DETAIL_STRING_BYTES)));
107 return {
108 ...projected,
109 ...(failed ? { outputIndicatesFailure: true } : {}),
110 ...(output?.trim() ? { outputOmitted: true } : {}),
111 };
112 }
113 case "file_change": {
114 const { diffStr, oldStr: _old, newStr: _new, ...projected } = item;
115 return item.status === "failed" && diffStr?.trim()
116 ? { ...projected, diffStr: truncateDetail(diffStr) }
117 : projected;
118 }
119 case "subagent":
120 return {
121 ...item,
122 prompt: truncateDetail(item.prompt) ?? "",
123 progress: truncateDetail(item.progress),
124 result: item.result === null ? null : (truncateDetail(item.result) ?? null),
125 };
126 case "dynamic_tool": {
127 const { output: rawOutput, ...projected } = item;
128 const output = compactDynamicToolOutput(rawOutput);
129 return {
130 ...projected,
131 input: summarizeDynamicValue(item.input),
132 ...(output === undefined ? {} : { output }),
133 ...(hasDynamicValue(rawOutput) ? { outputOmitted: true } : {}),
134 };
135 }
136 default:
137 return item;
138 }
139}
140
141function hasDynamicValue(value: unknown): boolean {
142 if (value === undefined || value === null) return false;
143 if (typeof value === "string") return value.trim().length > 0;
144 if (Array.isArray(value)) return value.length > 0;
145 return typeof value !== "object" || Object.keys(value).length > 0;
146}
147
148function boundDynamicValue(value: unknown): unknown {
149 if (value === undefined) return value;
150 if (typeof value === "string") return truncateDetail(value, MAX_ON_DEMAND_BYTES);
151 let json: string;
152 try {
153 json = JSON.stringify(value) ?? String(value);
154 } catch {
155 return "Unserializable tool value";
156 }
157 return Buffer.byteLength(json, "utf8") <= MAX_ON_DEMAND_BYTES
158 ? value
159 : truncateDetail(json, MAX_ON_DEMAND_BYTES);
160}
161
162/**
163 * When the rest is too large to send whole, its truncated text still comes with
164 * the image markers, in order, so clients can load each image by index.
165 */
166function boundToolOutput(output: unknown): unknown {
167 const omitted = omitToolOutputImageData(output);
168 const bounded = boundDynamicValue(omitted);
169 if (typeof bounded !== "string" || typeof omitted === "string") return bounded;
170 const images = toolOutputImages(omitted);
171 return images.length === 0
172 ? bounded
173 : [
174 { type: "text", text: bounded },
175 ...images.map((image) => ({ type: "image", mimeType: image.mimeType })),
176 ];
177}
178
179export function projectTurnItemForDetail(item: OrchestrationV2TurnItem): OrchestrationV2TurnItem {
180 switch (item.type) {
181 case "command_execution":
182 return {
183 ...item,
184 input: truncateDetail(item.input, MAX_ON_DEMAND_BYTES) ?? "",
185 output: truncateDetail(item.output, MAX_ON_DEMAND_BYTES),
186 };
187 case "dynamic_tool":
188 return {
189 ...item,
190 input: boundDynamicValue(item.input),
191 output: boundToolOutput(item.output),
192 };
193 case "subagent":
194 return {
195 ...item,
196 prompt: truncateDetail(item.prompt, MAX_ON_DEMAND_BYTES) ?? "",
197 progress: truncateDetail(item.progress, MAX_ON_DEMAND_BYTES),
198 result:
199 item.result === null ? null : (truncateDetail(item.result, MAX_ON_DEMAND_BYTES) ?? null),
200 };
201 case "handoff":
202 case "file_change":
203 return projectTurnItemForWire(item);
204 default:
205 return item;
206 }
207}
208
209export function projectContextHandoffForWire(
210 handoff: OrchestrationV2ContextHandoff,
211): OrchestrationV2ContextHandoff {
212 const { history: _history, delivery: _delivery, ...projected } = handoff;
213 return { ...projected, summaryText: "" };
214}
215
216export function projectThreadProjectionForWire(
217 projection: OrchestrationV2ThreadProjection,
218): OrchestrationV2ThreadProjection {
219 const projectedById = new Map<string, OrchestrationV2TurnItem>();
220 const project = (item: OrchestrationV2TurnItem) => {
221 const key = `${item.threadId}:${item.id}`;
222 const existing = projectedById.get(key);
223 if (existing !== undefined) return existing;
224 const projected = projectTurnItemForWire(item);
225 projectedById.set(key, projected);
226 return projected;
227 };
228 return {
229 ...projection,
230 contextHandoffs: projection.contextHandoffs.map(projectContextHandoffForWire),
231 turnItems: projection.turnItems.map(project),
232 visibleTurnItems: projection.visibleTurnItems.map((row) => ({
233 ...row,
234 item: project(row.item),
235 })),
236 };
237}
238
239export function projectDomainEventForWire(
240 event: OrchestrationV2DomainEvent,
241): OrchestrationV2DomainEvent {
242 return event.type === "turn-item.updated"
243 ? { ...event, payload: projectTurnItemForWire(event.payload) }
244 : event.type === "context-handoff.updated"
245 ? { ...event, payload: projectContextHandoffForWire(event.payload) }
246 : event;
247}