A self-improving RLM agent for coding workflows and long-running autonomous tasks.
Rust
fix(coding-agent): fail ACP prompt turns that ended in an error (#624)
Seth Kartencea90f81d900
diff --git a/packages/coding-agent/CHANGELOG.md b/packages/coding-agent/CHANGELOG.mdindex e08c0b55a6..cfc934e786 100644--- a/packages/coding-agent/CHANGELOG.md+++ b/packages/coding-agent/CHANGELOG.md@@ -8,6 +8,7 @@- Fixed top-level `--help` omitting `acp` from the supported `--mode` values ([#620](https://github.com/PrimeIntellect-ai/prime-agent/issues/620)).- Fixed `stop` and `rename` becoming prompts when `--daemon-socket` precedes the command ([#622](https://github.com/PrimeIntellect-ai/prime-agent/issues/622)).- Fixed subagent terminal notices arriving as anonymous follow-up prompts instead of attributed agent messages, so a parent can now tell which child reported completion, failure, or cancellation, and a busy parent is steered at the next turn boundary rather than waiting to go idle ([#617](https://github.com/PrimeIntellect-ai/prime-agent/issues/617)).+- Fixed ACP mode reporting a failed turn as a clean `end_turn`. A provider error, expired auth, or unusable model left `session/prompt` resolving with no updates at all, which reads to a client as a successful but empty turn; the turn now fails with the underlying error instead.## [0.6.0] - 2026-08-04diff --git a/packages/coding-agent/package.json b/packages/coding-agent/package.jsonindex 60a7e9c9c5..d5fb63f7ca 100644--- a/packages/coding-agent/package.json+++ b/packages/coding-agent/package.json@@ -44,7 +44,7 @@"postinstall": "node postinstall.cjs","prepublishOnly": "npm run clean && npm run build","bundle": "node scripts/bundle.mjs",- "test:kernel": "vitest --run --tagsFilter kernel-heavy test/acp-kernel-features.test.ts"+ "test:kernel": "vitest --run --tagsFilter kernel-heavy test/acp-kernel-features.test.ts test/acp-cold-cli.test.ts"},"dependencies": {"@agentclientprotocol/sdk": "^1.3.0",diff --git a/packages/coding-agent/src/modes/acp/acp-mode.ts b/packages/coding-agent/src/modes/acp/acp-mode.tsindex 28f4b8650c..fc7423da43 100644--- a/packages/coding-agent/src/modes/acp/acp-mode.ts+++ b/packages/coding-agent/src/modes/acp/acp-mode.ts@@ -2,6 +2,7 @@ import { randomUUID } from "node:crypto";import { resolve } from "node:path";import { Readable } from "node:stream";import * as acp from "@agentclientprotocol/sdk";+import type { AgentMessage } from "@earendil-works/pi-agent-core";import type { ImageContent } from "@earendil-works/pi-ai";import { VERSION } from "../../config.js";import type { AgentSessionRuntime } from "../../core/agent-session-runtime.js";@@ -112,6 +113,82 @@ function autonomousMeta(status: AgentAutonomousStatus | undefined): Record<strin});}+/**+ * The transcript as it stood before a turn started, recorded so the turn's own+ * messages can be told apart from everything older.+ *+ * A pre-turn message *count* cannot do that job: auto-compaction can fire during+ * a turn and rebuild `state.messages` (it filters, slices, and re-materializes+ * persisted entries), so this turn's failure can end up at a lower index than+ * the count taken before prompting. Membership is tracked by things a rebuild+ * preserves instead — the message objects themselves, plus a content key for+ * transports that hand back fresh copies (daemon RPC re-parses JSON, so identity+ * does not survive it) and for compaction paths that re-materialize a kept+ * message from its persisted entry with its original timestamp.+ */+interface TurnBoundary {+ identities: WeakSet<object>;+ keys: Set<string>;+}++/** Key for a kept message: compaction drops messages, it does not rewrite them. */+function messageKey(message: unknown): string | undefined {+ if (typeof message !== "object" || message === null) return undefined;+ const record = message as { role?: unknown; timestamp?: unknown; stopReason?: unknown; errorMessage?: unknown };+ if (typeof record.timestamp !== "number") return undefined;+ return JSON.stringify([+ record.role ?? null,+ record.timestamp,+ record.stopReason ?? null,+ record.errorMessage ?? null,+ ]);+}++function turnBoundary(messages: readonly AgentMessage[]): TurnBoundary {+ const identities = new WeakSet<object>();+ const keys = new Set<string>();+ for (const message of messages) {+ if (typeof message !== "object" || message === null) continue;+ identities.add(message);+ const key = messageKey(message);+ if (key) keys.add(key);+ }+ return { identities, keys };+}++function isPreTurn(message: unknown, boundary: TurnBoundary): boolean {+ if (typeof message !== "object" || message === null) return false;+ if (boundary.identities.has(message)) return true;+ const key = messageKey(message);+ return key !== undefined && boundary.keys.has(key);+}++/**+ * Error text from an assistant message this turn produced, when it failed.+ *+ * `promptAndWait` resolves for a failed turn just as it does for a successful+ * one, so the outcome has to be read off the transcript. Only messages that were+ * not in the transcript before the turn are considered: scanning the whole+ * transcript would let an earlier failed turn reject a later turn that never+ * called the model (a handled slash command, say), reporting a stale error.+ *+ * A transcript read that fails is not treated as success — that would restore+ * the silent-success behavior this exists to prevent.+ */+async function turnFailure(connection: AgentConnection, boundary: TurnBoundary): Promise<string | undefined> {+ const messages = await connection.getMessages();+ for (let index = messages.length - 1; index >= 0; index--) {+ const message = messages[index];+ if (message?.role !== "assistant") continue;+ // The newest assistant message predates the turn, so the turn appended none.+ if (isPreTurn(message, boundary)) return undefined;+ const assistant = message as { stopReason?: string; errorMessage?: string };+ if (assistant.stopReason !== "error") return undefined;+ return assistant.errorMessage || "the model request failed";+ }+ return undefined;+}+export async function runAcpMode(runtimeHost: AgentSessionRuntime): Promise<never> {const connection = new InProcessAgentConnection(runtimeHost);return runAcpModeWithConnection(connection, {@@ -230,6 +307,10 @@ export async function runAcpModeWithConnection(try {const { text, images } = promptContent(params.prompt);+ // Only this turn's messages may decide its outcome, and compaction can+ // rebuild the transcript mid-turn, so record the pre-turn messages+ // themselves rather than how many there were.+ const priorMessages = turnBoundary(await connection.getMessages());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.@@ -243,6 +324,15 @@ export async function runAcpModeWithConnection(}).catch(() => undefined);}+ // A turn that failed (provider error, auth, no usable model) must not be+ // reported as a clean end_turn. Print mode surfaces+ // `stopReason: "error"` with its errorMessage; ACP previously dropped+ // that and answered end_turn with no updates at all, which reads to a+ // client as a successful but empty turn.+ const failure = await turnFailure(connection, priorMessages);+ if (failure && !abort.signal.aborted) {+ throw new Error(`prime-agent turn failed: ${failure}`);+ }return { stopReason: acpStopReason({ cancelled: abort.signal.aborted, autonomous: status }) };} catch (error) {// Cancellation is a normal ACP prompt outcome, not a JSON-RPC error.diff --git a/packages/coding-agent/test/acp-cold-cli.test.ts b/packages/coding-agent/test/acp-cold-cli.test.tsnew file mode 100644index 0000000000..f08f7b3591--- /dev/null+++ b/packages/coding-agent/test/acp-cold-cli.test.ts@@ -0,0 +1,218 @@+import { spawn } from "node:child_process";+import { mkdirSync, mkdtempSync, rmSync, writeFileSync } from "node:fs";+import { createServer, type Server } from "node:http";+import { tmpdir } from "node:os";+import { join, resolve } from "node:path";+import { afterEach, describe, expect, it } from "vitest";+import { ENV_AGENT_DIR } from "../src/config.js";++/**+ * Cold real-CLI ACP coverage.+ *+ * Every other ACP test drives an in-process session with a faux provider already+ * wired up. That is exactly why a failed turn could report `end_turn` with no+ * updates: the failure mode only appears when a real `--mode acp` process talks+ * to a provider that rejects it. This spawns the real CLI over real stdio and+ * points it at a local server that answers 401.+ */++const cliPath = resolve(__dirname, "../src/cli.ts");+const tsxPath = resolve(__dirname, "../../../node_modules/tsx/dist/cli.mjs");++const tempDirs: string[] = [];+const servers: Server[] = [];++afterEach(async () => {+ for (const server of servers.splice(0)) {+ await new Promise<void>((done) => server.close(() => done()));+ }+ for (const dir of tempDirs.splice(0)) {+ rmSync(dir, { recursive: true, force: true });+ }+});++/** A provider endpoint that always rejects, so the turn fails for a real reason. */+async function startRejectingProvider(): Promise<string> {+ const server = createServer((_req, res) => {+ res.writeHead(401, { "Content-Type": "application/json" });+ res.end(JSON.stringify({ error: { message: "unauthorized in test" } }));+ });+ servers.push(server);+ await new Promise<void>((done) => server.listen(0, "127.0.0.1", () => done()));+ const address = server.address();+ const port = typeof address === "object" && address ? address.port : 0;+ return `http://127.0.0.1:${port}/v1`;+}++interface AcpResult {+ responses: Record<string, unknown>[];+ updates: number;+}++async function driveAcpTurn(baseUrl: string): Promise<AcpResult> {+ const tempRoot = mkdtempSync(join(tmpdir(), "pi-acp-cold-"));+ tempDirs.push(tempRoot);+ const agentDir = join(tempRoot, "agent");+ const projectDir = join(tempRoot, "project");+ mkdirSync(agentDir, { recursive: true });+ mkdirSync(projectDir, { recursive: true });+ writeFileSync(+ join(agentDir, "models.json"),+ JSON.stringify({+ providers: {+ intercept: {+ baseUrl,+ api: "openai-completions",+ apiKey: "test-key",+ models: [{ id: "cold/test-model", reasoning: false, input: ["text"] }],+ },+ },+ }),+ "utf-8",+ );++ const child = spawn(+ process.execPath,+ [+ tsxPath,+ cliPath,+ "--mode",+ "acp",+ "--provider",+ "intercept",+ "--model",+ "cold/test-model",+ "--no-session",+ "--offline",+ "--daemon-socket",+ join(tempRoot, "d.sock"),+ ],+ {+ cwd: projectDir,+ env: {+ ...process.env,+ [ENV_AGENT_DIR]: agentDir,+ HOME: agentDir,+ TSX_TSCONFIG_PATH: resolve(__dirname, "../../../tsconfig.json"),+ },+ stdio: ["pipe", "pipe", "pipe"],+ },+ );++ const responses: Record<string, unknown>[] = [];+ let updates = 0;+ let buffer = "";++ const send = (payload: unknown) => child.stdin.write(`${JSON.stringify(payload)}\n`);++ const done = new Promise<void>((resolveDone) => {+ child.stdout.on("data", (chunk) => {+ buffer += chunk.toString();+ // ACP frames are newline delimited; keep any partial trailing line.+ const lines = buffer.split("\n");+ buffer = lines.pop() ?? "";+ for (const line of lines) {+ if (!line.trim().startsWith("{")) continue;+ let frame: Record<string, unknown>;+ try {+ frame = JSON.parse(line) as Record<string, unknown>;+ } catch {+ continue;+ }+ if (frame.method === "session/update") {+ updates++;+ continue;+ }+ responses.push(frame);+ if (frame.id === 1) {+ send({+ jsonrpc: "2.0",+ id: 2,+ method: "session/new",+ params: { cwd: projectDir, mcpServers: [] },+ });+ } else if (frame.id === 2) {+ const sessionId = (frame.result as { sessionId?: string } | undefined)?.sessionId;+ send({+ jsonrpc: "2.0",+ id: 3,+ method: "session/prompt",+ params: { sessionId, prompt: [{ type: "text", text: "say hi" }] },+ });+ } else if (frame.id === 3) {+ resolveDone();+ }+ }+ });+ });++ send({+ jsonrpc: "2.0",+ id: 1,+ method: "initialize",+ params: { protocolVersion: 1, clientCapabilities: {} },+ });++ try {+ await Promise.race([+ done,+ new Promise<void>((_, reject) => setTimeout(() => reject(new Error("ACP turn timed out")), 150_000)),+ ]);+ } finally {+ // SIGKILL alone would strand whatever the CLI started for this socket (a+ // daemon supervisor, a Python kernel). Close stdin so the agent sees EOF and+ // unwinds its own children, then escalate only if it does not exit.+ child.stdin.end();+ // An already-dead child never emits "exit" again, so waiting on the event+ // alone would burn the full escalation budget after a crash.+ const alreadyExited = child.exitCode !== null || child.signalCode !== null;+ const exited = alreadyExited+ ? Promise.resolve()+ : new Promise<void>((resolveExit) => child.once("exit", () => resolveExit()));+ const exitedInTime = await Promise.race([+ exited.then(() => true),+ new Promise<boolean>((resolveTimeout) => setTimeout(() => resolveTimeout(false), 10_000)),+ ]);+ if (!exitedInTime) {+ child.kill("SIGTERM");+ const stoppedInTime = await Promise.race([+ exited.then(() => true),+ new Promise<boolean>((resolveTimeout) => setTimeout(() => resolveTimeout(false), 5_000)),+ ]);+ if (!stoppedInTime) child.kill("SIGKILL");+ }+ }+ return { responses, updates };+}++describe("ACP mode over a cold real CLI process", () => {+ it(+ "reports a provider failure instead of a silent end_turn",+ { tags: ["kernel-heavy"], timeout: 180_000 },+ async () => {+ const baseUrl = await startRejectingProvider();+ const { responses, updates } = await driveAcpTurn(baseUrl);++ const initialize = responses.find((frame) => frame.id === 1);+ expect(initialize, "the real CLI must answer initialize on stdout").toBeDefined();++ const prompt = responses.find((frame) => frame.id === 3);+ expect(prompt, "session/prompt must answer").toBeDefined();++ // The provider rejected, so the turn must not claim a clean completion.+ // Before this was fixed the answer was {stopReason: "end_turn"} with+ // updates === 0, which a client reads as a successful empty turn.+ const result = (prompt as { result?: { stopReason?: string } }).result;+ const error = (prompt as { error?: unknown }).error;+ expect(+ error !== undefined || result?.stopReason !== "end_turn",+ `a failed turn must not report end_turn (updates=${updates}, frame=${JSON.stringify(prompt)})`,+ ).toBe(true);++ // Failing loudly is only half of it: the client also has to be able to+ // tell *why*. Assert the provider's own rejection reaches the client+ // rather than a bare "Internal error".+ expect(JSON.stringify(error)).toContain("unauthorized in test");+ },+ );+});diff --git a/packages/coding-agent/test/suite/acp-features.test.ts b/packages/coding-agent/test/suite/acp-features.test.tsindex 84d647bdba..7b51917cf4 100644--- a/packages/coding-agent/test/suite/acp-features.test.ts+++ b/packages/coding-agent/test/suite/acp-features.test.ts@@ -2,6 +2,7 @@ import { mkdtempSync, rmSync } from "node:fs";import { tmpdir } from "node:os";import { join } from "node:path";import * as acp from "@agentclientprotocol/sdk";+import type { AgentMessage } from "@earendil-works/pi-agent-core";import { fauxAssistantMessage, fauxToolCall } from "@earendil-works/pi-ai";import { describe, expect, it, vi } from "vitest";import { ENV_AGENT_DIR } from "../../src/config.js";@@ -50,8 +51,8 @@ async function waitFor(predicate: () => boolean, timeoutMs = 15_000): Promise<vothrow new Error("timed out waiting for the expected ACP updates");}-async function connectAcp(harness: Harness): Promise<AcpFixture> {- const connection = new InProcessAgentConnection(runtimeHostFor(harness.session));+async function connectAcp(harness: Harness, existing?: InProcessAgentConnection): Promise<AcpFixture> {+ const connection = existing ?? new InProcessAgentConnection(runtimeHostFor(harness.session));const toAgent = new TransformStream<Uint8Array, Uint8Array>();const toClient = new TransformStream<Uint8Array, Uint8Array>();const updates: any[] = [];@@ -102,6 +103,46 @@ const ipythonTool = {},};+/**+ * Wrap a connection so a transcript rebuild runs mid-turn, right after+ * `promptAndWait` resolves and before the ACP handler inspects the outcome.+ *+ * Auto-compaction does exactly this to `state.messages`: it drops older messages+ * and re-materializes the ones it keeps (`buildSessionContext`, and the filters+ * and slices around it), so a message the turn appended can end up at a lower+ * index than the pre-turn message count. Driving a real compaction needs a+ * token-overflow response from the provider, so the rebuild is simulated here;+ * what matters is its shape, which is asserted in each test.+ */+function withMidTurnRebuild(+ harness: Harness,+ rebuild: (messages: AgentMessage[]) => AgentMessage[] | undefined,+): { connection: InProcessAgentConnection; arm: () => void } {+ const connection = new InProcessAgentConnection(runtimeHostFor(harness.session));+ const promptAndWait = connection.promptAndWait.bind(connection) as (...args: any[]) => Promise<any>;+ let armed = false;+ (connection as any).promptAndWait = async (...args: any[]) => {+ const result = await promptAndWait(...args);+ if (armed) {+ armed = false;+ const rebuilt = rebuild(harness.session.state.messages);+ if (rebuilt) harness.session.state.messages = rebuilt;+ }+ return result;+ };+ return {+ connection,+ arm: () => {+ armed = true;+ },+ };+}++/** Copy messages the way a rebuild from persisted entries does: new objects, same fields. */+function rematerialize(messages: AgentMessage[]): AgentMessage[] {+ return JSON.parse(JSON.stringify(messages));+}+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] });@@ -353,11 +394,14 @@ describe("ACP mode preserves prime-agent features", () => {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" }],- });+ // A seeded goal keeps requesting continuations, so this turn eventually+ // exhausts the faux queue and fails. The assertion is that goal state+ // reaches the client, which happens on the first turn either way.+ const turn = fixture.agent+ .request("session/prompt", { sessionId: fixture.sessionId, prompt: [{ type: "text", text: "start" }] })+ .catch(() => undefined);await waitFor(() => fixture.metaOf("goal").length > 0);+ await turn;const goals = fixture.metaOf("goal");expect(goals.length, "goal state must reach the ACP client").toBeGreaterThan(0);@@ -583,6 +627,126 @@ describe("ACP mode preserves prime-agent features", () => {harness.cleanup();}, 30_000);+ it("fails the prompt turn instead of reporting end_turn when the model errors", async () => {+ const harness = await createHarness();+ // A provider failure is the shape verifiers hit in a container: the turn+ // resolves, streams nothing, and previously answered a clean end_turn.+ harness.setResponses([fauxAssistantMessage("", { stopReason: "error", errorMessage: "Connection error." })]);+ const fixture = await connectAcp(harness);++ await expect(+ fixture.agent.request("session/prompt", {+ sessionId: fixture.sessionId,+ prompt: [{ type: "text", text: "say hi" }],+ }),+ ).rejects.toThrow();+ harness.cleanup();+ }, 30_000);++ it("does not let an earlier failed turn reject a later one", async () => {+ const harness = await createHarness();+ harness.setResponses([fauxAssistantMessage("", { stopReason: "error", errorMessage: "Connection error." })]);+ const fixture = await connectAcp(harness);++ // First turn fails and must be reported as a failure.+ await expect(+ fixture.agent.request("session/prompt", {+ sessionId: fixture.sessionId,+ prompt: [{ type: "text", text: "first" }],+ }),+ ).rejects.toThrow();++ // A slash command is handled without calling the model, so it appends no+ // assistant message. Scanning the whole transcript would surface the earlier+ // turn's error and wrongly reject this one.+ const second = await fixture.agent.request("session/prompt", {+ sessionId: fixture.sessionId,+ prompt: [{ type: "text", text: "/compact" }],+ });+ expect(second.stopReason).toBe("end_turn");+ harness.cleanup();+ }, 30_000);++ it("reports a failure that a mid-turn transcript rebuild moved below the pre-turn message count", async () => {+ const harness = await createHarness();+ harness.setResponses([+ fauxAssistantMessage("first turn done"),+ fauxAssistantMessage("", { stopReason: "error", errorMessage: "Connection error." }),+ ]);+ let rebuiltLength = 0;+ const { connection, arm } = withMidTurnRebuild(harness, (messages) => {+ // Keep only the tail, as compaction does: this turn's error message keeps+ // its content but moves to a much lower index.+ const rebuilt = rematerialize(messages.slice(-2));+ rebuiltLength = rebuilt.length;+ return rebuilt;+ });+ const fixture = await connectAcp(harness, connection);++ const first = await fixture.agent.request("session/prompt", {+ sessionId: fixture.sessionId,+ prompt: [{ type: "text", text: "first" }],+ });+ expect(first.stopReason).toBe("end_turn");++ const priorMessageCount = harness.session.state.messages.length;+ expect(priorMessageCount, "the first turn must leave messages behind to compact away").toBeGreaterThan(1);+ arm();++ const failure = await fixture.agent+ .request("session/prompt", {+ sessionId: fixture.sessionId,+ prompt: [{ type: "text", text: "second" }],+ })+ .then(+ (result: unknown) => ({ resolved: result }),+ (error: unknown) => ({ error }),+ );+ expect(+ "error" in failure,+ `a failed turn must not report a clean stop reason (got ${JSON.stringify(failure)})`,+ ).toBe(true);+ // The client must be told the turn failed, not handed a bare protocol error.+ expect(JSON.stringify(failure)).toContain("prime-agent turn failed");++ // The point of the test: a pre-turn count watermark would have skipped the+ // failure, because after the rebuild it sits below that count.+ expect(rebuiltLength, "the rebuild must shorten the transcript").toBeLessThanOrEqual(priorMessageCount);+ expect(rebuiltLength - 1, "the failure must land below the pre-turn count").toBeLessThan(priorMessageCount);+ harness.cleanup();+ }, 30_000);++ it("does not mistake a rebuilt copy of an earlier failure for this turn's failure", async () => {+ const harness = await createHarness();+ harness.setResponses([fauxAssistantMessage("", { stopReason: "error", errorMessage: "Connection error." })]);+ let rebuiltIdentities = false;+ const { connection, arm } = withMidTurnRebuild(harness, (messages) => {+ const rebuilt = rematerialize(messages);+ rebuiltIdentities = rebuilt.every((message, index) => message !== messages[index]);+ return rebuilt;+ });+ const fixture = await connectAcp(harness, connection);++ await expect(+ fixture.agent.request("session/prompt", {+ sessionId: fixture.sessionId,+ prompt: [{ type: "text", text: "first" }],+ }),+ ).rejects.toThrow();++ // A rebuild replaces every kept message with a fresh object, so object+ // identity alone cannot tell the earlier failure from a new one. The turn+ // below appends no assistant message and must still end cleanly.+ arm();+ const handled = await fixture.agent.request("session/prompt", {+ sessionId: fixture.sessionId,+ prompt: [{ type: "text", text: "/compact" }],+ });+ expect(handled.stopReason).toBe("end_turn");+ expect(rebuiltIdentities, "the rebuild must replace the message objects").toBe(true);+ 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));