Skip to content

armgit / mso

Public Imported from GitHub
0

Browser-based graphical shell and control plane for a Linux server you own — real terminal, file manager, live metrics and BYOK AI in one mobile-first workspace. Next.js 16 · React 19 · node-pty · Tailwind v4 · shadcn/ui. Public alpha, self-hosted.

refactor(agent): split ACP client into framing, rpc, permission and process (#144)

Abdurrahman Fakhruld8ac092e4b36
diff --git a/lib/agent/acp-client.ts b/lib/agent/acp-client.ts
index 5fdb3771..ab88f1ca 100644
--- a/lib/agent/acp-client.ts
+++ b/lib/agent/acp-client.ts
@@ -1,24 +1,31 @@
-import { spawn, type ChildProcess } from "node:child_process";
+import { AcpError } from "./acp-errors";
+import { ACP_MAX_LINE_BYTES, AcpLineReader } from "./acp-framing";
+import type { AcpPermissionPolicy } from "./acp-permission";
+import { parsePermissionRequest, permissionOutcome } from "./acp-permission";
+import { AcpProcess } from "./acp-process";
+import { AcpRpc, type AcpJson } from "./acp-rpc";
// ACP v1 transport, client side: newline-delimited JSON-RPC over stdio. MSO is the
// CLIENT — the agent CLI owns the model subscription, tools and approvals; this file
// only speaks the wire protocol and never assumes an optional method exists
// (capabilities are negotiated in `initialize`).
//
-// Line cap: ACP is one JSON object per line and the biggest real message is a tool
-// result or file body (MSO's own agent result budget is 64 KiB), so 1 MiB is generous
-// headroom. The cap exists so a runaway agent writing an endless line fails loudly and
-// kills the child instead of growing MSO's heap.
-export const ACP_MAX_LINE_BYTES = 1_048_576, ACP_CONTROL_TIMEOUT_MS = 20_000;
+// The four concerns live beside this file and are composed here:
+// acp-framing.ts lines in, one JSON line out, 1 MiB cap
+// acp-rpc.ts id counter, pending map, response dispatch
+// acp-permission.ts pure allow/deny decision for request_permission
+// acp-process.ts spawn/group-kill/stderr ring/dispose
+export { AcpError } from "./acp-errors";
+export { ACP_MAX_LINE_BYTES } from "./acp-framing";
+export { permissionOutcome } from "./acp-permission";
+export type { AcpPermissionOption, AcpPermissionPolicy, AcpPermissionRequest } from "./acp-permission";
+
+export const ACP_CONTROL_TIMEOUT_MS = 20_000;
// A prompt turn is the agent's whole model + tool loop and legitimately runs for
// minutes; this is ACP's OWN bound. `mso-readonly` keeps its separate 60s bound and
// neither bound is derived from the other.
export const ACP_PROMPT_TIMEOUT_MS = 15 * 60_000;
-const STDERR_RING_BYTES = 16 * 1024, KILL_GRACE_MS = 500;
-export class AcpError extends Error {
- constructor(message: string, public readonly status = 502) { super(message); this.name = "AcpError"; }
-}
export interface AcpAgentCapabilities { loadSession?: boolean }
export interface AcpInitializeResult {
protocolVersion: number; agentCapabilities?: AcpAgentCapabilities; agentInfo?: { name?: string; version?: string };
@@ -30,35 +37,15 @@ export type AcpSessionUpdate =
| { kind: "tool_call"; toolCallId: string; name: string; status: string }
| { kind: "tool_call_update"; toolCallId: string; name?: string; status?: string }
| { kind: "plan" } | { kind: "other"; sessionUpdate: string };
-export interface AcpPermissionOption { optionId: string; kind: string; name: string }
-export interface AcpPermissionRequest { sessionId: string; toolCall: Record<string, unknown>; options: AcpPermissionOption[] }
-/** Returns true only for a NARROW allow. An absent policy means DENY. */
-export type AcpPermissionPolicy = (request: AcpPermissionRequest) => boolean | Promise<boolean>;
export interface AcpClientOptions {
command: string; args?: readonly string[]; cwd?: string; env?: NodeJS.ProcessEnv; signal?: AbortSignal;
permissionPolicy?: AcpPermissionPolicy; onUpdate?: (update: AcpSessionUpdate) => void;
onDiagnostic?: (text: string) => void; controlTimeoutMs?: number; promptTimeoutMs?: number; maxLineBytes?: number;
}
-/**
- * The decision for one `session/request_permission`, or null when no offered option
- * can express it — the caller must treat null as a cancelled turn, never as consent.
- * `allow_always` is deliberately unselectable: t3code's lesson is that an "always"
- * grant is project-wide, so MSO answers `once` only and a prompt-injected agent cannot
- * widen a supervised session.
- */
-export function permissionOutcome(options: readonly AcpPermissionOption[], allow: boolean) {
- const wanted = allow ? ["allow_once"] : ["reject_once", "reject_always"];
- const chosen = options.find(option => wanted.includes(option.kind))
- ?? (allow ? undefined : options.find(option => option.kind.startsWith("reject")));
- return chosen ? { outcome: "selected" as const, optionId: chosen.optionId } : null;
-}
-type Pending = { resolve: (value: unknown) => void; reject: (error: unknown) => void; timer: NodeJS.Timeout };
-type Json = Record<string, unknown>;
export class AcpClient {
- private readonly child: ChildProcess; private readonly pending = new Map<number, Pending>();
- private readonly stderrRing: string[] = [];
- private readonly controlMs: number; private readonly promptMs: number; private readonly maxLine: number;
- private buffer = ""; private nextId = 1; private stderrBytes = 0;
+ private readonly process: AcpProcess; private readonly rpc: AcpRpc;
+ private readonly reader: AcpLineReader;
+ private readonly controlMs: number; private readonly promptMs: number;
private stopped: AcpError | null = null; private capabilities: AcpAgentCapabilities = {};
/** `session/update` sink. A caller may swap it per turn; it is never shared. */
onUpdate: (update: AcpSessionUpdate) => void;
@@ -68,25 +55,20 @@ export class AcpClient {
constructor(private readonly options: AcpClientOptions) {
this.controlMs = options.controlTimeoutMs ?? ACP_CONTROL_TIMEOUT_MS;
this.promptMs = options.promptTimeoutMs ?? ACP_PROMPT_TIMEOUT_MS;
- this.maxLine = options.maxLineBytes ?? ACP_MAX_LINE_BYTES;
+ this.reader = new AcpLineReader(options.maxLineBytes ?? ACP_MAX_LINE_BYTES);
this.onUpdate = options.onUpdate ?? (() => undefined);
this.permissionPolicy = options.permissionPolicy ?? null;
- // Explicit argv, no shell string, and a new process GROUP so abort kills what the
- // agent started, not only the direct pid.
- this.child = spawn(options.command, options.args ?? [], { cwd: options.cwd,
- env: options.env, shell: false, detached: true, stdio: ["pipe", "pipe", "pipe"] });
- // EPIPE on a child that already died must reject the request, not crash the process.
- this.child.stdin?.on("error", (error: Error) => this.stop(new AcpError(`acp_stdin_closed:${error.message}`)));
- this.child.stdout?.on("data", (chunk: Buffer) => this.onChunk(chunk));
- this.child.stderr?.on("data", (chunk: Buffer) => this.appendStderr(chunk.toString("utf8")));
- this.child.once("error", (error: Error) => this.stop(new AcpError(`acp_spawn_failed:${error.message}`, 500)));
- this.child.once("exit", (code, signal) => this.stop(new AcpError(`acp_agent_exited:${signal ?? code ?? "unknown"}`)));
+ this.rpc = new AcpRpc(message => this.write(message), error => this.stop(error),
+ text => this.options.onDiagnostic?.(text));
+ this.process = new AcpProcess({ command: options.command, args: options.args ?? [], cwd: options.cwd,
+ env: options.env, onStdout: chunk => this.onChunk(chunk), onFailure: error => this.stop(error),
+ onDiagnostic: options.onDiagnostic });
options.signal?.addEventListener("abort", () => this.abort(options.signal?.reason), { once: true });
if (options.signal?.aborted) this.abort(options.signal.reason);
}
/** Direct child pid; diagnostics and group-kill proof only. */
- get pid(): number | undefined { return this.child.pid; }
+ get pid(): number | undefined { return this.process.pid; }
async initialize(clientInfo = { name: "mso", version: "1" }): Promise<AcpInitializeResult> {
const result = await this.request<AcpInitializeResult>("initialize", { protocolVersion: 1,
clientCapabilities: { fs: { readTextFile: false, writeTextFile: false }, terminal: false, auth: { terminal: false } }, clientInfo });
@@ -116,14 +98,7 @@ export class AcpClient {
}
request<T = unknown>(method: string, params: unknown, timeoutMs = this.controlMs): Promise<T> {
if (this.stopped) return Promise.reject(this.stopped);
- const id = this.nextId++;
- return new Promise<T>((resolve, reject) => {
- const timer = setTimeout(() => this.stop(new AcpError(`acp_request_timeout:${method}`, 504)), timeoutMs);
- timer.unref?.();
- this.pending.set(id, { resolve: resolve as (value: unknown) => void, reject, timer });
- try { this.write({ jsonrpc: "2.0", id, method, params }); }
- catch (error) { clearTimeout(timer); this.pending.delete(id); reject(error); }
- });
+ return this.rpc.request<T>(method, params, timeoutMs);
}
/** Idempotent: kills the whole group and rejects every pending request. */
abort(reason?: unknown): void {
@@ -133,50 +108,26 @@ export class AcpClient {
dispose(): void { this.stop(new AcpError("acp_client_disposed", 499)); }
private write(message: unknown): void {
if (this.stopped) throw this.stopped;
- const stdin = this.child.stdin;
- if (!stdin || stdin.destroyed) throw new AcpError("acp_stdin_closed");
- try { stdin.write(`${JSON.stringify(message)}\n`); } catch (error) {
- this.stop(new AcpError(`acp_stdin_closed:${error instanceof Error ? error.message : "write failed"}`));
- }
+ this.process.write(message, error => this.stop(new AcpError(
+ `acp_stdin_closed:${error instanceof Error ? error.message : "write failed"}`)));
}
private stop(error: AcpError): AcpError {
if (this.stopped) return this.stopped;
this.stopped = error;
- for (const entry of this.pending.values()) { clearTimeout(entry.timer); entry.reject(error); }
- this.pending.clear();
- const pid = this.child.pid;
- if (pid) { // The whole GROUP: an agent CLI forks helpers that would outlive the pid.
- try { process.kill(-pid, "SIGTERM"); } catch { try { this.child.kill("SIGTERM"); } catch { /* already gone */ } }
- setTimeout(() => { try { process.kill(-pid, "SIGKILL"); } catch { /* already gone */ } }, KILL_GRACE_MS).unref?.();
- }
- try { this.child.stdin?.end(); } catch { /* already closed */ }
- this.child.stdout?.destroy(); this.child.stderr?.destroy();
+ this.rpc.rejectAll(error);
+ this.process.kill();
+ this.process.close();
return error;
}
- private appendStderr(text: string): void { // bounded ring, never parsed as protocol
- this.stderrRing.push(text); this.stderrBytes += Buffer.byteLength(text);
- while (this.stderrBytes > STDERR_RING_BYTES && this.stderrRing.length > 1) this.stderrBytes -= Buffer.byteLength(this.stderrRing.shift()!);
- this.options.onDiagnostic?.(text);
- }
private onChunk(chunk: Buffer): void {
// A stream listener must never throw; a failure stops the client, which rejects every
- // pending request with that same error.
- this.buffer += chunk.toString("utf8");
- for (;;) {
- const index = this.buffer.indexOf("\n");
- // An unterminated line past the cap kills the child; it is never truncated.
- if (index < 0) {
- if (Buffer.byteLength(this.buffer) > this.maxLine) this.stop(new AcpError("acp_line_too_large"));
- return;
- }
- const line = this.buffer.slice(0, index); this.buffer = this.buffer.slice(index + 1);
- if (Buffer.byteLength(line) > this.maxLine) { this.stop(new AcpError("acp_line_too_large")); return; }
- if (line.trim() && !this.stopped) this.onLine(line);
- }
+ // pending request with that same error. An unterminated or oversized line past the
+ // cap kills the child; it is never truncated.
+ if (!this.reader.push(chunk, line => { if (!this.stopped) this.onLine(line); })) this.stop(new AcpError("acp_line_too_large"));
}
private onLine(line: string): void {
- let message: Json;
- try { message = JSON.parse(line) as Json; }
+ let message: AcpJson;
+ try { message = JSON.parse(line) as AcpJson; }
catch { this.stop(new AcpError("acp_protocol_invalid_json")); return; }
// A non-object message is a protocol fault, not something to guess around.
if (!message || typeof message !== "object" || Array.isArray(message)) return void this.stop(new AcpError("acp_protocol_invalid_message"));
@@ -186,21 +137,7 @@ export class AcpClient {
else if (id === undefined) this.onNotification(method, message.params);
return;
}
- if (typeof id === "number") this.onResponse(id, message);
- }
- private onResponse(id: number, message: Json): void {
- // A response for an unknown id is stale or duplicate, not a protocol violation.
- const entry = this.pending.get(id);
- if (!entry) { this.appendStderr(`acp: ignoring response for unknown id ${id}\n`); return; }
- this.pending.delete(id); clearTimeout(entry.timer);
- const error = message.error as { code?: unknown; message?: unknown } | undefined;
- if (error) {
- const code = typeof error.code === "number" ? error.code : "unknown";
- // -32000 is ACP's `auth_required`: a policy refusal, not a transport fault.
- entry.reject(new AcpError(`acp_agent_error:${code}:${String(error.message ?? "")}`, code === -32000 ? 409 : 502));
- return;
- }
- entry.resolve(message.result);
+ if (typeof id === "number") this.rpc.handleResponse(id, message);
}
private onNotification(method: string, params: unknown): void {
if (method !== "session/update") return; // `$/` notifications may be ignored
@@ -236,7 +173,7 @@ function textOf(content: unknown): string {
/** Unknown `sessionUpdate` kinds are preserved as `other`, never thrown. */
export function parseSessionUpdate(raw: unknown): AcpSessionUpdate | null {
if (!raw || typeof raw !== "object" || Array.isArray(raw)) return null;
- const update = raw as Json, kind = update.sessionUpdate, toolCallId = update.toolCallId;
+ const update = raw as AcpJson, kind = update.sessionUpdate, toolCallId = update.toolCallId;
if (kind === "agent_message_chunk") return { kind: "agent_message", text: textOf(update.content) };
if (kind === "agent_thought_chunk") return { kind: "agent_thought", text: textOf(update.content) };
if (kind === "user_message_chunk") return { kind: "user_message", text: textOf(update.content) };
@@ -251,15 +188,3 @@ export function parseSessionUpdate(raw: unknown): AcpSessionUpdate | null {
}
return { kind: "other", sessionUpdate: typeof kind === "string" ? kind : "unknown" };
}
-function parsePermissionRequest(raw: unknown): AcpPermissionRequest | null {
- if (!raw || typeof raw !== "object" || Array.isArray(raw)) return null;
- const params = raw as Json;
- if (typeof params.sessionId !== "string" || !Array.isArray(params.options)) return null;
- const options: AcpPermissionOption[] = [];
- for (const row of params.options) {
- const option = row as Json | undefined;
- if (!option || typeof option.optionId !== "string" || typeof option.kind !== "string") return null;
- options.push({ optionId: option.optionId, kind: option.kind, name: typeof option.name === "string" ? option.name : option.optionId });
- }
- return { sessionId: params.sessionId, toolCall: (params.toolCall as Record<string, unknown>) ?? {}, options };
-}
diff --git a/lib/agent/acp-errors.ts b/lib/agent/acp-errors.ts
new file mode 100644
index 00000000..f7e843a9
--- /dev/null
+++ b/lib/agent/acp-errors.ts
@@ -0,0 +1,4 @@
+/** Transport/protocol fault carrying the status the API layer should surface. */
+export class AcpError extends Error {
+ constructor(message: string, public readonly status = 502) { super(message); this.name = "AcpError"; }
+}
diff --git a/lib/agent/acp-framing.ts b/lib/agent/acp-framing.ts
new file mode 100644
index 00000000..b08699a9
--- /dev/null
+++ b/lib/agent/acp-framing.ts
@@ -0,0 +1,33 @@
+import type { Writable } from "node:stream";
+// ACP stdio framing: newline-delimited JSON-RPC, one object per line, plus the write
+// path. This layer knows nothing about ids or methods.
+//
+// Line cap: ACP is one JSON object per line and the biggest real message is a tool
+// result or file body (MSO's own agent result budget is 64 KiB), so 1 MiB is generous
+// headroom. The cap exists so a runaway agent writing an endless line fails loudly and
+// kills the child instead of growing MSO's heap.
+export const ACP_MAX_LINE_BYTES = 1_048_576;
+
+/** Incremental newline splitter. Returns the lines found, or signals overflow. */
+export class AcpLineReader {
+ private buffer = "";
+ constructor(private readonly maxLineBytes: number) {}
+ /** Feeds one chunk. Calls `onLine` per complete line; returns false when over cap. */
+ push(chunk: Buffer, onLine: (line: string) => void): boolean {
+ this.buffer += chunk.toString("utf8");
+ for (;;) {
+ const index = this.buffer.indexOf("\n");
+ // An unterminated line past the cap kills the child; it is never truncated.
+ if (index < 0) return Buffer.byteLength(this.buffer) <= this.maxLineBytes;
+ const line = this.buffer.slice(0, index); this.buffer = this.buffer.slice(index + 1);
+ if (Buffer.byteLength(line) > this.maxLineBytes) return false;
+ if (line.trim()) onLine(line);
+ }
+ }
+}
+
+/** One JSON line on stdin. Throws when the pipe is already gone. */
+export function writeAcpLine(stdin: Writable | null | undefined, message: unknown): void {
+ if (!stdin || stdin.destroyed) throw new Error("acp_stdin_closed");
+ stdin.write(`${JSON.stringify(message)}\n`);
+}
diff --git a/lib/agent/acp-permission.test.ts b/lib/agent/acp-permission.test.ts
new file mode 100644
index 00000000..2fc10045
--- /dev/null
+++ b/lib/agent/acp-permission.test.ts
@@ -0,0 +1,36 @@
+import { describe, expect, it } from "vitest";
+import { parsePermissionRequest, permissionOutcome } from "./acp-permission";
+
+// Pure policy checks: no child process, no transport. The DENY-by-default and
+// no-`allow_always` rules are the security contract, so they are pinned here.
+describe("ACP permission policy", () => {
+ const menu = [{ optionId: "always", kind: "allow_always", name: "Always" },
+ { optionId: "once", kind: "allow_once", name: "Once" },
+ { optionId: "no", kind: "reject_once", name: "No" },
+ { optionId: "never", kind: "reject_always", name: "Never" }];
+
+ it("picks allow_once for allow and reject_once for deny, never allow_always", () => {
+ expect(permissionOutcome(menu, true)).toEqual({ outcome: "selected", optionId: "once" });
+ expect(permissionOutcome(menu, false)).toEqual({ outcome: "selected", optionId: "no" });
+ expect(permissionOutcome([{ optionId: "always", kind: "allow_always", name: "Always" }], true)).toBeNull();
+ });
+
+ it("returns null when an allow-only menu cannot express a denial", () => {
+ expect(permissionOutcome([{ optionId: "always", kind: "allow_always", name: "A" }], false)).toBeNull();
+ expect(permissionOutcome([], true)).toBeNull();
+ });
+
+ it("falls back to any reject-prefixed option", () => {
+ expect(permissionOutcome([{ optionId: "x", kind: "reject_custom", name: "X" }], false))
+ .toEqual({ outcome: "selected", optionId: "x" });
+ });
+
+ it("parses a well-formed request and rejects malformed input", () => {
+ expect(parsePermissionRequest({ sessionId: "s", options: [{ optionId: "o", kind: "allow_once" }] }))
+ .toEqual({ sessionId: "s", toolCall: {}, options: [{ optionId: "o", kind: "allow_once", name: "o" }] });
+ expect(parsePermissionRequest(null)).toBeNull();
+ expect(parsePermissionRequest([])).toBeNull();
+ expect(parsePermissionRequest({ sessionId: "s" })).toBeNull();
+ expect(parsePermissionRequest({ sessionId: "s", options: [{ kind: "allow_once" }] })).toBeNull();
+ });
+});
diff --git a/lib/agent/acp-permission.ts b/lib/agent/acp-permission.ts
new file mode 100644
index 00000000..69f202db
--- /dev/null
+++ b/lib/agent/acp-permission.ts
@@ -0,0 +1,34 @@
+// Permission policy for ACP `session/request_permission`, kept pure: no transport, no
+// process, no clock. Everything here is a decision about the menu the agent offered.
+
+export interface AcpPermissionOption { optionId: string; kind: string; name: string }
+export interface AcpPermissionRequest { sessionId: string; toolCall: Record<string, unknown>; options: AcpPermissionOption[] }
+/** Returns true only for a NARROW allow. An absent policy means DENY. */
+export type AcpPermissionPolicy = (request: AcpPermissionRequest) => boolean | Promise<boolean>;
+
+/**
+ * The decision for one `session/request_permission`, or null when no offered option
+ * can express it — the caller must treat null as a cancelled turn, never as consent.
+ * `allow_always` is deliberately unselectable: t3code's lesson is that an "always"
+ * grant is project-wide, so MSO answers `once` only and a prompt-injected agent cannot
+ * widen a supervised session.
+ */
+export function permissionOutcome(options: readonly AcpPermissionOption[], allow: boolean) {
+ const wanted = allow ? ["allow_once"] : ["reject_once", "reject_always"];
+ const chosen = options.find(option => wanted.includes(option.kind))
+ ?? (allow ? undefined : options.find(option => option.kind.startsWith("reject")));
+ return chosen ? { outcome: "selected" as const, optionId: chosen.optionId } : null;
+}
+
+export function parsePermissionRequest(raw: unknown): AcpPermissionRequest | null {
+ if (!raw || typeof raw !== "object" || Array.isArray(raw)) return null;
+ const params = raw as Record<string, unknown>;
+ if (typeof params.sessionId !== "string" || !Array.isArray(params.options)) return null;
+ const options: AcpPermissionOption[] = [];
+ for (const row of params.options) {
+ const option = row as Record<string, unknown> | undefined;
+ if (!option || typeof option.optionId !== "string" || typeof option.kind !== "string") return null;
+ options.push({ optionId: option.optionId, kind: option.kind, name: typeof option.name === "string" ? option.name : option.optionId });
+ }
+ return { sessionId: params.sessionId, toolCall: (params.toolCall as Record<string, unknown>) ?? {}, options };
+}
diff --git a/lib/agent/acp-process.ts b/lib/agent/acp-process.ts
new file mode 100644
index 00000000..43d2dd4e
--- /dev/null
+++ b/lib/agent/acp-process.ts
@@ -0,0 +1,69 @@
+// ACP child-process lifecycle: spawn with an explicit argv and a detached process
+// GROUP, bounded stderr ring, group kill (SIGTERM then SIGKILL after a grace period)
+// and stream teardown. Knows nothing about JSON-RPC ids or permission policy.
+import { spawn, type ChildProcess } from "node:child_process";
+import { AcpError } from "./acp-errors";
+import { writeAcpLine } from "./acp-framing";
+
+const STDERR_RING_BYTES = 16 * 1024, KILL_GRACE_MS = 500;
+
+export interface AcpProcessOptions {
+ command: string; args?: readonly string[]; cwd?: string; env?: NodeJS.ProcessEnv;
+ onStdout: (chunk: Buffer) => void;
+ /** Fatal transport fault: the client must stop and reject every pending request. */
+ onFailure: (error: AcpError) => void;
+ onDiagnostic?: (text: string) => void;
+}
+
+export class AcpProcess {
+ private readonly child: ChildProcess;
+ private readonly stderrRing: string[] = [];
+ private stderrBytes = 0;
+
+ constructor(options: AcpProcessOptions) {
+ // Explicit argv, no shell string, and a new process GROUP so abort kills what the
+ // agent started, not only the direct pid.
+ this.child = spawn(options.command, options.args ?? [], { cwd: options.cwd,
+ env: options.env, shell: false, detached: true, stdio: ["pipe", "pipe", "pipe"] });
+ // EPIPE on a child that already died must reject the request, not crash the process.
+ this.child.stdin?.on("error", (error: Error) => options.onFailure(new AcpError(`acp_stdin_closed:${error.message}`)));
+ this.child.stdout?.on("data", (chunk: Buffer) => options.onStdout(chunk));
+ this.child.stderr?.on("data", (chunk: Buffer) => this.appendStderr(chunk.toString("utf8")));
+ this.child.once("error", (error: Error) => options.onFailure(new AcpError(`acp_spawn_failed:${error.message}`, 500)));
+ this.child.once("exit", (code, signal) => options.onFailure(new AcpError(`acp_agent_exited:${signal ?? code ?? "unknown"}`)));
+ this.onDiagnostic = options.onDiagnostic;
+ }
+
+ private readonly onDiagnostic?: (text: string) => void;
+
+ /** Direct child pid; diagnostics and group-kill proof only. */
+ get pid(): number | undefined { return this.child.pid; }
+
+ /** One JSON line on stdin. Throws when the pipe is closed; `onWriteFailed` is the
+ * fatal path for a live pipe that refuses the write. */
+ write(message: unknown, onWriteFailed: (error: unknown) => void): void {
+ const stdin = this.child.stdin;
+ if (!stdin || stdin.destroyed) throw new AcpError("acp_stdin_closed");
+ try { writeAcpLine(stdin, message); } catch (error) { onWriteFailed(error); }
+ }
+
+ /** The whole GROUP: an agent CLI forks helpers that would outlive the pid. */
+ kill(): void {
+ const pid = this.child.pid;
+ if (!pid) return;
+ try { process.kill(-pid, "SIGTERM"); } catch { try { this.child.kill("SIGTERM"); } catch { /* already gone */ } }
+ setTimeout(() => { try { process.kill(-pid, "SIGKILL"); } catch { /* already gone */ } }, KILL_GRACE_MS).unref?.();
+ }
+
+ /** Releases stdio handles; the caller owns the stop/reject bookkeeping. */
+ close(): void {
+ try { this.child.stdin?.end(); } catch { /* already closed */ }
+ this.child.stdout?.destroy(); this.child.stderr?.destroy();
+ }
+
+ private appendStderr(text: string): void { // bounded ring, never parsed as protocol
+ this.stderrRing.push(text); this.stderrBytes += Buffer.byteLength(text);
+ while (this.stderrBytes > STDERR_RING_BYTES && this.stderrRing.length > 1) this.stderrBytes -= Buffer.byteLength(this.stderrRing.shift()!);
+ this.onDiagnostic?.(text);
+ }
+}
diff --git a/lib/agent/acp-rpc.ts b/lib/agent/acp-rpc.ts
new file mode 100644
index 00000000..4528fcea
--- /dev/null
+++ b/lib/agent/acp-rpc.ts
@@ -0,0 +1,50 @@
+// JSON-RPC id correlation: the id counter, the pending map, response dispatch and the
+// unknown-id rule. No transport, no child process, no method knowledge.
+import { AcpError } from "./acp-errors";
+
+export type AcpJson = Record<string, unknown>;
+type Pending = { resolve: (value: unknown) => void; reject: (error: unknown) => void; timer: NodeJS.Timeout };
+
+export class AcpRpc {
+ private nextId = 1;
+ private readonly pending = new Map<number, Pending>();
+
+ constructor(
+ private readonly send: (message: unknown) => void,
+ private readonly fail: (error: AcpError) => void,
+ private readonly onDiagnostic: (text: string) => void,
+ ) {}
+
+ request<T = unknown>(method: string, params: unknown, timeoutMs: number): Promise<T> {
+ const id = this.nextId++;
+ return new Promise<T>((resolve, reject) => {
+ const timer = setTimeout(() => this.fail(new AcpError(`acp_request_timeout:${method}`, 504)), timeoutMs);
+ timer.unref?.();
+ this.pending.set(id, { resolve: resolve as (value: unknown) => void, reject, timer });
+ try { this.send({ jsonrpc: "2.0", id, method, params }); }
+ catch (error) { clearTimeout(timer); this.pending.delete(id); reject(error); }
+ });
+ }
+
+ /** A response for an unknown id is stale or duplicate, not a protocol violation. */
+ handleResponse(id: number, message: AcpJson): void {
+ const entry = this.pending.get(id);
+ if (!entry) { this.onDiagnostic(`acp: ignoring response for unknown id ${id}\n`); return; }
+ this.pending.delete(id); clearTimeout(entry.timer);
+ const error = message.error as { code?: unknown; message?: unknown } | undefined;
+ if (error) {
+ const code = typeof error.code === "number" ? error.code : "unknown";
+ // -32000 is ACP's `auth_required`: a policy refusal, not a transport fault.
+ entry.reject(new AcpError(`acp_agent_error:${code}:${String(error.message ?? "")}`, code === -32000 ? 409 : 502));
+ return;
+ }
+ entry.resolve(message.result);
+ }
+
+ /** Rejects every pending request once; the stop path calls this.
+ * Idempotent: a second call finds an empty map. */
+ rejectAll(error: AcpError): void {
+ for (const entry of this.pending.values()) { clearTimeout(entry.timer); entry.reject(error); }
+ this.pending.clear();
+ }
+}