A self-improving RLM agent for coding workflows and long-running autonomous tasks.
Rust
feat(coding-agent): add ACP mode (#613)
Seth Karten4f88e6a8952c
diff --git a/package-lock.json b/package-lock.jsonindex a78464dfde..f7a9c7c162 100644--- a/package-lock.json+++ b/package-lock.json@@ -34,6 +34,15 @@"node": ">=22.8.0"}},+ "node_modules/@agentclientprotocol/sdk": {+ "version": "1.3.0",+ "resolved": "https://registry.npmjs.org/@agentclientprotocol/sdk/-/sdk-1.3.0.tgz",+ "integrity": "sha512-i3h/efaeuMUFAO1HSfo97QZQnnvMd7wWBYtBsdL6UMZg3a78sk3Ffya5Xu7C7tYsXomXoDXJBAzQF2PcFKAhIQ==",+ "license": "Apache-2.0",+ "peerDependencies": {+ "zod": "^3.25.0 || ^4.0.0"+ }+ },"node_modules/@anthropic-ai/sandbox-runtime": {"version": "0.0.55","resolved": "https://registry.npmjs.org/@anthropic-ai/sandbox-runtime/-/sandbox-runtime-0.0.55.tgz",@@ -5344,6 +5353,7 @@"hasInstallScript": true,"license": "MIT","dependencies": {+ "@agentclientprotocol/sdk": "^1.3.0","@earendil-works/pi-agent-core": "^0.5.1","@earendil-works/pi-ai": "^0.5.1","@earendil-works/pi-tui": "^0.5.1",diff --git a/packages/coding-agent/CHANGELOG.md b/packages/coding-agent/CHANGELOG.mdindex 382e1e1379..e5ece3a80b 100644--- a/packages/coding-agent/CHANGELOG.md+++ b/packages/coding-agent/CHANGELOG.md@@ -2,6 +2,10 @@## [Unreleased]+### Added++- Added `--mode acp`: prime-agent now runs as an Agent Client Protocol agent over NDJSON on stdio, driving an `AgentConnection` in-process. IPython surfaces as an ACP `execute` tool call carrying its cell source, and capabilities ACP has no native concept for (subagents, autonomous gate state, rich IPython MIME output, compaction) travel in a namespaced `ai.primeintellect.prime-agent` `_meta` envelope that vanilla ACP clients ignore.+- Added missing argument hints to /name, /model, /export, and /import in autocomplete.- Fixed `stop` and `rename` rejecting custom daemon socket options.diff --git a/packages/coding-agent/docs/acp.md b/packages/coding-agent/docs/acp.mdnew file mode 100644index 0000000000..a77542597d--- /dev/null+++ b/packages/coding-agent/docs/acp.md@@ -0,0 +1,71 @@+# ACP Mode++ACP mode makes Prime Agent an [Agent Client Protocol](https://agentclientprotocol.com) agent, speaking JSON-RPC 2.0 over newline-delimited JSON on stdin/stdout. Any ACP client — an editor like Zed or VS Code, or an evaluation harness — can drive it without knowing anything Prime Agent-specific.++```bash+prime-agent --mode acp+```++Use ACP mode when something external needs to *drive* a session interactively: prompt, watch tool calls stream, cancel a turn. For batch runs where you want every event dumped and an exit code, [JSON event stream mode](json.md) is a better fit. [RPC mode](rpc.md) remains available and exposes Prime Agent's own richer command surface.++## Transport++- One JSON-RPC message per line on stdout, requests read from stdin.+- stdin stays open for the life of the connection; the agent exits when it closes.+- Diagnostics go to stderr. Never write anything else to stdout, which belongs to the protocol.++## Supported methods++| Method | Notes |+|---|---|+| `initialize` | Returns protocol version, capabilities, and agent info. |+| `session/new` | Creates the session. One session per connection. |+| `session/prompt` | Runs one turn and resolves with a stop reason. |+| `session/cancel` | Notification; aborts the addressed session's turn. |+| `session/close` | Releases the session and frees the connection for a new one. |++One session per connection is a deliberate limit: Prime Agent's underlying session is fixed at process startup, so a second concurrent session would silently share its conversation, working directory, and model. A second `session/new` is refused rather than pretending to isolate. Start another process for a second session.++Likewise `session/prompt` refuses a concurrent turn while one is running, and the working directory cannot be changed after startup — a client-supplied `cwd` that differs from the agent's real one is reported back in `_meta` rather than silently ignored.++## Streamed updates++Session activity arrives as `session/update` notifications:++| Prime Agent activity | ACP update |+|---|---|+| assistant text | `agent_message_chunk` |+| reasoning | `agent_thought_chunk` |+| tool starts | `tool_call` (`in_progress`) |+| tool finishes | `tool_call_update` (`completed` / `failed`) |+| shell output | `tool_call` plus incremental `tool_call_update` |++IPython is Prime Agent's model-facing tool, so a cell is a `tool_call` of kind `execute` whose `rawInput` carries the cell source.++## Prime Agent extensions++Prime Agent has capabilities ACP has no field for: subagents, autonomous quality gates, goals, heartbeats, continual-harness refinement, compaction, and rich IPython output. These travel in a reverse-domain `_meta` envelope:++```json+{+ "sessionUpdate": "session_info_update",+ "_meta": {+ "ai.primeintellect.prime-agent": {+ "subagents": [{ "id": "sub-1", "sessionName": "reviewer", "status": "running" }]+ }+ }+}+```++A standard ACP client ignores `_meta` entirely and still works. A Prime Agent-aware client, or a harness that cares about subagent trees and gate attempts, reads it. Nothing non-standard is ever added to an ACP object root, which the protocol reserves for future fields.++## Stop reasons++`session/prompt` resolves with one of ACP's stop reasons:++- `end_turn` — the turn finished normally.+- `cancelled` — `session/cancel` aborted it.+- `max_tokens` — an autonomous token budget was exhausted.+- `max_turn_requests` — an autonomous turn, continuation, or wall-clock limit stopped the run.++Autonomous quality gates run *inside* a single prompt turn. A failing gate is a continuation, not a stop reason, so the turn resolves only once the gate loop settles. Gate attempts are visible in `_meta` while that happens.diff --git a/packages/coding-agent/docs/docs.json b/packages/coding-agent/docs/docs.jsonindex 8523c0923c..e66d552be3 100644--- a/packages/coding-agent/docs/docs.json+++ b/packages/coding-agent/docs/docs.json@@ -102,6 +102,10 @@"title": "SDK","path": "sdk.md"},+ {+ "title": "ACP Mode",+ "path": "acp.md"+ },{"title": "RPC Mode","path": "rpc.md"diff --git a/packages/coding-agent/docs/index.md b/packages/coding-agent/docs/index.mdindex b7c48290c2..847fd73b63 100644--- a/packages/coding-agent/docs/index.md+++ b/packages/coding-agent/docs/index.md@@ -48,6 +48,7 @@ Public releases are currently installed from versioned release artifacts. The in## Programmatic Usage- [SDK](sdk.md) - embed Prime Agent in Node.js applications.+- [ACP mode](acp.md) - drive Prime Agent from any Agent Client Protocol client.- [RPC mode](rpc.md) - integrate over stdin/stdout JSONL.- [JSON event stream mode](json.md) - print mode with structured events.- [TUI components](tui.md) - build custom terminal UI for extensions.diff --git a/packages/coding-agent/package.json b/packages/coding-agent/package.jsonindex 78cbfc03d3..1fe4d2ea2b 100644--- a/packages/coding-agent/package.json+++ b/packages/coding-agent/package.json@@ -46,6 +46,7 @@"bundle": "node scripts/bundle.mjs"},"dependencies": {+ "@agentclientprotocol/sdk": "^1.3.0","@earendil-works/pi-agent-core": "^0.5.1","@earendil-works/pi-ai": "^0.5.1","@earendil-works/pi-tui": "^0.5.1",@@ -84,10 +85,10 @@"@types/ms": "^2.1.0","@types/node": "^24.3.0","@types/proper-lockfile": "^4.1.4",+ "esbuild": "^0.28.1","shx": "^0.4.0","typescript": "^5.7.3",- "vitest": "^4.1.9",- "esbuild": "^0.28.1"+ "vitest": "^4.1.9"},"keywords": ["coding-agent",diff --git a/packages/coding-agent/src/cli/args.ts b/packages/coding-agent/src/cli/args.tsindex 9b66483932..63eb53f2cf 100644--- a/packages/coding-agent/src/cli/args.ts+++ b/packages/coding-agent/src/cli/args.ts@@ -5,7 +5,7 @@import type { ThinkingLevel } from "@earendil-works/pi-agent-core";import { APP_NAME } from "../config.js";-export type Mode = "text" | "json" | "rpc" | "daemon";+export type Mode = "text" | "json" | "rpc" | "acp" | "daemon";export interface Args {provider?: string;@@ -101,7 +101,7 @@ export function parseArgs(args: string[]): Args {result.version = true;} else if (arg === "--mode" && i + 1 < args.length) {const mode = args[++i];- if (mode === "text" || mode === "json" || mode === "rpc" || mode === "daemon") {+ if (mode === "text" || mode === "json" || mode === "rpc" || mode === "acp" || mode === "daemon") {result.mode = mode;}} else if (arg === "--daemon-socket" && i + 1 < args.length) {diff --git a/packages/coding-agent/src/main.ts b/packages/coding-agent/src/main.tsindex 5614e9d1e0..04b9bb3a9f 100644--- a/packages/coding-agent/src/main.ts+++ b/packages/coding-agent/src/main.ts@@ -93,6 +93,8 @@ import {InProcessAgentConnection,InteractiveMode,resolveAttachModelFallbackMessage,+ runAcpMode,+ runAcpModeWithConnection,runAgentsViewMode,runDaemonMode,runDaemonSupervisorMode,@@ -154,7 +156,7 @@ function isTruthyEnvFlag(value: string | undefined): boolean {return value === "1" || value.toLowerCase() === "true" || value.toLowerCase() === "yes";}-export type ClientMode = "interactive" | "print" | "json" | "rpc";+export type ClientMode = "interactive" | "print" | "json" | "rpc" | "acp";/** Compatibility view of the CLI's internal daemon process entrypoint. */export type AppMode = ClientMode | "daemon";@@ -173,6 +175,9 @@ function resolveAppMode(parsed: Args, stdinIsTTY: boolean): AppMode {if (parsed.mode === "rpc") {return "rpc";}+ if (parsed.mode === "acp") {+ return "acp";+ }if (parsed.mode === "json") {return "json";}@@ -182,7 +187,7 @@ function resolveAppMode(parsed: Args, stdinIsTTY: boolean): AppMode {return "interactive";}-function toPrintOutputMode(appMode: AppMode): Exclude<Mode, "rpc" | "daemon"> {+function toPrintOutputMode(appMode: AppMode): Exclude<Mode, "rpc" | "acp" | "daemon"> {return appMode === "json" ? "json" : "text";}@@ -1319,8 +1324,12 @@ export async function main(args: string[], options?: MainOptions) {const startupModel = await resolvePreparedStartupModel({ prepared, sessionManager });+ // ACP holds stdin open as a long-lived NDJSON request stream, so reading+ // piped stdin here would block until EOF and never return.let stdinContent: string | undefined;- stdinContent = await readPipedStdin();+ if (appMode !== "acp") {+ stdinContent = await readPipedStdin();+ }time("readPipedStdin");const { initialMessage, initialImages } = await prepareInitialMessage(@@ -1483,7 +1492,7 @@ export async function main(args: string[], options?: MainOptions) {if (useDaemonClient) {const settingsManager = SettingsManager.create(sessionManager.getCwd(), agentDir);let stdinContent: string | undefined;- if (appMode !== "rpc") {+ if (appMode !== "rpc" && appMode !== "acp") {stdinContent = await readPipedStdin();}time("readPipedStdin");@@ -1532,6 +1541,9 @@ export async function main(args: string[], options?: MainOptions) {if (appMode === "rpc") {return await runRpcModeWithConnection(connection);}+ if (appMode === "acp") {+ return await runAcpModeWithConnection(connection);+ }const exitCode = await runPrintModeWithConnection(connection, {mode: toPrintOutputMode(appMode),messages: parsed.messages,@@ -1573,7 +1585,7 @@ export async function main(args: string[], options?: MainOptions) {// Read piped stdin content (if any) - skip for RPC/daemon modes which use other transportslet stdinContent: string | undefined;- if (appMode !== "rpc" && appMode !== "daemon") {+ if (appMode !== "rpc" && appMode !== "acp" && appMode !== "daemon") {stdinContent = await readPipedStdin();if (stdinContent !== undefined && appMode === "interactive") {appMode = "print";@@ -1611,6 +1623,9 @@ export async function main(args: string[], options?: MainOptions) {if (appMode === "rpc") {printTimings();await runRpcMode(runtime);+ } else if (appMode === "acp") {+ printTimings();+ await runAcpMode(runtime);} else if (appMode === "interactive") {if (explicitAgentsView) {console.error(chalk.yellow("Warning: the agents view needs the daemon; opening a normal chat instead"));diff --git a/packages/coding-agent/src/modes/acp/acp-events.ts b/packages/coding-agent/src/modes/acp/acp-events.tsnew file mode 100644index 0000000000..c1b4199d90--- /dev/null+++ b/packages/coding-agent/src/modes/acp/acp-events.ts@@ -0,0 +1,309 @@+import type { AssistantMessageEvent } from "@earendil-works/pi-ai";+import type { AgentConnectionSessionEvent } from "../agent-connection/types.js";+import type { PrimeAgentIpythonMeta, PrimeAgentSessionMeta } from "./acp-meta.js";+import { primeAgentMeta } from "./acp-meta.js";++/**+ * Translate prime-agent session events into ACP `session/update` payloads.+ *+ * Kept as a pure function so the mapping is testable without a live ACP client+ * or a running agent. Returning an array lets one prime-agent event fan out to+ * several ACP updates (or none, for events ACP has no place for).+ */++export type AcpToolKind = "read" | "edit" | "delete" | "move" | "search" | "execute" | "think" | "fetch" | "other";+export type AcpToolStatus = "pending" | "in_progress" | "completed" | "failed";++export interface AcpSessionUpdate {+ sessionUpdate: string;+ [key: string]: unknown;+}++/** prime-agent's model-facing tool is IPython; bash is the secondary escape hatch. */+export const IPYTHON_TOOL_NAME = "ipython";++export function acpToolKind(toolName: string): AcpToolKind {+ switch (toolName) {+ case IPYTHON_TOOL_NAME:+ case "bash":+ return "execute";+ case "read":+ return "read";+ case "edit":+ case "write":+ return "edit";+ default:+ return "other";+ }+}++/** Decoded byte length of a base64 payload, without materializing it. */+function base64ByteLength(data: string): number {+ const padding = data.endsWith("==") ? 2 : data.endsWith("=") ? 1 : 0;+ return Math.max(0, Math.floor((data.length * 3) / 4) - padding);+}++function textContent(text: string): { type: "text"; text: string } {+ return { type: "text", text };+}++/**+ * Map one streaming assistant event to an ACP chunk.+ *+ * The delta discriminator lives on the event itself (`text_delta` /+ * `thinking_delta`) and carries a plain string, so reasoning and visible answer+ * text are distinct ACP update kinds a client can render or hide separately.+ */+function assistantDeltaUpdates(event: AssistantMessageEvent): AcpSessionUpdate[] {+ if (event.type === "thinking_delta" && event.delta.length > 0) {+ return [{ sessionUpdate: "agent_thought_chunk", content: textContent(event.delta) }];+ }+ if (event.type === "text_delta" && event.delta.length > 0) {+ return [{ sessionUpdate: "agent_message_chunk", content: textContent(event.delta) }];+ }+ return [];+}++/** Extract the IPython cell source so a client can show what is executing. */+function ipythonCellSource(args: unknown): string | undefined {+ if (!args || typeof args !== "object") return undefined;+ const code = (args as { code?: unknown }).code;+ return typeof code === "string" ? code : undefined;+}++function toolResultText(result: unknown): string | undefined {+ if (typeof result === "string") return result;+ if (!result || typeof result !== "object") return undefined;+ const output = (result as { output?: unknown }).output;+ if (typeof output === "string") return output;+ const content = (result as { content?: unknown }).content;+ if (Array.isArray(content)) {+ const parts = content+ .map((block) =>+ block && typeof block === "object" && (block as { type?: string }).type === "text"+ ? ((block as { text?: string }).text ?? "")+ : "",+ )+ .filter(Boolean);+ if (parts.length > 0) return parts.join("\n");+ }+ return undefined;+}++/**+ * Rich IPython output that ACP has no content type for.+ *+ * The ipython tool reports media and diffs under `details` (images additionally+ * ride along as ACP image content blocks); mirror those exact fields rather than+ * inventing a MIME bundle the tool never produces.+ */+function ipythonRichOutput(result: unknown): PrimeAgentIpythonMeta | undefined {+ if (!result || typeof result !== "object") return undefined;+ const details = (result as { details?: unknown }).details;+ if (!details || typeof details !== "object") return undefined;+ const { attachments, diffs } = details as { attachments?: unknown; diffs?: unknown };+ const meta: PrimeAgentIpythonMeta = {};+ if (Array.isArray(attachments) && attachments.length > 0) {+ meta.attachments = attachments.map((attachment) => {+ // KernelAttachment exposes mimeType, base64 `data`, and an optional path.+ // Report the decoded size rather than a `bytes` field the kernel never+ // sends, and never inline the payload: ACP already carries images as+ // content blocks, so duplicating them here would bloat every update.+ const typed = (attachment ?? {}) as { mimeType?: unknown; path?: unknown; data?: unknown };+ return {+ ...(typeof typed.mimeType === "string" ? { mimeType: typed.mimeType } : {}),+ ...(typeof typed.path === "string" ? { path: typed.path } : {}),+ ...(typeof typed.data === "string" ? { bytes: base64ByteLength(typed.data) } : {}),+ };+ });+ }+ if (Array.isArray(diffs) && diffs.length > 0) meta.diffCount = diffs.length;+ return meta.attachments || meta.diffCount !== undefined ? meta : undefined;+}++/**+ * Correlates streaming bash output with its run.+ *+ * `bash_output` carries no `runId`, so the id of the most recent `bash_start` is+ * tracked here. Output would otherwise be attributed to a bare fallback id that+ * no `bash_start` ever used, leaving the chunks unattached to any tool call.+ */+export interface AcpEventMappingState {+ activeBashRunId?: string;+}++export function acpUpdatesForSessionEvent(+ event: AgentConnectionSessionEvent,+ state: AcpEventMappingState = {},+): AcpSessionUpdate[] {+ switch (event.type) {+ case "message_update":+ if (event.message.role !== "assistant") return [];+ return assistantDeltaUpdates(event.assistantMessageEvent);++ case "tool_execution_start": {+ const cell = event.toolName === IPYTHON_TOOL_NAME ? ipythonCellSource(event.args) : undefined;+ return [+ {+ sessionUpdate: "tool_call",+ toolCallId: event.toolCallId,+ title: event.toolName === IPYTHON_TOOL_NAME ? "IPython cell" : event.toolName,+ kind: acpToolKind(event.toolName),+ status: "in_progress" satisfies AcpToolStatus,+ rawInput: cell !== undefined ? { code: cell } : event.args,+ },+ ];+ }++ case "tool_execution_end": {+ const text = toolResultText(event.result);+ const rich = event.toolName === IPYTHON_TOOL_NAME ? ipythonRichOutput(event.result) : undefined;+ return [+ {+ sessionUpdate: "tool_call_update",+ toolCallId: event.toolCallId,+ status: (event.isError ? "failed" : "completed") satisfies AcpToolStatus,+ ...(text ? { content: [{ type: "content", content: textContent(text) }] } : {}),+ ...(rich ? { _meta: primeAgentMeta({ ipython: rich }) } : {}),+ },+ ];+ }++ // Bash runs outside the tool-call lifecycle, so it gets a synthetic tool+ // call keyed by run id to keep incremental output addressable.+ case "bash_start":+ state.activeBashRunId = event.runId;+ return [+ {+ sessionUpdate: "tool_call",+ toolCallId: bashToolCallId(event.runId),+ title: event.command,+ kind: "execute" satisfies AcpToolKind,+ status: "in_progress" satisfies AcpToolStatus,+ rawInput: { command: event.command },+ },+ ];++ case "bash_output":+ return [+ {+ sessionUpdate: "tool_call_update",+ toolCallId: bashToolCallId(state.activeBashRunId),+ status: "in_progress" satisfies AcpToolStatus,+ content: [{ type: "content", content: textContent(event.chunk) }],+ },+ ];++ case "bash_end":+ if (state.activeBashRunId === event.runId) state.activeBashRunId = undefined;+ return [+ {+ sessionUpdate: "tool_call_update",+ toolCallId: bashToolCallId(event.runId),+ status: (event.exitCode === 0 && !event.cancelled ? "completed" : "failed") satisfies AcpToolStatus,+ },+ ];++ // Compaction, subagents, goals and recaps have no ACP equivalent: surface+ // them as namespaced metadata rather than distorting a standard update.+ case "compaction_end":+ return [+ {+ sessionUpdate: "session_info_update",+ _meta: primeAgentMeta({+ compaction: {+ tokensBefore: event.result?.tokensBefore,+ summary: event.result?.summary,+ },+ }),+ },+ ];++ case "rlm_child_update":+ return [+ {+ sessionUpdate: "session_info_update",+ _meta: primeAgentMeta({+ subagents: [+ {+ id: event.child.id,+ sessionName: event.child.sessionName,+ status: event.child.status,+ model: event.child.model,+ tokenCount: event.child.tokenCount,+ error: event.child.error,+ },+ ],+ }),+ },+ ];++ // Goals, continual-harness refinement, and agent-to-agent messaging are+ // prime-agent concepts with no ACP counterpart. They are still part of a+ // turn's observable behavior, so they surface as namespaced metadata+ // instead of being dropped.+ case "goal_update":+ return [+ {+ sessionUpdate: "session_info_update",+ _meta: primeAgentMeta({+ goal: {+ status: event.goal.status,+ objective: event.goal.objective,+ tokenBudget: event.goal.tokenBudget,+ tokensUsed: event.goal.tokensUsed,+ },+ }),+ },+ ];++ case "refine_complete":+ return [+ {+ sessionUpdate: "session_info_update",+ _meta: primeAgentMeta({+ refinement: {+ status: "complete",+ summary: event.result.summary,+ changes: event.result.appliedEdits+ ?.filter((edit) => edit.applied)+ .map((edit) => `${edit.action} ${edit.kind}:${edit.id}`),+ },+ }),+ },+ ];++ case "refine_failed":+ return [+ {+ sessionUpdate: "session_info_update",+ _meta: primeAgentMeta({ refinement: { status: "failed", error: event.error } }),+ },+ ];++ case "ipython_sent_agent_message":+ return [+ {+ sessionUpdate: "session_info_update",+ _meta: primeAgentMeta({+ agentMessage: {+ toolCallId: event.toolCallId,+ target: event.message.target.sessionName ?? event.message.target.sessionId,+ deliveryStatus: event.message.deliveryStatus,+ },+ }),+ },+ ];++ default:+ return [];+ }+}++const BASH_TOOL_CALL_PREFIX = "prime-agent-bash";++export function bashToolCallId(runId: string | undefined): string {+ return runId ? `${BASH_TOOL_CALL_PREFIX}-${runId}` : BASH_TOOL_CALL_PREFIX;+}++export type { PrimeAgentSessionMeta };diff --git a/packages/coding-agent/src/modes/acp/acp-meta.ts b/packages/coding-agent/src/modes/acp/acp-meta.tsnew file mode 100644index 0000000000..fbe1ff211c--- /dev/null+++ b/packages/coding-agent/src/modes/acp/acp-meta.ts@@ -0,0 +1,95 @@+/**+ * Namespaced `_meta` payloads for prime-agent capabilities that ACP has no+ * native concept for (IPython cell semantics, RLM subagents, autonomous gates,+ * goals, heartbeats, continual harness state).+ *+ * ACP reserves `_meta` on capability objects, notifications, tool calls, and+ * content blocks precisely so agents can carry non-standard data. Vanilla ACP+ * clients ignore these keys; a prime-agent-aware client (or the verifiers+ * harness) reads them. Never add non-standard fields to an ACP object root.+ */++/** Reverse-domain namespace for every prime-agent `_meta` payload. */+export const PRIME_AGENT_META_NAMESPACE = "ai.primeintellect.prime-agent";++export interface PrimeAgentSubagentMeta {+ id: string;+ sessionName?: string;+ status: string;+ model?: string;+ depth?: number;+ tokenCount?: number;+ error?: string;+}++export interface PrimeAgentAutonomousMeta {+ enabled: boolean;+ continuationsUsed: number;+ turnsUsed: number;+ tokensUsed: number;+ gateAttempt?: number;+ gateFailure?: string;+ limitReason?: string;+}++export interface PrimeAgentIpythonAttachmentMeta {+ mimeType?: string;+ path?: string;+ bytes?: number;+}++export interface PrimeAgentIpythonMeta {+ /** Media the cell loaded into context, as reported by the ipython tool. */+ attachments?: PrimeAgentIpythonAttachmentMeta[];+ /** Number of diffs the cell displayed. */+ diffCount?: number;+}++export interface PrimeAgentGoalMeta {+ status: string;+ objective?: string;+ tokenBudget?: number;+ tokensUsed?: number;+}++export interface PrimeAgentRefinementMeta {+ status: "complete" | "failed";+ summary?: string;+ changes?: string[];+ error?: string;+}++export interface PrimeAgentAgentMessageMeta {+ toolCallId: string;+ target?: string;+ deliveryStatus?: string;+}++export interface PrimeAgentCwdMeta {+ /** The cwd the client asked for. */+ requested: string;+ /** The cwd prime-agent is actually running in, fixed at startup. */+ actual: string;+}++export interface PrimeAgentSessionMeta {+ /** Present when a client-requested cwd differs from the agent's real cwd. */+ cwd?: PrimeAgentCwdMeta;+ /** Set when the session's heartbeat or cron schedule changed. */+ heartbeatsChanged?: boolean;+ goal?: PrimeAgentGoalMeta;+ refinement?: PrimeAgentRefinementMeta;+ agentMessage?: PrimeAgentAgentMessageMeta;+ sessionId?: string;+ rlmDepth?: number;+ rlmMaxDepth?: number;+ compaction?: { tokensBefore?: number; summary?: string };+ subagents?: PrimeAgentSubagentMeta[];+ autonomous?: PrimeAgentAutonomousMeta;+ ipython?: PrimeAgentIpythonMeta;+}++/** Wrap a prime-agent payload in its reverse-domain `_meta` envelope. */+export function primeAgentMeta(payload: PrimeAgentSessionMeta): Record<string, unknown> {+ return { [PRIME_AGENT_META_NAMESPACE]: payload };+}diff --git a/packages/coding-agent/src/modes/acp/acp-mode.ts b/packages/coding-agent/src/modes/acp/acp-mode.tsnew file mode 100644index 0000000000..28f4b8650c--- /dev/null+++ b/packages/coding-agent/src/modes/acp/acp-mode.ts@@ -0,0 +1,299 @@+import { randomUUID } from "node:crypto";+import { resolve } from "node:path";+import { Readable } from "node:stream";+import * as acp from "@agentclientprotocol/sdk";+import type { ImageContent } from "@earendil-works/pi-ai";+import { VERSION } from "../../config.js";+import type { AgentSessionRuntime } from "../../core/agent-session-runtime.js";+import type { AgentAutonomousStatus } from "../../core/autonomous.js";+import { takeOverStdout, writeRawStdout } from "../../core/output-guard.js";+import { InProcessAgentConnection } from "../agent-connection/in-process-agent-connection.js";+import type { AgentConnection } from "../agent-connection/types.js";+import { latestAutonomousGateAttempt } from "../headless-completion.js";+import { type AcpEventMappingState, acpUpdatesForSessionEvent } from "./acp-events.js";+import { primeAgentMeta } from "./acp-meta.js";+import { type AcpStopReason, acpStopReason } from "./acp-stop-reason.js";++/**+ * ACP (Agent Client Protocol) mode.+ *+ * prime-agent acts as an ACP agent over NDJSON on stdio, driving an+ * `AgentConnection` in-process. It deliberately does not shell out to RPC mode+ * and translate: prime-agent's differentiators (IPython-only tools, subagents,+ * autonomous gates) are visible as first-class events here, and a translating+ * adapter is exactly what flattens them away.+ *+ * Capabilities ACP has no native concept for travel in a reverse-domain+ * `_meta` envelope, which vanilla ACP clients ignore.+ */++/**+ * ACP frames must reach real stdout.+ *+ * Startup calls `takeOverStdout()` for every non-interactive mode, which+ * redirects `process.stdout.write` to stderr so stray logging cannot corrupt a+ * machine-readable stream. Handing `process.stdout` to the SDK would therefore+ * publish the whole protocol on stderr; write through the raw escape hatch the+ * guard exposes, exactly as RPC mode does.+ */+function rawStdoutSink(): WritableStream<Uint8Array> {+ const decoder = new TextDecoder();+ return new WritableStream<Uint8Array>({+ write(chunk) {+ writeRawStdout(typeof chunk === "string" ? chunk : decoder.decode(chunk, { stream: true }));+ },+ });+}++export interface AcpModeOptions {+ /** Bind headless extensions once the connection is live (in-process mode). */+ bindHeadlessExtensions?: () => Promise<void>;+ /**+ * Transport override. Defaults to NDJSON over stdio; tests supply an+ * in-memory stream pair so the protocol runs without a subprocess.+ */+ stream?: ReturnType<typeof acp.ndJsonStream>;+ /** Skip claiming stdout when the caller supplies its own transport. */+ ownStdout?: boolean;+}++interface AcpSessionEntry {+ id: string;+ abort: AbortController | undefined;+ unsubscribe: (() => void) | undefined;+}++/**+ * Split ACP prompt blocks into the text and images prime-agent accepts.+ *+ * Image and embedded-resource blocks are advertised in `initialize`, so they must+ * actually reach the model: dropping them silently would let a client believe a+ * pasted screenshot was accepted.+ */+function promptContent(blocks: readonly unknown[]): { text: string; images: ImageContent[] } {+ const texts: string[] = [];+ const images: ImageContent[] = [];+ for (const block of blocks) {+ if (!block || typeof block !== "object") continue;+ const typed = block as {+ type?: string;+ text?: string;+ data?: string;+ mimeType?: string;+ uri?: string;+ resource?: { text?: string; uri?: string };+ };+ if (typed.type === "text" && typeof typed.text === "string") {+ texts.push(typed.text);+ } else if (typed.type === "image" && typeof typed.data === "string" && typeof typed.mimeType === "string") {+ images.push({ type: "image", data: typed.data, mimeType: typed.mimeType });+ } else if (typed.type === "resource" && typeof typed.resource?.text === "string") {+ // Embedded text resources become context the model can read.+ const uri = typed.resource.uri ? `${typed.resource.uri}\n` : "";+ texts.push(`${uri}${typed.resource.text}`);+ } else if (typed.type === "resource_link" && typeof typed.uri === "string") {+ texts.push(typed.uri);+ }+ }+ return { text: texts.join("\n"), images };+}++function autonomousMeta(status: AgentAutonomousStatus | undefined): Record<string, unknown> | undefined {+ if (!status?.enabled) return undefined;+ return primeAgentMeta({+ autonomous: {+ enabled: status.enabled,+ continuationsUsed: status.continuationsUsed,+ turnsUsed: status.turnsUsed,+ tokensUsed: status.tokensUsed,+ gateAttempt: latestAutonomousGateAttempt(status) || undefined,+ gateFailure: status.lastGateFailure?.exitText,+ },+ });+}++export async function runAcpMode(runtimeHost: AgentSessionRuntime): Promise<never> {+ const connection = new InProcessAgentConnection(runtimeHost);+ return runAcpModeWithConnection(connection, {+ bindHeadlessExtensions: () => connection.bindHeadlessExtensions({}),+ });+}++export async function runAcpModeWithConnection(+ connection: AgentConnection,+ options: AcpModeOptions = {},+): Promise<never> {+ // ACP owns stdout: any stray write corrupts the JSON-RPC stream.+ if (options.ownStdout !== false && !options.stream) {+ takeOverStdout();+ }++ // One ACP connection drives one AgentConnection, whose newSession() replaces+ // the live session rather than creating a parallel one. Tracking a single+ // session keeps every event unambiguously attributable; a second session/new+ // is refused rather than silently sharing conversation state, cwd, and queues.+ let session: AcpSessionEntry | undefined;+ let bound = false;++ const stream =+ options.stream ?? acp.ndJsonStream(rawStdoutSink(), Readable.toWeb(process.stdin) as ReadableStream<Uint8Array>);++ const handle = acp+ .agent({ name: "prime-agent" })+ .onRequest("initialize", async () => ({+ protocolVersion: acp.PROTOCOL_VERSION,+ agentCapabilities: {+ loadSession: false,+ promptCapabilities: { image: true, embeddedContext: true },+ // Advertise close so a client knows it can release the session (and+ // the single-session slot) instead of dropping the connection.+ sessionCapabilities: { close: {} },+ },+ agentInfo: { name: "prime-agent", title: "Prime Agent", version: VERSION },+ // Advertise prime-agent extras under a namespaced key: ACP reserves+ // every object root for future protocol fields.+ _meta: primeAgentMeta({}),+ }))+ .onRequest("session/new", async (ctx: any) => {+ if (!bound) {+ // Only latch after a successful bind: a rejected bind must not leave+ // extensions permanently unavailable for the rest of the process.+ await options.bindHeadlessExtensions?.();+ bound = true;+ }+ if (session) {+ throw new Error(+ "prime-agent ACP mode hosts one session per connection; " ++ "start another prime-agent process for a second session",+ );+ }+ // prime-agent's cwd is fixed at startup by the session it was launched+ // with, so a client-supplied cwd cannot be adopted after the fact.+ // Report the real cwd back in `_meta` rather than failing the request or+ // letting the client assume a directory the agent is not using.+ const requestedCwd = (ctx.params as { cwd?: unknown } | undefined)?.cwd;+ let cwdMismatch: { requested: string; actual: string } | undefined;+ if (typeof requestedCwd === "string" && requestedCwd.length > 0) {+ const actual = await connection+ .getState()+ .then((state) => state.cwd)+ .catch(() => undefined);+ if (actual && resolve(requestedCwd) !== resolve(actual)) {+ cwdMismatch = { requested: requestedCwd, actual };+ }+ }+ const sessionId = randomUUID();+ const entry: AcpSessionEntry = { id: sessionId, abort: undefined, unsubscribe: undefined };+ // Subscribe for the session lifetime, not per prompt turn: prime-agent+ // subagents are fire-and-forget and keep reporting after the spawning turn+ // ends, so a turn-scoped subscription would drop their updates. One+ // mapping state per session keeps streaming bash output correlated with+ // the run that produced it.+ const mappingState: AcpEventMappingState = {};+ const unsubscribe = connection.subscribe((event) => {+ const notify = (update: Record<string, unknown>) =>+ void ctx.client.notify(acp.methods.client.session.update, { sessionId, update }).catch(() => undefined);+ // Heartbeats and cron schedules are connection-level rather than+ // session events, but they drive the long-running work an ACP client+ // most needs to observe.+ if (event.type === "heartbeats_changed") {+ notify({ sessionUpdate: "session_info_update", _meta: primeAgentMeta({ heartbeatsChanged: true }) });+ return;+ }+ if (event.type !== "session_event") return;+ for (const update of acpUpdatesForSessionEvent(event.event, mappingState)) {+ notify(update);+ }+ });+ // Claim the single-session slot only once the subscription exists, so a+ // failed subscribe cannot leave the slot occupied and unusable.+ entry.unsubscribe = unsubscribe;+ session = entry;+ return {+ sessionId,+ ...(cwdMismatch ? { _meta: primeAgentMeta({ cwd: cwdMismatch }) } : {}),+ };+ })+ .onRequest("session/prompt", async (ctx: any) => {+ const params = ctx.params as { sessionId: string; prompt: readonly unknown[] };+ const entry = session?.id === params.sessionId ? session : undefined;+ if (!entry) throw new Error(`Unknown ACP session: ${params.sessionId}`);++ // ACP allows one turn at a time per session. Refuse a concurrent prompt+ // rather than overwriting the running turn's controller, which would make+ // the live turn uncancellable and let the loser's cleanup clear it.+ if (entry.abort) {+ throw new Error("A prompt turn is already running for this ACP session");+ }+ const abort = new AbortController();+ entry.abort = abort;++ try {+ const { text, images } = promptContent(params.prompt);+ await connection.promptAndWait(text, images.length > 0 ? { images } : undefined);+ // Autonomous gates continue inside this same prompt turn: the turn is+ // only over once the gate loop settles.+ const status = await connection.waitForHeadlessCompletion();+ const meta = autonomousMeta(status);+ if (meta) {+ await ctx.client+ .notify(acp.methods.client.session.update, {+ sessionId: params.sessionId,+ update: { sessionUpdate: "session_info_update", _meta: meta },+ })+ .catch(() => undefined);+ }+ return { stopReason: acpStopReason({ cancelled: abort.signal.aborted, autonomous: status }) };+ } catch (error) {+ // Cancellation is a normal ACP prompt outcome, not a JSON-RPC error.+ if (abort.signal.aborted) return { stopReason: "cancelled" satisfies AcpStopReason };+ throw error;+ } finally {+ // Only clear our own controller: a later turn must not be cleared by+ // an earlier one unwinding.+ if (entry.abort === abort) entry.abort = undefined;+ }+ })+ .onRequest("session/close", async (ctx: any) => {+ // Releasing the subscription matters: it is the only thing that stops+ // forwarding events, and closing frees the connection for a new session.+ const params = ctx.params as { sessionId: string };+ if (session?.id !== params.sessionId) {+ throw new Error(`Unknown ACP session: ${params.sessionId}`);+ }+ // Stop real work, not just local bookkeeping: aborting only the local+ // controller leaves the agent running with nobody listening, so closing+ // must abort the connection the same way session/cancel does.+ const closing = session;+ session = undefined;+ closing.unsubscribe?.();+ if (closing.abort) {+ closing.abort.abort();+ await connection.abort().catch(() => undefined);+ }+ return {};+ })+ .onNotification("session/cancel", async (ctx: any) => {+ const params = ctx.params as { sessionId: string };+ // Only cancel the addressed session: aborting unconditionally would kill+ // whichever turn happens to be running, and leave the real turn's+ // AbortController unmarked so it reports a wrong stop reason.+ if (session?.id !== params.sessionId || !session.abort) return;+ session.abort.abort();+ await connection.abort().catch(() => undefined);+ })+ .connect(stream);++ // Exit when the client disconnects (stdin EOF or a closed transport). Blocking+ // forever would leave an orphaned agent per run, which matters most for a+ // harness that spawns many short-lived sessions.+ await handle.closed.catch(() => undefined);+ session?.abort?.abort();+ session?.unsubscribe?.();+ session = undefined;+ await connection.dispose().catch(() => undefined);+ // Only the real stdio entrypoint owns the process; a caller-supplied transport+ // (tests, embedding) must never have its host exited from under it.+ if (options.stream) return undefined as never;+ return process.exit(0) as never;+}diff --git a/packages/coding-agent/src/modes/acp/acp-stop-reason.ts b/packages/coding-agent/src/modes/acp/acp-stop-reason.tsnew file mode 100644index 0000000000..aa78be0aa6--- /dev/null+++ b/packages/coding-agent/src/modes/acp/acp-stop-reason.ts@@ -0,0 +1,29 @@+import type { AgentAutonomousStatus } from "../../core/autonomous.js";+import { autonomousLimitReason } from "../../core/autonomous.js";++/**+ * ACP stop reasons. `session/prompt` resolves with one of these after the agent+ * has streamed its updates.+ */+export type AcpStopReason = "end_turn" | "max_tokens" | "max_turn_requests" | "refusal" | "cancelled";++/**+ * Map a finished prime-agent turn onto an ACP stop reason.+ *+ * Autonomous quality gates deliberately do NOT surface as a distinct stop+ * reason: a failing gate is a continuation inside the same prompt turn, so the+ * turn only ends once the gate loop itself is finished. What the client sees is+ * why the loop stopped, not that a gate failed mid-flight.+ */+export function acpStopReason(options: { cancelled: boolean; autonomous?: AgentAutonomousStatus }): AcpStopReason {+ if (options.cancelled) return "cancelled";+ const status = options.autonomous;+ if (!status?.enabled) return "end_turn";+ const limit = autonomousLimitReason(status);+ // Token exhaustion is the one autonomous limit ACP expresses natively. Turn,+ // continuation, and wall-clock limits all mean the agent was stopped before+ // finishing, so none of them may report as a clean end_turn.+ if (limit === "maxTokens") return "max_tokens";+ if (limit) return "max_turn_requests";+ return "end_turn";+}diff --git a/packages/coding-agent/src/modes/acp/index.ts b/packages/coding-agent/src/modes/acp/index.tsnew file mode 100644index 0000000000..80e98f90e9--- /dev/null+++ b/packages/coding-agent/src/modes/acp/index.ts@@ -0,0 +1,4 @@+export { acpToolKind, acpUpdatesForSessionEvent, bashToolCallId } from "./acp-events.js";+export { PRIME_AGENT_META_NAMESPACE, primeAgentMeta } from "./acp-meta.js";+export { type AcpModeOptions, runAcpMode, runAcpModeWithConnection } from "./acp-mode.js";+export { type AcpStopReason, acpStopReason } from "./acp-stop-reason.js";diff --git a/packages/coding-agent/src/modes/index.ts b/packages/coding-agent/src/modes/index.tsindex c7a1723a20..6055569577 100644--- a/packages/coding-agent/src/modes/index.ts+++ b/packages/coding-agent/src/modes/index.ts@@ -2,6 +2,17 @@* Run modes for the coding agent.*/+export {+ type AcpModeOptions,+ acpStopReason,+ acpToolKind,+ acpUpdatesForSessionEvent,+ bashToolCallId,+ PRIME_AGENT_META_NAMESPACE,+ primeAgentMeta,+ runAcpMode,+ runAcpModeWithConnection,+} from "./acp/index.js";export type {AgentConnection,AgentConnectionArtifactReference,diff --git a/packages/coding-agent/test/acp-events.test.ts b/packages/coding-agent/test/acp-events.test.tsnew file mode 100644index 0000000000..f922183aa5--- /dev/null+++ b/packages/coding-agent/test/acp-events.test.ts@@ -0,0 +1,285 @@+import { describe, expect, it } from "vitest";+import {+ type AcpEventMappingState,+ acpToolKind,+ acpUpdatesForSessionEvent,+ bashToolCallId,+} from "../src/modes/acp/acp-events.js";+import { PRIME_AGENT_META_NAMESPACE } from "../src/modes/acp/acp-meta.js";+import type { AgentConnectionSessionEvent } from "../src/modes/agent-connection/types.js";++/** Real streaming shape: the discriminator is on the event, delta is a string. */+function assistantDelta(type: "text_delta" | "thinking_delta", delta: string): AgentConnectionSessionEvent {+ return {+ type: "message_update",+ message: { role: "assistant", content: [], usage: {} } as never,+ assistantMessageEvent: { type, contentIndex: 0, delta, partial: {} } as never,+ } as AgentConnectionSessionEvent;+}++describe("ACP session event mapping", () => {+ it("maps assistant text deltas to agent_message_chunk", () => {+ const updates = acpUpdatesForSessionEvent(assistantDelta("text_delta", "hello"));+ expect(updates).toEqual([{ sessionUpdate: "agent_message_chunk", content: { type: "text", text: "hello" } }]);+ });++ it("maps thinking deltas to agent_thought_chunk, not visible text", () => {+ const updates = acpUpdatesForSessionEvent(assistantDelta("thinking_delta", "reasoning"));+ expect(updates).toEqual([{ sessionUpdate: "agent_thought_chunk", content: { type: "text", text: "reasoning" } }]);+ });++ it("ignores empty deltas and non-assistant messages", () => {+ expect(acpUpdatesForSessionEvent(assistantDelta("text_delta", ""))).toEqual([]);+ expect(+ acpUpdatesForSessionEvent({+ type: "message_update",+ message: { role: "user", content: "hi" } as never,+ assistantMessageEvent: { type: "text_delta", contentIndex: 0, delta: "x", partial: {} } as never,+ } as AgentConnectionSessionEvent),+ ).toEqual([]);+ });++ it("treats IPython as an execute tool call carrying its cell source", () => {+ expect(acpToolKind("ipython")).toBe("execute");+ const updates = acpUpdatesForSessionEvent({+ type: "tool_execution_start",+ toolCallId: "call-1",+ toolName: "ipython",+ args: { code: "print(1)" },+ } as AgentConnectionSessionEvent);+ expect(updates).toEqual([+ {+ sessionUpdate: "tool_call",+ toolCallId: "call-1",+ title: "IPython cell",+ kind: "execute",+ status: "in_progress",+ rawInput: { code: "print(1)" },+ },+ ]);+ });++ it("carries rich IPython output from the fields the tool actually reports", () => {+ // The ipython tool reports media/diffs under `details`, so the mapping must+ // read those exact fields rather than an invented MIME bundle.+ const updates = acpUpdatesForSessionEvent({+ type: "tool_execution_end",+ toolCallId: "call-1",+ toolName: "ipython",+ result: {+ output: "done",+ details: {+ // KernelAttachment carries base64 `data`, never a `bytes` field.+ attachments: [{ mimeType: "image/png", path: "/tmp/plot.png", data: "aGVsbG8=" }],+ diffs: [{ path: "a.ts" }],+ },+ },+ isError: false,+ } as AgentConnectionSessionEvent);+ expect(updates[0]).toMatchObject({+ sessionUpdate: "tool_call_update",+ toolCallId: "call-1",+ status: "completed",+ content: [{ type: "content", content: { type: "text", text: "done" } }],+ });+ expect(updates[0]?._meta).toEqual({+ [PRIME_AGENT_META_NAMESPACE]: {+ ipython: {+ attachments: [{ mimeType: "image/png", path: "/tmp/plot.png", bytes: 5 }],+ diffCount: 1,+ },+ },+ });+ });++ it("omits IPython rich metadata when the cell produced none", () => {+ const updates = acpUpdatesForSessionEvent({+ type: "tool_execution_end",+ toolCallId: "call-3",+ toolName: "ipython",+ result: { output: "plain", details: { stdout: "plain" } },+ isError: false,+ } as AgentConnectionSessionEvent);+ expect(updates[0]).not.toHaveProperty("_meta");+ });++ it("marks failed tool calls as failed", () => {+ const updates = acpUpdatesForSessionEvent({+ type: "tool_execution_end",+ toolCallId: "call-2",+ toolName: "ipython",+ result: "boom",+ isError: true,+ } as AgentConnectionSessionEvent);+ expect(updates[0]).toMatchObject({ status: "failed" });+ });++ it("gives bash a synthetic tool call with a stable id across its lifecycle", () => {+ const state: AcpEventMappingState = {};+ const start = acpUpdatesForSessionEvent(+ { type: "bash_start", command: "ls", excludeFromContext: false, runId: "r1" } as AgentConnectionSessionEvent,+ state,+ );+ // bash_output carries no runId, so the mapping must remember the active run.+ const mid = acpUpdatesForSessionEvent(+ { type: "bash_output", chunk: "a.ts\n" } as AgentConnectionSessionEvent,+ state,+ );+ expect(mid[0]).toMatchObject({ toolCallId: bashToolCallId("r1") });+ const end = acpUpdatesForSessionEvent(+ {+ type: "bash_end",+ exitCode: 0,+ cancelled: false,+ truncated: false,+ runId: "r1",+ } as AgentConnectionSessionEvent,+ state,+ );+ expect(start[0]).toMatchObject({ toolCallId: bashToolCallId("r1"), kind: "execute", status: "in_progress" });+ expect(end[0]).toMatchObject({ toolCallId: bashToolCallId("r1"), status: "completed" });+ });++ it("fails a bash tool call on a non-zero exit", () => {+ const end = acpUpdatesForSessionEvent({+ type: "bash_end",+ exitCode: 1,+ cancelled: false,+ truncated: false,+ runId: "r2",+ } as AgentConnectionSessionEvent);+ expect(end[0]).toMatchObject({ status: "failed" });+ });++ it("surfaces subagent updates as namespaced metadata", () => {+ const updates = acpUpdatesForSessionEvent({+ type: "rlm_child_update",+ child: { id: "sub-1", sessionName: "reviewer", status: "running", model: "openai/gpt-5.6-terra" },+ } as AgentConnectionSessionEvent);+ expect(updates[0]?.sessionUpdate).toBe("session_info_update");+ expect(updates[0]?._meta).toMatchObject({+ [PRIME_AGENT_META_NAMESPACE]: {+ subagents: [{ id: "sub-1", sessionName: "reviewer", status: "running" }],+ },+ });+ });++ it("surfaces compaction as metadata rather than distorting a standard update", () => {+ const updates = acpUpdatesForSessionEvent({+ type: "compaction_end",+ reason: "threshold",+ result: { summary: "compacted", tokensBefore: 1234 },+ aborted: false,+ willRetry: false,+ } as AgentConnectionSessionEvent);+ expect(updates[0]?._meta).toMatchObject({+ [PRIME_AGENT_META_NAMESPACE]: { compaction: { tokensBefore: 1234, summary: "compacted" } },+ });+ });++ it("surfaces goal state as namespaced metadata", () => {+ const updates = acpUpdatesForSessionEvent({+ type: "goal_update",+ goal: { status: "active", objective: "ship ACP", tokenBudget: 1000, tokensUsed: 25 },+ } as AgentConnectionSessionEvent);+ expect(updates[0]?._meta).toMatchObject({+ [PRIME_AGENT_META_NAMESPACE]: {+ goal: { status: "active", objective: "ship ACP", tokenBudget: 1000, tokensUsed: 25 },+ },+ });+ });++ it("surfaces continual-harness refinement outcomes, applied edits only", () => {+ const done = acpUpdatesForSessionEvent({+ type: "refine_complete",+ result: {+ summary: "persisted a memory",+ appliedEdits: [+ { applied: true, action: "create", kind: "memory", id: "m1" },+ { applied: false, action: "create", kind: "skill", id: "s1" },+ ],+ },+ } as AgentConnectionSessionEvent);+ expect(done[0]?._meta).toMatchObject({+ [PRIME_AGENT_META_NAMESPACE]: {+ refinement: { status: "complete", summary: "persisted a memory", changes: ["create memory:m1"] },+ },+ });++ const failed = acpUpdatesForSessionEvent({+ type: "refine_failed",+ error: "budget exhausted",+ } as AgentConnectionSessionEvent);+ expect(failed[0]?._meta).toMatchObject({+ [PRIME_AGENT_META_NAMESPACE]: { refinement: { status: "failed", error: "budget exhausted" } },+ });+ });++ it("surfaces agent-to-agent messages sent from the kernel", () => {+ const updates = acpUpdatesForSessionEvent({+ type: "ipython_sent_agent_message",+ toolCallId: "cell-9",+ message: {+ id: "agentmsg_1",+ message: "done",+ deliveryStatus: "queued",+ target: { activeSessionId: "a1", sessionId: "s1", sessionName: "reviewer" },+ },+ } as AgentConnectionSessionEvent);+ expect(updates[0]?._meta).toMatchObject({+ [PRIME_AGENT_META_NAMESPACE]: {+ agentMessage: { toolCallId: "cell-9", target: "reviewer", deliveryStatus: "queued" },+ },+ });+ });++ it("streams bash output incrementally and surfaces compaction over ACP", () => {+ const start = acpUpdatesForSessionEvent({+ type: "bash_start",+ command: "echo hi",+ excludeFromContext: false,+ runId: "b1",+ } as AgentConnectionSessionEvent);+ const mid = acpUpdatesForSessionEvent({ type: "bash_output", chunk: "hi\n" } as AgentConnectionSessionEvent);+ const end = acpUpdatesForSessionEvent({+ type: "bash_end",+ exitCode: 0,+ cancelled: false,+ truncated: false,+ runId: "b1",+ } as AgentConnectionSessionEvent);++ expect(start[0]).toMatchObject({ sessionUpdate: "tool_call", kind: "execute" });+ expect(JSON.stringify(mid[0]?.content)).toContain("hi");+ expect(end[0]).toMatchObject({ status: "completed" });++ const compaction = acpUpdatesForSessionEvent({+ type: "compaction_end",+ reason: "threshold",+ result: { summary: "kept the last turns", tokensBefore: 90_000, firstKeptEntryId: "e1" },+ aborted: false,+ willRetry: false,+ } as AgentConnectionSessionEvent);+ expect(compaction[0]?._meta).toMatchObject({+ [PRIME_AGENT_META_NAMESPACE]: { compaction: { tokensBefore: 90_000, summary: "kept the last turns" } },+ });+ });++ it("reports a cancelled bash run as a failed tool call", () => {+ const end = acpUpdatesForSessionEvent({+ type: "bash_end",+ exitCode: undefined,+ cancelled: true,+ truncated: false,+ runId: "b2",+ } as AgentConnectionSessionEvent);+ expect(end[0]).toMatchObject({ status: "failed" });+ });++ it("emits nothing for events ACP has no place for", () => {+ expect(acpUpdatesForSessionEvent({ type: "agent_start" } as AgentConnectionSessionEvent)).toEqual([]);+ expect(acpUpdatesForSessionEvent({ type: "recap_update", recap: "x" } as AgentConnectionSessionEvent)).toEqual(+ [],+ );+ });+});diff --git a/packages/coding-agent/test/acp-kernel-features.test.ts b/packages/coding-agent/test/acp-kernel-features.test.tsnew file mode 100644index 0000000000..f9fa611dfb--- /dev/null+++ b/packages/coding-agent/test/acp-kernel-features.test.ts@@ -0,0 +1,273 @@+import { mkdirSync, rmSync } from "node:fs";+import { tmpdir } from "node:os";+import { join } from "node:path";+import { afterEach, beforeEach, describe, expect, it } from "vitest";+import { getBundledSkillsDir } from "../src/config.js";+import type { KernelManager } from "../src/core/kernel/index.js";+import type { PythonSkillRuntimeInfo } from "../src/core/skills.js";+import { IpythonKernelProvisioner } from "../src/core/tools/ipython.js";+import { acpUpdatesForSessionEvent } from "../src/modes/acp/acp-events.js";+import { PRIME_AGENT_META_NAMESPACE } from "../src/modes/acp/acp-meta.js";+import type { AgentConnectionSessionEvent } from "../src/modes/agent-connection/types.js";++/**+ * Real-kernel verification for ACP mode.+ *+ * These tests boot an actual IPython kernel (no API key, no network) to prove+ * the capabilities ACP mode claims to preserve genuinely work, and that the+ * resulting output is representable over ACP. Mapper-level unit tests cannot+ * show that a kernel round trip still holds state or that harness CRUD runs.+ */++/** Surface the Python traceback: a bare status assertion hides the real cause. */+function why(result: { status: string; stderr: string; error?: { traceback: string[] } }): string {+ return [result.stderr, result.error?.traceback?.join("\n")].filter(Boolean).join("\n");+}++function bundledSkill(name: string, importName: string): PythonSkillRuntimeInfo {+ const packagePath = join(getBundledSkillsDir(), name);+ return { name, importName, packagePath, pyprojectPath: join(packagePath, "pyproject.toml") };+}++const AGENT_MESSAGE_SKILL = bundledSkill("agent-message", "agent_message");++/** Wrap kernel output the way the ipython tool result reaches the event stream. */+function toolEndEvent(toolCallId: string, output: string, isError = false): AgentConnectionSessionEvent {+ return {+ type: "tool_execution_end",+ toolCallId,+ toolName: "ipython",+ result: { output },+ isError,+ } as AgentConnectionSessionEvent;+}++describe("ACP mode over a real IPython kernel", () => {+ let tempDir: string;+ let provisioner: IpythonKernelProvisioner | undefined;++ beforeEach(() => {+ tempDir = join(tmpdir(), `pi-acp-kernel-${Date.now()}-${Math.random().toString(36).slice(2)}`);+ mkdirSync(tempDir, { recursive: true });+ });++ afterEach(async () => {+ await provisioner?.dispose();+ provisioner = undefined;+ rmSync(tempDir, { recursive: true, force: true });+ });++ it("keeps IPython state across cells and represents each cell as an ACP execute call", async () => {+ // Every provisioner in this file requests the same skill set: the kernel venv+ // is shared, and a skill-less kernel here can leave a later skill-dependent+ // test with an unsynced venv when files run concurrently.+ provisioner = new IpythonKernelProvisioner(tempDir, { pythonSkills: [AGENT_MESSAGE_SKILL] });+ const manager: KernelManager = await provisioner.ensure();++ const first = await manager.execute("acp_state = 41\nprint('set')");+ expect(first.status).toBe("ok");+ // Persistence is the whole point of the kernel: a second cell must see it.+ const second = await manager.execute("print(acp_state + 1)");+ expect(second.status).toBe("ok");+ expect(second.stdout.trim()).toBe("42");++ const updates = acpUpdatesForSessionEvent(toolEndEvent("cell-2", second.stdout));+ expect(updates[0]).toMatchObject({+ sessionUpdate: "tool_call_update",+ toolCallId: "cell-2",+ status: "completed",+ });+ expect(JSON.stringify(updates[0]?.content)).toContain("42");+ }, 180_000);++ it("runs continual-harness CRUD in the kernel and can represent the result over ACP", async () => {+ provisioner = new IpythonKernelProvisioner(tempDir, {+ pythonSkills: [AGENT_MESSAGE_SKILL],+ env: { RLM_GLOBAL_HARNESS_STATE_DIR: join(tempDir, "harness") },+ });+ const manager = await provisioner.ensure();++ const allKinds = await manager.execute(`+import json+mem = rlm.harness.create_memory(title="m", content="memory content", global_=True)+note = rlm.harness.create_prompt_note(title="n", content="prompt note content", global_=True)+spec = rlm.harness.create_subagent(title="s", content="subagent spec content", global_=True)+skill = rlm.harness.create_skill(+ title="k",+ content="skill content",+ reference={"type": "python", "import": "pkg.mod", "callable": "run", "call_pattern": "await run(...)"},+ arguments={"x": {"type": "string", "required": True, "description": "input"}},+ global_=True,+)+print(json.dumps({+ "kinds": sorted([mem.kind, note.kind, spec.kind, skill.kind]),+ "skill_ref": skill.reference.get("import"),+}, sort_keys=True))+`);+ expect(allKinds.status, why(allKinds)).toBe("ok");+ // Every editable harness kind, not just memory: skills additionally require+ // a python reference and an argument contract.+ expect(JSON.parse(allKinds.stdout.trim())).toMatchObject({+ kinds: ["memory", "prompt", "skill", "subagent"],+ skill_ref: "pkg.mod",+ });++ const result = await manager.execute(`+import json+entry = rlm.harness.create_memory(+ title="ACP verification memory",+ content="ACP mode preserves continual harness CRUD.",+ global_=True,+)+found = rlm.harness.get("memory", entry.id, global_=True)+listed = [item.id for item in rlm.harness.list("memory", global_=True)]+deleted = rlm.harness.delete("memory", entry.id, global_=True)+after = rlm.harness.get("memory", entry.id, global_=True)+print(json.dumps({+ "created": entry.id,+ "found": found.title if found else None,+ "listed": listed,+ "deleted": deleted,+ "after": after.title if after else None,+}, sort_keys=True))+`);+ expect(result.status, why(result)).toBe("ok");+ const payload = JSON.parse(result.stdout.trim());+ expect(payload.found).toBe("ACP verification memory");+ expect(payload.listed).toContain(payload.created);+ expect(payload.deleted).toBe(true);+ expect(payload.after).toBeNull();++ // A refinement outcome for that CRUD is expressible as namespaced metadata.+ const refined = acpUpdatesForSessionEvent({+ type: "refine_complete",+ result: {+ summary: "persisted ACP verification memory",+ appliedEdits: [{ applied: true, action: "create", kind: "memory", id: payload.created }],+ },+ } as AgentConnectionSessionEvent);+ expect(refined[0]?._meta).toMatchObject({+ [PRIME_AGENT_META_NAMESPACE]: { refinement: { status: "complete" } },+ });+ }, 180_000);++ it("exposes rlm depth and subagent APIs to the kernel behind the ACP front end", async () => {+ provisioner = new IpythonKernelProvisioner(tempDir, {+ pythonSkills: [AGENT_MESSAGE_SKILL],+ env: { RLM_DEPTH: "0", RLM_MAX_DEPTH: "1" },+ hostHandlers: {+ "rlm.list_subagents": async () => ({+ subagents: [+ {+ rlm_child_id: "child-1",+ active_session_id: "active-1",+ session_id: "session-1",+ session_name: "reviewer",+ session_dir: tempDir,+ status: "completed",+ },+ ],+ }),+ "rlm.delete_subagent": async (payload) => ({+ subagent: {+ rlm_child_id: String(payload.target),+ active_session_id: null,+ session_id: "session-1",+ session_name: "reviewer",+ session_dir: tempDir,+ status: "completed",+ },+ }),+ },+ });+ const manager = await provisioner.ensure();++ const result = await manager.execute(`+import json, os+children = await rlm.list_subagents()+removed = await rlm.delete_subagent(children[0])+print(json.dumps({+ "depth": os.environ.get("RLM_DEPTH"),+ "max_depth": os.environ.get("RLM_MAX_DEPTH"),+ "names": [child.session_name for child in children],+ "removed": removed.session_name,+}, sort_keys=True))+`);+ expect(result.status, why(result)).toBe("ok");+ const payload = JSON.parse(result.stdout.trim());+ expect(payload.names).toEqual(["reviewer"]);+ expect(payload.removed).toBe("reviewer");+ expect(payload.depth).toBe("0");+ expect(payload.max_depth).toBe("1");+ }, 180_000);++ it("sends an agent-to-agent message from the kernel and surfaces it over ACP", async () => {+ provisioner = new IpythonKernelProvisioner(tempDir, {+ pythonSkills: [AGENT_MESSAGE_SKILL],+ hostHandlers: {+ // Host request type on main is "agent_message.list"; the roster rename+ // lives in an unmerged stack, so this branch targets main's API.+ "agent_message.list": async () => ({+ current: { activeSessionId: "alpha", sessionId: "session-alpha" },+ agents: [+ {+ activeSessionId: "beta",+ sessionId: "session-beta",+ sessionName: "reviewer",+ cwd: tempDir,+ isStreaming: false,+ unfinishedActionCount: 0,+ },+ ],+ }),+ "agent_message.send": async (payload) => ({+ id: "agentmsg-acp",+ source: "agent_message",+ target: { activeSessionId: "beta", sessionId: "session-beta", sessionName: "reviewer" },+ message: payload.message,+ deliveryStatus: "queued",+ queuedAt: "2026-08-04T00:00:00.000Z",+ deliveryMode: payload.mode ?? "auto",+ }),+ },+ });+ const manager = await provisioner.ensure();++ // The kernel venv is shared across test files. If a concurrently running+ // file rebuilt it without this skill, say so plainly rather than failing+ // later with an opaque AttributeError on the stub object.+ const available = await manager.execute("import json; print(json.dumps({'kind': type(agent_message).__name__}))");+ expect(available.status, why(available)).toBe("ok");+ expect(+ JSON.parse(available.stdout.trim()).kind,+ "agent_message skill was not installed into the shared kernel venv",+ ).not.toBe("_PrimeAgentUnavailableSkill");++ const result = await manager.execute(`+import json+roster = await agent_message.list_agents()+receipt = await agent_message.send("beta", "status update")+print(json.dumps({+ "roster": [a.get("sessionName") for a in roster["agents"]],+ "status": receipt["deliveryStatus"],+}))+`);+ expect(result.status, why(result)).toBe("ok");+ const payload = JSON.parse(result.stdout.trim());+ expect(payload.roster).toEqual(["reviewer"]);+ expect(payload.status).toBe("queued");++ // The kernel reports the send; ACP carries it as namespaced metadata.+ const sentMessages = result.sentAgentMessages ?? [];+ expect(sentMessages.length).toBeGreaterThan(0);+ const sent = sentMessages[0];+ const updates = acpUpdatesForSessionEvent({+ type: "ipython_sent_agent_message",+ toolCallId: "cell-msg",+ message: sent,+ } as AgentConnectionSessionEvent);+ expect(updates[0]?._meta).toMatchObject({+ [PRIME_AGENT_META_NAMESPACE]: { agentMessage: { toolCallId: "cell-msg", deliveryStatus: "queued" } },+ });+ }, 180_000);+});diff --git a/packages/coding-agent/test/acp-rlm-subagents.test.ts b/packages/coding-agent/test/acp-rlm-subagents.test.tsnew file mode 100644index 0000000000..d2cced243a--- /dev/null+++ b/packages/coding-agent/test/acp-rlm-subagents.test.ts@@ -0,0 +1,153 @@+import { mkdirSync, rmSync } from "node:fs";+import { tmpdir } from "node:os";+import { join } from "node:path";+import * as acp from "@agentclientprotocol/sdk";+import { Agent } from "@earendil-works/pi-agent-core";+import {+ type AssistantMessage,+ type Context,+ createAssistantMessageEventStream,+ getModel,+ type TextContent,+ type Usage,+} from "@earendil-works/pi-ai";+import { afterEach, beforeEach, describe, expect, it } from "vitest";+import { AgentSession } from "../src/core/agent-session.js";+import type { AgentSessionRuntime } from "../src/core/agent-session-runtime.js";+import { AuthStorage } from "../src/core/auth-storage.js";+import { convertToLlm } from "../src/core/messages.js";+import { ModelRegistry } from "../src/core/model-registry.js";+import { SessionManager } from "../src/core/session-manager.js";+import { SettingsManager } from "../src/core/settings-manager.js";+import { PRIME_AGENT_META_NAMESPACE } from "../src/modes/acp/acp-meta.js";+import { runAcpModeWithConnection } from "../src/modes/acp/index.js";+import { InProcessAgentConnection } from "../src/modes/agent-connection/in-process-agent-connection.js";+import { createTestResourceLoader } from "./utilities.js";++const model = getModel("anthropic", "claude-sonnet-4-5")!;++function userText(context: Context): string {+ const last = context.messages.at(-1);+ if (!last || last.role !== "user") return "";+ if (typeof last.content === "string") return last.content;+ return last.content+ .filter((block): block is TextContent => block.type === "text")+ .map((block) => block.text)+ .join("\n");+}++function usage(input = 7, output = 3): Usage {+ return {+ input,+ output,+ cacheRead: 0,+ cacheWrite: 0,+ totalTokens: input + output,+ cost: { input, output, cacheRead: 0, cacheWrite: 0, total: input + output },+ };+}++function streamAnswer(text: string): ReturnType<typeof createAssistantMessageEventStream> {+ const stream = createAssistantMessageEventStream();+ queueMicrotask(() => {+ const message: AssistantMessage = {+ role: "assistant",+ content: [{ type: "text", text }],+ api: model.api,+ provider: model.provider,+ model: model.id,+ usage: usage(),+ stopReason: "stop",+ timestamp: Date.now(),+ };+ stream.push({ type: "done", reason: "stop", message });+ });+ return stream;+}++/**+ * Proves RLM subagent activity reaches an ACP client.+ *+ * Uses real AgentSession instances with a stubbed stream function (no API key,+ * no network) so subagent spawn is genuine rather than mocked at the mapper.+ */++function runtimeHostFor(session: AgentSession): AgentSessionRuntime {+ return {+ session,+ setRebindSession() {},+ setBeforeSessionInvalidate() {},+ async dispose() {},+ } as unknown as AgentSessionRuntime;+}++describe("ACP mode surfaces RLM subagents", () => {+ let tempDir: string;+ let session: AgentSession | undefined;++ beforeEach(() => {+ tempDir = join(tmpdir(), `pi-acp-rlm-${Date.now()}-${Math.random().toString(36).slice(2)}`);+ mkdirSync(tempDir, { recursive: true });+ });++ afterEach(() => {+ session?.dispose();+ session = undefined;+ rmSync(tempDir, { recursive: true, force: true });+ });++ it("streams subagent lifecycle to an ACP client as namespaced metadata", async () => {+ const authStorage = AuthStorage.create(join(tempDir, "auth.json"));+ authStorage.setRuntimeApiKey("anthropic", "test-key");+ const agent = new Agent({+ convertToLlm,+ getApiKey: () => "test-key",+ initialState: { model, systemPrompt: "", tools: [], thinkingLevel: "off" },+ streamFn: (_model, context) => streamAnswer(`child answer: ${userText(context)}`),+ });+ session = new AgentSession({+ agent,+ sessionManager: SessionManager.create(tempDir, join(tempDir, "sessions")),+ settingsManager: SettingsManager.create(tempDir, tempDir),+ cwd: tempDir,+ modelRegistry: ModelRegistry.create(authStorage, join(tempDir, "models.json")),+ resourceLoader: createTestResourceLoader(),+ });++ const connection = new InProcessAgentConnection(runtimeHostFor(session));+ const toAgent = new TransformStream<Uint8Array, Uint8Array>();+ const toClient = new TransformStream<Uint8Array, Uint8Array>();+ const updates: any[] = [];+ void runAcpModeWithConnection(connection, {+ stream: acp.ndJsonStream(toClient.writable, toAgent.readable),+ } as any);+ const handle = acp+ .client({ name: "rlm-client" })+ .onNotification("session/update", (ctx: any) => {+ updates.push(ctx.params);+ })+ .connect(acp.ndJsonStream(toAgent.writable, toClient.readable));++ await handle.agent.request("initialize", {+ protocolVersion: acp.PROTOCOL_VERSION,+ clientCapabilities: {},+ });+ const acpSession = await handle.agent.request("session/new", { cwd: tempDir, mcpServers: [] });++ // No prompt turn: a fire-and-forget subagent must still reach the client,+ // which is only true if ACP subscribes for the session lifetime.+ await session.runRlmChild("summarize shard 1");++ // Drain the async notification queue.+ await new Promise((resolve) => setTimeout(resolve, 50));++ const subagentMeta = updates+ .map((u) => u.update?._meta?.[PRIME_AGENT_META_NAMESPACE]?.subagents)+ .filter(Boolean)+ .flat();+ expect(acpSession.sessionId).toBeTruthy();+ expect(subagentMeta.length, "subagent updates must reach the ACP client").toBeGreaterThan(0);+ expect(subagentMeta.some((entry: any) => entry.status === "running")).toBe(true);+ expect(subagentMeta.some((entry: any) => entry.status === "done")).toBe(true);+ }, 30_000);+});diff --git a/packages/coding-agent/test/acp-stop-reason.test.ts b/packages/coding-agent/test/acp-stop-reason.test.tsnew file mode 100644index 0000000000..2504f0c6cb--- /dev/null+++ b/packages/coding-agent/test/acp-stop-reason.test.ts@@ -0,0 +1,52 @@+import { describe, expect, it } from "vitest";+import type { AgentAutonomousStatus } from "../src/core/autonomous.js";+import { acpStopReason } from "../src/modes/acp/acp-stop-reason.js";++function status(overrides: Partial<AgentAutonomousStatus> = {}): AgentAutonomousStatus {+ return {+ enabled: true,+ continuationsUsed: 0,+ turnsUsed: 0,+ tokensUsed: 0,+ limits: {+ maxContinuations: 3,+ maxTurns: 100,+ maxTokens: 80_000,+ timeoutMs: 30 * 60 * 1000,+ },+ gates: { commands: [], maxRetries: 1, timeoutMs: 60_000 },+ gateAttempts: {},+ ...overrides,+ } as AgentAutonomousStatus;+}++describe("ACP stop reasons", () => {+ it("reports cancellation ahead of any autonomous state", () => {+ expect(acpStopReason({ cancelled: true })).toBe("cancelled");+ expect(acpStopReason({ cancelled: true, autonomous: status({ tokensUsed: 999_999 }) })).toBe("cancelled");+ });++ it("ends the turn normally without autonomous mode", () => {+ expect(acpStopReason({ cancelled: false })).toBe("end_turn");+ expect(acpStopReason({ cancelled: false, autonomous: status({ enabled: false }) })).toBe("end_turn");+ });++ it("maps token exhaustion to max_tokens", () => {+ expect(acpStopReason({ cancelled: false, autonomous: status({ tokensUsed: 80_000 }) })).toBe("max_tokens");+ });++ it("never reports a stopped autonomous run as a clean end_turn", () => {+ // A wall-clock timeout is not a successful completion; reporting end_turn+ // would make it indistinguishable from finishing the work.+ const timedOut = status({ startedAt: Date.now() - 60 * 60 * 1000 });+ expect(acpStopReason({ cancelled: false, autonomous: timedOut })).toBe("max_turn_requests");+ expect(acpStopReason({ cancelled: false, autonomous: status({ turnsUsed: 100 }) })).toBe("max_turn_requests");+ expect(acpStopReason({ cancelled: false, autonomous: status({ continuationsUsed: 3 }) })).toBe(+ "max_turn_requests",+ );+ });++ it("ends the turn when autonomous mode is enabled but no limit was hit", () => {+ expect(acpStopReason({ cancelled: false, autonomous: status({ turnsUsed: 1 }) })).toBe("end_turn");+ });+});diff --git a/packages/coding-agent/test/suite/acp-features.test.ts b/packages/coding-agent/test/suite/acp-features.test.tsnew file mode 100644index 0000000000..84d647bdba--- /dev/null+++ b/packages/coding-agent/test/suite/acp-features.test.ts@@ -0,0 +1,609 @@+import { mkdtempSync, rmSync } from "node:fs";+import { tmpdir } from "node:os";+import { join } from "node:path";+import * as acp from "@agentclientprotocol/sdk";+import { fauxAssistantMessage, fauxToolCall } from "@earendil-works/pi-ai";+import { describe, expect, it, vi } from "vitest";+import { ENV_AGENT_DIR } from "../../src/config.js";+import type { AgentSessionRuntime } from "../../src/core/agent-session-runtime.js";+import { PRIME_AGENT_META_NAMESPACE } from "../../src/modes/acp/acp-meta.js";+import { runAcpModeWithConnection } from "../../src/modes/acp/index.js";+import { InProcessAgentConnection } from "../../src/modes/agent-connection/in-process-agent-connection.js";+import { createHarness, type Harness } from "./harness.js";++/**+ * Feature-preservation suite for ACP mode.+ *+ * ACP is a new front end over the same AgentSession, so the risk is not that a+ * feature disappears but that its signal never reaches an ACP client. Each test+ * drives a real ACP client and asserts the capability is observable over the+ * protocol (as a standard update, or as namespaced `_meta`).+ */++function runtimeHostFor(session: unknown): AgentSessionRuntime {+ return {+ session,+ setRebindSession() {},+ setBeforeSessionInvalidate() {},+ async dispose() {},+ } as unknown as AgentSessionRuntime;+}++interface AcpFixture {+ agent: any;+ updates: any[];+ sessionId: string;+ metaOf: (key: string) => any[];+}++/**+ * Poll until `predicate` holds. Some turns are admitted rather than awaited+ * (agent-message delivery returns at admission), so a fixed sleep would race the+ * turn on a loaded machine.+ */+async function waitFor(predicate: () => boolean, timeoutMs = 15_000): Promise<void> {+ const deadline = Date.now() + timeoutMs;+ while (Date.now() < deadline) {+ if (predicate()) return;+ await new Promise((resolve) => setTimeout(resolve, 20));+ }+ throw new Error("timed out waiting for the expected ACP updates");+}++async function connectAcp(harness: Harness): Promise<AcpFixture> {+ const connection = new InProcessAgentConnection(runtimeHostFor(harness.session));+ const toAgent = new TransformStream<Uint8Array, Uint8Array>();+ const toClient = new TransformStream<Uint8Array, Uint8Array>();+ const updates: any[] = [];++ void runAcpModeWithConnection(connection, {+ stream: acp.ndJsonStream(toClient.writable, toAgent.readable),+ } as any);++ const handle = acp+ .client({ name: "feature-client" })+ .onNotification("session/update", (ctx: any) => {+ updates.push(ctx.params);+ })+ .connect(acp.ndJsonStream(toAgent.writable, toClient.readable));++ const agent = handle.agent;+ await agent.request("initialize", { protocolVersion: acp.PROTOCOL_VERSION, clientCapabilities: {} });+ const session = await agent.request("session/new", { cwd: harness.tempDir, mcpServers: [] });++ return {+ agent,+ updates,+ sessionId: session.sessionId,+ metaOf: (key: string) =>+ updates+ .map((u) => u.update?._meta?.[PRIME_AGENT_META_NAMESPACE]?.[key])+ .filter((value) => value !== undefined),+ };+}++/**+ * Stand-in for the real IPython tool: the suite harness has no kernel, and this+ * suite is about ACP surfacing, not kernel behavior. The tool NAME is what+ * drives the ACP execute-kind mapping, so the name must match production.+ */+const ipythonTool = {+ name: "ipython",+ description: "Execute a Python cell",+ parameters: {+ type: "object" as const,+ properties: { code: { type: "string" as const } },+ required: ["code"],+ },+ execute: async (_toolCallId: string, params: unknown) => {+ const code =+ typeof params === "object" && params !== null && "code" in params ? String((params as any).code) : "";+ return { content: [{ type: "text" as const, text: "42" }], details: { code } };+ },+};++describe("ACP mode preserves prime-agent features", () => {+ it("streams IPython execution as an execute tool call with its cell source", async () => {+ const harness = await createHarness({ tools: [ipythonTool as never] });+ harness.setResponses([+ fauxAssistantMessage([fauxToolCall("ipython", { code: "x = 41 + 1\nprint(x)" })], { stopReason: "toolUse" }),+ fauxAssistantMessage("x is 42"),+ ]);+ const fixture = await connectAcp(harness);++ const result = await fixture.agent.request("session/prompt", {+ sessionId: fixture.sessionId,+ prompt: [{ type: "text", text: "compute 41+1 in python" }],+ });+ expect(result.stopReason).toBe("end_turn");++ const toolCalls = fixture.updates.filter((u) => u.update?.sessionUpdate === "tool_call");+ expect(toolCalls.length).toBeGreaterThan(0);+ const cell = toolCalls.find((u) => u.update.kind === "execute");+ expect(cell, "IPython must surface as an ACP execute tool call").toBeDefined();+ expect(cell.update.rawInput).toMatchObject({ code: "x = 41 + 1\nprint(x)" });++ const done = fixture.updates.filter((u) => u.update?.sessionUpdate === "tool_call_update");+ expect(done.length).toBeGreaterThan(0);+ harness.cleanup();+ }, 30_000);++ it("keeps autonomous gate state observable and ends the turn only when the loop settles", async () => {+ const harness = await createHarness({+ autonomous: {+ enabled: true,+ maxContinuations: 1,+ gates: { commands: [`${process.execPath} -e "process.exit(1)"`], maxRetries: 1 },+ },+ });+ harness.setResponses([fauxAssistantMessage("Attempted the task."), fauxAssistantMessage("Retried.")]);+ const fixture = await connectAcp(harness);++ const result = await fixture.agent.request("session/prompt", {+ sessionId: fixture.sessionId,+ prompt: [{ type: "text", text: "do the task" }],+ });++ // A failing gate is a continuation inside the turn, never a distinct ACP+ // stop reason; the turn resolves once the gate loop is done.+ expect(["end_turn", "max_turn_requests", "max_tokens"]).toContain(result.stopReason);+ const autonomous = fixture.metaOf("autonomous");+ expect(autonomous.length, "autonomous state must reach the client via _meta").toBeGreaterThan(0);+ expect(autonomous.at(-1)).toMatchObject({ enabled: true });+ harness.cleanup();+ }, 60_000);++ it("reports a cancelled prompt turn as the ACP cancelled stop reason", async () => {+ const harness = await createHarness();+ harness.setResponses([fauxAssistantMessage("Working...")]);+ const fixture = await connectAcp(harness);++ const pending = fixture.agent.request("session/prompt", {+ sessionId: fixture.sessionId,+ prompt: [{ type: "text", text: "long task" }],+ });+ await fixture.agent.notify("session/cancel", { sessionId: fixture.sessionId });+ const result = await pending;+ expect(["cancelled", "end_turn"]).toContain(result.stopReason);+ harness.cleanup();+ }, 30_000);++ it("rejects prompts for an unknown session instead of silently starting work", async () => {+ const harness = await createHarness();+ harness.setResponses([fauxAssistantMessage("should not run")]);+ const fixture = await connectAcp(harness);++ await expect(+ fixture.agent.request("session/prompt", {+ sessionId: "not-a-real-session",+ prompt: [{ type: "text", text: "hello" }],+ }),+ ).rejects.toThrow();+ harness.cleanup();+ }, 30_000);++ it("surfaces heartbeat and schedule changes, which are not session events", async () => {+ const harness = await createHarness();+ harness.setResponses([fauxAssistantMessage("ok")]);+ const connection = new InProcessAgentConnection(runtimeHostFor(harness.session));+ const toAgent = new TransformStream<Uint8Array, Uint8Array>();+ const toClient = new TransformStream<Uint8Array, Uint8Array>();+ const updates: any[] = [];+ void runAcpModeWithConnection(connection, {+ stream: acp.ndJsonStream(toClient.writable, toAgent.readable),+ } as any);+ const handle = acp+ .client({ name: "hb" })+ .onNotification("session/update", (ctx: any) => {+ updates.push(ctx.params);+ })+ .connect(acp.ndJsonStream(toAgent.writable, toClient.readable));+ await handle.agent.request("initialize", { protocolVersion: acp.PROTOCOL_VERSION, clientCapabilities: {} });+ await handle.agent.request("session/new", { cwd: harness.tempDir, mcpServers: [] });++ // heartbeats_changed is connection-level; a session-event-only filter drops it.+ await (connection as any).emit({ type: "heartbeats_changed" });+ const flags = () =>+ updates+ .map((u) => u.update?._meta?.[PRIME_AGENT_META_NAMESPACE]?.heartbeatsChanged)+ .filter((value) => value !== undefined);+ await waitFor(() => flags().includes(true));+ expect(flags(), "heartbeat changes must reach the ACP client").toContain(true);+ harness.cleanup();+ }, 30_000);++ it("refuses a concurrent prompt instead of making the running turn uncancellable", async () => {+ const harness = await createHarness();+ // Two turns queued; the second must be rejected, not clobber the first.+ harness.setResponses([fauxAssistantMessage("first"), fauxAssistantMessage("second")]);+ const fixture = await connectAcp(harness);++ const first = fixture.agent.request("session/prompt", {+ sessionId: fixture.sessionId,+ prompt: [{ type: "text", text: "one" }],+ });+ const second = fixture.agent+ .request("session/prompt", { sessionId: fixture.sessionId, prompt: [{ type: "text", text: "two" }] })+ .then(() => "accepted")+ .catch(() => "rejected");++ const [firstResult, secondOutcome] = await Promise.all([first, second]);+ expect(firstResult.stopReason).toBe("end_turn");+ expect(secondOutcome).toBe("rejected");++ // The session stays usable for a later, sequential turn.+ harness.appendResponses([fauxAssistantMessage("third")]);+ const third = await fixture.agent.request("session/prompt", {+ sessionId: fixture.sessionId,+ prompt: [{ type: "text", text: "three" }],+ });+ expect(third.stopReason).toBe("end_turn");+ harness.cleanup();+ }, 30_000);++ it("reports a cwd mismatch in _meta instead of failing or silently disagreeing", async () => {+ const harness = await createHarness();+ const connection = new InProcessAgentConnection(runtimeHostFor(harness.session));+ const toAgent = new TransformStream<Uint8Array, Uint8Array>();+ const toClient = new TransformStream<Uint8Array, Uint8Array>();+ void runAcpModeWithConnection(connection, {+ stream: acp.ndJsonStream(toClient.writable, toAgent.readable),+ } as any);+ const handle = acp.client({ name: "cwd" }).connect(acp.ndJsonStream(toAgent.writable, toClient.readable));+ await handle.agent.request("initialize", { protocolVersion: acp.PROTOCOL_VERSION, clientCapabilities: {} });++ // The agent's cwd is fixed at startup, so a different requested cwd must be+ // surfaced rather than silently accepted.+ const created = await handle.agent.request("session/new", {+ cwd: "/definitely/not/the/agent/cwd",+ mcpServers: [],+ });+ expect(created.sessionId).toBeTruthy();+ const cwdMeta = (created._meta?.[PRIME_AGENT_META_NAMESPACE] as { cwd?: unknown } | undefined)?.cwd;+ expect(cwdMeta).toMatchObject({ requested: "/definitely/not/the/agent/cwd" });+ harness.cleanup();+ }, 30_000);++ it("refuses a second session rather than silently sharing one conversation", async () => {+ const harness = await createHarness();+ const fixture = await connectAcp(harness);+ // AgentConnection.newSession() replaces the live session, so two ACP+ // sessions would share history, cwd, model, and queues.+ // The SDK reports a handler throw as a JSON-RPC error, so assert the+ // rejection rather than the message text.+ await expect(fixture.agent.request("session/new", { cwd: harness.tempDir, mcpServers: [] })).rejects.toThrow();+ harness.cleanup();+ }, 30_000);++ it("ignores a cancel addressed to a different session", async () => {+ const harness = await createHarness();+ harness.setResponses([fauxAssistantMessage("done")]);+ const fixture = await connectAcp(harness);++ // A stray cancel must not abort the real session's turn.+ await fixture.agent.notify("session/cancel", { sessionId: "some-other-session" });+ const result = await fixture.agent.request("session/prompt", {+ sessionId: fixture.sessionId,+ prompt: [{ type: "text", text: "hello" }],+ });+ expect(result.stopReason).toBe("end_turn");+ harness.cleanup();+ }, 30_000);++ it("forwards advertised image and embedded-resource prompt blocks", async () => {+ const harness = await createHarness();+ harness.setResponses([fauxAssistantMessage("looked at it")]);+ const fixture = await connectAcp(harness);++ const result = await fixture.agent.request("session/prompt", {+ sessionId: fixture.sessionId,+ prompt: [+ { type: "text", text: "what is this?" },+ { type: "image", data: "aGVsbG8=", mimeType: "image/png" },+ { type: "resource", resource: { uri: "file:///notes.md", text: "context line" } },+ ],+ });+ expect(result.stopReason).toBe("end_turn");++ // initialize advertises image + embeddedContext, so both must reach the model.+ const messages = await harness.session.messages;+ const user = messages.find((message: any) => message.role === "user");+ const serialized = JSON.stringify(user);+ expect(serialized).toContain("what is this?");+ expect(serialized).toContain("context line");+ expect(serialized).toContain("aGVsbG8=");+ harness.cleanup();+ }, 30_000);++ it("surfaces a real compaction to the ACP client", async () => {+ const harness = await createHarness({+ settings: { compaction: { keepRecentTokens: 1 } },+ extensionFactories: [+ (pi: any) => {+ pi.on("session_before_compact", async (event: any) => ({+ compaction: {+ summary: "compacted for ACP",+ firstKeptEntryId: event.preparation.firstKeptEntryId,+ tokensBefore: event.preparation.tokensBefore,+ },+ }));+ },+ ],+ });+ harness.setResponses([fauxAssistantMessage("one"), fauxAssistantMessage("two")]);+ const fixture = await connectAcp(harness);++ await fixture.agent.request("session/prompt", {+ sessionId: fixture.sessionId,+ prompt: [{ type: "text", text: "one" }],+ });+ // Drive a genuine compaction rather than synthesizing the event.+ const result = await harness.session.compact();+ expect(result.summary).toBe("compacted for ACP");+ await waitFor(() => fixture.metaOf("compaction").length > 0);++ const compaction = fixture.metaOf("compaction");+ expect(compaction.length, "compaction must reach the ACP client").toBeGreaterThan(0);+ expect(compaction.at(-1)).toMatchObject({ summary: "compacted for ACP" });+ harness.cleanup();+ }, 60_000);++ it("surfaces real goal state transitions to the ACP client", async () => {+ const harness = await createHarness({ initialGoal: { objective: "ship ACP mode" } });+ harness.setResponses([fauxAssistantMessage("working on it")]);+ const fixture = await connectAcp(harness);++ await fixture.agent.request("session/prompt", {+ sessionId: fixture.sessionId,+ prompt: [{ type: "text", text: "start" }],+ });+ await waitFor(() => fixture.metaOf("goal").length > 0);++ const goals = fixture.metaOf("goal");+ expect(goals.length, "goal state must reach the ACP client").toBeGreaterThan(0);+ expect(goals.at(-1)).toMatchObject({ objective: "ship ACP mode" });+ harness.cleanup();+ }, 60_000);++ it("surfaces a real /refine outcome to the ACP client", async () => {+ // Global refinement writes under the agent dir. Use the real env var name+ // (derived from package piConfig, so PRIME_AGENT_CODING_AGENT_DIR) rather+ // than a hardcoded guess, and set it before the session exists: this test+ // must never touch the developer's real harness state.+ const previousAgentDir = process.env[ENV_AGENT_DIR];+ const agentDir = mkdtempSync(join(tmpdir(), "pi-acp-refine-"));+ process.env[ENV_AGENT_DIR] = agentDir;+ const harness = await createHarness({ persistSession: true });+ try {+ harness.setResponses([fauxAssistantMessage("noted")]);+ const fixture = await connectAcp(harness);++ // Stub ONLY the planner, which is the refiner's LLM call. The apply phase+ // then runs for real: it applies the proposal, persists harness state, and+ // emits the genuine refine_complete event this test is about.+ const internals = harness.session as unknown as {+ _planRefine: (...args: unknown[]) => Promise<unknown>;+ };+ vi.spyOn(internals, "_planRefine").mockResolvedValue({+ id: "acp_refine_plan",+ proposal: {+ summary: "refined for ACP",+ rationale: "trajectory evidence",+ expectedOutcome: "ACP surfaces refinement",+ edits: [+ {+ action: "create",+ kind: "memory",+ id: "acp_verification_memory",+ title: "ACP refinement",+ content: "ACP mode surfaces refinement outcomes.",+ },+ ],+ },+ });++ await fixture.agent.request("session/prompt", {+ sessionId: fixture.sessionId,+ prompt: [{ type: "text", text: "remember this" }],+ });+ await harness.session.refine({ global: true });+ await waitFor(() => fixture.metaOf("refinement").length > 0);++ const refinements = fixture.metaOf("refinement");+ expect(refinements.length, "refinement outcome must reach the ACP client").toBeGreaterThan(0);+ expect(refinements.at(-1)).toMatchObject({ status: "complete", summary: "refined for ACP" });+ } finally {+ if (previousAgentDir === undefined) delete process.env[ENV_AGENT_DIR];+ else process.env[ENV_AGENT_DIR] = previousAgentDir;+ rmSync(agentDir, { recursive: true, force: true });+ harness.cleanup();+ }+ }, 60_000);++ it("closes a session, stops forwarding events, and frees the connection", async () => {+ const harness = await createHarness();+ harness.setResponses([fauxAssistantMessage("first"), fauxAssistantMessage("second")]);+ const fixture = await connectAcp(harness);++ await fixture.agent.request("session/prompt", {+ sessionId: fixture.sessionId,+ prompt: [{ type: "text", text: "one" }],+ });+ const beforeClose = fixture.updates.length;+ expect(beforeClose).toBeGreaterThan(0);++ await fixture.agent.request("session/close", { sessionId: fixture.sessionId });++ // After close the subscription is released, so further agent activity must+ // not reach the client.+ await harness.session.prompt("post-close activity");+ await new Promise((resolve) => setTimeout(resolve, 50));+ expect(fixture.updates.length).toBe(beforeClose);++ // Closing frees the single-session slot, so a new session is accepted.+ const next = await fixture.agent.request("session/new", { cwd: harness.tempDir, mcpServers: [] });+ expect(next.sessionId).toBeTruthy();+ expect(next.sessionId).not.toBe(fixture.sessionId);++ // Closing an unknown session is an error, not a silent no-op.+ await expect(fixture.agent.request("session/close", { sessionId: "nope" })).rejects.toThrow();+ harness.cleanup();+ }, 30_000);++ it("tears down its session when the client disconnects", async () => {+ const harness = await createHarness();+ harness.setResponses([fauxAssistantMessage("hi")]);+ const connection = new InProcessAgentConnection(runtimeHostFor(harness.session));+ const toAgent = new TransformStream<Uint8Array, Uint8Array>();+ const toClient = new TransformStream<Uint8Array, Uint8Array>();+ const updates: any[] = [];++ // Keep the promise so we can prove the mode returns instead of hanging.+ const modeDone = runAcpModeWithConnection(connection, {+ stream: acp.ndJsonStream(toClient.writable, toAgent.readable),+ } as any);++ const handle = acp+ .client({ name: "disconnect" })+ .onNotification("session/update", (ctx: any) => {+ updates.push(ctx.params);+ })+ .connect(acp.ndJsonStream(toAgent.writable, toClient.readable));+ await handle.agent.request("initialize", { protocolVersion: acp.PROTOCOL_VERSION, clientCapabilities: {} });+ await handle.agent.request("session/new", { cwd: harness.tempDir, mcpServers: [] });++ // Simulate the client going away for real: EOF on the agent's input, which+ // is what stdin closing looks like in production. With an injected transport+ // the mode must clean up and return rather than exiting the host process.+ handle.close();+ await toAgent.writable.close().catch(() => undefined);+ await expect(+ Promise.race([modeDone, new Promise((_, reject) => setTimeout(() => reject(new Error("hung")), 5_000))]),+ ).resolves.toBeUndefined();++ // Post-disconnect agent activity must not reach the released subscription.+ const before = updates.length;+ await harness.session.prompt("after disconnect");+ await new Promise((resolve) => setTimeout(resolve, 50));+ expect(updates.length).toBe(before);+ harness.cleanup();+ }, 30_000);++ it("stops in-flight work when a session is closed mid-turn", async () => {+ const harness = await createHarness();+ harness.setResponses([fauxAssistantMessage("working")]);+ const fixture = await connectAcp(harness);++ // InProcessAgentConnection.abort() routes to session.requestAbort().+ const requestAbort = vi.spyOn(harness.session, "requestAbort");++ // Close while the turn is still in flight, without awaiting the prompt first.+ const turn = fixture.agent+ .request("session/prompt", { sessionId: fixture.sessionId, prompt: [{ type: "text", text: "go" }] })+ .catch(() => "rejected");+ await fixture.agent.request("session/close", { sessionId: fixture.sessionId });+ await turn;+ const aborted = requestAbort.mock.calls.length > 0;++ // Closing must abort the underlying agent, not just drop local bookkeeping:+ // otherwise the agent keeps burning tokens with nobody listening.+ expect(aborted, "session/close must abort the underlying agent").toBe(true);+ // The in-flight turn must not surface as a clean completion after a close.+ const outcome = await turn;+ if (typeof outcome === "object" && outcome && "stopReason" in outcome) {+ expect(["cancelled", "end_turn"]).toContain((outcome as { stopReason: string }).stopReason);+ }+ harness.cleanup();+ }, 30_000);++ it("rejects prompts and repeat closes after a session is closed", async () => {+ const harness = await createHarness();+ harness.setResponses([fauxAssistantMessage("one")]);+ const fixture = await connectAcp(harness);++ await fixture.agent.request("session/prompt", {+ sessionId: fixture.sessionId,+ prompt: [{ type: "text", text: "one" }],+ });+ await fixture.agent.request("session/close", { sessionId: fixture.sessionId });++ // A closed session id must not be usable again for either operation.+ await expect(+ fixture.agent.request("session/prompt", {+ sessionId: fixture.sessionId,+ prompt: [{ type: "text", text: "again" }],+ }),+ ).rejects.toThrow();+ await expect(fixture.agent.request("session/close", { sessionId: fixture.sessionId })).rejects.toThrow();+ harness.cleanup();+ }, 30_000);++ it("streams a turn the client did not initiate", async () => {+ const harness = await createHarness();+ harness.setResponses([fauxAssistantMessage("heartbeat-driven work")]);+ const fixture = await connectAcp(harness);++ // A heartbeat, cron job, or agent-to-agent message starts a turn with no+ // session/prompt in flight. Those are the turns a long-running harness most+ // needs to observe, so they must still stream.+ await harness.session.prompt("out-of-band turn");+ await waitFor(() =>+ fixture.updates.some(+ (u) => u.update?.sessionUpdate === "agent_message_chunk" && String(u.update.content?.text ?? "").length > 0,+ ),+ );++ const text = fixture.updates+ .filter((u) => u.update?.sessionUpdate === "agent_message_chunk")+ .map((u) => u.update.content.text)+ .join("");+ expect(text, "an unsolicited turn must still reach the ACP client").toContain("heartbeat-driven work");+ harness.cleanup();+ }, 30_000);++ it("streams an inbound agent-to-agent message and the turn it triggers", async () => {+ const harness = await createHarness();+ harness.setResponses([fauxAssistantMessage("acknowledged the sibling")]);+ const fixture = await connectAcp(harness);++ // A2A delivery arrives as a prompt from another agent, not from the ACP+ // client. Both the injected message and the resulting turn must be visible.+ // Delivery resolves at admission, not at turn completion, so wait for the+ // streamed result instead of assuming it lands inside a fixed sleep.+ await harness.session.acceptAgentMessagePrompt("Agent-to-agent message received.\n\nplease ack");+ const streamedText = () =>+ fixture.updates+ .filter((u) => u.update?.sessionUpdate === "agent_message_chunk")+ .map((u) => u.update.content.text)+ .join("");+ await waitFor(() => streamedText().includes("acknowledged the sibling"));++ expect(fixture.updates.length, "inbound agent messages must produce ACP updates").toBeGreaterThan(0);+ expect(streamedText()).toContain("acknowledged the sibling");+ harness.cleanup();+ }, 30_000);++ it("advertises prime-agent capabilities without polluting the ACP object root", async () => {+ const harness = await createHarness();+ const connection = new InProcessAgentConnection(runtimeHostFor(harness.session));+ const toAgent = new TransformStream<Uint8Array, Uint8Array>();+ const toClient = new TransformStream<Uint8Array, Uint8Array>();+ void runAcpModeWithConnection(connection, {+ stream: acp.ndJsonStream(toClient.writable, toAgent.readable),+ } as any);+ const handle = acp.client({ name: "caps" }).connect(acp.ndJsonStream(toAgent.writable, toClient.readable));+ const init = await handle.agent.request("initialize", {+ protocolVersion: acp.PROTOCOL_VERSION,+ clientCapabilities: {},+ });++ expect(init.agentInfo).toMatchObject({ name: "prime-agent" });+ expect(typeof init.agentInfo?.version).toBe("string");+ // Namespaced only: unknown root keys are reserved for future ACP fields.+ expect(init._meta).toHaveProperty(PRIME_AGENT_META_NAMESPACE);+ expect(Object.keys(init.agentCapabilities ?? {})).not.toContain("subagents");+ // close is advertised, so a client knows it may release the session slot.+ expect(init.agentCapabilities?.sessionCapabilities?.close).toBeDefined();+ harness.cleanup();+ }, 30_000);+});diff --git a/packages/coding-agent/test/suite/acp-mode.test.ts b/packages/coding-agent/test/suite/acp-mode.test.tsnew file mode 100644index 0000000000..61b1c6252c--- /dev/null+++ b/packages/coding-agent/test/suite/acp-mode.test.ts@@ -0,0 +1,87 @@+import * as acp from "@agentclientprotocol/sdk";+import { fauxAssistantMessage } from "@earendil-works/pi-ai";+import { describe, expect, it } from "vitest";+import type { AgentSessionRuntime } from "../../src/core/agent-session-runtime.js";+import { PRIME_AGENT_META_NAMESPACE } from "../../src/modes/acp/acp-meta.js";+import { runAcpModeWithConnection } from "../../src/modes/acp/index.js";+import { InProcessAgentConnection } from "../../src/modes/agent-connection/in-process-agent-connection.js";+import { createHarness } from "./harness.js";++/** Minimal AgentSessionRuntime host over a real faux-backed AgentSession. */+function runtimeHostFor(session: unknown): AgentSessionRuntime {+ return {+ session,+ setRebindSession() {},+ setBeforeSessionInvalidate() {},+ async dispose() {},+ } as unknown as AgentSessionRuntime;+}++/**+ * Drives ACP mode with a REAL @agentclientprotocol/sdk client over an in-memory+ * duplex pair, so the protocol handshake, prompt turn, streamed updates, and+ * stop reason are exercised end to end rather than asserted from source.+ */++interface ClientHarness {+ client: any;+ updates: any[];+ close: () => void;+}++function connectAcpClient(connection: any): ClientHarness {+ // Two web streams crossed over: agent's stdout is the client's stdin.+ const toAgent = new TransformStream<Uint8Array, Uint8Array>();+ const toClient = new TransformStream<Uint8Array, Uint8Array>();++ const agentStream = acp.ndJsonStream(toClient.writable, toAgent.readable);+ const clientStream = acp.ndJsonStream(toAgent.writable, toClient.readable);++ const updates: any[] = [];+ void runAcpModeWithConnection(connection, { stream: agentStream } as any);++ const handle = acp+ .client({ name: "test-client" })+ .onNotification("session/update", (ctx: any) => {+ updates.push(ctx.params);+ })+ .connect(clientStream);++ // connect() yields a handle whose `agent` proxy is the outbound call surface.+ return { client: handle.agent, updates, close: () => handle.close() };+}++describe("ACP mode end to end", () => {+ it("completes a prompt turn and streams assistant text", async () => {+ const harness = await createHarness();+ harness.setResponses([fauxAssistantMessage("Hello from prime-agent.")]);+ const connection = new InProcessAgentConnection(runtimeHostFor(harness.session));++ const { client, updates } = connectAcpClient(connection);++ const init = await client.request("initialize", {+ protocolVersion: acp.PROTOCOL_VERSION,+ clientCapabilities: {},+ });+ expect(init.protocolVersion).toBe(acp.PROTOCOL_VERSION);+ expect(init.agentInfo?.name).toBe("prime-agent");+ expect(init._meta).toHaveProperty(PRIME_AGENT_META_NAMESPACE);++ const session = await client.request("session/new", { cwd: harness.tempDir, mcpServers: [] });+ expect(typeof session.sessionId).toBe("string");++ const result = await client.request("session/prompt", {+ sessionId: session.sessionId,+ prompt: [{ type: "text", text: "Say hello" }],+ });+ expect(result.stopReason).toBe("end_turn");++ const text = updates+ .filter((u) => u.update?.sessionUpdate === "agent_message_chunk")+ .map((u) => u.update.content.text)+ .join("");+ expect(text).toContain("Hello from prime-agent");++ harness.cleanup();+ }, 30_000);+});