Open History to see the last commit
1#!/usr/bin/env node
2// @effect-diagnostics nodeBuiltinImport:off globalTimers:off
3/**
4 * A free ACP agent for dev servers. It plays recorded ACP transcripts with simulated
5 * streaming, so the real adapter, orchestration, and UI run without a paid model.
6 * Each scenario is a "model"; each prompt plays the next recorded turn.
7 * Unlike acp-replay-agent.ts, it does not assert the client's frames.
8 */
9import * as NodeCrypto from "node:crypto";
10import * as NodeFS from "node:fs";
11import * as NodeReadline from "node:readline";
12
13interface LogicalFrame {
14 readonly kind: "notification" | "request" | "response";
15 readonly method: string;
16 readonly params?: unknown;
17 readonly result?: unknown;
18}
19
20interface ReplayEntry {
21 readonly type: "emit_inbound" | "expect_outbound" | "runtime_exit" | "transcript_start";
22 readonly frame?: LogicalFrame;
23 readonly afterMs?: number;
24}
25
26interface JsonRpcMessage {
27 readonly jsonrpc?: string;
28 readonly id?: string | number | null;
29 readonly method?: string;
30 readonly params?: Record<string, unknown>;
31 readonly result?: unknown;
32 readonly error?: unknown;
33}
34
35export interface ReplayTurn {
36 /** Frames the agent sends: session updates and agent-to-client requests. */
37 readonly frames: ReadonlyArray<{ readonly frame: LogicalFrame; readonly afterMs?: number }>;
38 readonly stopReason: string;
39}
40
41const FIXTURES = "../src/orchestration-v2/testkit/fixtures";
42
43// Recorded fixtures the replay tests already pin, plus a hand-written UI showcase.
44// Use acpRegistry transcripts: vendor transcripts carry state in frames this agent drops.
45export const SCENARIOS = [
46 { id: "showcase", name: "Showcase", file: "./dev-replay/showcase_transcript.ndjson" },
47 {
48 id: "todo-list",
49 name: "Plan and reads",
50 file: `${FIXTURES}/todo_list/registry_transcript.ndjson`,
51 },
52 {
53 id: "approval",
54 name: "Write approval",
55 file: `${FIXTURES}/tool_call_read_only_on_request/registry_transcript.ndjson`,
56 },
57 {
58 id: "question",
59 name: "Question",
60 file: `${FIXTURES}/acp_elicitation/registry_transcript.ndjson`,
61 },
62 {
63 id: "multi-turn",
64 name: "Multi turn",
65 file: `${FIXTURES}/multi_turn/registry_transcript.ndjson`,
66 },
67 {
68 id: "command-output",
69 name: "Command output",
70 file: "./dev-replay/command_output_transcript.ndjson",
71 },
72] as const;
73
74// Session setup and vendor state stay out: they would replace the replay agent's own models.
75const REPLAYED_UPDATES = new Set([
76 "agent_message_chunk",
77 "agent_thought_chunk",
78 "tool_call",
79 "tool_call_update",
80 "plan",
81 "plan_update",
82 "plan_removed",
83 "session_info_update",
84 "usage_update",
85]);
86
87// Only requests that ask the user. A replayed terminal/create would run a real command.
88const REPLAYED_REQUESTS = new Set(["session/request_permission", "elicitation/create"]);
89
90const CHUNK_DELAY_MS = 30;
91const FRAME_DELAY_MS = 250;
92const MAX_RECORDED_DELAY_MS = 2_000;
93const WORDS_PER_CHUNK = 3;
94
95function isReplayedFrame(frame: LogicalFrame): boolean {
96 if (frame.kind === "request") return REPLAYED_REQUESTS.has(frame.method);
97 if (frame.kind !== "notification" || frame.method !== "session/update") return false;
98 const update = (frame.params as { update?: { sessionUpdate?: unknown } } | undefined)?.update;
99 return typeof update?.sessionUpdate === "string" && REPLAYED_UPDATES.has(update.sessionUpdate);
100}
101
102/** Splits a recorded transcript into the turns that follow each `session/prompt`. */
103export function parseReplayTurns(ndjson: string): ReadonlyArray<ReplayTurn> {
104 const turns: Array<{ frames: Array<ReplayTurn["frames"][number]>; stopReason: string }> = [];
105 // Frames after a prompt's response belong to background work, not to that turn.
106 let turn: (typeof turns)[number] | undefined;
107 for (const line of ndjson.split("\n")) {
108 if (line.trim().length === 0) continue;
109 const entry = JSON.parse(line) as ReplayEntry;
110 const frame = entry.frame;
111 if (frame === undefined) continue;
112 if (
113 entry.type === "expect_outbound" &&
114 frame.kind === "request" &&
115 frame.method === "session/prompt"
116 ) {
117 turn = { frames: [], stopReason: "end_turn" };
118 turns.push(turn);
119 continue;
120 }
121 if (entry.type !== "emit_inbound" || turn === undefined) continue;
122 if (frame.kind === "response" && frame.method === "session/prompt") {
123 const stopReason = (frame.result as { stopReason?: unknown } | undefined)?.stopReason;
124 if (typeof stopReason === "string") turn.stopReason = stopReason;
125 turn = undefined;
126 continue;
127 }
128 if (isReplayedFrame(frame)) {
129 turn.frames.push(entry.afterMs === undefined ? { frame } : { frame, afterMs: entry.afterMs });
130 }
131 }
132 return turns;
133}
134
135/** Splits streamed text into small chunks so the client sees real deltas. */
136export function streamChunks(text: string): ReadonlyArray<string> {
137 const words = text.match(/\S+\s*|\s+/g) ?? [];
138 const chunks: Array<string> = [];
139 for (let index = 0; index < words.length; index += WORDS_PER_CHUNK) {
140 chunks.push(words.slice(index, index + WORDS_PER_CHUNK).join(""));
141 }
142 return chunks.length === 0 ? [text] : chunks;
143}
144
145/** Fills the live session, workspace, and per-prompt tool ids, so repeated turns add rows. */
146function materialize(
147 value: unknown,
148 live: { readonly sessionId: string; readonly workspace: string; readonly turnKey: string },
149): unknown {
150 if (typeof value === "string") return value.replaceAll("<workspace>", live.workspace);
151 if (Array.isArray(value)) return value.map((entry) => materialize(entry, live));
152 if (typeof value !== "object" || value === null) return value;
153 return Object.fromEntries(
154 Object.entries(value).map(([key, entry]) => [
155 key,
156 key === "sessionId"
157 ? live.sessionId
158 : key === "toolCallId"
159 ? `${live.turnKey}-${String(entry)}`
160 : materialize(entry, live),
161 ]),
162 );
163}
164
165/** The tool call a permission answer rejected, if the user declined or cancelled. */
166function permissionRejectedToolCallId(request: LogicalFrame, answer: unknown): string | undefined {
167 if (request.method !== "session/request_permission") return undefined;
168 const params = request.params as {
169 toolCall?: { toolCallId?: string };
170 options?: ReadonlyArray<{ optionId: string; kind: string }>;
171 };
172 const outcome = (answer as { outcome?: { outcome?: string; optionId?: string } } | undefined)
173 ?.outcome;
174 const chosen = params.options?.find((option) => option.optionId === outcome?.optionId);
175 const rejected = outcome?.outcome !== "selected" || chosen?.kind.startsWith("reject") === true;
176 return rejected ? params.toolCall?.toolCallId : undefined;
177}
178
179function runAgent(): void {
180 const turnsByScenario = new Map<string, ReadonlyArray<ReplayTurn>>();
181 const loadTurns = (scenarioId: string) => {
182 const cached = turnsByScenario.get(scenarioId);
183 if (cached !== undefined) return cached;
184 const scenario = SCENARIOS.find((candidate) => candidate.id === scenarioId) ?? SCENARIOS[0];
185 const turns = parseReplayTurns(
186 NodeFS.readFileSync(new URL(scenario.file, import.meta.url), "utf8"),
187 );
188 turnsByScenario.set(scenarioId, turns);
189 return turns;
190 };
191
192 const sessions = new Map<
193 string,
194 { cwd: string; model: string; promptCount: number; cancel: (() => void) | undefined }
195 >();
196 const pendingAgentRequests = new Map<string, (result: unknown) => void>();
197 let nextAgentRequestId = 1;
198
199 const send = (message: JsonRpcMessage) =>
200 process.stdout.write(`${JSON.stringify({ jsonrpc: "2.0", ...message })}\n`);
201 // Resolves when `promise` settles or the turn is cancelled, whichever comes first.
202 const untilAbort = (promise: Promise<unknown>, signal: AbortSignal) =>
203 new Promise<void>((resolve) => {
204 if (signal.aborted) return resolve();
205 const onAbort = () => resolve();
206 signal.addEventListener("abort", onAbort, { once: true });
207 void promise.then(() => {
208 signal.removeEventListener("abort", onAbort);
209 resolve();
210 });
211 });
212 const sleep = (ms: number, signal: AbortSignal) =>
213 untilAbort(
214 new Promise((resolve) => setTimeout(resolve, Math.min(ms, MAX_RECORDED_DELAY_MS))),
215 signal,
216 );
217
218 const playTurn = async (
219 sessionId: string,
220 turn: ReplayTurn,
221 signal: AbortSignal,
222 ): Promise<"cancelled" | undefined> => {
223 const session = sessions.get(sessionId)!;
224 // Random, so a session loaded after a restart cannot reuse earlier tool rows.
225 const live = { sessionId, workspace: session.cwd, turnKey: NodeCrypto.randomUUID() };
226 for (const recorded of turn.frames) {
227 const frame = materialize(recorded.frame, live) as LogicalFrame;
228 if (frame.kind === "request") {
229 await sleep(recorded.afterMs ?? FRAME_DELAY_MS, signal);
230 if (signal.aborted) return;
231 const id = nextAgentRequestId++;
232 let answer: unknown;
233 const response = new Promise((resolve) =>
234 pendingAgentRequests.set(String(id), (result) => resolve((answer = result))),
235 );
236 send({ id, method: frame.method, params: frame.params as Record<string, unknown> });
237 await untilAbort(response, signal);
238 pendingAgentRequests.delete(String(id));
239 // The client answers "cancelled" when the user stops the turn mid-request.
240 const outcome = (answer as { outcome?: { outcome?: string } } | undefined)?.outcome;
241 if (signal.aborted || outcome?.outcome === "cancelled") return "cancelled";
242 const toolCallId = permissionRejectedToolCallId(frame, answer);
243 if (toolCallId === undefined) continue;
244 // The recording only has the approved path, so a rejection ends the turn here.
245 send({
246 method: "session/update",
247 params: {
248 sessionId,
249 update: { sessionUpdate: "tool_call_update", toolCallId, status: "failed" },
250 },
251 });
252 return;
253 }
254 const params = frame.params as { update: { sessionUpdate: string; content?: unknown } };
255 const content = params.update.content as { type?: string; text?: string } | undefined;
256 const text =
257 (params.update.sessionUpdate === "agent_message_chunk" ||
258 params.update.sessionUpdate === "agent_thought_chunk") &&
259 content?.type === "text"
260 ? content.text
261 : undefined;
262 // Live recordings hold one frame per token, so text defaults to the chunk pace.
263 const firstDelay = recorded.afterMs ?? (text === undefined ? FRAME_DELAY_MS : CHUNK_DELAY_MS);
264 const chunks = text === undefined ? [undefined] : streamChunks(text);
265 for (const [index, chunk] of chunks.entries()) {
266 await sleep(index === 0 ? firstDelay : CHUNK_DELAY_MS, signal);
267 if (signal.aborted) return;
268 send({
269 method: frame.method,
270 params:
271 chunk === undefined
272 ? params
273 : { ...params, update: { ...params.update, content: { ...content, text: chunk } } },
274 });
275 }
276 }
277 };
278
279 const handleRequest = async (message: JsonRpcMessage): Promise<unknown> => {
280 const params = message.params ?? {};
281 switch (message.method) {
282 case "initialize":
283 return {
284 protocolVersion: 1,
285 agentCapabilities: {
286 loadSession: true,
287 promptCapabilities: { image: false, audio: false, embeddedContext: true },
288 },
289 authMethods: [],
290 agentInfo: { name: "t3-dev-replay", version: "1" },
291 };
292 case "session/new":
293 case "session/load": {
294 // T3 starts one agent process per thread, so ids must be unique across processes.
295 // Loading after a restart keeps the thread usable; T3 already holds its history.
296 const sessionId =
297 message.method === "session/load" ? String(params.sessionId) : NodeCrypto.randomUUID();
298 const cwd = typeof params.cwd === "string" ? params.cwd : process.cwd();
299 sessions.set(sessionId, { cwd, model: SCENARIOS[0].id, promptCount: 0, cancel: undefined });
300 return {
301 ...(message.method === "session/new" ? { sessionId } : {}),
302 models: {
303 currentModelId: SCENARIOS[0].id,
304 availableModels: SCENARIOS.map((scenario) => ({
305 modelId: scenario.id,
306 name: scenario.name,
307 })),
308 },
309 };
310 }
311 case "session/set_model": {
312 const session = sessions.get(String(params.sessionId));
313 if (!SCENARIOS.some((scenario) => scenario.id === params.modelId)) {
314 throw Object.assign(new Error(`Unknown replay scenario ${String(params.modelId)}`), {
315 code: -32602,
316 });
317 }
318 if (session !== undefined && session.model !== params.modelId) {
319 session.model = String(params.modelId);
320 session.promptCount = 0;
321 }
322 return {};
323 }
324 case "session/prompt": {
325 const sessionId = String(params.sessionId);
326 const session = sessions.get(sessionId);
327 if (session === undefined) throw new Error(`Unknown session ${sessionId}`);
328 const turns = loadTurns(session.model);
329 const turn = turns[session.promptCount % Math.max(turns.length, 1)];
330 session.promptCount += 1;
331 const controller = new AbortController();
332 session.cancel = () => controller.abort();
333 let ended: "cancelled" | undefined;
334 try {
335 if (turn !== undefined) ended = await playTurn(sessionId, turn, controller.signal);
336 } finally {
337 session.cancel = undefined;
338 }
339 return {
340 stopReason:
341 controller.signal.aborted || ended === "cancelled"
342 ? "cancelled"
343 : (turn?.stopReason ?? "end_turn"),
344 };
345 }
346 case "session/close":
347 sessions.get(String(params.sessionId))?.cancel?.();
348 sessions.delete(String(params.sessionId));
349 return {};
350 case "authenticate":
351 case "session/set_mode":
352 return {};
353 default:
354 throw Object.assign(new Error(`Method not found: ${message.method}`), { code: -32601 });
355 }
356 };
357
358 const input = NodeReadline.createInterface({ input: process.stdin, crlfDelay: Infinity });
359 input.on("line", (line) => {
360 if (line.trim().length === 0) return;
361 let message: JsonRpcMessage;
362 try {
363 message = JSON.parse(line) as JsonRpcMessage;
364 } catch {
365 process.stderr.write(`dev replay agent ignored a line that is not JSON\n`);
366 return;
367 }
368 if (message.method === undefined) {
369 const resolve = pendingAgentRequests.get(String(message.id));
370 pendingAgentRequests.delete(String(message.id));
371 resolve?.(message.result);
372 return;
373 }
374 if (message.id === undefined || message.id === null) {
375 if (message.method === "session/cancel") {
376 sessions.get(String(message.params?.sessionId))?.cancel?.();
377 }
378 return;
379 }
380 const id = message.id;
381 handleRequest(message).then(
382 (result) => send({ id, result }),
383 (error: Error & { code?: number }) =>
384 send({ id, error: { code: error.code ?? -32603, message: error.message } }),
385 );
386 });
387}
388
389if (import.meta.main) runAgent();