@devries-cameron20 / t3code Mirror · read-only
Fork 0

The best way to control Claude Code, Codex and more from any computer or phone

Mirrored from https://github.com/Camo67/t3code.git

Synced Nov 21, 03:37 UTC

main
ts 513 lines 19 KB
Raw
1 #!/usr/bin/env node
2 // @effect-diagnostics nodeBuiltinImport:off globalTimers:off globalFetch: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 */
9 import * as NodeCrypto from "node:crypto";
10 import * as NodeFS from "node:fs";
11 import * as NodeReadline from "node:readline";
12
13 interface LogicalFrame {
14 readonly kind: "notification" | "request" | "response";
15 readonly method: string;
16 readonly params?: unknown;
17 readonly result?: unknown;
18 }
19
20 interface ReplayEntry {
21 readonly type: "emit_inbound" | "expect_outbound" | "runtime_exit" | "transcript_start";
22 readonly frame?: LogicalFrame;
23 readonly afterMs?: number;
24 }
25
26 interface 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
35 export 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
41 const 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.
45 export 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 {
73 id: "delegate-remote",
74 name: "Delegate to a linked environment",
75 file: "./dev-replay/delegate_remote_transcript.ndjson",
76 },
77 {
78 id: "remote-child",
79 name: "E2E suite run",
80 file: "./dev-replay/remote_child_transcript.ndjson",
81 },
82 ] as const;
83
84 // Session setup and vendor state stay out: they would replace the replay agent's own models.
85 const REPLAYED_UPDATES = new Set([
86 "agent_message_chunk",
87 "agent_thought_chunk",
88 "tool_call",
89 "tool_call_update",
90 "plan",
91 "plan_update",
92 "plan_removed",
93 "session_info_update",
94 "usage_update",
95 ]);
96
97 const MCP_CALL = "t3/mcp_call";
98
99 // Only requests that ask the user. A replayed terminal/create would run a real command.
100 // `t3/mcp_call` is this agent's own: it calls a T3 tool over the session's MCP server.
101 const REPLAYED_REQUESTS = new Set(["session/request_permission", "elicitation/create", MCP_CALL]);
102
103 const CHUNK_DELAY_MS = 30;
104 const FRAME_DELAY_MS = 250;
105 const MAX_RECORDED_DELAY_MS = 2_000;
106 const WORDS_PER_CHUNK = 3;
107
108 function isReplayedFrame(frame: LogicalFrame): boolean {
109 if (frame.kind === "request") return REPLAYED_REQUESTS.has(frame.method);
110 if (frame.kind !== "notification" || frame.method !== "session/update") return false;
111 const update = (frame.params as { update?: { sessionUpdate?: unknown } } | undefined)?.update;
112 return typeof update?.sessionUpdate === "string" && REPLAYED_UPDATES.has(update.sessionUpdate);
113 }
114
115 /** Splits a recorded transcript into the turns that follow each `session/prompt`. */
116 export function parseReplayTurns(ndjson: string): ReadonlyArray<ReplayTurn> {
117 const turns: Array<{ frames: Array<ReplayTurn["frames"][number]>; stopReason: string }> = [];
118 // Frames after a prompt's response belong to background work, not to that turn.
119 let turn: (typeof turns)[number] | undefined;
120 for (const line of ndjson.split("\n")) {
121 if (line.trim().length === 0) continue;
122 const entry = JSON.parse(line) as ReplayEntry;
123 const frame = entry.frame;
124 if (frame === undefined) continue;
125 if (
126 entry.type === "expect_outbound" &&
127 frame.kind === "request" &&
128 frame.method === "session/prompt"
129 ) {
130 turn = { frames: [], stopReason: "end_turn" };
131 turns.push(turn);
132 continue;
133 }
134 if (entry.type !== "emit_inbound" || turn === undefined) continue;
135 if (frame.kind === "response" && frame.method === "session/prompt") {
136 const stopReason = (frame.result as { stopReason?: unknown } | undefined)?.stopReason;
137 if (typeof stopReason === "string") turn.stopReason = stopReason;
138 turn = undefined;
139 continue;
140 }
141 if (isReplayedFrame(frame)) {
142 turn.frames.push(entry.afterMs === undefined ? { frame } : { frame, afterMs: entry.afterMs });
143 }
144 }
145 return turns;
146 }
147
148 /** Splits streamed text into small chunks so the client sees real deltas. */
149 export function streamChunks(text: string): ReadonlyArray<string> {
150 const words = text.match(/\S+\s*|\s+/g) ?? [];
151 const chunks: Array<string> = [];
152 for (let index = 0; index < words.length; index += WORDS_PER_CHUNK) {
153 chunks.push(words.slice(index, index + WORDS_PER_CHUNK).join(""));
154 }
155 return chunks.length === 0 ? [text] : chunks;
156 }
157
158 /**
159 * Values a recording can name as `<var:name>`, read per turn from the JSON file at
160 * T3_DEV_REPLAY_VARS, for ids that change every run such as another environment's.
161 */
162 function readReplayVars(): Record<string, string> {
163 const file = process.env.T3_DEV_REPLAY_VARS;
164 if (file === undefined || file === "") return {};
165 try {
166 return JSON.parse(NodeFS.readFileSync(file, "utf8")) as Record<string, string>;
167 } catch {
168 return {};
169 }
170 }
171
172 /** Fills the live session, workspace, vars, and per-prompt tool ids, so repeated turns add rows. */
173 function materialize(
174 value: unknown,
175 live: {
176 readonly sessionId: string;
177 readonly workspace: string;
178 readonly turnKey: string;
179 readonly vars: Record<string, string>;
180 },
181 ): unknown {
182 if (typeof value === "string") {
183 return value
184 .replaceAll("<workspace>", live.workspace)
185 .replace(/<var:([\w-]+)>/g, (match, name: string) => live.vars[name] ?? match);
186 }
187 if (Array.isArray(value)) return value.map((entry) => materialize(entry, live));
188 if (typeof value !== "object" || value === null) return value;
189 return Object.fromEntries(
190 Object.entries(value).map(([key, entry]) => [
191 key,
192 key === "sessionId"
193 ? live.sessionId
194 : key === "toolCallId"
195 ? `${live.turnKey}-${String(entry)}`
196 : materialize(entry, live),
197 ]),
198 );
199 }
200
201 /** The tool call a permission answer rejected, if the user declined or cancelled. */
202 function permissionRejectedToolCallId(request: LogicalFrame, answer: unknown): string | undefined {
203 if (request.method !== "session/request_permission") return undefined;
204 const params = request.params as {
205 toolCall?: { toolCallId?: string };
206 options?: ReadonlyArray<{ optionId: string; kind: string }>;
207 };
208 const outcome = (answer as { outcome?: { outcome?: string; optionId?: string } } | undefined)
209 ?.outcome;
210 const chosen = params.options?.find((option) => option.optionId === outcome?.optionId);
211 const rejected = outcome?.outcome !== "selected" || chosen?.kind.startsWith("reject") === true;
212 return rejected ? params.toolCall?.toolCallId : undefined;
213 }
214
215 interface McpServer {
216 readonly endpoint: string;
217 readonly authorization: string;
218 }
219
220 /** The T3 MCP server T3 hands the agent in session/new, through the stdio bridge's env. */
221 function t3McpServer(servers: unknown): McpServer | undefined {
222 if (!Array.isArray(servers)) return undefined;
223 for (const server of servers as ReadonlyArray<{
224 env?: ReadonlyArray<{ name: string; value: string }>;
225 }>) {
226 const env = new Map((server.env ?? []).map((entry) => [entry.name, entry.value]));
227 const endpoint = env.get("T3_ACP_MCP_ENDPOINT");
228 const authorization = env.get("T3_ACP_MCP_AUTHORIZATION");
229 if (endpoint !== undefined && authorization !== undefined) return { endpoint, authorization };
230 }
231 return undefined;
232 }
233
234 /** One MCP tools/call over streamable HTTP: initialize, initialized, then the call. */
235 async function callT3Tool(server: McpServer, name: string, args: unknown): Promise<unknown> {
236 let sessionHeader: string | undefined;
237 const post = async (body: object) => {
238 const response = await fetch(server.endpoint, {
239 method: "POST",
240 headers: {
241 authorization: server.authorization,
242 accept: "application/json, text/event-stream",
243 "content-type": "application/json",
244 ...(sessionHeader === undefined ? {} : { "mcp-session-id": sessionHeader }),
245 },
246 body: JSON.stringify({ jsonrpc: "2.0", ...body }),
247 });
248 sessionHeader = response.headers.get("mcp-session-id") ?? sessionHeader;
249 const text = await response.text();
250 // A streamed answer carries the JSON-RPC message on a `data:` line.
251 const data = text.split("\n").find((line) => line.startsWith("data:"));
252 return text.length === 0 ? undefined : JSON.parse(data === undefined ? text : data.slice(5));
253 };
254 await post({
255 id: 1,
256 method: "initialize",
257 params: {
258 protocolVersion: "2025-06-18",
259 capabilities: {},
260 clientInfo: { name: "t3-dev-replay", version: "1" },
261 },
262 });
263 await post({ method: "notifications/initialized" });
264 return post({ id: 2, method: "tools/call", params: { name, arguments: args } });
265 }
266
267 function runAgent(): void {
268 const turnsByScenario = new Map<string, ReadonlyArray<ReplayTurn>>();
269 const loadTurns = (scenarioId: string) => {
270 const cached = turnsByScenario.get(scenarioId);
271 if (cached !== undefined) return cached;
272 const scenario = SCENARIOS.find((candidate) => candidate.id === scenarioId) ?? SCENARIOS[0];
273 const turns = parseReplayTurns(
274 NodeFS.readFileSync(new URL(scenario.file, import.meta.url), "utf8"),
275 );
276 turnsByScenario.set(scenarioId, turns);
277 return turns;
278 };
279
280 const sessions = new Map<
281 string,
282 {
283 cwd: string;
284 model: string;
285 promptCount: number;
286 cancel: (() => void) | undefined;
287 mcp: McpServer | undefined;
288 }
289 >();
290 const pendingAgentRequests = new Map<string, (result: unknown) => void>();
291 let nextAgentRequestId = 1;
292
293 const send = (message: JsonRpcMessage) =>
294 process.stdout.write(`${JSON.stringify({ jsonrpc: "2.0", ...message })}\n`);
295 // Resolves when `promise` settles or the turn is cancelled, whichever comes first.
296 const untilAbort = (promise: Promise<unknown>, signal: AbortSignal) =>
297 new Promise<void>((resolve) => {
298 if (signal.aborted) return resolve();
299 const onAbort = () => resolve();
300 signal.addEventListener("abort", onAbort, { once: true });
301 void promise.then(() => {
302 signal.removeEventListener("abort", onAbort);
303 resolve();
304 });
305 });
306 const sleep = (ms: number, signal: AbortSignal) =>
307 untilAbort(
308 new Promise((resolve) => setTimeout(resolve, Math.min(ms, MAX_RECORDED_DELAY_MS))),
309 signal,
310 );
311
312 const playTurn = async (
313 sessionId: string,
314 turn: ReplayTurn,
315 signal: AbortSignal,
316 ): Promise<"cancelled" | undefined> => {
317 const session = sessions.get(sessionId)!;
318 // Random, so a session loaded after a restart cannot reuse earlier tool rows.
319 const live = {
320 sessionId,
321 workspace: session.cwd,
322 turnKey: NodeCrypto.randomUUID(),
323 vars: readReplayVars(),
324 };
325 for (const recorded of turn.frames) {
326 const frame = materialize(recorded.frame, live) as LogicalFrame;
327 if (frame.kind === "request" && frame.method === MCP_CALL) {
328 await sleep(recorded.afterMs ?? FRAME_DELAY_MS, signal);
329 if (signal.aborted) return;
330 const call = frame.params as { name: string; arguments?: unknown };
331 if (session.mcp === undefined) {
332 process.stderr.write(`dev replay agent has no T3 MCP server for ${call.name}\n`);
333 continue;
334 }
335 const result = await callT3Tool(session.mcp, call.name, call.arguments ?? {}).catch(
336 (error: unknown) => ({ error: String(error) }),
337 );
338 const failed = result as { error?: unknown; result?: { isError?: boolean } } | undefined;
339 if (failed?.error !== undefined || failed?.result?.isError === true) {
340 process.stderr.write(
341 `dev replay agent: ${call.name} failed: ${JSON.stringify(result)}\n`,
342 );
343 }
344 continue;
345 }
346 if (frame.kind === "request") {
347 await sleep(recorded.afterMs ?? FRAME_DELAY_MS, signal);
348 if (signal.aborted) return;
349 const id = nextAgentRequestId++;
350 let answer: unknown;
351 const response = new Promise((resolve) =>
352 pendingAgentRequests.set(String(id), (result) => resolve((answer = result))),
353 );
354 send({ id, method: frame.method, params: frame.params as Record<string, unknown> });
355 await untilAbort(response, signal);
356 pendingAgentRequests.delete(String(id));
357 // The client answers "cancelled" when the user stops the turn mid-request.
358 const outcome = (answer as { outcome?: { outcome?: string } } | undefined)?.outcome;
359 if (signal.aborted || outcome?.outcome === "cancelled") return "cancelled";
360 const toolCallId = permissionRejectedToolCallId(frame, answer);
361 if (toolCallId === undefined) continue;
362 // The recording only has the approved path, so a rejection ends the turn here.
363 send({
364 method: "session/update",
365 params: {
366 sessionId,
367 update: { sessionUpdate: "tool_call_update", toolCallId, status: "failed" },
368 },
369 });
370 return;
371 }
372 const params = frame.params as { update: { sessionUpdate: string; content?: unknown } };
373 const content = params.update.content as { type?: string; text?: string } | undefined;
374 const text =
375 (params.update.sessionUpdate === "agent_message_chunk" ||
376 params.update.sessionUpdate === "agent_thought_chunk") &&
377 content?.type === "text"
378 ? content.text
379 : undefined;
380 // Live recordings hold one frame per token, so text defaults to the chunk pace.
381 const firstDelay = recorded.afterMs ?? (text === undefined ? FRAME_DELAY_MS : CHUNK_DELAY_MS);
382 const chunks = text === undefined ? [undefined] : streamChunks(text);
383 for (const [index, chunk] of chunks.entries()) {
384 await sleep(index === 0 ? firstDelay : CHUNK_DELAY_MS, signal);
385 if (signal.aborted) return;
386 send({
387 method: frame.method,
388 params:
389 chunk === undefined
390 ? params
391 : { ...params, update: { ...params.update, content: { ...content, text: chunk } } },
392 });
393 }
394 }
395 };
396
397 const handleRequest = async (message: JsonRpcMessage): Promise<unknown> => {
398 const params = message.params ?? {};
399 switch (message.method) {
400 case "initialize":
401 return {
402 protocolVersion: 1,
403 agentCapabilities: {
404 loadSession: true,
405 promptCapabilities: { image: false, audio: false, embeddedContext: true },
406 },
407 authMethods: [],
408 agentInfo: { name: "t3-dev-replay", version: "1" },
409 };
410 case "session/new":
411 case "session/load": {
412 // T3 starts one agent process per thread, so ids must be unique across processes.
413 // Loading after a restart keeps the thread usable; T3 already holds its history.
414 const sessionId =
415 message.method === "session/load" ? String(params.sessionId) : NodeCrypto.randomUUID();
416 const cwd = typeof params.cwd === "string" ? params.cwd : process.cwd();
417 sessions.set(sessionId, {
418 cwd,
419 model: SCENARIOS[0].id,
420 promptCount: 0,
421 cancel: undefined,
422 mcp: t3McpServer(params.mcpServers),
423 });
424 return {
425 ...(message.method === "session/new" ? { sessionId } : {}),
426 models: {
427 currentModelId: SCENARIOS[0].id,
428 availableModels: SCENARIOS.map((scenario) => ({
429 modelId: scenario.id,
430 name: scenario.name,
431 })),
432 },
433 };
434 }
435 case "session/set_model": {
436 const session = sessions.get(String(params.sessionId));
437 if (!SCENARIOS.some((scenario) => scenario.id === params.modelId)) {
438 throw Object.assign(new Error(`Unknown replay scenario ${String(params.modelId)}`), {
439 code: -32602,
440 });
441 }
442 if (session !== undefined && session.model !== params.modelId) {
443 session.model = String(params.modelId);
444 session.promptCount = 0;
445 }
446 return {};
447 }
448 case "session/prompt": {
449 const sessionId = String(params.sessionId);
450 const session = sessions.get(sessionId);
451 if (session === undefined) throw new Error(`Unknown session ${sessionId}`);
452 const turns = loadTurns(session.model);
453 const turn = turns[session.promptCount % Math.max(turns.length, 1)];
454 session.promptCount += 1;
455 const controller = new AbortController();
456 session.cancel = () => controller.abort();
457 let ended: "cancelled" | undefined;
458 try {
459 if (turn !== undefined) ended = await playTurn(sessionId, turn, controller.signal);
460 } finally {
461 session.cancel = undefined;
462 }
463 return {
464 stopReason:
465 controller.signal.aborted || ended === "cancelled"
466 ? "cancelled"
467 : (turn?.stopReason ?? "end_turn"),
468 };
469 }
470 case "session/close":
471 sessions.get(String(params.sessionId))?.cancel?.();
472 sessions.delete(String(params.sessionId));
473 return {};
474 case "authenticate":
475 case "session/set_mode":
476 return {};
477 default:
478 throw Object.assign(new Error(`Method not found: ${message.method}`), { code: -32601 });
479 }
480 };
481
482 const input = NodeReadline.createInterface({ input: process.stdin, crlfDelay: Infinity });
483 input.on("line", (line) => {
484 if (line.trim().length === 0) return;
485 let message: JsonRpcMessage;
486 try {
487 message = JSON.parse(line) as JsonRpcMessage;
488 } catch {
489 process.stderr.write(`dev replay agent ignored a line that is not JSON\n`);
490 return;
491 }
492 if (message.method === undefined) {
493 const resolve = pendingAgentRequests.get(String(message.id));
494 pendingAgentRequests.delete(String(message.id));
495 resolve?.(message.result);
496 return;
497 }
498 if (message.id === undefined || message.id === null) {
499 if (message.method === "session/cancel") {
500 sessions.get(String(message.params?.sessionId))?.cancel?.();
501 }
502 return;
503 }
504 const id = message.id;
505 handleRequest(message).then(
506 (result) => send({ id, result }),
507 (error: Error & { code?: number }) =>
508 send({ id, error: { code: error.code ?? -32603, message: error.message } }),
509 );
510 });
511 }
512
513 if (import.meta.main) runAgent();