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

acp-replay-agent.ts

329 lines11.0 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;
53/**
54 * A recording can span processes: a `runtime_exit` mid-transcript marks where
55 * one agent process ended, and a respawned replay agent continues from the
56 * cursor the previous one left in the status file.
57 */
58function resumedCursor(): number {
59 try {
60 const previous = JSON.parse(NodeFS.readFileSync(statusPath ?? "", "utf8")) as {
61 readonly cursor?: unknown;
62 readonly failure?: unknown;
63 };
64 const resumeAt = typeof previous.cursor === "number" ? previous.cursor : 0;
65 return previous.failure === undefined &&
66 transcript.entries[resumeAt - 1]?.type === "runtime_exit"
67 ? resumeAt
68 : 0;
69 } catch {
70 return 0;
71 }
73let cursor = resumedCursor();
74let stopped = false;
75let nextAgentRequestId = 1;
76// Several requests of one method can be open at once (a prompt steer is a second
77// session/prompt while the first runs), so responses pair first-in-first-out per method.
78const pendingClientRequestIds = new Map<string, Array<string | number>>();
79const pendingAgentRequestMethods = new Map<string, string>();
80​
81// The test reads status while this agent may still be running; rename makes each
82// write atomic so a reader never sees a truncated file.
83function writeStatus(failure?: unknown): void {
84 const temporaryStatusPath = `${replayStatusPath}.${process.pid}.tmp`;
85 NodeFS.writeFileSync(
86 temporaryStatusPath,
87 JSON.stringify({
88 scenario: transcript.scenario,
89 cursor,
90 total: transcript.entries.length,
91 ...(failure === undefined ? {} : { failure }),
92 }),
93 "utf8",
94 );
95 NodeFS.renameSync(temporaryStatusPath, replayStatusPath);
97​
98function stableStringify(value: unknown): string {
99 if (Array.isArray(value)) {
100 return `[${value.map(stableStringify).join(",")}]`;
101 }
102 if (typeof value === "object" && value !== null) {
103 const record = value as Record<string, unknown>;
104 return `{${Object.keys(record)
105 .toSorted()
106 .map((key) => `${JSON.stringify(key)}:${stableStringify(record[key])}`)
107 .join(",")}}`;
108 }
109 return JSON.stringify(value);
111​
112function expandExpectedString(value: string): string {
113 return value.replaceAll("<workspace>", replayWorkspace);
115​
116function matchesExpected(expected: unknown, actual: unknown): boolean {
117 if (expected === "<any>") return true;
118 if (typeof expected === "string" && typeof actual === "string") {
119 const expanded = expandExpectedString(expected);
120 if (!expanded.includes("<any>")) return expanded === actual;
121 const parts = expanded.split("<any>");
122 let offset = 0;
123 for (const part of parts) {
124 const index = actual.indexOf(part, offset);
125 if (index === -1) return false;
126 offset = index + part.length;
127 }
128 return true;
129 }
130 if (Array.isArray(expected)) {
131 return (
132 Array.isArray(actual) &&
133 expected.length === actual.length &&
134 expected.every((entry, index) => matchesExpected(entry, actual[index]))
135 );
136 }
137 if (typeof expected === "object" && expected !== null) {
138 if (typeof actual !== "object" || actual === null || Array.isArray(actual)) return false;
139 const expectedRecord = expected as Record<string, unknown>;
140 const actualRecord = actual as Record<string, unknown>;
141 const expectedKeys = Object.keys(expectedRecord).toSorted();
142 const actualKeys = Object.keys(actualRecord).toSorted();
143 return (
144 stableStringify(expectedKeys) === stableStringify(actualKeys) &&
145 expectedKeys.every((key) => matchesExpected(expectedRecord[key], actualRecord[key]))
146 );
147 }
148 return Object.is(expected, actual);
150​
151function stopWithFailure(detail: string, actual?: unknown): void {
152 if (stopped) return;
153 stopped = true;
154 const entry = transcript.entries[cursor];
155 const failure = {
156 detail,
157 cursor,
158 expected: entry,
159 ...(actual === undefined ? {} : { actual }),
160 };
161 writeStatus(failure);
162 process.stderr.write(`ACP replay mismatch: ${JSON.stringify(failure)}\n`);
163 process.exitCode = 1;
164 process.stdin.pause();
166​
167function send(message: JsonRpcMessage): void {
168 process.stdout.write(`${JSON.stringify(message)}\n`);
170​
171function pendingClientRequestId(method: string): string | number | undefined {
172 const ids = pendingClientRequestIds.get(method);
173 const id = ids?.shift();
174 if (ids !== undefined && ids.length === 0) pendingClientRequestIds.delete(method);
175 return id;
177​
178function logicalIncoming(message: JsonRpcMessage): LogicalFrame | undefined {
179 if (typeof message.method === "string") {
180 return {
181 kind:
182 message.id === undefined || message.id === null || message.id === ""
183 ? "notification"
184 : "request",
185 method: message.method,
186 ...(message.params === undefined ? {} : { params: message.params }),
187 };
188 }
189 if (message.id === undefined || message.id === null) return undefined;
190 const method = pendingAgentRequestMethods.get(String(message.id));
191 if (method === undefined) return undefined;
192 return {
193 kind: "response",
194 method,
195 ...(message.result === undefined ? {} : { result: message.result }),
196 ...(message.error === undefined ? {} : { error: message.error }),
197 };
199​
200function materializeInbound(value: unknown): unknown {
201 if (typeof value === "string") return expandExpectedString(value);
202 if (Array.isArray(value)) return value.map(materializeInbound);
203 if (typeof value !== "object" || value === null) return value;
204 return Object.fromEntries(
205 Object.entries(value).map(([key, entry]) => [key, materializeInbound(entry)]),
206 );
208​
209function inboundMessage(recorded: LogicalFrame): JsonRpcMessage | undefined {
210 const frame = materializeInbound(recorded) as LogicalFrame;
211 switch (frame.kind) {
212 case "notification":
213 return {
214 jsonrpc: "2.0",
215 method: frame.method,
216 ...(frame.params === undefined ? {} : { params: frame.params }),
217 };
218 case "request": {
219 const id = nextAgentRequestId;
220 nextAgentRequestId += 1;
221 pendingAgentRequestMethods.set(String(id), frame.method);
222 return {
223 jsonrpc: "2.0",
224 id,
225 method: frame.method,
226 ...(frame.params === undefined ? {} : { params: frame.params }),
227 headers: [],
228 };
229 }
230 case "response": {
231 const id = pendingClientRequestId(frame.method);
232 if (id === undefined) {
233 stopWithFailure(`No pending client request for ${frame.method}`, frame);
234 return undefined;
235 }
236 return {
237 jsonrpc: "2.0",
238 id,
239 ...(frame.result === undefined ? {} : { result: frame.result }),
240 ...(frame.error === undefined ? {} : { error: frame.error }),
241 };
242 }
243 }
245​
246// T3 may kill the agent after its last reply. Record the batch, including trailing
247// runtime exits, before publishing any frames.
248function flushInbound(): void {
249 const messages: Array<JsonRpcMessage> = [];
250 while (!stopped) {
251 const entry = transcript.entries[cursor];
252 if (entry === undefined || entry.type === "expect_outbound") break;
253 if (entry.type === "runtime_exit") {
254 if (entry.status !== "success" && entry.status !== "cancelled") {
255 stopWithFailure(`Recorded runtime exit was ${entry.status ?? "unknown"}`, entry.error);
256 break;
257 }
258 cursor += 1;
259 // Frames after a mid-transcript exit belong to the next process.
260 if (cursor < transcript.entries.length) break;
261 continue;
262 }
263 const frame = entry.frame as LogicalFrame;
264 if (
265 typeof frame !== "object" ||
266 frame === null ||
267 !["notification", "request", "response"].includes(frame.kind) ||
268 typeof frame.method !== "string"
269 ) {
270 stopWithFailure("Invalid emit_inbound logical ACP frame", entry.frame);
271 break;
272 }
273 const message = inboundMessage(frame);
274 if (message === undefined) break;
275 messages.push(message);
276 cursor += 1;
277 }
278 if (!stopped) writeStatus();
279 messages.forEach(send);
281​
282function handleMessage(message: JsonRpcMessage): void {
283 if (stopped) return;
284 const actual = logicalIncoming(message);
285 if (actual === undefined) {
286 stopWithFailure("Could not identify outbound ACP frame", message);
287 return;
288 }
289 const entry = transcript.entries[cursor];
290 if (entry?.type !== "expect_outbound" || !matchesExpected(entry.frame, actual)) {
291 stopWithFailure("Unexpected outbound ACP frame", actual);
292 if (actual.kind === "request" && message.id !== undefined && message.id !== null) {
293 send({
294 jsonrpc: "2.0",
295 id: message.id,
296 error: { code: -32603, message: "ACP replay frame mismatch" },
297 });
298 }
299 return;
300 }
301 if (actual.kind === "request" && message.id !== undefined && message.id !== null) {
302 const pending = pendingClientRequestIds.get(actual.method) ?? [];
303 pending.push(message.id);
304 pendingClientRequestIds.set(actual.method, pending);
305 } else if (actual.kind === "response" && message.id !== undefined && message.id !== null) {
306 pendingAgentRequestMethods.delete(String(message.id));
307 }
308 cursor += 1;
309 flushInbound();
311​
312flushInbound();
313​
314const input = NodeReadline.createInterface({ input: process.stdin, crlfDelay: Infinity });
315input.on("line", (line) => {
316 if (stopped || line.trim().length === 0) return;
317 try {
318 handleMessage(JSON.parse(line) as JsonRpcMessage);
319 } catch (cause) {
320 stopWithFailure("Failed to decode outbound ACP JSON-RPC", String(cause));
321 }
322});
323​
324input.on("close", () => {
325 const processEnded = transcript.entries[cursor - 1]?.type === "runtime_exit";
326 if (!stopped && cursor !== transcript.entries.length && !processEnded) {
327 stopWithFailure("ACP replay input closed before transcript completion");
328 }
329});