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