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

WireProjection.ts

438 lines16.5 KB

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