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

WireProjection.ts

322 lines11.3 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​
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`;
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;
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 };
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 }
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;
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);
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 ];
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 "file_change":
204 return {
205 ...projectTurnItemForWire(item),
206 ...(item.diffStr === undefined
207 ? {}
208 : { diffStr: truncateDetail(item.diffStr, MAX_ON_DEMAND_BYTES) }),
209 ...(!item.diffStr?.trim() && item.oldStr !== undefined
210 ? { oldStr: truncateDetail(item.oldStr, MAX_ON_DEMAND_BYTES) }
211 : {}),
212 ...(!item.diffStr?.trim() && item.newStr !== undefined
213 ? { newStr: truncateDetail(item.newStr, MAX_ON_DEMAND_BYTES) }
214 : {}),
215 };
216 case "handoff":
217 return projectTurnItemForWire(item);
218 default:
219 return item;
220 }
222​
223export function projectContextHandoffForWire(
224 handoff: OrchestrationV2ContextHandoff,
225): OrchestrationV2ContextHandoff {
226 const { history: _history, delivery: _delivery, ...projected } = handoff;
227 return { ...projected, summaryText: "" };
229​
230export function projectThreadProjectionForWire(
231 projection: OrchestrationV2ThreadProjection,
232): OrchestrationV2ThreadProjection {
233 const projectedById = new Map<string, OrchestrationV2TurnItem>();
234 const project = (item: OrchestrationV2TurnItem) => {
235 const key = `${item.threadId}:${item.id}`;
236 const existing = projectedById.get(key);
237 if (existing !== undefined) return existing;
238 const projected = projectTurnItemForWire(item);
239 projectedById.set(key, projected);
240 return projected;
241 };
242 return {
243 ...projection,
244 contextHandoffs: projection.contextHandoffs.map(projectContextHandoffForWire),
245 turnItems: projection.turnItems.map(project),
246 visibleTurnItems: projection.visibleTurnItems.map((row) => ({
247 ...row,
248 item: project(row.item),
249 })),
250 };
252​
253export function projectDomainEventForWire(
254 event: OrchestrationV2DomainEvent,
255): OrchestrationV2DomainEvent {
256 return event.type === "turn-item.updated"
257 ? { ...event, payload: projectTurnItemForWire(event.payload) }
258 : event.type === "context-handoff.updated"
259 ? { ...event, payload: projectContextHandoffForWire(event.payload) }
260 : event;
262​
263const LIVE_DEDUPE_MEMORY = 32;
264​
265function remember<K, V>(memory: Map<K, V>, key: K, value: V): void {
266 memory.delete(key);
267 memory.set(key, value);
268 if (memory.size > LIVE_DEDUPE_MEMORY) memory.delete(memory.keys().next().value as K);
270​
271/**
272 * One per subscription, after coalescing, so it remembers only records the client received. A
273 * record event comes before the turn item that repeats its body, so the item (or a repeated
274 * subagent record) ships blank and marked. The other order, or a forgotten record, only costs
275 * bytes: the repeat ships whole.
276 */
277export function makeLiveBodyDeduper(): (
278 item: OrchestrationV2ThreadStreamItem,
279) => OrchestrationV2ThreadStreamItem {
280 const messageText = new Map<MessageId, string>();
281 const checkpointFiles = new Map<CheckpointId, OrchestrationV2Checkpoint["files"]>();
282 const subagents = new Map<NodeId, Pick<OrchestrationV2Subagent, "prompt" | "result">>();
283 const source = {
284 messageText: (id: MessageId) => messageText.get(id),
285 checkpointFiles: (id: CheckpointId) => checkpointFiles.get(id),
286 subagent: (id: NodeId) => subagents.get(id),
287 };
288 const rememberSubagent = ({ id, prompt, result }: OrchestrationV2Subagent) =>
289 remember(subagents, id, { prompt, result });
290 return (item) => {
291 if (item.kind === "snapshot") {
292 // The client now holds exactly these records; their bodies are never blanked.
293 const { messages, checkpoints, subagents: records } = item.projection;
294 for (const message of messages) remember(messageText, message.id, message.text);
295 for (const checkpoint of checkpoints)
296 remember(checkpointFiles, checkpoint.id, checkpoint.files);
297 for (const subagent of records) rememberSubagent(subagent);
298 return item;
299 }
300 if (item.kind !== "event") return item;
301 const { event } = item;
302 switch (event.type) {
303 case "message.updated":
304 remember(messageText, event.payload.id, event.payload.text);
305 return item;
306 case "checkpoint.captured":
307 remember(checkpointFiles, event.payload.id, event.payload.files);
308 return item;
309 case "subagent.updated": {
310 const payload = dedupeSubagentBodies(event.payload, subagents.get(event.payload.id));
311 rememberSubagent(event.payload);
312 return payload === event.payload ? item : { ...item, event: { ...event, payload } };
313 }
314 case "turn-item.updated": {
315 const payload = dedupeTurnItemBodies(event.payload, source);
316 return payload === event.payload ? item : { ...item, event: { ...event, payload } };
317 }
318 default:
319 return item;
320 }
321 };