diff --git a/docs/air-extensions.md b/docs/air-extensions.md index 0aaa1f1d..517bb07f 100644 --- a/docs/air-extensions.md +++ b/docs/air-extensions.md @@ -994,6 +994,20 @@ When an announced task leaves that list, the adapter reports `stopped`. A later terminal event can correct that state to `completed` or `failed`. At shutdown, the adapter finishes each open task as `failed` or `stopped`. +### Autonomous turn + +Claude Code can start a turn of its own after the prompt ended, for example to answer the notification of a finished background task. +ACP v1 has no session state, so the adapter publishes such a turn as an async task. +The task has the id `autonomous-turn-`, the name `Claude is working`, `taskType: "turn"`, and `showInTranscript: false`. +Its description is the summary of the last task notification, when there is one. +The task starts at the SDK `running` state while no prompt is active or queued. +When the state stays `running`, as it does while background agents run, it starts at the first root output with no prompt open. +It ends `completed` at the result of the turn or at the SDK `idle` state, and `failed` at an error result. +A coalesced placeholder result (`num_turns: 0`) does not end it. +A prompt that the turn takes in ends the task, because that prompt owns the turn now. +A stop request interrupts the turn instead of stopping an SDK task. +It returns `{ "stopped": false }` while a prompt waits for its turn, because the interrupt would drop that prompt. + ### Stop request The client sends `_session/async_task/stop`: diff --git a/package-lock.json b/package-lock.json index 0ed0e966..89d1f643 100644 --- a/package-lock.json +++ b/package-lock.json @@ -104,9 +104,6 @@ "cpu": [ "arm64" ], - "libc": [ - "glibc" - ], "license": "SEE LICENSE IN LICENSE.md", "optional": true, "os": [ @@ -120,9 +117,6 @@ "cpu": [ "arm64" ], - "libc": [ - "musl" - ], "license": "SEE LICENSE IN LICENSE.md", "optional": true, "os": [ @@ -136,9 +130,6 @@ "cpu": [ "x64" ], - "libc": [ - "glibc" - ], "license": "SEE LICENSE IN LICENSE.md", "optional": true, "os": [ @@ -152,9 +143,6 @@ "cpu": [ "x64" ], - "libc": [ - "musl" - ], "license": "SEE LICENSE IN LICENSE.md", "optional": true, "os": [ @@ -678,9 +666,6 @@ "arm64" ], "dev": true, - "libc": [ - "glibc" - ], "license": "MIT", "optional": true, "os": [ @@ -699,9 +684,6 @@ "arm64" ], "dev": true, - "libc": [ - "musl" - ], "license": "MIT", "optional": true, "os": [ @@ -720,9 +702,6 @@ "ppc64" ], "dev": true, - "libc": [ - "glibc" - ], "license": "MIT", "optional": true, "os": [ @@ -741,9 +720,6 @@ "s390x" ], "dev": true, - "libc": [ - "glibc" - ], "license": "MIT", "optional": true, "os": [ @@ -762,9 +738,6 @@ "x64" ], "dev": true, - "libc": [ - "glibc" - ], "license": "MIT", "optional": true, "os": [ @@ -783,9 +756,6 @@ "x64" ], "dev": true, - "libc": [ - "musl" - ], "license": "MIT", "optional": true, "os": [ @@ -2693,9 +2663,6 @@ "arm64" ], "dev": true, - "libc": [ - "glibc" - ], "license": "MPL-2.0", "optional": true, "os": [ @@ -2718,9 +2685,6 @@ "arm64" ], "dev": true, - "libc": [ - "musl" - ], "license": "MPL-2.0", "optional": true, "os": [ @@ -2743,9 +2707,6 @@ "x64" ], "dev": true, - "libc": [ - "glibc" - ], "license": "MPL-2.0", "optional": true, "os": [ @@ -2768,9 +2729,6 @@ "x64" ], "dev": true, - "libc": [ - "musl" - ], "license": "MPL-2.0", "optional": true, "os": [ diff --git a/src/acp-agent.ts b/src/acp-agent.ts index dc6aeac2..aca531ff 100644 --- a/src/acp-agent.ts +++ b/src/acp-agent.ts @@ -4394,7 +4394,18 @@ export class ClaudeAcpAgent { if (!session || !asyncTasks?.claimStop(params.asyncTaskId)) return { stopped: false }; try { - await session.query.stopTask(params.asyncTaskId); + if (asyncTasks.isAutonomousTurn(params.asyncTaskId)) { + // The task stands for a turn that Claude Code started on its own, so + // stopping it interrupts that turn. A prompt that waits for its turn + // would be folded into it, and the interrupt would drop that prompt. + if ((session.turnQueue ?? []).some((turn) => !turn.settled)) { + asyncTasks.releaseStop(params.asyncTaskId); + return { stopped: false }; + } + await session.query.interrupt(); + } else { + await session.query.stopTask(params.asyncTaskId); + } await asyncTasks.taskStopped(params.asyncTaskId); return { stopped: true }; } catch (error) { @@ -4983,6 +4994,7 @@ export class ClaudeAcpAgent { if (!head) { return; } + if (asyncTasks.autonomousTurnOpen) await asyncTasks.autonomousTurnEnded("completed"); activateTurn(head); }; @@ -5943,6 +5955,21 @@ export class ClaudeAcpAgent { this.startAutonomousCycle(params.sessionId, session, message); + // From CLI 2.1.270 the state stays `running` while background agents + // run, so a turn that their notification starts has no `running` + // transition. Its first output with no prompt open starts its task. + if ( + asyncTasks.enabled && + !asyncTasks.autonomousTurnOpen && + (message.type === "assistant" || message.type === "stream_event") && + message.parent_tool_use_id === null && + !session.cancelled && + !session.activeTurn && + !firstUnsettledQueuedTurn() + ) { + await asyncTasks.autonomousTurnStarted(); + } + switch (message.type) { case "system": switch (message.subtype) { @@ -6091,6 +6118,20 @@ export class ClaudeAcpAgent { sessionIndex.noteSessionState(session, previousState, message.state); if (message.state === "running") this.sessionIndex.onTurnStarted(params.sessionId); this.sessionIndex.onOwnSessionChanged(params.sessionId); + // With no prompt active or queued, the agent runs a turn of + // its own, for example for a task notification. The client + // sees it as an async task (see autonomousTurnStarted). + if ( + asyncTasks.enabled && + message.state === "running" && + previousState !== "running" && + !session.activeTurn && + !firstUnsettledQueuedTurn() + ) { + await asyncTasks.autonomousTurnStarted(); + } else if (message.state === "idle" && asyncTasks.autonomousTurnOpen) { + await asyncTasks.autonomousTurnEnded("completed"); + } if ( message.state === "running" && previousState !== "running" && @@ -6799,6 +6840,15 @@ export class ClaudeAcpAgent { const startedByClaudeCode = message.origin != null && AUTONOMOUS_RESULT_ORIGINS.has(message.origin.kind); const isAutonomousResult = startedByClaudeCode && !answersPendingPrompt(message); + // A placeholder result (`num_turns: 0`, see below) comes before + // the followup that answers it, so the autonomous turn goes on. + if ( + isAutonomousResult && + asyncTasks.autonomousTurnOpen && + (message.num_turns > 0 || message.is_error) + ) { + await asyncTasks.autonomousTurnEnded(message.is_error ? "failed" : "completed"); + } const pendingExitPlanModeInterruption = session.pendingExitPlanModeInterruption; const pendingExitPlanContextReset = session.pendingExitPlanContextReset; try { @@ -7793,6 +7843,10 @@ export class ClaudeAcpAgent { // mid-message, so deltas already streamed belong to the turn // being activated — clearing would forget them and let its // result re-emit the answer. + // A prompt folded into an autonomous turn owns that turn now. + if (asyncTasks.autonomousTurnOpen) { + await asyncTasks.autonomousTurnEnded("completed"); + } activateTurn(queued); } break; diff --git a/src/async-tasks.ts b/src/async-tasks.ts index 93be8fd3..fb859f69 100644 --- a/src/async-tasks.ts +++ b/src/async-tasks.ts @@ -1,3 +1,4 @@ +import { randomUUID } from "node:crypto"; import type { ClientCapabilities } from "@agentclientprotocol/sdk/unstable"; import type { AcpSessionNotification, AsyncTaskState } from "./acp-subagents.js"; import { AIR_ASYNC_TASKS_CAPABILITY, clientSupportsAirCapability } from "./air-extension.js"; @@ -39,6 +40,12 @@ type AsyncTask = { terminalSource?: TerminalSource; /** The optional fields that the client holds now, as JSON. */ published: Map; + /** + * Whether the task stands for a model turn that Claude Code started on its + * own, see {@link AsyncTaskRuntime.autonomousTurnStarted}. The SDK knows no + * such task, so its background task list never ends it. + */ + autonomousTurn: boolean; }; type TaskIdentity = { taskId?: unknown; task_id?: unknown }; @@ -121,6 +128,10 @@ export class AsyncTaskRuntime { * The oldest entries are dropped. */ private readonly outputPathsByToolCall = new Map(); + /** The task of the autonomous turn that runs now. */ + private autonomousTurn?: AsyncTask; + /** The summary of the last task notification, which usually starts the next autonomous turn. */ + private lastNotificationSummary?: string; constructor( readonly enabled: boolean, @@ -300,6 +311,7 @@ export class AsyncTaskRuntime { const state = taskState(message.status); if (!taskId || !state || state === "running" || state === "paused") return; + this.lastNotificationSummary = nonBlankString(message.summary) ?? this.lastNotificationSummary; const task = this.task(taskId); const wasTerminal = isTerminal(task.state); const correctsLevelState = wasTerminal && task.terminalSource === "level"; @@ -363,6 +375,7 @@ export class AsyncTaskRuntime { if ( (task.announced || task.held) && !task.ignored && + !task.autonomousTurn && !isTerminal(task.state) && !live.has(task.id) ) { @@ -378,6 +391,7 @@ export class AsyncTaskRuntime { } async finishAll(state: Extract): Promise { + this.autonomousTurn = undefined; const errors: unknown[] = []; for (const task of this.tasks.values()) { if ((task.announced || task.held) && !task.ignored && !isTerminal(task.state)) { @@ -412,6 +426,7 @@ export class AsyncTaskRuntime { const task = this.tasks.get(taskId); if (!task || !task.announced || task.ignored || task.stopAnnounced) return; task.stopAnnounced = true; + if (this.autonomousTurn === task) this.autonomousTurn = undefined; // No terminal summary: a stopped task leaves the Async Tasks panel at once, // so anything said there is said to nobody. await this.finish(task, "stopped", undefined, "event"); @@ -438,6 +453,47 @@ export class AsyncTaskRuntime { ); } + /** + * Publishes a model turn that Claude Code started with no prompt open, for + * example to answer a task notification. ACP v1 has no session state, and + * the client already got the stop reason of its last prompt, so this task is + * the only sign that the agent works. The tool calls of the turn are in the + * transcript already, so the task is not shown there. Does nothing while + * such a task is open. + */ + async autonomousTurnStarted(): Promise { + if (!this.enabled || this.autonomousTurn) return; + const task = this.task(`autonomous-turn-${randomUUID()}`); + task.autonomousTurn = true; + task.startedObserved = true; + task.name = "Claude is working"; + task.taskType = "turn"; + task.description = + this.lastNotificationSummary ?? "Claude Code started a turn without a prompt."; + task.showInTranscript = false; + this.lastNotificationSummary = undefined; + this.autonomousTurn = task; + await this.announce(task, { withoutToolCall: true }); + } + + /** Whether the task of an autonomous turn is open. */ + get autonomousTurnOpen(): boolean { + return this.autonomousTurn !== undefined; + } + + /** Ends the task of the autonomous turn that runs now, if there is one. */ + async autonomousTurnEnded(state: "completed" | "failed"): Promise { + const task = this.autonomousTurn; + if (!task) return; + this.autonomousTurn = undefined; + await this.finish(task, state, undefined, "event"); + } + + /** Whether the task stands for an autonomous turn, which a stop interrupts. */ + isAutonomousTurn(taskId: string): boolean { + return this.tasks.get(taskId)?.autonomousTurn === true; + } + /** Whether a task of the tool call went to the background, so the client gets it. */ isBackgroundedToolCall(toolCallId: string): boolean { for (const task of this.tasks.values()) { @@ -488,6 +544,8 @@ export class AsyncTaskRuntime { clear(): void { this.tasks.clear(); this.outputPathsByToolCall.clear(); + this.autonomousTurn = undefined; + this.lastNotificationSummary = undefined; } /** @@ -520,6 +578,7 @@ export class AsyncTaskRuntime { stopAnnounced: false, state: "running", published: new Map(), + autonomousTurn: false, }; this.tasks.set(taskId, task); return task; diff --git a/src/tests/acp-agent.test.ts b/src/tests/acp-agent.test.ts index ca773af3..8f142820 100644 --- a/src/tests/acp-agent.test.ts +++ b/src/tests/acp-agent.test.ts @@ -23254,6 +23254,233 @@ describe("deferred settlement for live background subagents (issues #864/#866)", await agent.sessions["test-session"]?.consumer; }); }); + describe("autonomous turn as an async task", () => { + const airAgent = async (capabilities: string[] = ["asyncTasks"]) => { + const updates: AcpSessionNotification[] = []; + const agent = new ClaudeAcpAgent( + { + sessionUpdate: async (notification: AcpSessionNotification) => { + updates.push(notification); + }, + } as unknown as AcpClient, + { log: () => {}, error: () => {} }, + ); + await agent.initialize({ + protocolVersion: 1, + clientCapabilities: { + _meta: { jetbrains: { air: { version: 1, capabilities } } }, + }, + }); + const asyncTaskUpdates = () => + updates.flatMap(({ update }) => + update.sessionUpdate.startsWith("async_task_") ? [update as any] : [], + ); + return { agent, updates, asyncTaskUpdates }; + }; + + const shellNotification = () => ({ + ...taskNotification("bg-1"), + summary: 'Background command "sleep 20" completed (exit code 0)', + }); + + it("publishes a turn that Claude Code runs after end_turn and ends it at its result", async () => { + const { agent, asyncTaskUpdates } = await airAgent(); + let wake = () => {}; + const woken = new Promise((resolve) => (wake = resolve)); + injectGeneratorSession(agent, (input) => { + async function* messageGenerator() { + const iter = input[Symbol.asyncIterator](); + yield userEcho((await iter.next()).value); + yield running(); + yield assistantText("started it"); + yield resultMessage(); + yield idle(); + await woken; + yield shellNotification(); + yield running(); + yield assistantText("it finished"); + // A coalesced placeholder does not end the turn. + yield resultMessage({ origin: { kind: "task-notification" }, num_turns: 0 }); + yield resultMessage({ origin: { kind: "task-notification" } }); + yield idle(); + } + return messageGenerator(); + }); + + const response = await agent.prompt({ + sessionId: "test-session", + prompt: [{ type: "text", text: "run it in the background" }], + }); + expect(response.stopReason).toBe("end_turn"); + expect(asyncTaskUpdates()).toEqual([]); + + wake(); + await agent.sessions["test-session"]?.consumer; + + const [spawned, ...rest] = asyncTaskUpdates(); + expect(spawned).toEqual({ + sessionUpdate: "async_task_spawned", + asyncTaskId: expect.stringMatching(/^autonomous-turn-/), + name: "Claude is working", + taskType: "turn", + description: 'Background command "sleep 20" completed (exit code 0)', + showInTranscript: false, + canStop: true, + }); + expect(rest).toEqual([ + { + sessionUpdate: "async_task_state_update", + asyncTaskId: spawned.asyncTaskId, + state: "completed", + }, + ]); + }); + + it("starts at the first output when the state never left running", async () => { + const { agent, asyncTaskUpdates } = await airAgent(); + let wake = () => {}; + const woken = new Promise((resolve) => (wake = resolve)); + injectGeneratorSession(agent, (input) => { + async function* messageGenerator() { + const iter = input[Symbol.asyncIterator](); + yield userEcho((await iter.next()).value); + yield running(); + yield resultMessage(); + await woken; + yield assistantText("on my own"); + yield resultMessage({ origin: { kind: "task-notification" } }); + } + return messageGenerator(); + }); + + await agent.prompt({ sessionId: "test-session", prompt: [{ type: "text", text: "go" }] }); + wake(); + await agent.sessions["test-session"]?.consumer; + + expect(asyncTaskUpdates().map((update) => update.state ?? update.sessionUpdate)).toEqual([ + "async_task_spawned", + "completed", + ]); + }); + + it("ends the turn task when a prompt is folded into the turn", async () => { + const { agent, updates, asyncTaskUpdates } = await airAgent(); + let wake = () => {}; + const woken = new Promise((resolve) => (wake = resolve)); + let autonomousRunning = () => {}; + const autonomous = new Promise((resolve) => (autonomousRunning = resolve)); + injectGeneratorSession(agent, (input) => { + async function* messageGenerator() { + const iter = input[Symbol.asyncIterator](); + yield userEcho((await iter.next()).value); + yield running(); + yield resultMessage(); + yield idle(); + await woken; + yield running(); + yield assistantText("on my own"); + autonomousRunning(); + yield userEcho((await iter.next()).value); + yield assistantText("answer to the folded prompt"); + yield resultMessage({ origin: { kind: "task-notification" } }); + yield idle(); + } + return messageGenerator(); + }); + + await agent.prompt({ sessionId: "test-session", prompt: [{ type: "text", text: "go" }] }); + wake(); + await autonomous; + const second = await agent.prompt({ + sessionId: "test-session", + prompt: [{ type: "text", text: "and this" }], + }); + expect(second.stopReason).toBe("end_turn"); + await agent.sessions["test-session"]?.consumer; + + expect(asyncTaskUpdates().map((update) => update.state ?? update.sessionUpdate)).toEqual([ + "async_task_spawned", + "completed", + ]); + const kinds = updates.map(({ update }) => + update.sessionUpdate === "agent_message_chunk" && update.content.type === "text" + ? update.content.text + : update.sessionUpdate, + ); + expect(kinds.indexOf("async_task_state_update")).toBeLessThan( + kinds.indexOf("answer to the folded prompt"), + ); + }); + + it("interrupts the turn when the client stops its task", async () => { + const { agent, asyncTaskUpdates } = await airAgent(); + let wake = () => {}; + const woken = new Promise((resolve) => (wake = resolve)); + let finish = () => {}; + const finished = new Promise((resolve) => (finish = resolve)); + injectGeneratorSession(agent, (input) => { + async function* messageGenerator() { + const iter = input[Symbol.asyncIterator](); + yield userEcho((await iter.next()).value); + yield running(); + yield resultMessage(); + yield idle(); + await woken; + yield running(); + yield assistantText("on my own"); + await finished; + yield resultMessage({ + origin: { kind: "task-notification" }, + subtype: "error_during_execution", + is_error: true, + }); + yield idle(); + } + return messageGenerator(); + }); + + await agent.prompt({ sessionId: "test-session", prompt: [{ type: "text", text: "go" }] }); + wake(); + await waitFor(() => asyncTaskUpdates().length === 1); + const session = agent.sessions["test-session"]!; + const asyncTaskId = asyncTaskUpdates()[0].asyncTaskId; + + await expect( + agent.stopAsyncTask({ sessionId: "test-session", asyncTaskId }), + ).resolves.toEqual({ stopped: true }); + expect(session.query.interrupt).toHaveBeenCalledTimes(1); + expect(session.query.stopTask).not.toHaveBeenCalled(); + finish(); + await session.consumer; + + expect(asyncTaskUpdates().map((update) => update.state ?? update.sessionUpdate)).toEqual([ + "async_task_spawned", + "stopped", + ]); + }); + + it("publishes nothing to a client without async tasks", async () => { + const { agent, asyncTaskUpdates } = await airAgent([]); + injectGeneratorSession(agent, (input) => { + async function* messageGenerator() { + const iter = input[Symbol.asyncIterator](); + yield userEcho((await iter.next()).value); + yield running(); + yield resultMessage(); + yield idle(); + yield running(); + yield assistantText("on my own"); + yield resultMessage({ origin: { kind: "task-notification" } }); + yield idle(); + } + return messageGenerator(); + }); + + await agent.prompt({ sessionId: "test-session", prompt: [{ type: "text", text: "go" }] }); + await agent.sessions["test-session"]?.consumer; + expect(asyncTaskUpdates()).toEqual([]); + }); + }); }); describe("turn steering (_session/steering)", () => { diff --git a/src/tests/async-tasks.test.ts b/src/tests/async-tasks.test.ts index 7243ebcb..e0f1c32b 100644 --- a/src/tests/async-tasks.test.ts +++ b/src/tests/async-tasks.test.ts @@ -7,6 +7,24 @@ import { } from "../async-tasks.js"; describe("AsyncTaskRuntime", () => { + it("keeps an autonomous turn open across the SDK task list and fails it at shutdown", async () => { + const updates: AcpSessionNotification[] = []; + const runtime = new AsyncTaskRuntime(true, "root", async (notification) => { + updates.push(notification); + }); + + await runtime.autonomousTurnStarted(); + await runtime.autonomousTurnStarted(); + await runtime.backgroundTasksChanged([]); + expect(runtime.autonomousTurnOpen).toBe(true); + await runtime.finishAll("failed"); + + expect(runtime.autonomousTurnOpen).toBe(false); + expect( + updates.map(({ update }) => (update as { state?: string }).state ?? update.sessionUpdate), + ).toEqual(["async_task_spawned", "failed"]); + }); + it("recovers a background Bash task from its structured tool result", async () => { const updates: AcpSessionNotification[] = []; const runtime = new AsyncTaskRuntime(true, "root", async (notification) => {