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

WireProjection.ts

150 lines5.3 KB

1import type {
2 OrchestrationV2DomainEvent,
3 OrchestrationV2ContextHandoff,
4 OrchestrationV2ThreadProjection,
5 OrchestrationV2TurnItem,
6} from "@t3tools/contracts";
7import { compactDynamicToolOutput, toolOutputIndicatesFailure } from "@t3tools/shared/toolOutput";
8​
9const MAX_DETAIL_STRING_BYTES = 32_768;
10const MAX_DYNAMIC_VALUE_BYTES = 16_384;
11​
12function truncateDetail(value: string | undefined): string | undefined {
13 if (
14 value === undefined ||
15 (value.length <= MAX_DETAIL_STRING_BYTES &&
16 Buffer.byteLength(value, "utf8") <= MAX_DETAIL_STRING_BYTES)
17 ) {
18 return value;
19 }
20 // UTF-8 needs at least one byte per UTF-16 code unit. Only encode the prefix
21 // that could fit, rather than allocating a buffer for the complete output.
22 const prefix = Buffer.from(value.slice(0, MAX_DETAIL_STRING_BYTES), "utf8")
23 .subarray(0, MAX_DETAIL_STRING_BYTES)
24 .toString("utf8")
25 .replace(/\uFFFD$/u, "");
26 return `${prefix}\n… output truncated for transport`;
28​
29function summarizeDynamicValue(value: unknown): unknown {
30 let serialized: string;
31 try {
32 if (typeof value === "string" && value.length > MAX_DYNAMIC_VALUE_BYTES) {
33 serialized = value;
34 } else {
35 const json = JSON.stringify(value) ?? String(value);
36 if (Buffer.byteLength(json, "utf8") <= MAX_DYNAMIC_VALUE_BYTES) {
37 return value;
38 }
39 serialized = typeof value === "string" ? value : json;
40 }
41 } catch {
42 serialized = "Unserializable tool output";
43 }
44​
45 // Preserve the first nonblank normalized line, but stop after the preview.
46 // Splitting and normalizing every line can allocate far more than the input.
47 const start = /\S/u.exec(serialized)?.index;
48 let firstLine = start === undefined ? "Large tool output" : "";
49 let pendingSpace = false;
50 for (let index = start ?? serialized.length; index < serialized.length; index += 1) {
51 const character = serialized[index]!;
52 if (character === "\n") break;
53 if (/\s/u.test(character)) {
54 pendingSpace = true;
55 continue;
56 }
57 if (pendingSpace) firstLine += " ";
58 firstLine += character;
59 pendingSpace = false;
60 if (firstLine.length > 160) break;
61 }
62 return {
63 summary: firstLine.length <= 160 ? firstLine : `${firstLine.slice(0, 159).trimEnd()}…`,
64 truncated: true,
65 };
67​
68export function projectTurnItemForWire(item: OrchestrationV2TurnItem): OrchestrationV2TurnItem {
69 switch (item.type) {
70 case "handoff": {
71 const { summary: _summary, ...projected } = item;
72 return projected;
73 }
74 case "command_execution": {
75 const { output, ...projected } = item;
76 // Clients used this preview to recognize provider-reported failures. Keep
77 // the outcome without retaining or serializing the output that proved it.
78 const failed =
79 item.outputIndicatesFailure === true ||
80 (item.exitCode !== undefined && item.exitCode !== 0) ||
81 (output !== undefined &&
82 toolOutputIndicatesFailure(output.slice(0, MAX_DETAIL_STRING_BYTES)));
83 return failed ? { ...projected, outputIndicatesFailure: true } : projected;
84 }
85 case "file_change": {
86 // File identity and counts are enough for activity. Full diffs already
87 // have a dedicated read path and remain intact in persistence.
88 const { diffStr: _diff, oldStr: _old, newStr: _new, ...projected } = item;
89 return projected;
90 }
91 case "subagent":
92 return {
93 ...item,
94 prompt: truncateDetail(item.prompt) ?? "",
95 progress: truncateDetail(item.progress),
96 result: item.result === null ? null : (truncateDetail(item.result) ?? null),
97 };
98 case "dynamic_tool": {
99 const { output: rawOutput, ...projected } = item;
100 const output = compactDynamicToolOutput(rawOutput);
101 return {
102 ...projected,
103 input: summarizeDynamicValue(item.input),
104 ...(output === undefined ? {} : { output }),
105 };
106 }
107 default:
108 return item;
109 }
111​
112export function projectContextHandoffForWire(
113 handoff: OrchestrationV2ContextHandoff,
114): OrchestrationV2ContextHandoff {
115 const { history: _history, delivery: _delivery, ...projected } = handoff;
116 return { ...projected, summaryText: "" };
118​
119export function projectThreadProjectionForWire(
120 projection: OrchestrationV2ThreadProjection,
121): OrchestrationV2ThreadProjection {
122 const projectedById = new Map<string, OrchestrationV2TurnItem>();
123 const project = (item: OrchestrationV2TurnItem) => {
124 const key = `${item.threadId}:${item.id}`;
125 const existing = projectedById.get(key);
126 if (existing !== undefined) return existing;
127 const projected = projectTurnItemForWire(item);
128 projectedById.set(key, projected);
129 return projected;
130 };
131 return {
132 ...projection,
133 contextHandoffs: projection.contextHandoffs.map(projectContextHandoffForWire),
134 turnItems: projection.turnItems.map(project),
135 visibleTurnItems: projection.visibleTurnItems.map((row) => ({
136 ...row,
137 item: project(row.item),
138 })),
139 };
141​
142export function projectDomainEventForWire(
143 event: OrchestrationV2DomainEvent,
144): OrchestrationV2DomainEvent {
145 return event.type === "turn-item.updated"
146 ? { ...event, payload: projectTurnItemForWire(event.payload) }
147 : event.type === "context-handoff.updated"
148 ? { ...event, payload: projectContextHandoffForWire(event.payload) }
149 : event;