Skip to content
Source
Sign inSign up
pingdotgg/t3code
Open History to see the last commit

WireProjection.ts

378 lines13.6 KB

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`;
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;
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 };
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;
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 };
145​
146function capCheckpointItemFiles(item: OrchestrationV2TurnItem): OrchestrationV2TurnItem {
147 return item.type === "checkpoint" ? capCheckpointFiles(item) : item;
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 const failed =
161 item.outputIndicatesFailure === true ||
162 (item.exitCode !== undefined && item.exitCode !== 0) ||
163 (output !== undefined &&
164 toolOutputIndicatesFailure(output.slice(0, MAX_DETAIL_STRING_BYTES)));
165 return {
166 ...projected,
167 ...(failed ? { outputIndicatesFailure: true } : {}),
168 ...(output?.trim() ? { outputOmitted: true } : {}),
169 };
170 }
171 case "file_change": {
172 const { diffStr, oldStr: _old, newStr: _new, ...projected } = item;
173 return item.status === "failed" && diffStr?.trim()
174 ? { ...projected, diffStr: truncateDetail(diffStr) }
175 : projected;
176 }
177 case "subagent":
178 return {
179 ...item,
180 prompt: truncateDetail(item.prompt) ?? "",
181 progress: truncateDetail(item.progress),
182 result: item.result === null ? null : (truncateDetail(item.result) ?? null),
183 };
184 case "dynamic_tool": {
185 const { output: rawOutput, ...projected } = item;
186 const output = compactDynamicToolOutput(rawOutput);
187 return {
188 ...projected,
189 input: summarizeDynamicValue(item.input),
190 ...(output === undefined ? {} : { output }),
191 ...(hasDynamicValue(rawOutput) ? { outputOmitted: true } : {}),
192 };
193 }
194 default:
195 return item;
196 }
198​
199function hasDynamicValue(value: unknown): boolean {
200 if (value === undefined || value === null) return false;
201 if (typeof value === "string") return value.trim().length > 0;
202 if (Array.isArray(value)) return value.length > 0;
203 return typeof value !== "object" || Object.keys(value).length > 0;
205​
206function boundDynamicValue(value: unknown): unknown {
207 if (value === undefined) return value;
208 if (typeof value === "string") return truncateDetail(value, MAX_ON_DEMAND_BYTES);
209 let json: string;
210 try {
211 json = JSON.stringify(value) ?? String(value);
212 } catch {
213 return "Unserializable tool value";
214 }
215 return Buffer.byteLength(json, "utf8") <= MAX_ON_DEMAND_BYTES
216 ? value
217 : truncateDetail(json, MAX_ON_DEMAND_BYTES);
219​
220/** Preserve ordered image markers in truncated output so clients can load images by index. */
221function boundToolOutput(output: unknown): unknown {
222 const omitted = omitToolOutputImageData(output);
223 const bounded = boundDynamicValue(omitted);
224 if (typeof bounded !== "string" || typeof omitted === "string") return bounded;
225 const images = toolOutputImages(omitted);
226 return images.length === 0
227 ? bounded
228 : [
229 { type: "text", text: bounded },
230 ...images.map((image) => ({ type: "image", mimeType: image.mimeType })),
231 ];
233​
234export function projectTurnItemForDetail(item: OrchestrationV2TurnItem): OrchestrationV2TurnItem {
235 switch (item.type) {
236 case "command_execution":
237 return {
238 ...item,
239 input: truncateDetail(item.input, MAX_ON_DEMAND_BYTES) ?? "",
240 output: truncateDetail(item.output, MAX_ON_DEMAND_BYTES),
241 };
242 case "dynamic_tool":
243 return {
244 ...item,
245 input: boundDynamicValue(item.input),
246 output: boundToolOutput(item.output),
247 };
248 case "subagent":
249 return {
250 ...item,
251 prompt: truncateDetail(item.prompt, MAX_ON_DEMAND_BYTES) ?? "",
252 progress: truncateDetail(item.progress, MAX_ON_DEMAND_BYTES),
253 result:
254 item.result === null ? null : (truncateDetail(item.result, MAX_ON_DEMAND_BYTES) ?? null),
255 };
256 case "file_change":
257 return {
258 ...projectTurnItemForWire(item),
259 ...(item.diffStr === undefined
260 ? {}
261 : { diffStr: truncateDetail(item.diffStr, MAX_ON_DEMAND_BYTES) }),
262 ...(!item.diffStr?.trim() && item.oldStr !== undefined
263 ? { oldStr: truncateDetail(item.oldStr, MAX_ON_DEMAND_BYTES) }
264 : {}),
265 ...(!item.diffStr?.trim() && item.newStr !== undefined
266 ? { newStr: truncateDetail(item.newStr, MAX_ON_DEMAND_BYTES) }
267 : {}),
268 };
269 case "handoff":
270 return projectTurnItemForWire(item);
271 default:
272 return item;
273 }
275​
276export function projectContextHandoffForWire(
277 handoff: OrchestrationV2ContextHandoff,
278): OrchestrationV2ContextHandoff {
279 const { history: _history, delivery: _delivery, ...projected } = handoff;
280 return { ...projected, summaryText: "" };
282​
283export function projectThreadProjectionForWire(
284 projection: OrchestrationV2ThreadProjection,
285): OrchestrationV2ThreadProjection {
286 const projectedById = new Map<string, OrchestrationV2TurnItem>();
287 const project = (item: OrchestrationV2TurnItem) => {
288 const key = `${item.threadId}:${item.id}`;
289 const existing = projectedById.get(key);
290 if (existing !== undefined) return existing;
291 const projected = projectTurnItemForWire(item);
292 projectedById.set(key, projected);
293 return projected;
294 };
295 return {
296 ...projection,
297 checkpoints: projection.checkpoints.map(capCheckpointFiles),
298 contextHandoffs: projection.contextHandoffs.map(projectContextHandoffForWire),
299 turnItems: projection.turnItems.map(project),
300 visibleTurnItems: projection.visibleTurnItems.map((row) => ({
301 ...row,
302 item: project(row.item),
303 })),
304 };
306​
307export function projectDomainEventForWire(
308 event: OrchestrationV2DomainEvent,
309): OrchestrationV2DomainEvent {
310 return event.type === "turn-item.updated"
311 ? { ...event, payload: projectTurnItemForWire(event.payload) }
312 : event.type === "context-handoff.updated"
313 ? { ...event, payload: projectContextHandoffForWire(event.payload) }
314 : event.type === "checkpoint.captured"
315 ? { ...event, payload: capCheckpointFiles(event.payload) }
316 : event;
318​
319const LIVE_DEDUPE_MEMORY = 32;
320​
321function remember<K, V>(memory: Map<K, V>, key: K, value: V): void {
322 memory.delete(key);
323 memory.set(key, value);
324 if (memory.size > LIVE_DEDUPE_MEMORY) memory.delete(memory.keys().next().value as K);
326​
327/**
328 * One per subscription, after coalescing, so it remembers only records the client received. A
329 * record event comes before the turn item that repeats its body, so the item (or a repeated
330 * subagent record) ships blank and marked. The other order, or a forgotten record, only costs
331 * bytes: the repeat ships whole.
332 */
333export function makeLiveBodyDeduper(): (
334 item: OrchestrationV2ThreadStreamItem,
335) => OrchestrationV2ThreadStreamItem {
336 const messageText = new Map<MessageId, string>();
337 const checkpointFiles = new Map<CheckpointId, OrchestrationV2Checkpoint["files"]>();
338 const subagents = new Map<NodeId, Pick<OrchestrationV2Subagent, "prompt" | "result">>();
339 const source = {
340 messageText: (id: MessageId) => messageText.get(id),
341 checkpointFiles: (id: CheckpointId) => checkpointFiles.get(id),
342 subagent: (id: NodeId) => subagents.get(id),
343 };
344 const rememberSubagent = ({ id, prompt, result }: OrchestrationV2Subagent) =>
345 remember(subagents, id, { prompt, result });
346 return (item) => {
347 if (item.kind === "snapshot") {
348 // The client now holds exactly these records; their bodies are never blanked.
349 const { messages, checkpoints, subagents: records } = item.projection;
350 for (const message of messages) remember(messageText, message.id, message.text);
351 for (const checkpoint of checkpoints)
352 remember(checkpointFiles, checkpoint.id, checkpoint.files);
353 for (const subagent of records) rememberSubagent(subagent);
354 return item;
355 }
356 if (item.kind !== "event") return item;
357 const { event } = item;
358 switch (event.type) {
359 case "message.updated":
360 remember(messageText, event.payload.id, event.payload.text);
361 return item;
362 case "checkpoint.captured":
363 remember(checkpointFiles, event.payload.id, event.payload.files);
364 return item;
365 case "subagent.updated": {
366 const payload = dedupeSubagentBodies(event.payload, subagents.get(event.payload.id));
367 rememberSubagent(event.payload);
368 return payload === event.payload ? item : { ...item, event: { ...event, payload } };
369 }
370 case "turn-item.updated": {
371 const payload = dedupeTurnItemBodies(event.payload, source);
372 return payload === event.payload ? item : { ...item, event: { ...event, payload } };
373 }
374 default:
375 return item;
376 }
377 };