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