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.

feat(agent): drive installed agent CLIs over ACP (#143)

Abdurrahman Fakhrul9593389088b1
diff --git a/app/api/v1/agent-profiles/run/route.ts b/app/api/v1/agent-profiles/run/route.ts
index e8912b45..bd72e20c 100644
--- a/app/api/v1/agent-profiles/run/route.ts
+++ b/app/api/v1/agent-profiles/run/route.ts
@@ -1,10 +1,12 @@
import { NextResponse } from "next/server";
import { getSessionContext } from "@/lib/auth/require-session";
import { readRequestJson, RequestBodyError } from "@/lib/security/request-body";
+import { redactText } from "@/lib/security/redact-text";
import { rateLimited } from "@/lib/host/limits-api";
import { msoCapabilityRuntime } from "@/lib/mcp/capability-runtime";
import { SelectedModelConfigError } from "@/lib/ai/selected-model-stream";
import { AgentProfileError } from "@/lib/agent/profile-schema";
+import { AcpError } from "@/lib/agent/acp-client";
import { runAgentProfile } from "@/lib/agent/profile-runtime";
export const runtime = "nodejs";
@@ -28,6 +30,7 @@ export async function POST(req: Request) {
const result = await runAgentProfile({ session: context.session, body, capabilities: msoCapabilityRuntime, signal: req.signal });
return NextResponse.json(result, { headers });
} catch (error) {
+ if (error instanceof AcpError) return fail(redactText(error.message, 300), error.status);
if (error instanceof AgentProfileError || error instanceof RequestBodyError || error instanceof SelectedModelConfigError) return fail(error.message, error.status);
return fail(req.signal.aborted ? "profile_run_cancelled" : "profile_run_failed", req.signal.aborted ? 499 : 502);
} finally { if (admitted) active.delete(device); }
diff --git a/lib/agent/acp-client.test.ts b/lib/agent/acp-client.test.ts
new file mode 100644
index 00000000..4710a5e9
--- /dev/null
+++ b/lib/agent/acp-client.test.ts
@@ -0,0 +1,196 @@
+import { afterEach, beforeEach, describe, expect, it } from "vitest";
+import { mkdtemp, readFile, rm, writeFile } from "node:fs/promises";
+import os from "node:os";
+import path from "node:path";
+import { AcpClient, AcpError, parseSessionUpdate, type AcpClientOptions } from "./acp-client";
+
+// The fake agent is a real child process speaking newline-delimited JSON-RPC. It is
+// injected through the SAME seam production uses — an explicit argv with shell:false —
+// so there is no test-only branch inside the client.
+const FAKE = String.raw`
+const plan = JSON.parse(process.argv[2] || "{}");
+const fs = require("node:fs");
+const write = m => process.stdout.write(JSON.stringify(m) + "\n");
+const record = line => { if (plan.record) fs.appendFileSync(plan.record, line + "\n"); };
+const sessionId = "sess_fixture";
+let authenticated = !plan.authRequired;
+function handle(m) {
+ const { id, method } = m;
+ record("in:" + method);
+ if (plan.silent) return;
+ if (method === "initialize") return write({ jsonrpc: "2.0", id, result: { protocolVersion: 1,
+ agentInfo: { name: "fake", version: "1" },
+ agentCapabilities: { loadSession: !!plan.loadSession, sessionCapabilities: {} } } });
+ if (method === "authenticate") { authenticated = true; return write({ jsonrpc: "2.0", id, result: {} }); }
+ if (method === "session/new") {
+ if (!authenticated) return write({ jsonrpc: "2.0", id, error: { code: -32000, message: "auth_required" } });
+ if (plan.pidFile) fs.writeFileSync(plan.pidFile, String(process.pid));
+ return write({ jsonrpc: "2.0", id, result: { sessionId } });
+ }
+ if (method === "session/prompt") {
+ for (const update of plan.updates || []) write({ jsonrpc: "2.0", method: "session/update", params: { sessionId, update } });
+ if (plan.permission) write({ jsonrpc: "2.0", id: 9001, method: "session/request_permission",
+ params: { sessionId, toolCall: { toolCallId: "t1", title: "Run" }, options: plan.permission } });
+ if (plan.oversized) { process.stdout.write("x".repeat(plan.oversized) + "\n"); return; }
+ if (plan.hang) return;
+ return write({ jsonrpc: "2.0", id, result: { stopReason: plan.stopReason || "end_turn" } });
+ }
+ if (method === "session/cancel") return;
+ if (id !== undefined) write({ jsonrpc: "2.0", id, error: { code: -32601, message: "method not found" } });
+}
+let buffer = "";
+process.stdin.setEncoding("utf8");
+process.stdin.on("data", chunk => {
+ buffer += chunk;
+ for (;;) {
+ const index = buffer.indexOf("\n");
+ if (index < 0) return;
+ const line = buffer.slice(0, index); buffer = buffer.slice(index + 1);
+ if (!line.trim()) continue;
+ const message = JSON.parse(line);
+ if (message.id === 9001) record("permission:" + JSON.stringify(message.result || message.error));
+ handle(message);
+ }
+});
+process.stdin.on("end", () => process.exit(0));
+`;
+
+// Second agent: answers in reverse order and also sends a response for an id nobody
+// asked about, which must not crash the client.
+const REVERSING = String.raw`
+let ids = [], buffer = "";
+const write = m => process.stdout.write(JSON.stringify(m) + "\n");
+process.stdin.setEncoding("utf8");
+process.stdin.on("data", chunk => {
+ buffer += chunk;
+ for (;;) {
+ const index = buffer.indexOf("\n");
+ if (index < 0) return;
+ const line = buffer.slice(0, index); buffer = buffer.slice(index + 1);
+ if (!line.trim()) continue;
+ const m = JSON.parse(line);
+ ids.push({ id: m.id, method: m.method });
+ const results = { initialize: { protocolVersion: 1, agentCapabilities: {} },
+ "session/new": { sessionId: "sess_rev" }, "session/prompt": { stopReason: "end_turn" } };
+ write({ jsonrpc: "2.0", id: 99999, result: { stale: true } });
+ for (const row of [...ids].reverse()) write({ jsonrpc: "2.0", id: row.id, result: results[row.method] || {} });
+ ids = [];
+ }
+});
+process.stdin.on("end", () => process.exit(0));
+`;
+
+let root: string, agent: string, reversing: string;
+beforeEach(async () => {
+ root = await mkdtemp(path.join(os.tmpdir(), "mso-acp-client-"));
+ agent = path.join(root, "fake-agent.cjs"); reversing = path.join(root, "fake-reversing.cjs");
+ await writeFile(agent, FAKE); await writeFile(reversing, REVERSING);
+});
+afterEach(async () => { await rm(root, { recursive: true, force: true }); });
+
+const fake = (plan: object, extra: Partial<AcpClientOptions> = {}) =>
+ new AcpClient({ command: process.execPath, args: [agent, JSON.stringify(plan)], ...extra });
+const alive = (pid: number) => { try { process.kill(pid, 0); return true; } catch { return false; } };
+const settle = () => new Promise(resolve => setTimeout(resolve, 400));
+
+describe("ACP stdio client", () => {
+ it("correlates out-of-order responses, ignores an unknown id, and never crashes", async () => {
+ const peer = new AcpClient({ command: process.execPath, args: [reversing] });
+ expect((await peer.initialize()).protocolVersion).toBe(1);
+ expect(await peer.newSession({ cwd: root })).toBe("sess_rev");
+ expect(await peer.prompt("sess_rev", "go")).toBe("end_turn");
+ peer.dispose();
+ });
+
+ it("dispatches session/update notifications apart from request replies", async () => {
+ const updates: string[] = [];
+ const peer = fake({ updates: [{ sessionUpdate: "agent_message_chunk", content: { type: "text", text: "hi" } }] });
+ peer.onUpdate = update => { updates.push(update.kind); };
+ await peer.initialize();
+ const session = await peer.newSession({ cwd: root });
+ // A notification must not resolve the pending prompt; only the reply does.
+ expect(await peer.prompt(session, "go")).toBe("end_turn");
+ expect(updates).toEqual(["agent_message"]);
+ peer.dispose();
+ });
+
+ it("ignores an unknown session/update kind without throwing", async () => {
+ const updates: string[] = [];
+ const peer = fake({ updates: [{ sessionUpdate: "future_extension_kind", payload: { x: 1 } },
+ { sessionUpdate: "tool_call", toolCallId: "t1", name: "fs_read", status: "completed" }] });
+ peer.onUpdate = update => { updates.push(update.kind); };
+ await peer.initialize(); await peer.prompt(await peer.newSession({ cwd: root }), "go");
+ expect(updates).toEqual(["other", "tool_call"]);
+ peer.dispose();
+ });
+
+ it("DENIES session/request_permission with no policy, and never picks an always-grant", async () => {
+ const none = path.join(root, "none.log"), allow = path.join(root, "allow.log");
+ const options = [{ optionId: "always", kind: "allow_always", name: "Always" },
+ { optionId: "once", kind: "allow_once", name: "Once" }, { optionId: "no", kind: "reject_once", name: "No" }];
+ const denying = fake({ permission: options, record: none });
+ await denying.initialize(); await denying.prompt(await denying.newSession({ cwd: root }), "go");
+ await settle(); denying.dispose();
+ expect((await readFile(none, "utf8")).split("\n").find(line => line.startsWith("permission:")))
+ .toBe(`permission:{"outcome":{"outcome":"selected","optionId":"no"}}`);
+
+ const allowing = fake({ permission: options, record: allow }, { permissionPolicy: () => true });
+ await allowing.initialize(); await allowing.prompt(await allowing.newSession({ cwd: root }), "go");
+ await settle(); allowing.dispose();
+ // An allow policy still only yields `allow_once`: no project-wide widening.
+ expect((await readFile(allow, "utf8")).split("\n").find(line => line.startsWith("permission:")))
+ .toBe(`permission:{"outcome":{"outcome":"selected","optionId":"once"}}`);
+ });
+
+ it("cancels the turn when an allow-only menu cannot express a denial", async () => {
+ const record = path.join(root, "cancelled.log");
+ const peer = fake({ permission: [{ optionId: "always", kind: "allow_always", name: "Always" }], record });
+ await peer.initialize(); await peer.prompt(await peer.newSession({ cwd: root }), "go");
+ await settle(); peer.dispose();
+ const lines = (await readFile(record, "utf8")).split("\n");
+ expect(lines.find(line => line.startsWith("permission:"))).toBe(`permission:{"outcome":{"outcome":"cancelled"}}`);
+ expect(lines).toContain("in:session/cancel");
+ });
+
+ it("abort rejects pending requests, kills the child's process group, and is idempotent", async () => {
+ const pidFile = path.join(root, "child.pid");
+ const peer = fake({ hang: true, pidFile });
+ await peer.initialize(); await peer.newSession({ cwd: root });
+ const pending = peer.prompt("sess_fixture", "never finishes");
+ const pid = Number(await readFile(pidFile, "utf8"));
+ expect(peer.pid).toBe(pid);
+ peer.abort(new Error("test stop"));
+ await expect(pending).rejects.toThrow(/acp_aborted:test stop/);
+ expect(() => peer.abort()).not.toThrow();
+ peer.abort(); peer.dispose();
+ await settle();
+ expect({ alive: alive(pid) }).toEqual({ alive: false });
+ });
+
+ it("kills the child and errors clearly when one inbound line exceeds the cap", async () => {
+ // The agent answers initialize, then emits an oversized line for session/prompt.
+ const peer = fake({ oversized: 4_096 }, { maxLineBytes: 1_024 });
+ await peer.initialize();
+ const pid = peer.pid!, session = await peer.newSession({ cwd: root });
+ await expect(peer.prompt(session, "go")).rejects.toThrow(/acp_line_too_large/);
+ await settle();
+ expect({ alive: alive(pid) }).toEqual({ alive: false });
+ peer.dispose();
+ });
+
+ it("times out a stalled control request, destroys the child, and refuses later work", async () => {
+ const peer = fake({ silent: true }, { controlTimeoutMs: 150 });
+ await expect(peer.initialize()).rejects.toThrow(/acp_request_timeout:initialize/);
+ await expect(peer.request("session/new", {})).rejects.toBeInstanceOf(AcpError);
+ peer.dispose();
+ });
+});
+
+describe("session update parsing", () => {
+ it("keeps unknown kinds instead of throwing", () => {
+ expect(parseSessionUpdate({ sessionUpdate: "mystery", x: 1 })).toEqual({ kind: "other", sessionUpdate: "mystery" });
+ expect(parseSessionUpdate(null)).toBeNull();
+ expect(parseSessionUpdate({ sessionUpdate: "tool_call", toolCallId: "t", name: "n" }))
+ .toEqual({ kind: "tool_call", toolCallId: "t", name: "n", status: "pending" });
+ });
+});
diff --git a/lib/agent/acp-client.ts b/lib/agent/acp-client.ts
new file mode 100644
index 00000000..5fdb3771
--- /dev/null
+++ b/lib/agent/acp-client.ts
@@ -0,0 +1,265 @@
+import { spawn, type ChildProcess } from "node:child_process";
+
+// 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;
+// 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 };
+ authMethods?: Array<{ id: string; name?: string; type?: string }>;
+}
+/** One parsed `session/update`. Unknown kinds stay labelled; nothing throws. */
+export type AcpSessionUpdate =
+ | { kind: "agent_message" | "agent_thought" | "user_message"; text: string }
+ | { 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 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;
+ /** Current permission gate. Null or absent means DENY every request. */
+ permissionPolicy: AcpPermissionPolicy | null;
+
+ 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.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"}`)));
+ 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; }
+ 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 });
+ if (result?.protocolVersion !== 1) throw this.stop(new AcpError("acp_protocol_version_unsupported"));
+ this.capabilities = result.agentCapabilities ?? {};
+ return result;
+ }
+ async authenticate(methodId: string): Promise<void> { await this.request("authenticate", { methodId }); }
+ async newSession(input: { cwd: string; mcpServers?: unknown[]; additionalDirectories?: string[] }): Promise<string> {
+ const result = await this.request<{ sessionId?: unknown }>("session/new", { cwd: input.cwd,
+ mcpServers: input.mcpServers ?? [], ...(input.additionalDirectories?.length ? { additionalDirectories: input.additionalDirectories } : {}) });
+ if (typeof result?.sessionId !== "string" || !result.sessionId) throw new AcpError("acp_session_id_missing");
+ return result.sessionId;
+ }
+ /** Only legal when the agent advertised `loadSession` in `initialize`. */
+ async loadSession(input: { sessionId: string; cwd: string; mcpServers?: unknown[] }): Promise<void> {
+ if (this.capabilities.loadSession !== true) throw new AcpError("acp_session_load_unsupported", 409);
+ await this.request("session/load", { sessionId: input.sessionId, cwd: input.cwd, mcpServers: input.mcpServers ?? [] });
+ }
+ async prompt(sessionId: string, text: string): Promise<string> {
+ const result = await this.request<{ stopReason?: unknown }>("session/prompt", { sessionId, prompt: [{ type: "text", text }] }, this.promptMs);
+ return typeof result?.stopReason === "string" ? result.stopReason : "unknown";
+ }
+ /** Fire-and-forget client notification (`session/cancel`). Best effort. */
+ notify(method: string, params: unknown): void {
+ try { this.write({ jsonrpc: "2.0", method, params }); } catch { /* child already gone */ }
+ }
+ 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); }
+ });
+ }
+ /** Idempotent: kills the whole group and rejects every pending request. */
+ abort(reason?: unknown): void {
+ const detail = reason instanceof Error ? reason.message : typeof reason === "string" ? reason : "aborted";
+ this.stop(reason instanceof AcpError ? reason : new AcpError(`acp_aborted:${detail}`, 499));
+ }
+ 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"}`));
+ }
+ }
+ 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();
+ 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);
+ }
+ }
+ private onLine(line: string): void {
+ let message: Json;
+ try { message = JSON.parse(line) as Json; }
+ 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"));
+ const id = message.id, method = message.method;
+ if (typeof method === "string") {
+ if (typeof id === "number") void this.onAgentRequest(id, method, message.params);
+ 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);
+ }
+ private onNotification(method: string, params: unknown): void {
+ if (method !== "session/update") return; // `$/` notifications may be ignored
+ const update = parseSessionUpdate((params as { update?: unknown } | undefined)?.update);
+ if (update) this.onUpdate(update);
+ }
+ private async onAgentRequest(id: number, method: string, params: unknown): Promise<void> {
+ if (method !== "session/request_permission") {
+ // Never answer an unknown client method with an implicit success.
+ this.write({ jsonrpc: "2.0", id, error: { code: -32601, message: `unsupported client method ${method}` } });
+ return;
+ }
+ const request = parsePermissionRequest(params);
+ if (!request) { this.write({ jsonrpc: "2.0", id, error: { code: -32602, message: "invalid permission request" } }); return; }
+ let allow = false; // no policy at all means DENY: never an implicit allow
+ if (this.permissionPolicy) {
+ try { allow = (await this.permissionPolicy(request)) === true; } catch { allow = false; }
+ }
+ const outcome = permissionOutcome(request.options, allow);
+ if (outcome) { this.write({ jsonrpc: "2.0", id, result: { outcome } }); return; }
+ // No offered option can express the answer (an allow-only menu, or a widening-only
+ // grant). Denial stays explicit — cancel the turn instead of leaving the agent free
+ // to proceed, and never answer with an "always" option.
+ this.write({ jsonrpc: "2.0", id, result: { outcome: { outcome: "cancelled" } } });
+ this.notify("session/cancel", { sessionId: request.sessionId });
+ }
+}
+
+function textOf(content: unknown): string {
+ const block = content as { type?: unknown; text?: unknown } | undefined;
+ return block?.type === "text" && typeof block.text === "string" ? block.text : "";
+}
+/** 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;
+ 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) };
+ if (kind === "plan") return { kind: "plan" };
+ if (kind === "tool_call" || kind === "tool_call_update") {
+ if (typeof toolCallId !== "string") return null;
+ const name = typeof update.name === "string" ? update.name : typeof update.title === "string" ? update.title : undefined;
+ const status = typeof update.status === "string" ? update.status : kind === "tool_call" ? "pending" : undefined;
+ return kind === "tool_call"
+ ? { kind, toolCallId, name: name ?? toolCallId, status: status ?? "pending" }
+ : { kind, toolCallId, ...(name ? { name } : {}), ...(status ? { status } : {}) };
+ }
+ 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-drivers.test.ts b/lib/agent/acp-drivers.test.ts
new file mode 100644
index 00000000..a444e691
--- /dev/null
+++ b/lib/agent/acp-drivers.test.ts
@@ -0,0 +1,140 @@
+import { afterEach, beforeEach, describe, expect, it } from "vitest";
+import { chmod, mkdtemp, readFile, rm, writeFile } from "node:fs/promises";
+import os from "node:os";
+import path from "node:path";
+import { ACP_DRIVERS, acpDriver, createAcpInstance, describeAcpDriver, probeAcpDriver, requireAcpDriver } from "./acp-drivers";
+import { AcpError } from "./acp-client";
+
+// One fake agent script serves every driver kind: the driver's argv differs, the
+// per-instance env tag differs, and no real CLI ever runs in tests.
+const FAKE = String.raw`#!/usr/bin/env node
+const fs = require("node:fs");
+const tag = process.env.FAKE_ACP_TAG || "x";
+const write = m => process.stdout.write(JSON.stringify(m) + "\n");
+const sessionId = "sess_" + tag;
+let buffer = "";
+const record = line => { if (process.env.FAKE_ACP_LOG) fs.appendFileSync(process.env.FAKE_ACP_LOG, tag + ":" + line + "\n"); };
+function handle(m) {
+ const { id, method } = m;
+ record("in:" + method);
+ if (method === "initialize") return write({ jsonrpc: "2.0", id, result: { protocolVersion: 1, agentCapabilities: { loadSession: false } } });
+ if (method === "authenticate") return write({ jsonrpc: "2.0", id, result: {} });
+ if (method === "session/new") return write({ jsonrpc: "2.0", id, result: { sessionId } });
+ if (method === "session/prompt") {
+ const text = (m.params.prompt[0] || {}).text || "";
+ return write({ jsonrpc: "2.0", id, result: { stopReason: text === "fail" ? "refusal" : "end_turn" } });
+ }
+ if (id !== undefined) write({ jsonrpc: "2.0", id, error: { code: -32601, message: "method not found" } });
+}
+process.stdin.setEncoding("utf8");
+process.stdin.on("data", chunk => {
+ buffer += chunk;
+ for (;;) {
+ const index = buffer.indexOf("\n");
+ if (index < 0) return;
+ const line = buffer.slice(0, index); buffer = buffer.slice(index + 1);
+ if (line.trim()) handle(JSON.parse(line));
+ }
+});
+process.stdin.on("end", () => process.exit(0));
+`;
+
+// Answers `auth_required` on purpose, to prove authenticate happens only on demand.
+const AUTH_AGENT = String.raw`#!/usr/bin/env node
+const fs = require("node:fs");
+const write = m => process.stdout.write(JSON.stringify(m) + "\n");
+let authenticated = false, buffer = "";
+const record = line => { if (process.env.FAKE_ACP_LOG) fs.appendFileSync(process.env.FAKE_ACP_LOG, "auth:" + line + "\n"); };
+function handle(m) {
+ const { id, method } = m;
+ record("in:" + method);
+ if (method === "initialize") return write({ jsonrpc: "2.0", id, result: { protocolVersion: 1, agentCapabilities: {} } });
+ if (method === "authenticate") { authenticated = true; return write({ jsonrpc: "2.0", id, result: {} }); }
+ if (method === "session/new") return authenticated
+ ? write({ jsonrpc: "2.0", id, result: { sessionId: "sess_auth" } })
+ : write({ jsonrpc: "2.0", id, error: { code: -32000, message: "auth_required" } });
+ if (id !== undefined) write({ jsonrpc: "2.0", id, error: { code: -32601, message: "method not found" } });
+}
+process.stdin.setEncoding("utf8");
+process.stdin.on("data", chunk => {
+ buffer += chunk;
+ for (;;) {
+ const index = buffer.indexOf("\n");
+ if (index < 0) return;
+ const line = buffer.slice(0, index); buffer = buffer.slice(index + 1);
+ if (line.trim()) handle(JSON.parse(line));
+ }
+});
+process.stdin.on("end", () => process.exit(0));
+`;
+
+let root: string, agent: string, authAgent: string, log: string;
+beforeEach(async () => {
+ root = await mkdtemp(path.join(os.tmpdir(), "mso-acp-drivers-"));
+ agent = path.join(root, "fake-agent"); authAgent = path.join(root, "auth-agent");
+ log = path.join(root, "acp.log");
+ await writeFile(agent, FAKE); await writeFile(authAgent, AUTH_AGENT);
+ await chmod(agent, 0o755); await chmod(authAgent, 0o755);
+ process.env.FAKE_ACP_LOG = log;
+});
+afterEach(async () => { delete process.env.FAKE_ACP_LOG; await rm(root, { recursive: true, force: true }); });
+const logged = async () => { try { return (await readFile(log, "utf8")).split("\n").filter(Boolean); } catch { return []; } };
+
+describe("ACP driver registry", () => {
+ it("ships at least two real driver kinds as DATA with argv arrays, never shell strings", () => {
+ expect(ACP_DRIVERS.length).toBeGreaterThanOrEqual(2);
+ for (const driver of ACP_DRIVERS) {
+ expect(driver).toMatchObject({ id: expect.any(String), displayName: expect.any(String),
+ executable: expect.any(String), installHint: expect.any(String) });
+ expect(Array.isArray(driver.args)).toBe(true);
+ expect(driver.args.every(arg => typeof arg === "string" && !/\s/.test(arg))).toBe(true);
+ }
+ expect(acpDriver("opencode").args).toEqual(["acp"]);
+ expect(() => acpDriver("nope")).toThrow(/acp_driver_unknown/);
+ });
+
+ it("resolves through PATH and fails with a clear not-installed error instead of a spawn ENOENT", () => {
+ expect(describeAcpDriver("opencode", { path: root }))
+ .toMatchObject({ id: "opencode", installed: false, executablePath: null });
+ expect(() => requireAcpDriver("opencode", { path: root })).toThrow(/acp_driver_not_installed:opencode/);
+ // A PATH entry that does contain the executable resolves to its absolute path.
+ expect(describeAcpDriver("opencode", { path: `${root}${path.delimiter}/nonexistent` }).executablePath).toBeNull();
+ });
+
+ it("never authenticates and never creates a session during an availability probe", async () => {
+ const probe = await probeAcpDriver("opencode", { executablePath: agent });
+ expect(probe).toMatchObject({ protocolVersion: 1, loadSession: false });
+ expect(await logged()).toEqual(["x:in:initialize"]);
+ });
+
+ it("keeps two instances of the SAME driver isolated under interleaved requests", async () => {
+ const first = createAcpInstance("opencode", { executablePath: agent, cwd: root, env: { ...process.env, FAKE_ACP_TAG: "one" } });
+ const second = createAcpInstance("opencode", { executablePath: agent, cwd: root, env: { ...process.env, FAKE_ACP_TAG: "two" } });
+ expect(first.id).not.toBe(second.id);
+ expect(first.client).not.toBe(second.client);
+ await Promise.all([first.initialize(), second.initialize()]);
+ const [left, right] = await Promise.all([first.openSession({ cwd: root }), second.openSession({ cwd: root })]);
+ expect([left, right]).toEqual(["sess_one", "sess_two"]);
+ const [a, b] = await Promise.all([first.client.prompt(left, "alpha"), second.client.prompt(right, "fail")]);
+ // Different stop reasons from two children: no cross-talk between instances.
+ expect([a, b]).toEqual(["end_turn", "refusal"]);
+ first.dispose(); second.dispose();
+ });
+
+ it("authenticates only after the agent answers auth_required, then retries the session", async () => {
+ const instance = createAcpInstance("opencode", { executablePath: authAgent, cwd: root });
+ await instance.initialize();
+ expect(await logged()).toEqual(["auth:in:initialize"]);
+ expect(await instance.openSession({ cwd: root })).toBe("sess_auth");
+ expect(await logged()).toEqual(["auth:in:initialize", "auth:in:session/new", "auth:in:authenticate", "auth:in:session/new"]);
+ instance.dispose();
+ });
+
+ it("propagates a non-auth session failure instead of retrying it as a login", async () => {
+ const instance = createAcpInstance("opencode", { executablePath: agent, cwd: root });
+ await instance.initialize();
+ instance.client.abort(new Error("gone"));
+ await expect(instance.openSession({ cwd: root })).rejects.toBeInstanceOf(AcpError);
+ instance.dispose();
+ });
+});
diff --git a/lib/agent/acp-drivers.ts b/lib/agent/acp-drivers.ts
new file mode 100644
index 00000000..ba7b5961
--- /dev/null
+++ b/lib/agent/acp-drivers.ts
@@ -0,0 +1,131 @@
+import { accessSync, constants, statSync } from "node:fs";
+import path from "node:path";
+import { randomUUID } from "node:crypto";
+import { AcpClient, AcpError, type AcpClientOptions, type AcpInitializeResult } from "./acp-client";
+
+// Driver + instance registry. Following t3code: a DRIVER KIND is data (how to launch an
+// integration), an INSTANCE is one configuration + account lifecycle and owns its own
+// child. Work routes through an instance, never through a driver kind, so two accounts
+// on the same CLI cannot share a process, session or mutable state.
+
+export interface AcpDriver {
+ id: string;
+ displayName: string;
+ /** Executable name resolved through PATH; never a shell string. */
+ executable: string;
+ /** Fixed argv. Nothing user-supplied is ever concatenated into it. */
+ args: readonly string[];
+ /** Auth method id to use ONLY when the agent answers `auth_required` (-32000). */
+ authenticateMethodId?: string;
+ /** Documented ACP entry point, printed by `mso` diagnostics and the not-installed error. */
+ installHint: string;
+}
+
+// Both drivers were verified on this host: `opencode acp` and `hermes-acp` answer
+// `initialize` with protocolVersion 1. Codex and Claude Code do not expose ACP, so a
+// "codex" driver here would be a lie about the wire protocol.
+export const ACP_DRIVERS: readonly AcpDriver[] = [
+ { id: "opencode", displayName: "OpenCode", executable: "opencode", args: ["acp"], authenticateMethodId: "opencode-login",
+ installHint: "opencode — install from https://opencode.ai" },
+ { id: "hermes", displayName: "Hermes Agent", executable: "hermes-acp", args: [],
+ installHint: "hermes-acp — install Hermes Agent with its ACP adapter" },
+];
+
+export function acpDriver(id: string): AcpDriver {
+ const driver = ACP_DRIVERS.find(row => row.id === id);
+ if (!driver) throw new AcpError("acp_driver_unknown", 422);
+ return driver;
+}
+
+export interface AcpDriverInfo {
+ id: string; displayName: string; installed: boolean; executablePath: string | null;
+ args: readonly string[]; authenticateMethodId?: string; installHint: string;
+}
+
+/** PATH lookup without spawning: a missing binary is a clear "not installed", not ENOENT. */
+function which(executable: string, envPath = process.env.PATH ?? ""): string | null {
+ if (executable.includes("/")) {
+ try { return statSync(executable).isFile() ? executable : null; } catch { return null; }
+ }
+ for (const dir of envPath.split(path.delimiter).filter(Boolean)) {
+ const candidate = path.join(dir, executable);
+ try { accessSync(candidate, constants.X_OK); if (statSync(candidate).isFile()) return candidate; } catch { /* next */ }
+ }
+ return null;
+}
+
+/**
+ * Data-only availability: resolves the executable and reports it. Deliberately does
+ * NOT spawn, so it cannot authenticate and cannot create a session — setup must never
+ * be a health-check side effect (session/new may start MCP servers or a login browser).
+ */
+export function describeAcpDriver(id: string, options: { path?: string } = {}): AcpDriverInfo {
+ const driver = acpDriver(id), executablePath = which(driver.executable, options.path);
+ return { id: driver.id, displayName: driver.displayName, installed: executablePath !== null, executablePath,
+ args: driver.args, ...(driver.authenticateMethodId ? { authenticateMethodId: driver.authenticateMethodId } : {}),
+ installHint: driver.installHint };
+}
+
+export function requireAcpDriver(id: string, options: { path?: string } = {}): { driver: AcpDriver; executablePath: string } {
+ const info = describeAcpDriver(id, options);
+ if (!info.executablePath) throw new AcpError(`acp_driver_not_installed:${id}:${info.installHint}`, 501);
+ return { driver: acpDriver(id), executablePath: info.executablePath };
+}
+
+/**
+ * One live instance: opaque id, one driver kind, one child process, its own session.
+ * There is no shared map inside the client, so interleaved requests on two instances
+ * cannot cross-talk.
+ */
+export interface AcpInstance {
+ readonly id: string;
+ readonly driverId: string;
+ readonly client: AcpClient;
+ /** Handshake only. Never authenticates and never creates a session. */
+ initialize(): Promise<AcpInitializeResult>;
+ /** Opens a session; authenticates only if the agent answers `auth_required`. */
+ openSession(input: { cwd: string }): Promise<string>;
+ dispose(): void;
+}
+
+export interface CreateInstanceOptions extends Omit<AcpClientOptions, "command" | "args"> {
+ /** Overrides PATH resolution (tests inject a fake agent here). */
+ executablePath?: string;
+ path?: string;
+}
+
+export function createAcpInstance(driverId: string, options: CreateInstanceOptions = {}): AcpInstance {
+ const driver = acpDriver(driverId);
+ const executablePath = options.executablePath ?? requireAcpDriver(driverId, { path: options.path }).executablePath;
+ const client = new AcpClient({ ...options, command: executablePath, args: driver.args });
+ return {
+ id: `acp_${randomUUID()}`, driverId, client,
+ initialize: () => client.initialize(),
+ async openSession(input) {
+ const create = () => client.newSession({ cwd: input.cwd });
+ try { return await create(); }
+ catch (error) {
+ // -32000 is `auth_required`. Authenticate ONCE, only because the agent asked.
+ if (!(error instanceof AcpError) || !error.message.includes(":-32000:") || !driver.authenticateMethodId) throw error;
+ await client.authenticate(driver.authenticateMethodId);
+ return create();
+ }
+ },
+ dispose: () => client.dispose(),
+ };
+}
+
+/** Initialize-only handshake: proves the protocol without creating a session. */
+export async function probeAcpDriver(driverId: string, options: { path?: string; executablePath?: string } = {}): Promise<{
+ driver: AcpDriverInfo; agent: AcpInitializeResult["agentInfo"]; protocolVersion: number; loadSession: boolean;
+}> {
+ const info = describeAcpDriver(driverId, { path: options.path });
+ const executablePath = options.executablePath ?? info.executablePath;
+ if (!executablePath) throw new AcpError(`acp_driver_not_installed:${driverId}:${info.installHint}`, 501);
+ const client = new AcpClient({ command: executablePath, args: acpDriver(driverId).args });
+ try {
+ const result = await client.initialize();
+ return { driver: info, agent: result.agentInfo, protocolVersion: result.protocolVersion,
+ loadSession: result.agentCapabilities?.loadSession === true };
+ } finally { client.dispose(); }
+}
diff --git a/lib/agent/acp-runtime.test.ts b/lib/agent/acp-runtime.test.ts
new file mode 100644
index 00000000..3765224b
--- /dev/null
+++ b/lib/agent/acp-runtime.test.ts
@@ -0,0 +1,185 @@
+import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
+import { chmod, mkdtemp, rm, writeFile } from "node:fs/promises";
+import os from "node:os";
+import path from "node:path";
+import type { AgentProfile, AgentProfileConfig } from "@/lib/contracts/agent-profile";
+import type { AcpPermissionRequest } from "./acp-client";
+
+const mock = vi.hoisted(() => ({ create: vi.fn(), event: vi.fn(), history: vi.fn() }));
+vi.mock("./session-store", () => ({ createAgentSession: mock.create, appendAgentSessionEvent: mock.event, updateAgentSessionHistory: mock.history }));
+
+const { ACP_PROFILE_RUN_TIMEOUT_MS, acpRunStatus, runAcpAgentProfile } = await import("./acp-runtime");
+const { createAcpInstance } = await import("./acp-drivers");
+const { AcpError } = await import("./acp-client");
+const { parseProfileConfig, validateProfileStore } = await import("./profile-schema");
+
+// Real child process, same seam production uses: explicit argv + shell:false.
+const FAKE = String.raw`#!/usr/bin/env node
+const write = m => process.stdout.write(JSON.stringify(m) + "\n");
+const updates = JSON.parse(process.env.FAKE_ACP_UPDATES || "[]");
+let buffer = "";
+function handle(m) {
+ const { id, method } = m;
+ if (method === "initialize") return write({ jsonrpc: "2.0", id, result: { protocolVersion: 1, agentCapabilities: {} } });
+ if (method === "session/new") return write({ jsonrpc: "2.0", id, result: { sessionId: "sess_run" } });
+ if (method === "session/prompt") {
+ for (const update of updates) write({ jsonrpc: "2.0", method: "session/update", params: { sessionId: "sess_run", update } });
+ if (process.env.FAKE_ACP_PERMISSION) write({ jsonrpc: "2.0", id: 9001, method: "session/request_permission",
+ params: { sessionId: "sess_run", toolCall: { toolCallId: "t1" },
+ options: [{ optionId: "once", kind: "allow_once", name: "Once" }, { optionId: "no", kind: "reject_once", name: "No" }] } });
+ return write({ jsonrpc: "2.0", id, result: { stopReason: process.env.FAKE_ACP_STOP || "end_turn" } });
+ }
+ if (id !== undefined) write({ jsonrpc: "2.0", id, error: { code: -32601, message: "method not found" } });
+}
+process.stdin.setEncoding("utf8");
+process.stdin.on("data", chunk => {
+ buffer += chunk;
+ for (;;) {
+ const index = buffer.indexOf("\n");
+ if (index < 0) return;
+ const line = buffer.slice(0, index); buffer = buffer.slice(index + 1);
+ if (line.trim()) handle(JSON.parse(line));
+ }
+});
+process.stdin.on("end", () => process.exit(0));
+`;
+
+let root: string, agent: string;
+const owner = "web:aaaaaaaaaaaaaaaa";
+const profile = (config: Partial<AgentProfileConfig> = {}): AgentProfile => ({
+ id: "profile_00000000-0000-0000-0000-000000000001", owner, revision: 3,
+ createdAt: "2026-01-01T00:00:00.000Z", updatedAt: "2026-01-01T00:00:00.000Z", enabled: true, history: [],
+ config: { name: "ACP reader", avatar: "", instructions: "Be brief.", runtime: "acp-cli",
+ model: { provider: "selected-account", model: "exact-model" }, tools: [], acp: { driver: "opencode" }, ...config },
+});
+beforeEach(async () => {
+ root = await mkdtemp(path.join(os.tmpdir(), "mso-acp-run-"));
+ agent = path.join(root, "acp-agent"); await writeFile(agent, FAKE); await chmod(agent, 0o755);
+ Object.values(mock).forEach(fn => fn.mockReset());
+ mock.create.mockResolvedValue({ id: "run-fixture" }); mock.event.mockResolvedValue(undefined); mock.history.mockResolvedValue(undefined);
+});
+afterEach(async () => { await rm(root, { recursive: true, force: true }); });
+
+const instance = (env: Record<string, string> = {}, config: Partial<AgentProfileConfig> = {}) => ({
+ shared: createAcpInstance("opencode", { executablePath: agent, cwd: root, env: { ...process.env, ...env } }),
+ config });
+function run(input: { env?: Record<string, string>; config?: Partial<AgentProfileConfig>; permissionPolicy?: (request: AcpPermissionRequest) => boolean | Promise<boolean>; liveAuthorization?: () => Promise<void> } = {}) {
+ const { shared, config } = instance(input.env, input.config);
+ return runAcpAgentProfile({ profile: profile(config), prompt: "Inspect source", principal: owner,
+ signal: new AbortController().signal, liveAuthorization: input.liveAuthorization ?? vi.fn().mockResolvedValue(undefined),
+ resolveInstance: () => shared, ...(input.permissionPolicy ? { permissionPolicy: input.permissionPolicy } : {}) })
+ .finally(() => shared.dispose());
+}
+
+describe("ACP profile runtime bridge", () => {
+ it("returns the SAME AgentProfileRunResult shape the mso-readonly runtime returns", async () => {
+ const result = await run({ env: { FAKE_ACP_UPDATES: JSON.stringify([
+ { sessionUpdate: "agent_message_chunk", content: { type: "text", text: "Verified " } },
+ { sessionUpdate: "agent_message_chunk", content: { type: "text", text: "source" } },
+ { sessionUpdate: "tool_call", toolCallId: "t1", name: "fs_read", status: "pending" },
+ { sessionUpdate: "tool_call_update", toolCallId: "t1", status: "completed" },
+ { sessionUpdate: "tool_call", toolCallId: "t2", name: "fs_search", status: "in_progress" }]) } });
+ expect(result).toEqual({ runId: "run-fixture", profileId: profile().id, profileRevision: 3,
+ model: { provider: "selected-account", model: "exact-model" }, status: "completed", text: "Verified source",
+ rounds: 1, toolCalls: [{ name: "fs_read", ok: true }, { name: "fs_search", ok: false }] });
+ expect(mock.history).toHaveBeenCalledWith(owner, "run-fixture",
+ [{ role: "user", text: "Inspect source" }, { role: "assistant", text: "Verified source" }]);
+ expect(mock.event).toHaveBeenLastCalledWith(owner, "run-fixture", expect.objectContaining({ state: "completed" }));
+ });
+
+ it("maps refusal, cancellation and max_tokens to partial — never completed", async () => {
+ expect(acpRunStatus("end_turn")).toBe("completed");
+ expect(acpRunStatus("refusal")).toBe("partial");
+ expect(acpRunStatus("cancelled")).toBe("partial");
+ expect(acpRunStatus("max_tokens")).toBe("partial");
+ expect((await run({ env: { FAKE_ACP_STOP: "refusal" } })).status).toBe("partial");
+ expect((await run({ env: { FAKE_ACP_STOP: "cancelled" } })).status).toBe("partial");
+ });
+
+ it("treats a denied permission request as a partial turn, not a completed one", async () => {
+ // No permissionPolicy at all: the client denies, so the run cannot report success.
+ expect((await run({ env: { FAKE_ACP_PERMISSION: "1" } })).status).toBe("partial");
+ });
+
+ it("allows only when a narrow policy approves, and records the outcome the agent reported", async () => {
+ const policy = vi.fn(async (_request: AcpPermissionRequest) => true);
+ const result = await run({ env: { FAKE_ACP_PERMISSION: "1",
+ FAKE_ACP_UPDATES: JSON.stringify([{ sessionUpdate: "tool_call", toolCallId: "t1", name: "fs_read", status: "completed" }]) },
+ permissionPolicy: policy });
+ expect(policy).toHaveBeenCalledOnce();
+ expect(result).toMatchObject({ status: "completed", toolCalls: [{ name: "fs_read", ok: true }] });
+ });
+
+ it("keeps the existing authority chain live before and after the turn", async () => {
+ const liveAuthorization = vi.fn().mockResolvedValue(undefined);
+ await run({ liveAuthorization });
+ expect(liveAuthorization.mock.calls.length).toBeGreaterThanOrEqual(4);
+ });
+
+ it("withholds the final answer when authority is withdrawn after the turn", async () => {
+ const liveAuthorization = vi.fn().mockResolvedValueOnce(undefined).mockResolvedValueOnce(undefined)
+ .mockResolvedValueOnce(undefined).mockRejectedValue(new Error("profile_owner_session_revoked"));
+ await expect(run({ liveAuthorization })).rejects.toThrow("profile_owner_session_revoked");
+ expect(mock.event).toHaveBeenLastCalledWith(owner, "run-fixture", expect.objectContaining({ state: "failed" }));
+ });
+
+ it("refuses an acp-cli profile with no driver reference", async () => {
+ const { acp: _acp, ...withoutAcp } = profile().config;
+ void _acp;
+ await expect(runAcpAgentProfile({ profile: { ...profile(), config: withoutAcp as AgentProfileConfig }, prompt: "x",
+ principal: owner, signal: new AbortController().signal, liveAuthorization: async () => undefined }))
+ .rejects.toThrow("profile_runtime_unsupported");
+ });
+
+ it("reports a not-installed or unknown driver clearly, without spawning a real CLI", async () => {
+ // ACP bound is stated per runtime and is NOT the mso-readonly 60s bound.
+ expect(ACP_PROFILE_RUN_TIMEOUT_MS).toBe(600_000);
+ await expect(runAcpAgentProfile({ profile: profile({ acp: { driver: "not-a-driver" } }), prompt: "x",
+ principal: owner, signal: new AbortController().signal, liveAuthorization: async () => undefined }))
+ .rejects.toBeInstanceOf(AcpError);
+ });
+});
+
+describe("profile config backward compatibility", () => {
+ const old = { name: "Reader", avatar: "", instructions: "Show findings.", runtime: "mso-readonly",
+ model: { provider: "selected-account", model: "exact-model" }, tools: ["fs_read"] };
+
+ it("still parses an existing mso-readonly config to the byte-identical old shape", () => {
+ // No `acp` key is invented for an old config.
+ expect(parseProfileConfig(old)).toEqual(old);
+ expect(JSON.stringify(parseProfileConfig(old))).toBe(JSON.stringify(old));
+ });
+
+ it("still rejects exactly what it rejected before: secrets, stronger runtimes, unknown fields", () => {
+ expect(() => parseProfileConfig({ ...old, apiKey: "x" })).toThrow("unsupported_profile_field");
+ expect(() => parseProfileConfig({ ...old, runtime: "acp" })).toThrow("profile_runtime_unsupported");
+ expect(() => parseProfileConfig({ ...old, runtime: "shell" })).toThrow("profile_runtime_unsupported");
+ expect(() => parseProfileConfig({ ...old, acp: { driver: "opencode" } })).toThrow("unsupported_profile_field");
+ expect(() => parseProfileConfig({ ...old, tools: ["exec_run"] })).toThrow("profile_tool_unsupported");
+ expect(() => parseProfileConfig({ ...old, model: { ...old.model, token: "x" } })).toThrow("unsupported_profile_field");
+ });
+
+ it("validates a stored old-shape profile after the new runtime kind was added", () => {
+ const at = "2026-01-01T00:00:00.000Z";
+ const store = { version: 1 as const, revision: 1, defaultProfileId: "profile_00000000-0000-0000-0000-000000000001",
+ profiles: [{ id: "profile_00000000-0000-0000-0000-000000000001", owner, revision: 1, createdAt: at, updatedAt: at,
+ enabled: true, config: old, history: [{ revision: 1, at, actor: owner, action: "create" as const, reason: "First", config: old, enabled: true }] }] };
+ expect(validateProfileStore(store, owner)).toEqual(store);
+ });
+
+ it("accepts the new acp-cli runtime with its driver reference, and keeps tools honest", () => {
+ const accepted = parseProfileConfig({ ...old, runtime: "acp-cli", tools: [], acp: { driver: "opencode" } });
+ expect(accepted).toMatchObject({ runtime: "acp-cli", acp: { driver: "opencode" }, tools: [] });
+ expect(parseProfileConfig({ ...old, runtime: "acp-cli", tools: [], acp: { driver: "opencode", instance: "acp_abc-123" } }).acp)
+ .toEqual({ driver: "opencode", instance: "acp_abc-123" });
+ // An ACP agent owns its own tools; MSO must not also promise saved read tools.
+ expect(() => parseProfileConfig({ ...old, runtime: "acp-cli", acp: { driver: "opencode" } })).toThrow("profile_tool_unsupported");
+ expect(() => parseProfileConfig({ ...old, runtime: "acp-cli", tools: [] })).toThrow("profile_acp_required");
+ expect(() => parseProfileConfig({ ...old, runtime: "acp-cli" })).toThrow("profile_acp_required");
+ expect(() => parseProfileConfig({ ...old, runtime: "acp-cli", tools: [], acp: { driver: "../etc" } })).toThrow("invalid_profile_acp_driver");
+ expect(() => parseProfileConfig({ ...old, runtime: "acp-cli", tools: [], acp: { driver: "opencode", instance: "x" } }))
+ .toThrow("invalid_profile_acp_instance");
+ expect(() => parseProfileConfig({ ...old, runtime: "acp-cli", tools: [], acp: { driver: "opencode", token: "x" } }))
+ .toThrow("unsupported_profile_field");
+ });
+});
diff --git a/lib/agent/acp-runtime.ts b/lib/agent/acp-runtime.ts
new file mode 100644
index 00000000..cdde3e12
--- /dev/null
+++ b/lib/agent/acp-runtime.ts
@@ -0,0 +1,117 @@
+import type { AgentProfile, AgentProfileRunResult } from "@/lib/contracts/agent-profile";
+import { type AcpPermissionPolicy, type AcpPermissionRequest, type AcpSessionUpdate } from "./acp-client";
+import { createAcpInstance, type AcpInstance } from "./acp-drivers";
+import { AgentProfileError } from "./profile-schema";
+import { appendAgentSessionEvent, createAgentSession, updateAgentSessionHistory } from "./session-store";
+
+// Bridge from a saved profile to an INSTALLED agent CLI over ACP.
+//
+// Additive by design: `mso-readonly` keeps its own 60s bound and its own result path in
+// profile-runtime.ts. An ACP turn legitimately runs far longer — the CLI owns a whole
+// model + tool loop — so its ceiling is stated here, per runtime, and is NEVER derived
+// from the old 60s one.
+export const ACP_PROFILE_RUN_TIMEOUT_MS = 10 * 60_000;
+
+/** ACP stop reasons mapped honestly: only a clean end of turn is `completed`. */
+export function acpRunStatus(stopReason: string): "completed" | "partial" {
+ return stopReason === "end_turn" ? "completed" : "partial";
+}
+
+export interface AcpProfileRunInput {
+ profile: AgentProfile;
+ prompt: string;
+ /** Server-derived owner principal, never a client value. */
+ principal: string;
+ signal: AbortSignal;
+ /** The existing authority chain: owner grant + saved revision re-read. */
+ liveAuthorization: () => Promise<void>;
+ /** Optional narrow allow policy. Without one the agent's requests are all denied. */
+ permissionPolicy?: AcpPermissionPolicy;
+ cwd?: string;
+ /** Test seam: production spawns one isolated instance per run. */
+ resolveInstance?: (driver: string) => AcpInstance | undefined;
+}
+
+/**
+ * What one turn observed. Everything here comes from `session/update` the agent really
+ * sent: nothing is assumed about tool names, and a call the agent never reported as
+ * `completed` is not a success.
+ */
+interface TurnTape {
+ text: string;
+ denied: boolean;
+ calls: Map<string, { name: string; status: string }>;
+}
+
+function tape(update: AcpSessionUpdate, state: TurnTape): void {
+ if (update.kind === "agent_message") state.text += update.text;
+ else if (update.kind === "tool_call") state.calls.set(update.toolCallId, { name: update.name, status: update.status });
+ else if (update.kind === "tool_call_update") {
+ const previous = state.calls.get(update.toolCallId);
+ state.calls.set(update.toolCallId, { name: update.name ?? previous?.name ?? update.toolCallId,
+ status: update.status ?? previous?.status ?? "pending" });
+ }
+}
+
+/** Denial is recorded, not inferred: every unapproved permission is a partial turn. */
+function recordingPolicy(state: TurnTape, policy?: AcpPermissionPolicy): AcpPermissionPolicy {
+ return async (request: AcpPermissionRequest) => {
+ const allow = policy ? (await policy(request)) === true : false;
+ if (!allow) state.denied = true;
+ return allow;
+ };
+}
+
+export async function runAcpAgentProfile(input: AcpProfileRunInput): Promise<AgentProfileRunResult> {
+ const { profile } = input, ref = profile.config.acp;
+ if (profile.config.runtime !== "acp-cli" || !ref) throw new AgentProfileError("profile_runtime_unsupported", 422);
+ await input.liveAuthorization();
+ const run = await createAgentSession(input.principal, "alfa", { title: profile.config.name, titleSource: "manual",
+ memorySnapshot: { capturedAt: new Date().toISOString(), user: "", memory: "", schemaVersion: 1, recordCount: 0 } });
+ const controller = new AbortController(), state: TurnTape = { text: "", denied: false, calls: new Map() };
+ const signal = AbortSignal.any([input.signal, controller.signal]);
+ // Per-runtime ceiling; abort kills the child's whole process group, not just the turn.
+ const timer = setTimeout(() => controller.abort(new AgentProfileError("profile_run_timeout", 504)), ACP_PROFILE_RUN_TIMEOUT_MS);
+ const injected = input.resolveInstance?.(ref.driver);
+ const instance = injected ?? createAcpInstance(ref.driver, { cwd: input.cwd ?? process.cwd(), signal });
+ // A run owns its own sink and its own gate, even on a shared instance: without an
+ // explicit allow policy the gate denies, so nothing is ever implicitly approved.
+ // ponytail: a turn swaps the shared client's sink/gate in place; fine because
+ // production gives every run its own instance. Add per-turn sessions if a shared
+ // instance ever needs concurrent turns.
+ instance.client.onUpdate = update => tape(update, state);
+ instance.client.permissionPolicy = recordingPolicy(state, input.permissionPolicy);
+ try {
+ await instance.initialize();
+ await input.liveAuthorization();
+ const sessionId = await instance.openSession({ cwd: input.cwd ?? process.cwd() });
+ await input.liveAuthorization();
+ const stopReason = await instance.client.prompt(sessionId, promptText(profile, input.prompt));
+ await input.liveAuthorization();
+ signal.throwIfAborted();
+ const status = state.denied ? "partial" : acpRunStatus(stopReason);
+ const toolCalls = [...state.calls.values()].map(call => ({ name: call.name, ok: call.status === "completed" }));
+ await updateAgentSessionHistory(input.principal, run.id, history(input.prompt, state.text));
+ await appendAgentSessionEvent(input.principal, run.id, { kind: "note", state: status, detail: `Profile ${profile.id}, revision ${profile.revision}; ACP ${ref.driver} ${stopReason}` });
+ await input.liveAuthorization();
+ signal.throwIfAborted();
+ return { runId: run.id, profileId: profile.id, profileRevision: profile.revision, model: profile.config.model,
+ status, text: state.text, rounds: 1, toolCalls };
+ } catch (error) {
+ await appendAgentSessionEvent(input.principal, run.id, { kind: "note", state: "failed",
+ detail: `Profile ${profile.id}, revision ${profile.revision}; task stopped` }).catch(() => undefined);
+ throw controller.signal.aborted ? controller.signal.reason : error;
+ } finally {
+ clearTimeout(timer);
+ if (!injected) instance.dispose();
+ }
+}
+
+function promptText(profile: AgentProfile, prompt: string): string {
+ const instructions = profile.config.instructions.trim();
+ return instructions ? `${instructions}\n\n${prompt}` : prompt;
+}
+
+function history(prompt: string, text: string) {
+ return [{ role: "user", text: prompt }, { role: "assistant", text }];
+}
diff --git a/lib/agent/profile-runtime.ts b/lib/agent/profile-runtime.ts
index 15f59a32..fbe989ad 100644
--- a/lib/agent/profile-runtime.ts
+++ b/lib/agent/profile-runtime.ts
@@ -8,6 +8,8 @@ import { createAgentSession, updateAgentSessionHistory, appendAgentSessionEvent
import { AgentProfileError, profileFields, profileObject, profilePrincipal, profileRevision, profileText } from "./profile-schema";
import { requireAgentProfile } from "./profile-store";
import { runBoundedAgent } from "./bounded-runner";
+import { runAcpAgentProfile } from "./acp-runtime";
+import type { AcpInstance } from "./acp-drivers";
export function profileRuntimeAuthority(session: SessionPayload, profile: AgentProfile, capabilities: CapabilityRuntime, options: { signal?: AbortSignal; sessionId?: string } = {}) {
if (!session.device_id) throw new AgentProfileError("profile_owner_unsupported", 403);
@@ -37,7 +39,7 @@ export function profileRuntimeAuthority(session: SessionPayload, profile: AgentP
return { runtime, context, liveAuthorization };
}
-export async function runAgentProfile(input: { session: SessionPayload; body: unknown; capabilities: CapabilityRuntime; signal: AbortSignal }): Promise<AgentProfileRunResult> {
+export async function runAgentProfile(input: { session: SessionPayload; body: unknown; capabilities: CapabilityRuntime; signal: AbortSignal; resolveAcpInstance?: (driver: string) => AcpInstance | undefined }): Promise<AgentProfileRunResult> {
if (!input.session.device_id) throw new AgentProfileError("profile_owner_unsupported", 403);
const body = profileObject(input.body); profileFields(body, ["profileId", "profileRevision", "prompt"]);
const principal = profilePrincipal(`web:${input.session.device_id}`), revision = profileRevision(body.profileRevision);
@@ -46,6 +48,13 @@ export async function runAgentProfile(input: { session: SessionPayload; body: un
input.signal.throwIfAborted();
if (!await liveSessionAuthorized(input.session, "owner")) throw new AgentProfileError("profile_owner_session_revoked", 403);
const profile = await requireAgentProfile(principal, id, revision);
+ // `acp-cli` hands the turn to an installed agent CLI and owns its own, longer bound.
+ // The `mso-readonly` path below keeps its unchanged 60s bound.
+ if (profile.config.runtime === "acp-cli") {
+ const authority = profileRuntimeAuthority(input.session, profile, input.capabilities, { signal: input.signal });
+ return runAcpAgentProfile({ profile, prompt, principal, signal: input.signal, liveAuthorization: authority.liveAuthorization,
+ ...(input.resolveAcpInstance ? { resolveInstance: input.resolveAcpInstance } : {}) });
+ }
const controller = new AbortController(), timeout = setTimeout(() => controller.abort(new AgentProfileError("profile_run_timeout", 504)), 60_000);
const signal = AbortSignal.any([input.signal, controller.signal]);
let runId: string | undefined;
diff --git a/lib/agent/profile-schema.ts b/lib/agent/profile-schema.ts
index ab8f2ec4..a64eae22 100644
--- a/lib/agent/profile-schema.ts
+++ b/lib/agent/profile-schema.ts
@@ -24,15 +24,35 @@ export function profileRevision(raw: unknown, zero = false): number {
}
export function parseProfileConfig(input: unknown): AgentProfileConfig {
const raw = profileObject(input);
- profileFields(raw, ["name", "avatar", "instructions", "model", "runtime", "tools"]);
- if (raw.runtime !== "mso-readonly") throw new AgentProfileError("profile_runtime_unsupported", 422);
+ profileFields(raw, ["name", "avatar", "instructions", "model", "runtime", "tools", "acp"]);
+ // `mso-readonly` stays accepted verbatim; `acp-cli` hands the turn to an installed
+ // agent CLI over the Agent Client Protocol. Anything else is still unsupported.
+ if (raw.runtime !== "mso-readonly" && raw.runtime !== "acp-cli") throw new AgentProfileError("profile_runtime_unsupported", 422);
+ // An ACP profile must name its driver: the runtime cannot guess which CLI to drive.
+ if (raw.runtime === "acp-cli" && raw.acp === undefined) throw new AgentProfileError("profile_acp_required", 422);
+ const acp = raw.runtime === "acp-cli" ? parseProfileAcp(raw.acp) : undefined;
+ if (acp === undefined && raw.acp !== undefined) throw new AgentProfileError("unsupported_profile_field");
const model = profileObject(raw.model); profileFields(model, ["provider", "model"]);
const provider = profileText(model.provider, "provider", 64), modelId = profileText(model.model, "model", 200);
if (!/^[a-z0-9][a-z0-9-]{0,63}$/.test(provider) || ["constructor", "prototype"].includes(provider) || /\s/.test(modelId)) throw new AgentProfileError("invalid_profile_model");
if (!Array.isArray(raw.tools) || raw.tools.length > PROFILE_READ_TOOLS.length || new Set(raw.tools).size !== raw.tools.length) throw new AgentProfileError("invalid_profile_tools");
if (raw.tools.some((name) => !(PROFILE_READ_TOOLS as readonly unknown[]).includes(name))) throw new AgentProfileError("profile_tool_unsupported", 422);
+ // An ACP agent owns its own tools; MSO must not also promise saved read tools.
+ if (acp && raw.tools.length) throw new AgentProfileError("profile_tool_unsupported", 422);
return { name: profileText(raw.name, "name", 80), avatar: profileText(raw.avatar ?? "", "avatar", 8, true),
- instructions: profileText(raw.instructions ?? "", "instructions", 4000, true), runtime: "mso-readonly", model: { provider, model: modelId }, tools: [...raw.tools] };
+ instructions: profileText(raw.instructions ?? "", "instructions", 4000, true),
+ runtime: acp ? "acp-cli" : "mso-readonly", model: { provider, model: modelId }, tools: [...raw.tools],
+ ...(acp ? { acp } : {}) };
+}
+function parseProfileAcp(input: unknown): NonNullable<AgentProfileConfig["acp"]> {
+ const raw = profileObject(input);
+ profileFields(raw, ["driver", "instance"]);
+ const driver = profileText(raw.driver, "acp_driver", 64);
+ if (!/^[a-z][a-z0-9-]{0,63}$/.test(driver)) throw new AgentProfileError("invalid_profile_acp_driver");
+ if (raw.instance === undefined) return { driver };
+ const instance = profileText(raw.instance, "acp_instance", 80);
+ if (!/^acp_[A-Za-z0-9_-]{1,72}$/.test(instance)) throw new AgentProfileError("invalid_profile_acp_instance");
+ return { driver, instance };
}
export function emptyProfileStore(): AgentProfileStore { return { version: 1, revision: 0, defaultProfileId: null, profiles: [] }; }
export function validateProfileStore(input: unknown, owner: string): AgentProfileStore {
diff --git a/lib/contracts/agent-profile.ts b/lib/contracts/agent-profile.ts
index 97e7b7e2..fa1610d3 100644
--- a/lib/contracts/agent-profile.ts
+++ b/lib/contracts/agent-profile.ts
@@ -2,13 +2,24 @@ export const PROFILE_READ_TOOLS = [
"vps_status", "fs_list", "fs_read", "fs_search", "fs_usage", "projects_list",
"project_get", "project_candidate_search", "project_capabilities",
] as const;
+/** `mso-readonly` is MSO's own HTTP model runtime; `acp-cli` drives an installed agent CLI. */
+export type AgentProfileRuntime = "mso-readonly" | "acp-cli";
+/** Which installed ACP driver + instance a profile runs against. */
+export interface AgentProfileAcpRef {
+ /** Driver kind id from `ACP_DRIVERS` (e.g. "opencode", "hermes"). */
+ driver: string;
+ /** Instance id. Absent means "spawn a fresh isolated instance for this run". */
+ instance?: string;
+}
export interface AgentProfileConfig {
name: string;
avatar: string;
instructions: string;
- runtime: "mso-readonly";
+ runtime: AgentProfileRuntime;
model: { provider: string; model: string };
tools: string[];
+ /** Present only for `runtime: "acp-cli"`. Absent configs keep the old shape. */
+ acp?: AgentProfileAcpRef;
}
export type AgentProfileAction = "create" | "edit" | "clone" | "default" | "enable" | "disable";
export interface AgentProfileRevision {