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

acp-replay-agent.ts

300 lines9.8 KB

1#!/usr/bin/env node
2// @effect-diagnostics nodeBuiltinImport:off
3import * as NodeFS from "node:fs";
4import * as NodeReadline from "node:readline";
5​
6interface ReplayEntry {
7 readonly type: "emit_inbound" | "expect_outbound" | "runtime_exit";
8 readonly label?: string;
9 readonly frame?: unknown;
10 readonly status?: "success" | "error" | "cancelled";
11 readonly error?: unknown;
13​
14interface ReplayTranscript {
15 readonly scenario: string;
16 readonly entries: ReadonlyArray<ReplayEntry>;
18​
19interface LogicalFrame {
20 readonly kind: "notification" | "request" | "response";
21 readonly method: string;
22 readonly params?: unknown;
23 readonly result?: unknown;
24 readonly error?: unknown;
26​
27interface JsonRpcMessage {
28 readonly jsonrpc?: string;
29 readonly id?: string | number | null;
30 readonly method?: string;
31 readonly params?: unknown;
32 readonly result?: unknown;
33 readonly error?: unknown;
34 readonly headers?: ReadonlyArray<unknown>;
36​
37const encodedTranscript = process.env.T3_ACP_REPLAY_TRANSCRIPT;
38const transcriptPath = process.env.T3_ACP_REPLAY_TRANSCRIPT_PATH;
39const statusPath = process.env.T3_ACP_REPLAY_STATUS_PATH;
40const replayWorkspace = process.env.T3_ACP_REPLAY_WORKSPACE ?? process.cwd();
41​
42if ((encodedTranscript === undefined && transcriptPath === undefined) || statusPath === undefined) {
43 process.stderr.write("ACP replay requires transcript and status environment variables.\n");
44 process.exit(2);
46​
47const replayStatusPath = statusPath;
48const transcript = JSON.parse(
49 transcriptPath === undefined
50 ? Buffer.from(encodedTranscript ?? "", "base64").toString("utf8")
51 : NodeFS.readFileSync(transcriptPath, "utf8"),
52) as ReplayTranscript;
53let cursor = 0;
54let stopped = false;
55let nextAgentRequestId = 1;
56const pendingClientRequestIds = new Map<string, string | number>();
57const pendingAgentRequestMethods = new Map<string, string>();
58​
59// The test reads status while this agent may still be running; rename makes each
60// write atomic so a reader never sees a truncated file.
61function writeStatus(failure?: unknown): void {
62 const temporaryStatusPath = `${replayStatusPath}.${process.pid}.tmp`;
63 NodeFS.writeFileSync(
64 temporaryStatusPath,
65 JSON.stringify({
66 scenario: transcript.scenario,
67 cursor,
68 total: transcript.entries.length,
69 ...(failure === undefined ? {} : { failure }),
70 }),
71 "utf8",
72 );
73 NodeFS.renameSync(temporaryStatusPath, replayStatusPath);
75​
76function stableStringify(value: unknown): string {
77 if (Array.isArray(value)) {
78 return `[${value.map(stableStringify).join(",")}]`;
79 }
80 if (typeof value === "object" && value !== null) {
81 const record = value as Record<string, unknown>;
82 return `{${Object.keys(record)
83 .toSorted()
84 .map((key) => `${JSON.stringify(key)}:${stableStringify(record[key])}`)
85 .join(",")}}`;
86 }
87 return JSON.stringify(value);
89​
90function expandExpectedString(value: string): string {
91 return value.replaceAll("<workspace>", replayWorkspace);
93​
94function matchesExpected(expected: unknown, actual: unknown): boolean {
95 if (expected === "<any>") return true;
96 if (typeof expected === "string" && typeof actual === "string") {
97 const expanded = expandExpectedString(expected);
98 if (!expanded.includes("<any>")) return expanded === actual;
99 const parts = expanded.split("<any>");
100 let offset = 0;
101 for (const part of parts) {
102 const index = actual.indexOf(part, offset);
103 if (index === -1) return false;
104 offset = index + part.length;
105 }
106 return true;
107 }
108 if (Array.isArray(expected)) {
109 return (
110 Array.isArray(actual) &&
111 expected.length === actual.length &&
112 expected.every((entry, index) => matchesExpected(entry, actual[index]))
113 );
114 }
115 if (typeof expected === "object" && expected !== null) {
116 if (typeof actual !== "object" || actual === null || Array.isArray(actual)) return false;
117 const expectedRecord = expected as Record<string, unknown>;
118 const actualRecord = actual as Record<string, unknown>;
119 const expectedKeys = Object.keys(expectedRecord).toSorted();
120 const actualKeys = Object.keys(actualRecord).toSorted();
121 return (
122 stableStringify(expectedKeys) === stableStringify(actualKeys) &&
123 expectedKeys.every((key) => matchesExpected(expectedRecord[key], actualRecord[key]))
124 );
125 }
126 return Object.is(expected, actual);
128​
129function stopWithFailure(detail: string, actual?: unknown): void {
130 if (stopped) return;
131 stopped = true;
132 const entry = transcript.entries[cursor];
133 const failure = {
134 detail,
135 cursor,
136 expected: entry,
137 ...(actual === undefined ? {} : { actual }),
138 };
139 writeStatus(failure);
140 process.stderr.write(`ACP replay mismatch: ${JSON.stringify(failure)}\n`);
141 process.exitCode = 1;
142 process.stdin.pause();
144​
145function send(message: JsonRpcMessage): void {
146 process.stdout.write(`${JSON.stringify(message)}\n`);
148​
149function pendingClientRequestId(method: string): string | number | undefined {
150 return pendingClientRequestIds.get(method);
152​
153function logicalIncoming(message: JsonRpcMessage): LogicalFrame | undefined {
154 if (typeof message.method === "string") {
155 return {
156 kind:
157 message.id === undefined || message.id === null || message.id === ""
158 ? "notification"
159 : "request",
160 method: message.method,
161 ...(message.params === undefined ? {} : { params: message.params }),
162 };
163 }
164 if (message.id === undefined || message.id === null) return undefined;
165 const method = pendingAgentRequestMethods.get(String(message.id));
166 if (method === undefined) return undefined;
167 return {
168 kind: "response",
169 method,
170 ...(message.result === undefined ? {} : { result: message.result }),
171 ...(message.error === undefined ? {} : { error: message.error }),
172 };
174​
175function materializeInbound(value: unknown): unknown {
176 if (typeof value === "string") return expandExpectedString(value);
177 if (Array.isArray(value)) return value.map(materializeInbound);
178 if (typeof value !== "object" || value === null) return value;
179 return Object.fromEntries(
180 Object.entries(value).map(([key, entry]) => [key, materializeInbound(entry)]),
181 );
183​
184function inboundMessage(recorded: LogicalFrame): JsonRpcMessage | undefined {
185 const frame = materializeInbound(recorded) as LogicalFrame;
186 switch (frame.kind) {
187 case "notification":
188 return {
189 jsonrpc: "2.0",
190 method: frame.method,
191 ...(frame.params === undefined ? {} : { params: frame.params }),
192 };
193 case "request": {
194 const id = nextAgentRequestId;
195 nextAgentRequestId += 1;
196 pendingAgentRequestMethods.set(String(id), frame.method);
197 return {
198 jsonrpc: "2.0",
199 id,
200 method: frame.method,
201 ...(frame.params === undefined ? {} : { params: frame.params }),
202 headers: [],
203 };
204 }
205 case "response": {
206 const id = pendingClientRequestId(frame.method);
207 if (id === undefined) {
208 stopWithFailure(`No pending client request for ${frame.method}`, frame);
209 return undefined;
210 }
211 pendingClientRequestIds.delete(frame.method);
212 return {
213 jsonrpc: "2.0",
214 id,
215 ...(frame.result === undefined ? {} : { result: frame.result }),
216 ...(frame.error === undefined ? {} : { error: frame.error }),
217 };
218 }
219 }
221​
222// T3 may kill the agent after its last reply. Record the batch, including trailing
223// runtime exits, before publishing any frames.
224function flushInbound(): void {
225 const messages: Array<JsonRpcMessage> = [];
226 while (!stopped) {
227 const entry = transcript.entries[cursor];
228 if (entry === undefined || entry.type === "expect_outbound") break;
229 if (entry.type === "runtime_exit") {
230 if (entry.status !== "success" && entry.status !== "cancelled") {
231 stopWithFailure(`Recorded runtime exit was ${entry.status ?? "unknown"}`, entry.error);
232 break;
233 }
234 cursor += 1;
235 continue;
236 }
237 const frame = entry.frame as LogicalFrame;
238 if (
239 typeof frame !== "object" ||
240 frame === null ||
241 !["notification", "request", "response"].includes(frame.kind) ||
242 typeof frame.method !== "string"
243 ) {
244 stopWithFailure("Invalid emit_inbound logical ACP frame", entry.frame);
245 break;
246 }
247 const message = inboundMessage(frame);
248 if (message === undefined) break;
249 messages.push(message);
250 cursor += 1;
251 }
252 if (!stopped) writeStatus();
253 messages.forEach(send);
255​
256function handleMessage(message: JsonRpcMessage): void {
257 if (stopped) return;
258 const actual = logicalIncoming(message);
259 if (actual === undefined) {
260 stopWithFailure("Could not identify outbound ACP frame", message);
261 return;
262 }
263 const entry = transcript.entries[cursor];
264 if (entry?.type !== "expect_outbound" || !matchesExpected(entry.frame, actual)) {
265 stopWithFailure("Unexpected outbound ACP frame", actual);
266 if (actual.kind === "request" && message.id !== undefined && message.id !== null) {
267 send({
268 jsonrpc: "2.0",
269 id: message.id,
270 error: { code: -32603, message: "ACP replay frame mismatch" },
271 });
272 }
273 return;
274 }
275 if (actual.kind === "request" && message.id !== undefined && message.id !== null) {
276 pendingClientRequestIds.set(actual.method, message.id);
277 } else if (actual.kind === "response" && message.id !== undefined && message.id !== null) {
278 pendingAgentRequestMethods.delete(String(message.id));
279 }
280 cursor += 1;
281 flushInbound();
283​
284flushInbound();
285​
286const input = NodeReadline.createInterface({ input: process.stdin, crlfDelay: Infinity });
287input.on("line", (line) => {
288 if (stopped || line.trim().length === 0) return;
289 try {
290 handleMessage(JSON.parse(line) as JsonRpcMessage);
291 } catch (cause) {
292 stopWithFailure("Failed to decode outbound ACP JSON-RPC", String(cause));
293 }
294});
295​
296input.on("close", () => {
297 if (!stopped && cursor !== transcript.entries.length) {
298 stopWithFailure("ACP replay input closed before transcript completion");
299 }
300});