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
24// A checkpoint over vendored or generated trees can list 15k+ files; the card needs a prefix.
25const MAX_WIRE_CHECKPOINT_FILES = 200;
26const MAX_DETAIL_STRING_BYTES = 32_768;
27const MAX_DYNAMIC_VALUE_BYTES = 16_384;
28const MAX_ON_DEMAND_BYTES = 256 * 1024;
29
30function truncateDetail(
31 value: string | undefined,
32 maxBytes = MAX_DETAIL_STRING_BYTES,
33): string | undefined {
34 if (
35 value === undefined ||
36 (value.length <= maxBytes && Buffer.byteLength(value, "utf8") <= maxBytes)
37 ) {
38 return value;
39 }
40 // UTF-8 needs at least one byte per UTF-16 unit; encode only a potentially fitting prefix.
41 const prefix = Buffer.from(value.slice(0, maxBytes), "utf8")
42 .subarray(0, maxBytes)
43 .toString("utf8")
44 .replace(/\uFFFD$/u, "");
45 return `${prefix}\n… output truncated for transport`;
46}
47
48/** Bound stored diffs to the client wire limit to avoid retaining invisible data in SQLite and heap. */
49export function boundFileChangeForStorage(item: OrchestrationV2TurnItem): OrchestrationV2TurnItem {
50 if (item.type !== "file_change") return item;
51 const { diffStr, oldStr, newStr } = item;
52 const bounded = {
53 ...item,
54 ...(diffStr === undefined ? {} : { diffStr: truncateDetail(diffStr) }),
55 ...(oldStr === undefined ? {} : { oldStr: truncateDetail(oldStr) }),
56 ...(newStr === undefined ? {} : { newStr: truncateDetail(newStr) }),
57 };
58 return bounded.diffStr === diffStr && bounded.oldStr === oldStr && bounded.newStr === newStr
59 ? item
60 : bounded;
61}
62
63function summarizeDynamicValue(value: unknown): unknown {
64 let serialized: string;
65 try {
66 if (typeof value === "string" && value.length > MAX_DYNAMIC_VALUE_BYTES) {
67 serialized = value;
68 } else {
69 const json = JSON.stringify(value) ?? String(value);
70 if (Buffer.byteLength(json, "utf8") <= MAX_DYNAMIC_VALUE_BYTES) {
71 return value;
72 }
73 serialized = typeof value === "string" ? value : json;
74 }
75 } catch {
76 serialized = "Unserializable tool output";
77 }
78
79 // Splitting and normalizing every line can allocate far more than the input.
80 const start = /\S/u.exec(serialized)?.index;
81 let firstLine = start === undefined ? "Large tool output" : "";
82 let pendingSpace = false;
83 for (let index = start ?? serialized.length; index < serialized.length; index += 1) {
84 const character = serialized[index]!;
85 if (character === "\n") break;
86 if (/\s/u.test(character)) {
87 pendingSpace = true;
88 continue;
89 }
90 if (pendingSpace) firstLine += " ";
91 firstLine += character;
92 pendingSpace = false;
93 if (firstLine.length > 160) break;
94 }
95 return {
96 summary: firstLine.length <= 160 ? firstLine : `${firstLine.slice(0, 159).trimEnd()}…`,
97 truncated: true,
98 };
99}
100
101type CheckpointFiles = Pick<OrchestrationV2Checkpoint, "files" | "filesTotal">;
102
103// Same input, same output object: snapshot compaction relies on shared item identity.
104const cappedCheckpointFiles = new WeakMap<object, object>();
105
106function capCheckpointFiles<T extends CheckpointFiles>(value: T): T {
107 if (value.files.length <= MAX_WIRE_CHECKPOINT_FILES || value.filesTotal !== undefined) {
108 return value;
109 }
110 const cached = cappedCheckpointFiles.get(value);
111 if (cached !== undefined) return cached as T;
112 let additions = 0;
113 let deletions = 0;
114 for (const file of value.files) {
115 additions += file.additions;
116 deletions += file.deletions;
117 }
118 const capped = {
119 ...value,
120 files: value.files.slice(0, MAX_WIRE_CHECKPOINT_FILES),
121 filesTotal: { count: value.files.length, additions, deletions },
122 };
123 cappedCheckpointFiles.set(value, capped);
124 return capped;
125}
126
127/** Idempotent; bounded snapshots that skip `projectThreadProjectionForWire` still need it. */
128export function capProjectionCheckpointFilesForWire(
129 projection: OrchestrationV2ThreadProjection,
130): OrchestrationV2ThreadProjection {
131 const checkpoints = projection.checkpoints.map(capCheckpointFiles);
132 const turnItems = projection.turnItems.map(capCheckpointItemFiles);
133 const visibleTurnItems = projection.visibleTurnItems.map((row) => {
134 const item = capCheckpointItemFiles(row.item);
135 return item === row.item ? row : { ...row, item };
136 });
137 const unchanged = (next: ReadonlyArray<unknown>, previous: ReadonlyArray<unknown>) =>
138 next.every((value, index) => value === previous[index]);
139 return unchanged(checkpoints, projection.checkpoints) &&
140 unchanged(turnItems, projection.turnItems) &&
141 unchanged(visibleTurnItems, projection.visibleTurnItems)
142 ? projection
143 : { ...projection, checkpoints, turnItems, visibleTurnItems };
144}
145
146function capCheckpointItemFiles(item: OrchestrationV2TurnItem): OrchestrationV2TurnItem {
147 return item.type === "checkpoint" ? capCheckpointFiles(item) : item;
148}
149
150export function projectTurnItemForWire(item: OrchestrationV2TurnItem): OrchestrationV2TurnItem {
151 switch (item.type) {
152 case "checkpoint":
153 return capCheckpointFiles(item);
154 case "handoff": {
155 const { summary: _summary, ...projected } = item;
156 return projected;
157 }
158 case "command_execution": {
159 const { output, ...projected } = item;
160 // A successful search can print "ENOENT" or "exit code 2", so output text
161 // decides only when the provider reported no exit code.
162 const failed =
163 item.exitCode === undefined
164 ? item.outputIndicatesFailure === true ||
165 (output !== undefined &&
166 toolOutputIndicatesFailure(output.slice(0, MAX_DETAIL_STRING_BYTES)))
167 : item.exitCode !== 0;
168 return {
169 ...projected,
170 ...(failed ? { outputIndicatesFailure: true } : {}),
171 ...(output?.trim() ? { outputOmitted: true } : {}),
172 };
173 }
174 case "file_change": {
175 const { diffStr, oldStr: _old, newStr: _new, ...projected } = item;
176 return item.status === "failed" && diffStr?.trim()
177 ? { ...projected, diffStr: truncateDetail(diffStr) }
178 : projected;
179 }
180 case "subagent":
181 return {
182 ...item,
183 prompt: truncateDetail(item.prompt) ?? "",
184 progress: truncateDetail(item.progress),
185 result: item.result === null ? null : (truncateDetail(item.result) ?? null),
186 };
187 case "dynamic_tool": {
188 const { output: rawOutput, ...projected } = item;
189 const output = compactDynamicToolOutput(rawOutput);
190 return {
191 ...projected,
192 input: summarizeDynamicValue(item.input),
193 ...(output === undefined ? {} : { output }),
194 ...(hasDynamicValue(rawOutput) ? { outputOmitted: true } : {}),
195 };
196 }
197 default:
198 return item;
199 }
200}
201
202function hasDynamicValue(value: unknown): boolean {
203 if (value === undefined || value === null) return false;
204 if (typeof value === "string") return value.trim().length > 0;
205 if (Array.isArray(value)) return value.length > 0;
206 return typeof value !== "object" || Object.keys(value).length > 0;
207}
208
209function boundDynamicValue(value: unknown): unknown {
210 if (value === undefined) return value;
211 if (typeof value === "string") return truncateDetail(value, MAX_ON_DEMAND_BYTES);
212 let json: string;
213 try {
214 json = JSON.stringify(value) ?? String(value);
215 } catch {
216 return "Unserializable tool value";
217 }
218 return Buffer.byteLength(json, "utf8") <= MAX_ON_DEMAND_BYTES
219 ? value
220 : truncateDetail(json, MAX_ON_DEMAND_BYTES);
221}
222
223/** Preserve ordered image markers in truncated output so clients can load images by index. */
224function boundToolOutput(output: unknown): unknown {
225 const omitted = omitToolOutputImageData(output);
226 const bounded = boundDynamicValue(omitted);
227 if (typeof bounded !== "string" || typeof omitted === "string") return bounded;
228 const images = toolOutputImages(omitted);
229 return images.length === 0
230 ? bounded
231 : [
232 { type: "text", text: bounded },
233 ...images.map((image) => ({ type: "image", mimeType: image.mimeType })),
234 ];
235}
236
237export function projectTurnItemForDetail(item: OrchestrationV2TurnItem): OrchestrationV2TurnItem {
238 switch (item.type) {
239 case "command_execution":
240 return {
241 ...item,
242 input: truncateDetail(item.input, MAX_ON_DEMAND_BYTES) ?? "",
243 output: truncateDetail(item.output, MAX_ON_DEMAND_BYTES),
244 };
245 case "dynamic_tool":
246 return {
247 ...item,
248 input: boundDynamicValue(item.input),
249 output: boundToolOutput(item.output),
250 };
251 case "subagent":
252 return {
253 ...item,
254 prompt: truncateDetail(item.prompt, MAX_ON_DEMAND_BYTES) ?? "",
255 progress: truncateDetail(item.progress, MAX_ON_DEMAND_BYTES),
256 result:
257 item.result === null ? null : (truncateDetail(item.result, MAX_ON_DEMAND_BYTES) ?? null),
258 };
259 case "file_change":
260 return {
261 ...projectTurnItemForWire(item),
262 ...(item.diffStr === undefined
263 ? {}
264 : { diffStr: truncateDetail(item.diffStr, MAX_ON_DEMAND_BYTES) }),
265 ...(!item.diffStr?.trim() && item.oldStr !== undefined
266 ? { oldStr: truncateDetail(item.oldStr, MAX_ON_DEMAND_BYTES) }
267 : {}),
268 ...(!item.diffStr?.trim() && item.newStr !== undefined
269 ? { newStr: truncateDetail(item.newStr, MAX_ON_DEMAND_BYTES) }
270 : {}),
271 };
272 case "handoff":
273 return projectTurnItemForWire(item);
274 default:
275 return item;
276 }
277}
278
279export function projectContextHandoffForWire(
280 handoff: OrchestrationV2ContextHandoff,
281): OrchestrationV2ContextHandoff {
282 const { history: _history, delivery: _delivery, ...projected } = handoff;
283 return { ...projected, summaryText: "" };
284}
285
286export function projectThreadProjectionForWire(
287 projection: OrchestrationV2ThreadProjection,
288): OrchestrationV2ThreadProjection {
289 const projectedById = new Map<string, OrchestrationV2TurnItem>();
290 const project = (item: OrchestrationV2TurnItem) => {
291 const key = `${item.threadId}:${item.id}`;
292 const existing = projectedById.get(key);
293 if (existing !== undefined) return existing;
294 const projected = projectTurnItemForWire(item);
295 projectedById.set(key, projected);
296 return projected;
297 };
298 return {
299 ...projection,
300 checkpoints: projection.checkpoints.map(capCheckpointFiles),
301 contextHandoffs: projection.contextHandoffs.map(projectContextHandoffForWire),
302 turnItems: projection.turnItems.map(project),
303 visibleTurnItems: projection.visibleTurnItems.map((row) => ({
304 ...row,
305 item: project(row.item),
306 })),
307 };
308}
309
310export function projectDomainEventForWire(
311 event: OrchestrationV2DomainEvent,
312): OrchestrationV2DomainEvent {
313 return event.type === "turn-item.updated"
314 ? { ...event, payload: projectTurnItemForWire(event.payload) }
315 : event.type === "context-handoff.updated"
316 ? { ...event, payload: projectContextHandoffForWire(event.payload) }
317 : event.type === "checkpoint.captured"
318 ? { ...event, payload: capCheckpointFiles(event.payload) }
319 : event;
320}
321
322const LIVE_DEDUPE_MEMORY = 32;
323
324function remember<K, V>(memory: Map<K, V>, key: K, value: V): void {
325 memory.delete(key);
326 memory.set(key, value);
327 if (memory.size > LIVE_DEDUPE_MEMORY) memory.delete(memory.keys().next().value as K);
328}
329
330/**
331 * One per subscription, after coalescing, so it remembers only records the client received. A
332 * record event comes before the turn item that repeats its body, so the item (or a repeated
333 * subagent record) ships blank and marked. The other order, or a forgotten record, only costs
334 * bytes: the repeat ships whole.
335 */
336export function makeLiveBodyDeduper(): (
337 item: OrchestrationV2ThreadStreamItem,
338) => OrchestrationV2ThreadStreamItem {
339 const messageText = new Map<MessageId, string>();
340 const checkpointFiles = new Map<CheckpointId, OrchestrationV2Checkpoint["files"]>();
341 const subagents = new Map<NodeId, Pick<OrchestrationV2Subagent, "prompt" | "result">>();
342 const source = {
343 messageText: (id: MessageId) => messageText.get(id),
344 checkpointFiles: (id: CheckpointId) => checkpointFiles.get(id),
345 subagent: (id: NodeId) => subagents.get(id),
346 };
347 const rememberSubagent = ({ id, prompt, result }: OrchestrationV2Subagent) =>
348 remember(subagents, id, { prompt, result });
349 return (item) => {
350 if (item.kind === "snapshot") {
351 // The client now holds exactly these records; their bodies are never blanked.
352 const { messages, checkpoints, subagents: records } = item.projection;
353 for (const message of messages) remember(messageText, message.id, message.text);
354 for (const checkpoint of checkpoints)
355 remember(checkpointFiles, checkpoint.id, checkpoint.files);
356 for (const subagent of records) rememberSubagent(subagent);
357 return item;
358 }
359 if (item.kind !== "event") return item;
360 const { event } = item;
361 switch (event.type) {
362 case "message.updated":
363 remember(messageText, event.payload.id, event.payload.text);
364 return item;
365 case "checkpoint.captured":
366 remember(checkpointFiles, event.payload.id, event.payload.files);
367 return item;
368 case "subagent.updated": {
369 const payload = dedupeSubagentBodies(event.payload, subagents.get(event.payload.id));
370 rememberSubagent(event.payload);
371 return payload === event.payload ? item : { ...item, event: { ...event, payload } };
372 }
373 case "turn-item.updated": {
374 const payload = dedupeTurnItemBodies(event.payload, source);
375 return payload === event.payload ? item : { ...item, event: { ...event, payload } };
376 }
377 default:
378 return item;
379 }
380 };
381}