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