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

dev-replay-agent.ts

392 lines15.2 KB

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