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

acp-replay-agent.ts

285 lines8.7 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 statusPath = process.env.T3_ACP_REPLAY_STATUS_PATH;
39const replayWorkspace = process.env.T3_ACP_REPLAY_WORKSPACE ?? process.cwd();
40​
41if (encodedTranscript === undefined || statusPath === undefined) {
42 process.stderr.write("ACP replay requires transcript and status environment variables.\n");
43 process.exit(2);
45​
46const replayStatusPath = statusPath;
47const transcript = JSON.parse(
48 Buffer.from(encodedTranscript, "base64").toString("utf8"),
49) as ReplayTranscript;
50let cursor = 0;
51let stopped = false;
52let nextAgentRequestId = 1;
53const pendingClientRequestIds = new Map<string, string | number>();
54const pendingAgentRequestMethods = new Map<string, string>();
55​
56function writeStatus(failure?: unknown): void {
57 NodeFS.writeFileSync(
58 replayStatusPath,
59 JSON.stringify({
60 scenario: transcript.scenario,
61 cursor,
62 total: transcript.entries.length,
63 ...(failure === undefined ? {} : { failure }),
64 }),
65 "utf8",
66 );
68​
69function stableStringify(value: unknown): string {
70 if (Array.isArray(value)) {
71 return `[${value.map(stableStringify).join(",")}]`;
72 }
73 if (typeof value === "object" && value !== null) {
74 const record = value as Record<string, unknown>;
75 return `{${Object.keys(record)
76 .toSorted()
77 .map((key) => `${JSON.stringify(key)}:${stableStringify(record[key])}`)
78 .join(",")}}`;
79 }
80 return JSON.stringify(value);
82​
83function expandExpectedString(value: string): string {
84 return value.replaceAll("<workspace>", replayWorkspace);
86​
87function matchesExpected(expected: unknown, actual: unknown): boolean {
88 if (expected === "<any>") return true;
89 if (typeof expected === "string" && typeof actual === "string") {
90 const expanded = expandExpectedString(expected);
91 if (!expanded.includes("<any>")) return expanded === actual;
92 const parts = expanded.split("<any>");
93 let offset = 0;
94 for (const part of parts) {
95 const index = actual.indexOf(part, offset);
96 if (index === -1) return false;
97 offset = index + part.length;
98 }
99 return true;
100 }
101 if (Array.isArray(expected)) {
102 return (
103 Array.isArray(actual) &&
104 expected.length === actual.length &&
105 expected.every((entry, index) => matchesExpected(entry, actual[index]))
106 );
107 }
108 if (typeof expected === "object" && expected !== null) {
109 if (typeof actual !== "object" || actual === null || Array.isArray(actual)) return false;
110 const expectedRecord = expected as Record<string, unknown>;
111 const actualRecord = actual as Record<string, unknown>;
112 const expectedKeys = Object.keys(expectedRecord).toSorted();
113 const actualKeys = Object.keys(actualRecord).toSorted();
114 return (
115 stableStringify(expectedKeys) === stableStringify(actualKeys) &&
116 expectedKeys.every((key) => matchesExpected(expectedRecord[key], actualRecord[key]))
117 );
118 }
119 return Object.is(expected, actual);
121​
122function stopWithFailure(detail: string, actual?: unknown): void {
123 if (stopped) return;
124 stopped = true;
125 const entry = transcript.entries[cursor];
126 const failure = {
127 detail,
128 cursor,
129 expected: entry,
130 ...(actual === undefined ? {} : { actual }),
131 };
132 writeStatus(failure);
133 process.stderr.write(`ACP replay mismatch: ${JSON.stringify(failure)}\n`);
134 process.exitCode = 1;
135 process.stdin.pause();
137​
138function advance(): void {
139 cursor += 1;
140 writeStatus();
142​
143function send(message: JsonRpcMessage): void {
144 process.stdout.write(`${JSON.stringify(message)}\n`);
146​
147function pendingClientRequestId(method: string): string | number | undefined {
148 return pendingClientRequestIds.get(method);
150​
151function logicalIncoming(message: JsonRpcMessage): LogicalFrame | undefined {
152 if (typeof message.method === "string") {
153 return {
154 kind:
155 message.id === undefined || message.id === null || message.id === ""
156 ? "notification"
157 : "request",
158 method: message.method,
159 ...(message.params === undefined ? {} : { params: message.params }),
160 };
161 }
162 if (message.id === undefined || message.id === null) return undefined;
163 const method = pendingAgentRequestMethods.get(String(message.id));
164 if (method === undefined) return undefined;
165 return {
166 kind: "response",
167 method,
168 ...(message.result === undefined ? {} : { result: message.result }),
169 ...(message.error === undefined ? {} : { error: message.error }),
170 };
172​
173function emitInbound(frame: LogicalFrame): void {
174 switch (frame.kind) {
175 case "notification":
176 send({
177 jsonrpc: "2.0",
178 method: frame.method,
179 ...(frame.params === undefined ? {} : { params: frame.params }),
180 });
181 return;
182 case "request": {
183 const id = nextAgentRequestId;
184 nextAgentRequestId += 1;
185 pendingAgentRequestMethods.set(String(id), frame.method);
186 send({
187 jsonrpc: "2.0",
188 id,
189 method: frame.method,
190 ...(frame.params === undefined ? {} : { params: frame.params }),
191 headers: [],
192 });
193 return;
194 }
195 case "response": {
196 const id = pendingClientRequestId(frame.method);
197 if (id === undefined) {
198 stopWithFailure(`No pending client request for ${frame.method}`, frame);
199 return;
200 }
201 pendingClientRequestIds.delete(frame.method);
202 send({
203 jsonrpc: "2.0",
204 id,
205 ...(frame.result === undefined ? {} : { result: frame.result }),
206 ...(frame.error === undefined ? {} : { error: frame.error }),
207 });
208 }
209 }
211​
212function flushInbound(): void {
213 while (!stopped) {
214 const entry = transcript.entries[cursor];
215 if (entry === undefined || entry.type === "expect_outbound") return;
216 if (entry.type === "runtime_exit") {
217 if (entry.status !== "success" && entry.status !== "cancelled") {
218 stopWithFailure(`Recorded runtime exit was ${entry.status ?? "unknown"}`, entry.error);
219 return;
220 }
221 advance();
222 continue;
223 }
224 const frame = entry.frame as LogicalFrame;
225 if (
226 typeof frame !== "object" ||
227 frame === null ||
228 !["notification", "request", "response"].includes(frame.kind) ||
229 typeof frame.method !== "string"
230 ) {
231 stopWithFailure("Invalid emit_inbound logical ACP frame", entry.frame);
232 return;
233 }
234 emitInbound(frame);
235 if (stopped) return;
236 advance();
237 }
239​
240function handleMessage(message: JsonRpcMessage): void {
241 if (stopped) return;
242 const actual = logicalIncoming(message);
243 if (actual === undefined) {
244 stopWithFailure("Could not identify outbound ACP frame", message);
245 return;
246 }
247 const entry = transcript.entries[cursor];
248 if (entry?.type !== "expect_outbound" || !matchesExpected(entry.frame, actual)) {
249 if (actual.kind === "request" && message.id !== undefined && message.id !== null) {
250 send({
251 jsonrpc: "2.0",
252 id: message.id,
253 error: { code: -32603, message: "ACP replay frame mismatch" },
254 });
255 }
256 stopWithFailure("Unexpected outbound ACP frame", actual);
257 return;
258 }
259 if (actual.kind === "request" && message.id !== undefined && message.id !== null) {
260 pendingClientRequestIds.set(actual.method, message.id);
261 } else if (actual.kind === "response" && message.id !== undefined && message.id !== null) {
262 pendingAgentRequestMethods.delete(String(message.id));
263 }
264 advance();
265 flushInbound();
267​
268writeStatus();
269flushInbound();
270​
271const input = NodeReadline.createInterface({ input: process.stdin, crlfDelay: Infinity });
272input.on("line", (line) => {
273 if (stopped || line.trim().length === 0) return;
274 try {
275 handleMessage(JSON.parse(line) as JsonRpcMessage);
276 } catch (cause) {
277 stopWithFailure("Failed to decode outbound ACP JSON-RPC", String(cause));
278 }
279});
280​
281input.on("close", () => {
282 if (!stopped && cursor !== transcript.entries.length) {
283 stopWithFailure("ACP replay input closed before transcript completion");
284 }
285});