Open History to see the last commit
1import type {
2 CheckpointId,
3 MessageId,
4 NodeId,
5 OrchestrationV2Checkpoint,
6 OrchestrationV2DomainEvent,
7 OrchestrationV2ContextHandoff,
8 OrchestrationV2Subagent,
9 OrchestrationV2ThreadProjection,
10 OrchestrationV2ThreadStreamItem,
11 OrchestrationV2TurnItem,
12} from "@t3tools/contracts";
13import {
14 dedupeSubagentBodies,
15 dedupeTurnItemBodies,
16} from "@t3tools/shared/orchestrationV2DedupedBodies";
17import {
18 compactDynamicToolOutput,
19 omitToolOutputImageData,
20 toolOutputImages,
21 toolOutputIndicatesFailure,
22} from "@t3tools/shared/toolOutput";
23
24const MAX_DETAIL_STRING_BYTES = 32_768;
25const MAX_DYNAMIC_VALUE_BYTES = 16_384;
26const MAX_ON_DEMAND_BYTES = 256 * 1024;
27
28function truncateDetail(
29 value: string | undefined,
30 maxBytes = MAX_DETAIL_STRING_BYTES,
31): string | undefined {
32 if (
33 value === undefined ||
34 (value.length <= maxBytes && Buffer.byteLength(value, "utf8") <= maxBytes)
35 ) {
36 return value;
37 }
38 // UTF-8 needs at least one byte per UTF-16 unit; encode only a potentially fitting prefix.
39 const prefix = Buffer.from(value.slice(0, maxBytes), "utf8")
40 .subarray(0, maxBytes)
41 .toString("utf8")
42 .replace(/\uFFFD$/u, "");
43 return `${prefix}\n… output truncated for transport`;
44}
45
46/** Bound stored diffs to the client wire limit to avoid retaining invisible data in SQLite and heap. */
47export function boundFileChangeForStorage(item: OrchestrationV2TurnItem): OrchestrationV2TurnItem {
48 if (item.type !== "file_change") return item;
49 const { diffStr, oldStr, newStr } = item;
50 const bounded = {
51 ...item,
52 ...(diffStr === undefined ? {} : { diffStr: truncateDetail(diffStr) }),
53 ...(oldStr === undefined ? {} : { oldStr: truncateDetail(oldStr) }),
54 ...(newStr === undefined ? {} : { newStr: truncateDetail(newStr) }),
55 };
56 return bounded.diffStr === diffStr && bounded.oldStr === oldStr && bounded.newStr === newStr
57 ? item
58 : bounded;
59}
60
61function summarizeDynamicValue(value: unknown): unknown {
62 let serialized: string;
63 try {
64 if (typeof value === "string" && value.length > MAX_DYNAMIC_VALUE_BYTES) {
65 serialized = value;
66 } else {
67 const json = JSON.stringify(value) ?? String(value);
68 if (Buffer.byteLength(json, "utf8") <= MAX_DYNAMIC_VALUE_BYTES) {
69 return value;
70 }
71 serialized = typeof value === "string" ? value : json;
72 }
73 } catch {
74 serialized = "Unserializable tool output";
75 }
76
77 // Splitting and normalizing every line can allocate far more than the input.
78 const start = /\S/u.exec(serialized)?.index;
79 let firstLine = start === undefined ? "Large tool output" : "";
80 let pendingSpace = false;
81 for (let index = start ?? serialized.length; index < serialized.length; index += 1) {
82 const character = serialized[index]!;
83 if (character === "\n") break;
84 if (/\s/u.test(character)) {
85 pendingSpace = true;
86 continue;
87 }
88 if (pendingSpace) firstLine += " ";
89 firstLine += character;
90 pendingSpace = false;
91 if (firstLine.length > 160) break;
92 }
93 return {
94 summary: firstLine.length <= 160 ? firstLine : `${firstLine.slice(0, 159).trimEnd()}…`,
95 truncated: true,
96 };
97}
98
99export function projectTurnItemForWire(item: OrchestrationV2TurnItem): OrchestrationV2TurnItem {
100 switch (item.type) {
101 case "handoff": {
102 const { summary: _summary, ...projected } = item;
103 return projected;
104 }
105 case "command_execution": {
106 const { output, ...projected } = item;
107 const failed =
108 item.outputIndicatesFailure === true ||
109 (item.exitCode !== undefined && item.exitCode !== 0) ||
110 (output !== undefined &&
111 toolOutputIndicatesFailure(output.slice(0, MAX_DETAIL_STRING_BYTES)));
112 return {
113 ...projected,
114 ...(failed ? { outputIndicatesFailure: true } : {}),
115 ...(output?.trim() ? { outputOmitted: true } : {}),
116 };
117 }
118 case "file_change": {
119 const { diffStr, oldStr: _old, newStr: _new, ...projected } = item;
120 return item.status === "failed" && diffStr?.trim()
121 ? { ...projected, diffStr: truncateDetail(diffStr) }
122 : projected;
123 }
124 case "subagent":
125 return {
126 ...item,
127 prompt: truncateDetail(item.prompt) ?? "",
128 progress: truncateDetail(item.progress),
129 result: item.result === null ? null : (truncateDetail(item.result) ?? null),
130 };
131 case "dynamic_tool": {
132 const { output: rawOutput, ...projected } = item;
133 const output = compactDynamicToolOutput(rawOutput);
134 return {
135 ...projected,
136 input: summarizeDynamicValue(item.input),
137 ...(output === undefined ? {} : { output }),
138 ...(hasDynamicValue(rawOutput) ? { outputOmitted: true } : {}),
139 };
140 }
141 default:
142 return item;
143 }
144}
145
146function hasDynamicValue(value: unknown): boolean {
147 if (value === undefined || value === null) return false;
148 if (typeof value === "string") return value.trim().length > 0;
149 if (Array.isArray(value)) return value.length > 0;
150 return typeof value !== "object" || Object.keys(value).length > 0;
151}
152
153function boundDynamicValue(value: unknown): unknown {
154 if (value === undefined) return value;
155 if (typeof value === "string") return truncateDetail(value, MAX_ON_DEMAND_BYTES);
156 let json: string;
157 try {
158 json = JSON.stringify(value) ?? String(value);
159 } catch {
160 return "Unserializable tool value";
161 }
162 return Buffer.byteLength(json, "utf8") <= MAX_ON_DEMAND_BYTES
163 ? value
164 : truncateDetail(json, MAX_ON_DEMAND_BYTES);
165}
166
167/** Preserve ordered image markers in truncated output so clients can load images by index. */
168function boundToolOutput(output: unknown): unknown {
169 const omitted = omitToolOutputImageData(output);
170 const bounded = boundDynamicValue(omitted);
171 if (typeof bounded !== "string" || typeof omitted === "string") return bounded;
172 const images = toolOutputImages(omitted);
173 return images.length === 0
174 ? bounded
175 : [
176 { type: "text", text: bounded },
177 ...images.map((image) => ({ type: "image", mimeType: image.mimeType })),
178 ];
179}
180
181export function projectTurnItemForDetail(item: OrchestrationV2TurnItem): OrchestrationV2TurnItem {
182 switch (item.type) {
183 case "command_execution":
184 return {
185 ...item,
186 input: truncateDetail(item.input, MAX_ON_DEMAND_BYTES) ?? "",
187 output: truncateDetail(item.output, MAX_ON_DEMAND_BYTES),
188 };
189 case "dynamic_tool":
190 return {
191 ...item,
192 input: boundDynamicValue(item.input),
193 output: boundToolOutput(item.output),
194 };
195 case "subagent":
196 return {
197 ...item,
198 prompt: truncateDetail(item.prompt, MAX_ON_DEMAND_BYTES) ?? "",
199 progress: truncateDetail(item.progress, MAX_ON_DEMAND_BYTES),
200 result:
201 item.result === null ? null : (truncateDetail(item.result, MAX_ON_DEMAND_BYTES) ?? null),
202 };
203 case "handoff":
204 case "file_change":
205 return projectTurnItemForWire(item);
206 default:
207 return item;
208 }
209}
210
211export function projectContextHandoffForWire(
212 handoff: OrchestrationV2ContextHandoff,
213): OrchestrationV2ContextHandoff {
214 const { history: _history, delivery: _delivery, ...projected } = handoff;
215 return { ...projected, summaryText: "" };
216}
217
218export function projectThreadProjectionForWire(
219 projection: OrchestrationV2ThreadProjection,
220): OrchestrationV2ThreadProjection {
221 const projectedById = new Map<string, OrchestrationV2TurnItem>();
222 const project = (item: OrchestrationV2TurnItem) => {
223 const key = `${item.threadId}:${item.id}`;
224 const existing = projectedById.get(key);
225 if (existing !== undefined) return existing;
226 const projected = projectTurnItemForWire(item);
227 projectedById.set(key, projected);
228 return projected;
229 };
230 return {
231 ...projection,
232 contextHandoffs: projection.contextHandoffs.map(projectContextHandoffForWire),
233 turnItems: projection.turnItems.map(project),
234 visibleTurnItems: projection.visibleTurnItems.map((row) => ({
235 ...row,
236 item: project(row.item),
237 })),
238 };
239}
240
241export function projectDomainEventForWire(
242 event: OrchestrationV2DomainEvent,
243): OrchestrationV2DomainEvent {
244 return event.type === "turn-item.updated"
245 ? { ...event, payload: projectTurnItemForWire(event.payload) }
246 : event.type === "context-handoff.updated"
247 ? { ...event, payload: projectContextHandoffForWire(event.payload) }
248 : event;
249}
250
251const LIVE_DEDUPE_MEMORY = 32;
252
253function remember<K, V>(memory: Map<K, V>, key: K, value: V): void {
254 memory.delete(key);
255 memory.set(key, value);
256 if (memory.size > LIVE_DEDUPE_MEMORY) memory.delete(memory.keys().next().value as K);
257}
258
259/**
260 * One per subscription, after coalescing, so it remembers only records the client received. A
261 * record event comes before the turn item that repeats its body, so the item (or a repeated
262 * subagent record) ships blank and marked. The other order, or a forgotten record, only costs
263 * bytes: the repeat ships whole.
264 */
265export function makeLiveBodyDeduper(): (
266 item: OrchestrationV2ThreadStreamItem,
267) => OrchestrationV2ThreadStreamItem {
268 const messageText = new Map<MessageId, string>();
269 const checkpointFiles = new Map<CheckpointId, OrchestrationV2Checkpoint["files"]>();
270 const subagents = new Map<NodeId, Pick<OrchestrationV2Subagent, "prompt" | "result">>();
271 const source = {
272 messageText: (id: MessageId) => messageText.get(id),
273 checkpointFiles: (id: CheckpointId) => checkpointFiles.get(id),
274 subagent: (id: NodeId) => subagents.get(id),
275 };
276 const rememberSubagent = ({ id, prompt, result }: OrchestrationV2Subagent) =>
277 remember(subagents, id, { prompt, result });
278 return (item) => {
279 if (item.kind === "snapshot") {
280 // The client now holds exactly these records; their bodies are never blanked.
281 const { messages, checkpoints, subagents: records } = item.projection;
282 for (const message of messages) remember(messageText, message.id, message.text);
283 for (const checkpoint of checkpoints)
284 remember(checkpointFiles, checkpoint.id, checkpoint.files);
285 for (const subagent of records) rememberSubagent(subagent);
286 return item;
287 }
288 if (item.kind !== "event") return item;
289 const { event } = item;
290 switch (event.type) {
291 case "message.updated":
292 remember(messageText, event.payload.id, event.payload.text);
293 return item;
294 case "checkpoint.captured":
295 remember(checkpointFiles, event.payload.id, event.payload.files);
296 return item;
297 case "subagent.updated": {
298 const payload = dedupeSubagentBodies(event.payload, subagents.get(event.payload.id));
299 rememberSubagent(event.payload);
300 return payload === event.payload ? item : { ...item, event: { ...event, payload } };
301 }
302 case "turn-item.updated": {
303 const payload = dedupeTurnItemBodies(event.payload, source);
304 return payload === event.payload ? item : { ...item, event: { ...event, payload } };
305 }
306 default:
307 return item;
308 }
309 };
310}