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

WireProjection.ts

241 lines8.3 KB

1import type {
2 OrchestrationV2DomainEvent,
3 OrchestrationV2ContextHandoff,
4 OrchestrationV2ThreadProjection,
5 OrchestrationV2TurnItem,
6} from "@t3tools/contracts";
7import {
8 compactDynamicToolOutput,
9 omitToolOutputImageData,
10 toolOutputImages,
11 toolOutputIndicatesFailure,
12} from "@t3tools/shared/toolOutput";
13​
14const MAX_DETAIL_STRING_BYTES = 32_768;
15const MAX_DYNAMIC_VALUE_BYTES = 16_384;
16const MAX_ON_DEMAND_BYTES = 256 * 1024;
17​
18function truncateDetail(
19 value: string | undefined,
20 maxBytes = MAX_DETAIL_STRING_BYTES,
21): string | undefined {
22 if (
23 value === undefined ||
24 (value.length <= maxBytes && Buffer.byteLength(value, "utf8") <= maxBytes)
25 ) {
26 return value;
27 }
28 // UTF-8 needs at least one byte per UTF-16 code unit. Only encode the prefix
29 // that could fit, rather than allocating a buffer for the complete output.
30 const prefix = Buffer.from(value.slice(0, maxBytes), "utf8")
31 .subarray(0, maxBytes)
32 .toString("utf8")
33 .replace(/\uFFFD$/u, "");
34 return `${prefix}\n… output truncated for transport`;
36​
37function summarizeDynamicValue(value: unknown): unknown {
38 let serialized: string;
39 try {
40 if (typeof value === "string" && value.length > MAX_DYNAMIC_VALUE_BYTES) {
41 serialized = value;
42 } else {
43 const json = JSON.stringify(value) ?? String(value);
44 if (Buffer.byteLength(json, "utf8") <= MAX_DYNAMIC_VALUE_BYTES) {
45 return value;
46 }
47 serialized = typeof value === "string" ? value : json;
48 }
49 } catch {
50 serialized = "Unserializable tool output";
51 }
52​
53 // Preserve the first nonblank normalized line, but stop after the preview.
54 // Splitting and normalizing every line can allocate far more than the input.
55 const start = /\S/u.exec(serialized)?.index;
56 let firstLine = start === undefined ? "Large tool output" : "";
57 let pendingSpace = false;
58 for (let index = start ?? serialized.length; index < serialized.length; index += 1) {
59 const character = serialized[index]!;
60 if (character === "\n") break;
61 if (/\s/u.test(character)) {
62 pendingSpace = true;
63 continue;
64 }
65 if (pendingSpace) firstLine += " ";
66 firstLine += character;
67 pendingSpace = false;
68 if (firstLine.length > 160) break;
69 }
70 return {
71 summary: firstLine.length <= 160 ? firstLine : `${firstLine.slice(0, 159).trimEnd()}…`,
72 truncated: true,
73 };
75​
76export function projectTurnItemForWire(item: OrchestrationV2TurnItem): OrchestrationV2TurnItem {
77 switch (item.type) {
78 case "handoff": {
79 const { summary: _summary, ...projected } = item;
80 return projected;
81 }
82 case "command_execution": {
83 const { output, ...projected } = item;
84 // Clients used this preview to recognize provider-reported failures. Keep
85 // the outcome without retaining or serializing the output that proved it.
86 const failed =
87 item.outputIndicatesFailure === true ||
88 (item.exitCode !== undefined && item.exitCode !== 0) ||
89 (output !== undefined &&
90 toolOutputIndicatesFailure(output.slice(0, MAX_DETAIL_STRING_BYTES)));
91 return {
92 ...projected,
93 ...(failed ? { outputIndicatesFailure: true } : {}),
94 ...(output?.trim() ? { outputOmitted: true } : {}),
95 };
96 }
97 case "file_change": {
98 // File identity and counts are enough for activity. Full diffs already
99 // have a dedicated read path and remain intact in persistence.
100 const { diffStr, oldStr: _old, newStr: _new, ...projected } = item;
101 // A failed edit stores the provider's error where the diff would be.
102 return item.status === "failed" && diffStr?.trim()
103 ? { ...projected, diffStr: truncateDetail(diffStr) }
104 : projected;
105 }
106 case "subagent":
107 return {
108 ...item,
109 prompt: truncateDetail(item.prompt) ?? "",
110 progress: truncateDetail(item.progress),
111 result: item.result === null ? null : (truncateDetail(item.result) ?? null),
112 };
113 case "dynamic_tool": {
114 const { output: rawOutput, ...projected } = item;
115 const output = compactDynamicToolOutput(rawOutput);
116 return {
117 ...projected,
118 input: summarizeDynamicValue(item.input),
119 ...(output === undefined ? {} : { output }),
120 ...(hasDynamicValue(rawOutput) ? { outputOmitted: true } : {}),
121 };
122 }
123 default:
124 return item;
125 }
127​
128function hasDynamicValue(value: unknown): boolean {
129 if (value === undefined || value === null) return false;
130 if (typeof value === "string") return value.trim().length > 0;
131 if (Array.isArray(value)) return value.length > 0;
132 return typeof value !== "object" || Object.keys(value).length > 0;
134​
135function boundDynamicValue(value: unknown): unknown {
136 if (value === undefined) return value;
137 if (typeof value === "string") return truncateDetail(value, MAX_ON_DEMAND_BYTES);
138 let json: string;
139 try {
140 // Compact, so measuring does not inflate the value; clients indent it.
141 json = JSON.stringify(value) ?? String(value);
142 } catch {
143 return "Unserializable tool value";
144 }
145 return Buffer.byteLength(json, "utf8") <= MAX_ON_DEMAND_BYTES
146 ? value
147 : truncateDetail(json, MAX_ON_DEMAND_BYTES);
149​
150/**
151 * A tool output for a detail read, without image bytes. When the rest is too
152 * large to send whole, its truncated text still comes with the image markers,
153 * in order, so clients can load each image by index.
154 */
155function boundToolOutput(output: unknown): unknown {
156 const omitted = omitToolOutputImageData(output);
157 const bounded = boundDynamicValue(omitted);
158 if (typeof bounded !== "string" || typeof omitted === "string") return bounded;
159 const images = toolOutputImages(omitted);
160 return images.length === 0
161 ? bounded
162 : [
163 { type: "text", text: bounded },
164 ...images.map((image) => ({ type: "image", mimeType: image.mimeType })),
165 ];
167​
168/**
169 * Projects one item for an on-demand detail read: keeps the input and output
170 * the timeline withholds, bounded so a huge result cannot stall the socket.
171 * Image bytes are left out; clients load them as `tool-output-image` assets.
172 */
173export function projectTurnItemForDetail(item: OrchestrationV2TurnItem): OrchestrationV2TurnItem {
174 switch (item.type) {
175 case "command_execution":
176 return {
177 ...item,
178 input: truncateDetail(item.input, MAX_ON_DEMAND_BYTES) ?? "",
179 output: truncateDetail(item.output, MAX_ON_DEMAND_BYTES),
180 };
181 case "dynamic_tool":
182 return {
183 ...item,
184 input: boundDynamicValue(item.input),
185 output: boundToolOutput(item.output),
186 };
187 case "subagent":
188 return {
189 ...item,
190 prompt: truncateDetail(item.prompt, MAX_ON_DEMAND_BYTES) ?? "",
191 progress: truncateDetail(item.progress, MAX_ON_DEMAND_BYTES),
192 result:
193 item.result === null ? null : (truncateDetail(item.result, MAX_ON_DEMAND_BYTES) ?? null),
194 };
195 case "handoff":
196 case "file_change":
197 return projectTurnItemForWire(item);
198 default:
199 return item;
200 }
202​
203export function projectContextHandoffForWire(
204 handoff: OrchestrationV2ContextHandoff,
205): OrchestrationV2ContextHandoff {
206 const { history: _history, delivery: _delivery, ...projected } = handoff;
207 return { ...projected, summaryText: "" };
209​
210export function projectThreadProjectionForWire(
211 projection: OrchestrationV2ThreadProjection,
212): OrchestrationV2ThreadProjection {
213 const projectedById = new Map<string, OrchestrationV2TurnItem>();
214 const project = (item: OrchestrationV2TurnItem) => {
215 const key = `${item.threadId}:${item.id}`;
216 const existing = projectedById.get(key);
217 if (existing !== undefined) return existing;
218 const projected = projectTurnItemForWire(item);
219 projectedById.set(key, projected);
220 return projected;
221 };
222 return {
223 ...projection,
224 contextHandoffs: projection.contextHandoffs.map(projectContextHandoffForWire),
225 turnItems: projection.turnItems.map(project),
226 visibleTurnItems: projection.visibleTurnItems.map((row) => ({
227 ...row,
228 item: project(row.item),
229 })),
230 };
232​
233export function projectDomainEventForWire(
234 event: OrchestrationV2DomainEvent,
235): OrchestrationV2DomainEvent {
236 return event.type === "turn-item.updated"
237 ? { ...event, payload: projectTurnItemForWire(event.payload) }
238 : event.type === "context-handoff.updated"
239 ? { ...event, payload: projectContextHandoffForWire(event.payload) }
240 : event;