mirror of
https://github.com/agentclientprotocol/claude-agent-acp.git
synced 2026-12-05 23:51:32 +00:00
Compare commits
26 Commits
main
...
air/sessio
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
e4dbca6898 | ||
|
|
a2d2c979c9 | ||
|
|
51bea29407 | ||
|
|
3291e9227a | ||
|
|
a0ffe1c0fe | ||
|
|
e663a9c6bf | ||
|
|
3428948014 | ||
|
|
ce640c9b7f | ||
|
|
5f73cb52e1 | ||
|
|
cafd3cd74b | ||
|
|
dc7a07f69e | ||
|
|
a94e4edd0d | ||
|
|
95ef066fae | ||
|
|
f9b2ce422f | ||
|
|
131110a84e | ||
|
|
84a148f7fd | ||
|
|
8c473cc4d0 | ||
|
|
eeb6f9cc97 | ||
|
|
99d906d6bb | ||
|
|
6f5e8665fe | ||
|
|
44360be253 | ||
|
|
5423b66bc8 | ||
|
|
0cf44c4ceb | ||
|
|
b1f55b7f9d | ||
|
|
2eda6a9d9c | ||
|
|
48461736de |
@@ -1,3 +1,3 @@
|
||||
{
|
||||
".": "0.115.0"
|
||||
".": "0.114.0"
|
||||
}
|
||||
|
||||
23
CHANGELOG.md
23
CHANGELOG.md
@@ -1,28 +1,5 @@
|
||||
# Changelog
|
||||
|
||||
## [0.115.0](https://github.com/agentclientprotocol/claude-agent-acp/compare/v0.114.0...v0.115.0) (2026-12-04)
|
||||
|
||||
|
||||
### Features
|
||||
|
||||
* answer _providers/models with the models and the candidates that Claude Code knows ([#1746](https://github.com/agentclientprotocol/claude-agent-acp/issues/1746)) ([871487e](https://github.com/agentclientprotocol/claude-agent-acp/commit/871487e83e05e80a2a32e120d9c18bb33a07d3ae))
|
||||
* read subagents lazily with `_session/read` ([#1754](https://github.com/agentclientprotocol/claude-agent-acp/issues/1754)) ([f597600](https://github.com/agentclientprotocol/claude-agent-acp/commit/f597600e914d8c974f79522514722f5068cbd9b5))
|
||||
|
||||
|
||||
### Bug Fixes
|
||||
|
||||
* keep each record of parallel tool calls in `_session/read` and the subagent load replay ([#1747](https://github.com/agentclientprotocol/claude-agent-acp/issues/1747)) ([75376d1](https://github.com/agentclientprotocol/claude-agent-acp/commit/75376d11d67c08c1b711868cad5dfb0596517ce4))
|
||||
* keep the history before a compaction whose parent is not in the transcript ([#1760](https://github.com/agentclientprotocol/claude-agent-acp/issues/1760)) ([a6cce14](https://github.com/agentclientprotocol/claude-agent-acp/commit/a6cce148d7f2acc157fa043252015e5660562d27))
|
||||
|
||||
|
||||
### Performance Improvements
|
||||
|
||||
* keep the quiet read path for tools that render from the transcript ([#1762](https://github.com/agentclientprotocol/claude-agent-acp/issues/1762)) ([a522885](https://github.com/agentclientprotocol/claude-agent-acp/commit/a522885da9bcba623b14a136d6ec47f3787b4f11))
|
||||
* rebuild only the status after a child append in a status read ([#1763](https://github.com/agentclientprotocol/claude-agent-acp/issues/1763)) ([e41665c](https://github.com/agentclientprotocol/claude-agent-acp/commit/e41665c206b9816ec70fb97c5daca0cf90b7caf0))
|
||||
* refuse a cursor of another read before the render ([#1761](https://github.com/agentclientprotocol/claude-agent-acp/issues/1761)) ([173debc](https://github.com/agentclientprotocol/claude-agent-acp/commit/173debc43db31b3a3214dbf684f7b366e4caca02))
|
||||
* scan a parent transcript incrementally for new nested launches ([#1764](https://github.com/agentclientprotocol/claude-agent-acp/issues/1764)) ([2286950](https://github.com/agentclientprotocol/claude-agent-acp/commit/2286950ed15d09a64e3e01c108398c9263f39efc))
|
||||
* skip history replay for unchanged session reads ([#1736](https://github.com/agentclientprotocol/claude-agent-acp/issues/1736)) ([5fb2db3](https://github.com/agentclientprotocol/claude-agent-acp/commit/5fb2db36eb637bace51a5d4d301b5bd0d3176477))
|
||||
|
||||
## [0.114.0](https://github.com/agentclientprotocol/claude-agent-acp/compare/v0.113.0...v0.114.0) (2026-12-01)
|
||||
|
||||
|
||||
|
||||
@@ -33,6 +33,7 @@ It describes only this adapter.
|
||||
- [Context compaction](#context-compaction)
|
||||
- [Question custom answers](#question-custom-answers)
|
||||
- [Load replay end](#load-replay-end)
|
||||
- [Session writers](#session-writers)
|
||||
- [Session fork point](#session-fork-point)
|
||||
- [Session rewind](#session-rewind)
|
||||
- [Presentation hints](#presentation-hints)
|
||||
@@ -131,6 +132,7 @@ The `initialize` response of an AIR client carries the agent side of the extensi
|
||||
"diffPatch",
|
||||
"planFile",
|
||||
"backgroundSubagents",
|
||||
"sessionWriterGuard",
|
||||
"knownModels"
|
||||
],
|
||||
"goal": {
|
||||
@@ -184,6 +186,7 @@ It does not serve the [tool call contract](#tool-call-contract) yet.
|
||||
| `sessionListSubscribe` | with `sessionIndex` | Nothing on its own: the agent lists it to tell that it supports `_session/list/subscribe`. | [List subscription](#list-subscription) |
|
||||
| `sessionWorktrees` | with `sessionIndex` | Nothing on its own: the agent lists it to tell that rows carry `agentWorktree` for a worktree Claude Code made. | [List response](#list-response) |
|
||||
| `sessionRewind` | on request | Accepts `_session/rewind`, and announces its session cursors with the `rewind` capability. | [Session rewind](#session-rewind) |
|
||||
| `sessionWriterGuard` | yes | Refuses `session/load`, `session/resume` and `session/prompt` of a session that another live process holds. | [Session writers](#session-writers) |
|
||||
| `loadReplayEnd` | no | Sends one `session_info_update` after the whole history replay of a loaded session. | [Load replay end](#load-replay-end) |
|
||||
| `rawInputRendering` | no | Sends no display copy of readable input in `content`. The client renders `rawInput`. | [Tool call contract](#tool-call-contract) |
|
||||
|
||||
@@ -1922,6 +1925,49 @@ After the history replay of the loaded session, the agent then sends one more up
|
||||
- It does not come for a live update, and it does not come to a client without the capability.
|
||||
- The `session/load` can still fail after it, for example when the CLI start fails after the replay. The event means that the recorded history arrived whole. The client decides what to do with the failed load.
|
||||
|
||||
## Session writers
|
||||
|
||||
Each Claude Code process writes a record in its live registry, `<config>/sessions/<pid>.json`, with the id of its session.
|
||||
Two processes that write one transcript damage it. So the agent tells and guards the writers of a session by this registry.
|
||||
|
||||
A record is live when all of these are true:
|
||||
|
||||
- The file name is `<pid>.json`, and the record has this `pid` and a `sessionId`.
|
||||
- The record has no `pidDomain`, or the pid domain of this machine.
|
||||
- The process is alive: `kill(pid, 0)` succeeds or fails with `EPERM`.
|
||||
- The recorded `procStart` equals the start time of the process from `ps`. A reused pid then does not count.
|
||||
- A record older than 24 hours counts only when its `procStart` matches.
|
||||
|
||||
The registry has no parent pid. So the agent tells its own Claude Code process by the session: a session that this agent process runs has the record of its own process.
|
||||
A session runs here while its query is open. A session whose query closed keeps its record in the agent, but its process ended. While the agent starts or replaces the query of a session, the session still runs here. This covers a load, a resume, a rewind with its recovery, a provider switch, a plan restart, and the respawn after a sign-out. Then the writer check of a load, a resume or a prompt waits until the start or the replacement ends. In the first 10 seconds after the agent closed the query of a session, the writer check does not count the process of this agent that ends as another writer: it waits until that process ends, at most for the rest of the 10 seconds. This covers a sign-out, a replacement of the query, and `session/close`. The process that ends is the one that the last writer check saw alone while the session ran here. Without such a check, it is each process with a live record of the session at the close. So a record of another process that was live at the close can delay the refusal by up to 10 seconds. A record of another process that appears later refuses at once. The `held` of a refusal names the newest record that is not the known process of this agent. Without a known process, it can name the process of this agent.
|
||||
|
||||
- **Held**: a live record has the session, and this agent process does not run it.
|
||||
- The agent advertises `sessionWriterGuard`. A client that declares it gets these refusals:
|
||||
- `session/load` and `session/resume` of a session that this agent process does not run, when one live record has the session;
|
||||
- `session/load`, `session/resume` and `session/prompt` of a session that this agent process runs, when more than one live record has the session. A refused prompt also closes the Claude Code process of the agent: the other process is the newer act of the user.
|
||||
- A client that does not declare `sessionWriterGuard` loads and prompts a held session as before.
|
||||
|
||||
The refusal has the form that the Codex adapter uses for the same case:
|
||||
|
||||
```json
|
||||
{
|
||||
"code": -32600,
|
||||
"message": "This Claude session is in use by another Claude Code process. Close it there, or continue the session there.",
|
||||
"data": {
|
||||
"reason": "thread_active_writer",
|
||||
"sessionId": "…",
|
||||
"held": { "entrypoint": "cli", "status": "busy" },
|
||||
"details": "session … already has an active writer"
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
Known gaps:
|
||||
|
||||
- A Claude Code version that writes no registry record is never held.
|
||||
- A turn that runs when the other process starts goes on to its end. The next prompt gets the refusal.
|
||||
- After an IDE crash, the Claude Code process of that IDE can live on. Its session is held until the process ends.
|
||||
|
||||
## Session fork point
|
||||
|
||||
AIR can fork a session at one agent message.
|
||||
|
||||
4
package-lock.json
generated
4
package-lock.json
generated
@@ -1,12 +1,12 @@
|
||||
{
|
||||
"name": "@agentclientprotocol/claude-agent-acp",
|
||||
"version": "0.115.0",
|
||||
"version": "0.114.0",
|
||||
"lockfileVersion": 3,
|
||||
"requires": true,
|
||||
"packages": {
|
||||
"": {
|
||||
"name": "@agentclientprotocol/claude-agent-acp",
|
||||
"version": "0.115.0",
|
||||
"version": "0.114.0",
|
||||
"license": "Apache-2.0",
|
||||
"dependencies": {
|
||||
"@agentclientprotocol/sdk": "2.12.0",
|
||||
|
||||
@@ -3,7 +3,7 @@
|
||||
"publishConfig": {
|
||||
"access": "public"
|
||||
},
|
||||
"version": "0.115.0",
|
||||
"version": "0.114.0",
|
||||
"description": "An ACP-compatible coding agent powered by the Claude Agent SDK (TypeScript)",
|
||||
"main": "dist/lib.js",
|
||||
"types": "dist/lib.d.ts",
|
||||
|
||||
@@ -63,6 +63,14 @@ export const AIR_SESSION_REWIND_CAPABILITY = "sessionRewind";
|
||||
* advertise it.
|
||||
*/
|
||||
export const AIR_LOAD_REPLAY_END_CAPABILITY = "loadReplayEnd";
|
||||
/**
|
||||
* The agent refuses a second writer of a session: `session/load`,
|
||||
* `session/resume` and `session/prompt` fail with `data.reason`
|
||||
* `thread_active_writer` when another live Claude Code process holds the
|
||||
* session. The agent advertises it; only a client that declares it gets the
|
||||
* refusals.
|
||||
*/
|
||||
export const AIR_SESSION_WRITER_GUARD_CAPABILITY = "sessionWriterGuard";
|
||||
|
||||
/** The `_meta.jetbrains.air` keys that the ACP tool call contract defines. */
|
||||
export const AIR_COMMAND_TITLE_KEY = "commandTitle";
|
||||
|
||||
@@ -15,8 +15,10 @@
|
||||
* so a reused pid does not count;
|
||||
* - a record older than 24 hours counts only when its `procStart` matches.
|
||||
*
|
||||
* A snapshot is cached for {@link SNAPSHOT_TTL_MS}. The records tell only the
|
||||
* `state` of a session list row; no operation is refused for them.
|
||||
* A snapshot is cached for {@link SNAPSHOT_TTL_MS}. The records tell the
|
||||
* `state` of a session list row, and {@link LiveSessionRegistry.recordsOf}
|
||||
* tells the writers of one session to the writer guard (see
|
||||
* `src/v1/session-writers.ts`).
|
||||
*/
|
||||
|
||||
import { execFile } from "node:child_process";
|
||||
@@ -121,6 +123,8 @@ function defaultPidDomain(): Promise<string> {
|
||||
|
||||
type RawRecord = Record<string, unknown>;
|
||||
|
||||
type ReadFilesOptions = { recentStarts?: boolean; sessionId?: string };
|
||||
|
||||
async function readRecord(file: string): Promise<RawRecord | undefined> {
|
||||
for (let attempt = 0; attempt < 2; attempt++) {
|
||||
let text: string;
|
||||
@@ -180,15 +184,23 @@ export class LiveSessionRegistry {
|
||||
return snapshot;
|
||||
}
|
||||
|
||||
/**
|
||||
* The live records of `sessionId` now, one for each process that holds it.
|
||||
* It reads the registry again and does not use the snapshot cache.
|
||||
*/
|
||||
recordsOf(sessionId: string): Promise<LiveRecord[]> {
|
||||
return this.read({ sessionId, recentStarts: true });
|
||||
}
|
||||
|
||||
/** Every live record, several per session when several processes hold it. */
|
||||
private async read(): Promise<LiveRecord[]> {
|
||||
private async read(options: ReadFilesOptions = {}): Promise<LiveRecord[]> {
|
||||
let names: string[];
|
||||
try {
|
||||
names = await fs.readdir(this.dir());
|
||||
} catch {
|
||||
return [];
|
||||
}
|
||||
return [...(await this.readFiles(names)).values()].filter(
|
||||
return [...(await this.readFiles(names, options)).values()].filter(
|
||||
(record): record is LiveRecord => record !== undefined,
|
||||
);
|
||||
}
|
||||
@@ -199,11 +211,12 @@ export class LiveSessionRegistry {
|
||||
* is not `<pid>.json` (a `.key` file, a temporary file) is never opened and
|
||||
* not in the result. The rules of {@link read} apply. `recentStarts` takes
|
||||
* a start time that `ps` gave in the last 10 s when it matches the record,
|
||||
* so a record that changes often does not run `ps` each time.
|
||||
* so a record that changes often does not run `ps` each time. `sessionId`
|
||||
* keeps only the records of that session, and runs no `ps` for the others.
|
||||
*/
|
||||
async readFiles(
|
||||
names: readonly string[],
|
||||
options: { recentStarts?: boolean } = {},
|
||||
options: ReadFilesOptions = {},
|
||||
): Promise<Map<string, LiveRecord | undefined>> {
|
||||
const dir = this.dir();
|
||||
const result = new Map<string, LiveRecord | undefined>();
|
||||
@@ -217,6 +230,7 @@ export class LiveSessionRegistry {
|
||||
const pid = Number(match[1]);
|
||||
const raw = await readRecord(path.join(dir, name));
|
||||
if (!raw || raw.pid !== pid || typeof raw.sessionId !== "string") return;
|
||||
if (options.sessionId !== undefined && raw.sessionId !== options.sessionId) return;
|
||||
if (typeof raw.pidDomain === "string" && raw.pidDomain !== domain) return;
|
||||
if (!this.isAlive(pid)) return;
|
||||
candidates.push({ name, pid, raw });
|
||||
|
||||
@@ -696,6 +696,18 @@ export function replaySubagentTerminalState(
|
||||
: "failed";
|
||||
}
|
||||
|
||||
/**
|
||||
* Whether the tool result `block` only tells that a background launch
|
||||
* started. Claude Code answers such a launch at once with "Async agent
|
||||
* launched", so the result is not the end of the child. Its task
|
||||
* notification tells the end.
|
||||
*/
|
||||
export function isBackgroundLaunchResult(block: Record<string, unknown>): boolean {
|
||||
return (
|
||||
block.is_error !== true && /^\s*Async agent launched\b/.test(replayContentText(block.content))
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* How `child`'s work ended: the state of its last task notification, else
|
||||
* `cancelled` for a child the user stopped, else the result of its foreground
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
{"kind":"initialize","payload":{"_meta":{"jetbrains":{"air":{"capabilities":["sessionFailure","agentFileChangeReport","nativeSubagentSessions","asyncTasks","customInstructions","recommendedValue","diffPatch","planFile","backgroundSubagents","knownModels"],"goal":{"actions":["set","clear"],"controlMethod":"_session/goal","version":1},"version":1}},"sessionRead":{"filters":{"subagents":{}},"subagents":{},"supported":true},"steering":{"supported":true}},"agentCapabilities":{"_meta":{"authStatus":{},"claudeCode":{"promptQueueing":true}},"auth":{"logout":{},"status":{}},"loadSession":true,"mcpCapabilities":{"acp":true,"http":true,"sse":true},"promptCapabilities":{"embeddedContext":true,"image":true},"providers":{},"sessionCapabilities":{"additionalDirectories":{},"close":{},"delete":{},"fork":{},"list":{},"options":{},"resume":{},"status":{},"subagents":{},"systemPrompt":{"mode":{"override":{}}},"title":{}}},"agentInfo":{"name":"@agentclientprotocol/claude-agent-acp","title":"Claude Agent","version":"<version>"},"authMethods":[],"protocolVersion":1}}
|
||||
{"kind":"initialize","payload":{"_meta":{"jetbrains":{"air":{"capabilities":["sessionFailure","agentFileChangeReport","nativeSubagentSessions","asyncTasks","customInstructions","recommendedValue","diffPatch","planFile","backgroundSubagents","sessionWriterGuard","knownModels"],"goal":{"actions":["set","clear"],"controlMethod":"_session/goal","version":1},"version":1}},"sessionRead":{"filters":{"subagents":{}},"subagents":{},"supported":true},"steering":{"supported":true}},"agentCapabilities":{"_meta":{"authStatus":{},"claudeCode":{"promptQueueing":true}},"auth":{"logout":{},"status":{}},"loadSession":true,"mcpCapabilities":{"acp":true,"http":true,"sse":true},"promptCapabilities":{"embeddedContext":true,"image":true},"providers":{},"sessionCapabilities":{"additionalDirectories":{},"close":{},"delete":{},"fork":{},"list":{},"options":{},"resume":{},"status":{},"subagents":{},"systemPrompt":{"mode":{"override":{}}},"title":{}}},"agentInfo":{"name":"@agentclientprotocol/claude-agent-acp","title":"Claude Agent","version":"<version>"},"authMethods":[],"protocolVersion":1}}
|
||||
{"kind":"sessionUpdate","payload":{"sessionId":"<session>","update":{"content":{"text":"Fix the bug","type":"text"},"messageId":"00000000-0000-4000-8000-00000000c001","sessionUpdate":"user_message_chunk"}}}
|
||||
{"kind":"sessionUpdate","payload":{"sessionId":"<session>","update":{"content":{"text":"Check the file.","type":"text"},"messageId":"msg_r1","sessionUpdate":"agent_thought_chunk"}}}
|
||||
{"kind":"sessionUpdate","payload":{"sessionId":"<session>","update":{"content":{"text":"I will edit it.","type":"text"},"messageId":"msg_r1","sessionUpdate":"agent_message_chunk"}}}
|
||||
|
||||
@@ -1,3 +1,3 @@
|
||||
{"kind":"initialize","payload":{"_meta":{"jetbrains":{"air":{"capabilities":["sessionFailure","agentFileChangeReport","nativeSubagentSessions","asyncTasks","customInstructions","recommendedValue","diffPatch","planFile","backgroundSubagents","knownModels"],"goal":{"actions":["set","clear"],"controlMethod":"_session/goal","version":1},"version":1}},"sessionRead":{"filters":{"subagents":{}},"subagents":{},"supported":true},"steering":{"supported":true}},"agentCapabilities":{"_meta":{"authStatus":{},"claudeCode":{"promptQueueing":true}},"auth":{"logout":{},"status":{}},"loadSession":true,"mcpCapabilities":{"acp":true,"http":true,"sse":true},"promptCapabilities":{"embeddedContext":true,"image":true},"providers":{},"sessionCapabilities":{"additionalDirectories":{},"close":{},"delete":{},"fork":{},"list":{},"options":{},"resume":{},"status":{},"subagents":{},"systemPrompt":{"mode":{"override":{}}},"title":{}}},"agentInfo":{"name":"@agentclientprotocol/claude-agent-acp","title":"Claude Agent","version":"<version>"},"authMethods":[],"protocolVersion":1}}
|
||||
{"kind":"initialize","payload":{"_meta":{"jetbrains":{"air":{"capabilities":["sessionFailure","agentFileChangeReport","nativeSubagentSessions","asyncTasks","customInstructions","recommendedValue","diffPatch","planFile","backgroundSubagents","sessionWriterGuard","knownModels"],"goal":{"actions":["set","clear"],"controlMethod":"_session/goal","version":1},"version":1}},"sessionRead":{"filters":{"subagents":{}},"subagents":{},"supported":true},"steering":{"supported":true}},"agentCapabilities":{"_meta":{"authStatus":{},"claudeCode":{"promptQueueing":true}},"auth":{"logout":{},"status":{}},"loadSession":true,"mcpCapabilities":{"acp":true,"http":true,"sse":true},"promptCapabilities":{"embeddedContext":true,"image":true},"providers":{},"sessionCapabilities":{"additionalDirectories":{},"close":{},"delete":{},"fork":{},"list":{},"options":{},"resume":{},"status":{},"subagents":{},"systemPrompt":{"mode":{"override":{}}},"title":{}}},"agentInfo":{"name":"@agentclientprotocol/claude-agent-acp","title":"Claude Agent","version":"<version>"},"authMethods":[],"protocolVersion":1}}
|
||||
{"kind":"newSession","payload":{"configOptions":[{"category":"model","currentValue":"claude-sonnet-4-6","description":"AI model to use","id":"model","name":"Model","options":[{"description":"Fast","name":"Claude Sonnet 4.6","value":"claude-sonnet-4-6"}],"type":"select"},{"category":"mode","currentValue":"auto","description":"Session permission mode","id":"mode","name":"Mode","options":[{"_meta":{"jetbrains":{"air":{"kind":"standard","version":1}}},"description":"Always ask before making changes","name":"Manual","value":"default"},{"_meta":{"jetbrains":{"air":{"kind":"standard","version":1}}},"description":"Automatically accept all file edits","name":"Accept edits","value":"acceptEdits"},{"_meta":{"jetbrains":{"air":{"kind":"plan","version":1}}},"description":"Create a plan before making changes","name":"Plan","value":"plan"},{"_meta":{"jetbrains":{"air":{"kind":"auto_review","version":1}}},"description":"Claude handles permission decisions","name":"Auto","value":"auto"},{"_meta":{"jetbrains":{"air":{"kind":"full_access","version":1}}},"description":"Accepts all permissions","name":"Bypass permissions","value":"bypassPermissions"}],"type":"select"}],"modes":{"availableModes":[{"_meta":{"jetbrains":{"air":{"kind":"standard","version":1}}},"description":"Always ask before making changes","id":"default","name":"Manual"},{"_meta":{"jetbrains":{"air":{"kind":"standard","version":1}}},"description":"Automatically accept all file edits","id":"acceptEdits","name":"Accept edits"},{"_meta":{"jetbrains":{"air":{"kind":"plan","version":1}}},"description":"Create a plan before making changes","id":"plan","name":"Plan"},{"_meta":{"jetbrains":{"air":{"kind":"auto_review","version":1}}},"description":"Claude handles permission decisions","id":"auto","name":"Auto"},{"_meta":{"jetbrains":{"air":{"kind":"full_access","version":1}}},"description":"Accepts all permissions","id":"bypassPermissions","name":"Bypass permissions"}],"currentModeId":"auto"},"sessionId":"<session>"}}
|
||||
{"kind":"sessionUpdate","payload":{"sessionId":"<session>","update":{"availableCommands":[{"description":"Show the MCP servers and their status, or reconnect, enable, or disable a server","input":{"hint":"[reconnect|enable|disable [<server>|all]]"},"name":"mcp"},{"description":"Manage Claude Code plugins and marketplaces","input":{"hint":"[install|uninstall|enable|disable|update|list|marketplace …] …"},"name":"plugin"}],"sessionUpdate":"available_commands_update"}}}
|
||||
|
||||
@@ -3259,6 +3259,135 @@ describe("task notification replay", () => {
|
||||
});
|
||||
});
|
||||
|
||||
describe("the end of a background Agent", () => {
|
||||
const agentCapabilities = {
|
||||
subagents: {},
|
||||
_meta: { jetbrains: { air: { version: 1, capabilities: ["asyncTasks"] } } },
|
||||
} as ClientCapabilities;
|
||||
const backgroundLaunch = (inputFlag: boolean) => [
|
||||
record({
|
||||
type: "assistant",
|
||||
uuid: "a1",
|
||||
message: {
|
||||
id: "m1",
|
||||
role: "assistant",
|
||||
model: "claude-opus-5",
|
||||
content: [
|
||||
{
|
||||
type: "tool_use",
|
||||
id: "toolu_agent",
|
||||
name: "Agent",
|
||||
input: {
|
||||
description: "Explore",
|
||||
prompt: "Look around",
|
||||
...(inputFlag ? { run_in_background: true } : {}),
|
||||
},
|
||||
},
|
||||
],
|
||||
},
|
||||
}),
|
||||
record({
|
||||
type: "user",
|
||||
uuid: "u2",
|
||||
message: {
|
||||
role: "user",
|
||||
content: [
|
||||
{
|
||||
type: "tool_result",
|
||||
tool_use_id: "toolu_agent",
|
||||
content: [{ type: "text", text: "Async agent launched successfully.\nagentId: a1" }],
|
||||
},
|
||||
],
|
||||
},
|
||||
}),
|
||||
];
|
||||
const agentNotification = (status: string, uuid = `u-${status}`) =>
|
||||
record({
|
||||
type: "user",
|
||||
uuid,
|
||||
message: { role: "user", content: notificationText(status, "toolu_agent") },
|
||||
origin: { kind: "task-notification" },
|
||||
});
|
||||
const later = record({
|
||||
type: "user",
|
||||
uuid: "u9",
|
||||
message: { role: "user", content: "What did it find?" },
|
||||
});
|
||||
const trace = (updates: AcpSessionNotification[]) =>
|
||||
updates.flatMap(({ sessionId: target, update }) =>
|
||||
update.sessionUpdate === "subagent_spawned" ||
|
||||
update.sessionUpdate === "subagent_state_update" ||
|
||||
update.sessionUpdate === "user_message_chunk"
|
||||
? [
|
||||
[
|
||||
target,
|
||||
update.sessionUpdate,
|
||||
(update as { state?: string }).state ??
|
||||
(update as { content?: { text?: string } }).content?.text,
|
||||
],
|
||||
]
|
||||
: [],
|
||||
);
|
||||
|
||||
it.each([
|
||||
{ status: "completed", state: "completed" },
|
||||
{ status: "failed", state: "failed" },
|
||||
{ status: "stopped", state: "cancelled" },
|
||||
])("sends the $status end at the position of its notification", async ({ status, state }) => {
|
||||
const updates = await replay(
|
||||
[...backgroundLaunch(false), agentNotification(status), later],
|
||||
agentCapabilities,
|
||||
);
|
||||
|
||||
expect(trace(updates)).toEqual([
|
||||
["s1", "subagent_spawned", undefined],
|
||||
["s1", "subagent_state_update", state],
|
||||
["s1", "user_message_chunk", "What did it find?"],
|
||||
// The end state of each child after the history.
|
||||
["s1", "subagent_state_update", state],
|
||||
]);
|
||||
expect(
|
||||
updates.find(({ update }) => update.sessionUpdate === "subagent_state_update")?.update,
|
||||
).toEqual({
|
||||
sessionUpdate: "subagent_state_update",
|
||||
subagentSessionId: "s1:replay-subagent:toolu_agent",
|
||||
state,
|
||||
});
|
||||
});
|
||||
|
||||
it("sends a repeated notification of the same end once at its position", async () => {
|
||||
const updates = await replay(
|
||||
[
|
||||
...backgroundLaunch(true),
|
||||
agentNotification("completed"),
|
||||
agentNotification("completed", "u-again"),
|
||||
later,
|
||||
],
|
||||
agentCapabilities,
|
||||
);
|
||||
|
||||
expect(trace(updates)).toEqual([
|
||||
["s1", "subagent_spawned", undefined],
|
||||
["s1", "subagent_state_update", "completed"],
|
||||
["s1", "user_message_chunk", "What did it find?"],
|
||||
["s1", "subagent_state_update", "completed"],
|
||||
]);
|
||||
});
|
||||
|
||||
it.each([false, true])(
|
||||
"does not take the launch result for the end of a child without a notification (input flag %s)",
|
||||
async (inputFlag) => {
|
||||
const updates = await replay(backgroundLaunch(inputFlag), agentCapabilities);
|
||||
|
||||
// The process that ran the child is gone, so the load ends it as disconnected.
|
||||
expect(trace(updates)).toEqual([
|
||||
["s1", "subagent_spawned", undefined],
|
||||
["s1", "subagent_state_update", "disconnected"],
|
||||
]);
|
||||
},
|
||||
);
|
||||
});
|
||||
|
||||
it("keeps a task-notification delivery with a subkind as a prompt", async () => {
|
||||
const updates = await replay([
|
||||
record({
|
||||
@@ -15526,6 +15655,7 @@ describe("logout", () => {
|
||||
"diffPatch",
|
||||
"planFile",
|
||||
"backgroundSubagents",
|
||||
"sessionWriterGuard",
|
||||
"knownModels",
|
||||
],
|
||||
goal: { version: 1, controlMethod: GOAL_CONTROL_METHOD, actions: ["set", "clear"] },
|
||||
@@ -15551,6 +15681,7 @@ describe("logout", () => {
|
||||
"diffPatch",
|
||||
"planFile",
|
||||
"backgroundSubagents",
|
||||
"sessionWriterGuard",
|
||||
"knownModels",
|
||||
],
|
||||
goal: { version: 1, controlMethod: GOAL_CONTROL_METHOD, actions: ["set", "clear"] },
|
||||
|
||||
@@ -289,6 +289,7 @@ describe("sessionIndex negotiation", () => {
|
||||
"diffPatch",
|
||||
"planFile",
|
||||
"backgroundSubagents",
|
||||
"sessionWriterGuard",
|
||||
"knownModels",
|
||||
];
|
||||
|
||||
|
||||
533
src/tests/v1/session-writers.test.ts
Normal file
533
src/tests/v1/session-writers.test.ts
Normal file
@@ -0,0 +1,533 @@
|
||||
import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
|
||||
import type { ClientCapabilities, SessionNotification } from "@agentclientprotocol/sdk/unstable";
|
||||
import { execFileSync, spawn, spawnSync } from "node:child_process";
|
||||
import { mkdir, mkdtemp, rm, writeFile } from "node:fs/promises";
|
||||
import os from "node:os";
|
||||
import path from "node:path";
|
||||
import { query } from "@anthropic-ai/claude-agent-sdk";
|
||||
import type { AcpClient } from "../../acp-client.js";
|
||||
import { ClaudeAcpAgent } from "../../v1/acp-agent.js";
|
||||
import { initializeClient } from "../helpers.js";
|
||||
import { mockSessionState } from "./session-doubles.js";
|
||||
|
||||
vi.mock("@anthropic-ai/claude-agent-sdk", async (importOriginal) => {
|
||||
const actual = await importOriginal<typeof import("@anthropic-ai/claude-agent-sdk")>();
|
||||
return {
|
||||
...actual,
|
||||
query: vi.fn(() => {
|
||||
throw new Error("The writer guard must not start Claude Code");
|
||||
}),
|
||||
};
|
||||
});
|
||||
|
||||
const sessionId = "44444444-4444-4444-8444-444444444444";
|
||||
const cwd = "/tmp/proj";
|
||||
const record = {
|
||||
type: "user",
|
||||
uuid: "u1",
|
||||
parentUuid: null,
|
||||
sessionId,
|
||||
cwd,
|
||||
version: "2.0.0",
|
||||
userType: "external",
|
||||
isSidechain: false,
|
||||
timestamp: "2026-09-24T00:00:00.000Z",
|
||||
message: { role: "user", content: "Hi" },
|
||||
};
|
||||
|
||||
describe("the writer guard", () => {
|
||||
let configDir: string;
|
||||
let originalConfigDir: string | undefined;
|
||||
let agent: ClaudeAcpAgent;
|
||||
|
||||
/** The start time of `pid` as the CLI records it in the live registry. */
|
||||
const processStart = (pid: number) =>
|
||||
execFileSync("ps", ["-o", "lstart=", "-p", String(pid)], {
|
||||
env: { ...process.env, LC_ALL: "C", TZ: "UTC" },
|
||||
})
|
||||
.toString()
|
||||
.trim();
|
||||
/** Writes the live registry record of `pid` for the session, as Claude Code writes it. */
|
||||
const register = (pid: number, extra: Record<string, unknown> = {}) =>
|
||||
writeFile(
|
||||
path.join(configDir, "sessions", `${pid}.json`),
|
||||
JSON.stringify({
|
||||
pid,
|
||||
sessionId,
|
||||
cwd,
|
||||
kind: "interactive",
|
||||
entrypoint: "cli",
|
||||
status: "busy",
|
||||
procStart: "procStart" in extra ? extra.procStart : processStart(pid),
|
||||
startedAt: Date.now(),
|
||||
updatedAt: Date.now(),
|
||||
...extra,
|
||||
}),
|
||||
);
|
||||
/** A pid of a process that ended. */
|
||||
const deadPid = () => spawnSync(process.execPath, ["-e", ""]).pid!;
|
||||
const newAgent = async (capabilities: string[]) => {
|
||||
await agent?.dispose();
|
||||
agent = new ClaudeAcpAgent(
|
||||
{ sessionUpdate: async (_update: SessionNotification) => {} } as unknown as AcpClient,
|
||||
{ log: () => {}, error: () => {} },
|
||||
);
|
||||
await initializeClient(agent, {
|
||||
_meta: { jetbrains: { air: { version: 1, capabilities } } },
|
||||
} as ClientCapabilities);
|
||||
};
|
||||
const load = () => agent.loadSession({ sessionId, cwd, mcpServers: [] });
|
||||
const resume = () => agent.resumeSession({ sessionId, cwd, mcpServers: [] });
|
||||
/** The session start of a load and a resume, which the guard comes before. */
|
||||
const stubStart = () => {
|
||||
const started = new Error("the session starts");
|
||||
return [
|
||||
vi.spyOn(agent as any, "createSessionWhileReplaying").mockRejectedValue(started),
|
||||
vi.spyOn(agent as any, "getOrCreateSession").mockRejectedValue(started),
|
||||
];
|
||||
};
|
||||
const refusal = {
|
||||
code: -32600,
|
||||
data: {
|
||||
reason: "thread_active_writer",
|
||||
sessionId,
|
||||
held: { entrypoint: "cli", status: "busy" },
|
||||
details: `session ${sessionId} already has an active writer`,
|
||||
},
|
||||
};
|
||||
|
||||
beforeEach(async () => {
|
||||
configDir = await mkdtemp(path.join(os.tmpdir(), "claude-acp-session-writers-"));
|
||||
originalConfigDir = process.env.CLAUDE_CONFIG_DIR;
|
||||
process.env.CLAUDE_CONFIG_DIR = configDir;
|
||||
const projectDir = path.join(configDir, "projects", "-tmp-proj");
|
||||
await mkdir(projectDir, { recursive: true });
|
||||
await mkdir(path.join(configDir, "sessions"));
|
||||
await writeFile(path.join(projectDir, `${sessionId}.jsonl`), JSON.stringify(record) + "\n");
|
||||
});
|
||||
|
||||
afterEach(async () => {
|
||||
expect(vi.mocked(query)).not.toHaveBeenCalled();
|
||||
await agent.dispose();
|
||||
vi.restoreAllMocks();
|
||||
if (originalConfigDir === undefined) delete process.env.CLAUDE_CONFIG_DIR;
|
||||
else process.env.CLAUDE_CONFIG_DIR = originalConfigDir;
|
||||
await rm(configDir, { recursive: true, force: true });
|
||||
});
|
||||
|
||||
it("refuses a load and a resume of a held session for a client that declared it", async () => {
|
||||
await newAgent(["nativeSubagentSessions", "sessionWriterGuard"]);
|
||||
await register(process.pid);
|
||||
const starts = stubStart();
|
||||
|
||||
await expect(load()).rejects.toMatchObject(refusal);
|
||||
await expect(resume()).rejects.toMatchObject(refusal);
|
||||
for (const start of starts) expect(start).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it("refuses a load of a session that a live terminal process holds", async () => {
|
||||
await newAgent(["nativeSubagentSessions", "sessionWriterGuard"]);
|
||||
const terminal = spawn("sleep", ["30"]);
|
||||
try {
|
||||
await new Promise((resolve) => terminal.once("spawn", resolve));
|
||||
await register(terminal.pid!);
|
||||
const starts = stubStart();
|
||||
|
||||
await expect(load()).rejects.toMatchObject(refusal);
|
||||
for (const start of starts) expect(start).not.toHaveBeenCalled();
|
||||
} finally {
|
||||
terminal.kill();
|
||||
}
|
||||
});
|
||||
|
||||
it("starts a held session for a client that did not declare it", async () => {
|
||||
await newAgent(["nativeSubagentSessions"]);
|
||||
await register(process.pid);
|
||||
stubStart();
|
||||
|
||||
await expect(load()).rejects.toThrow("the session starts");
|
||||
await expect(resume()).rejects.toThrow("the session starts");
|
||||
});
|
||||
|
||||
it("starts a free session for a client that declared it", async () => {
|
||||
await newAgent(["nativeSubagentSessions", "sessionWriterGuard"]);
|
||||
await register(deadPid(), { procStart: "Thu Jan 1 00:00:00 2026" });
|
||||
stubStart();
|
||||
|
||||
await expect(load()).rejects.toThrow("the session starts");
|
||||
});
|
||||
|
||||
it("counts a session whose query closed as not run here: a live record holds it", async () => {
|
||||
await newAgent(["nativeSubagentSessions", "sessionWriterGuard"]);
|
||||
const sessions = (agent as any).sessions;
|
||||
sessions[sessionId] = mockSessionState({}, agent, sessionId);
|
||||
sessions[sessionId].queryClosed = true;
|
||||
// The process of the closed query ended, so this record is of a terminal.
|
||||
await register(process.pid);
|
||||
const starts = stubStart();
|
||||
try {
|
||||
await expect(load()).rejects.toMatchObject(refusal);
|
||||
await expect(resume()).rejects.toMatchObject(refusal);
|
||||
for (const start of starts) expect(start).not.toHaveBeenCalled();
|
||||
} finally {
|
||||
delete sessions[sessionId];
|
||||
}
|
||||
});
|
||||
|
||||
/** A session with a query that a replacement can close. */
|
||||
const openSession = () =>
|
||||
mockSessionState({ input: { end: vi.fn() }, query: { close: vi.fn() } }, agent, sessionId);
|
||||
/**
|
||||
* A replacement of the query of the session, as a rewind or a sign-out
|
||||
* respawn runs it. The new query starts when `end` is called.
|
||||
*/
|
||||
const startReplacement = () => {
|
||||
const sessions = (agent as any).sessions;
|
||||
let end!: () => void;
|
||||
const started = new Promise<void>((resolve) => (end = resolve));
|
||||
vi.spyOn(agent as any, "recreateLiveSession").mockImplementation(async () => {
|
||||
await started;
|
||||
sessions[sessionId] = openSession();
|
||||
});
|
||||
vi.spyOn(agent as any, "restoreSessionChoices").mockResolvedValue(undefined);
|
||||
vi.spyOn(agent as any, "ensureConsumer").mockImplementation(() => {});
|
||||
vi.spyOn(agent as any, "connectRemoteControlAtStartup").mockResolvedValue(undefined);
|
||||
const session = sessions[sessionId];
|
||||
const running = (agent as any).replaceSessionQuery(
|
||||
sessionId,
|
||||
session,
|
||||
session.creationParams ?? { cwd, mcpServers: [] },
|
||||
) as Promise<void>;
|
||||
return { end, running };
|
||||
};
|
||||
/** A live process with a registry record of the session, as a Claude Code process of this agent has. */
|
||||
const liveProcess = async (extra: Record<string, unknown> = {}) => {
|
||||
const child = spawn("sleep", ["30"]);
|
||||
await new Promise((resolve) => child.once("spawn", resolve));
|
||||
await register(child.pid!, { entrypoint: "sdk-ts", ...extra });
|
||||
const exited = new Promise((resolve) => child.once("exit", resolve));
|
||||
let stopped: Promise<void> | undefined;
|
||||
return {
|
||||
stop: () =>
|
||||
(stopped ??= (async () => {
|
||||
child.kill();
|
||||
await exited;
|
||||
})()),
|
||||
};
|
||||
};
|
||||
|
||||
it("admits a prompt during a replacement of the query after the replacement ends", async () => {
|
||||
await newAgent(["nativeSubagentSessions", "sessionWriterGuard"]);
|
||||
const sessions = (agent as any).sessions;
|
||||
sessions[sessionId] = openSession();
|
||||
const teardown = vi.spyOn(agent as any, "teardownSession").mockResolvedValue(undefined);
|
||||
// The old process of this agent still ends, and the new one has started.
|
||||
const old = await liveProcess({ statusUpdatedAt: Date.now() - 1000 });
|
||||
const fresh = await liveProcess();
|
||||
const { end, running } = startReplacement();
|
||||
try {
|
||||
let admitted = false;
|
||||
const admission = ((agent as any).admitPromptWriter(sessionId) as Promise<void>).then(
|
||||
() => (admitted = true),
|
||||
);
|
||||
await new Promise((resolve) => setTimeout(resolve, 50));
|
||||
expect(admitted).toBe(false);
|
||||
|
||||
await old.stop();
|
||||
end();
|
||||
await running;
|
||||
await admission;
|
||||
expect(admitted).toBe(true);
|
||||
expect(teardown).not.toHaveBeenCalled();
|
||||
} finally {
|
||||
end();
|
||||
await old.stop();
|
||||
await fresh.stop();
|
||||
delete sessions[sessionId];
|
||||
}
|
||||
});
|
||||
|
||||
it("waits for a replacement of the query before the writer check of a resume", async () => {
|
||||
await newAgent(["nativeSubagentSessions", "sessionWriterGuard"]);
|
||||
const sessions = (agent as any).sessions;
|
||||
sessions[sessionId] = openSession();
|
||||
const old = await liveProcess({ statusUpdatedAt: Date.now() - 1000 });
|
||||
const fresh = await liveProcess();
|
||||
const { end, running } = startReplacement();
|
||||
const starts = stubStart();
|
||||
try {
|
||||
const resuming = resume();
|
||||
await new Promise((resolve) => setTimeout(resolve, 50));
|
||||
await old.stop();
|
||||
end();
|
||||
await running;
|
||||
// The check sees the new query of this agent and one live record: the resume goes on.
|
||||
await expect(resuming).rejects.toThrow("the session starts");
|
||||
expect(starts[1]).toHaveBeenCalled();
|
||||
} finally {
|
||||
end();
|
||||
await old.stop();
|
||||
await fresh.stop();
|
||||
delete sessions[sessionId];
|
||||
}
|
||||
});
|
||||
|
||||
it("admits a prompt right after a sign-out without a wait", async () => {
|
||||
await newAgent(["nativeSubagentSessions", "sessionWriterGuard"]);
|
||||
const sessions = (agent as any).sessions;
|
||||
const session = openSession();
|
||||
session.creationParams = { cwd, mcpServers: [] };
|
||||
sessions[sessionId] = session;
|
||||
process.argv.push("--hide-claude-auth");
|
||||
try {
|
||||
(agent as any).markSessionForSignOutRespawn(sessionId, session);
|
||||
expect(session.queryClosed).toBe(true);
|
||||
|
||||
// No live record: the writer check of the prompt answers at once.
|
||||
const admitted = (agent as any).admitPromptWriter(sessionId) as Promise<void>;
|
||||
const late = new Promise((resolve) => setTimeout(() => resolve("late"), 1000));
|
||||
expect(await Promise.race([admitted.then(() => "admitted"), late])).toBe("admitted");
|
||||
} finally {
|
||||
process.argv.splice(process.argv.indexOf("--hide-claude-auth"), 1);
|
||||
clearTimeout((agent as any).closingHandovers?.get(sessionId)?.timer);
|
||||
delete sessions[sessionId];
|
||||
}
|
||||
});
|
||||
|
||||
/** A session of this agent whose query a sign-out closes. */
|
||||
const signOut = (session: any) => {
|
||||
process.argv.push("--hide-claude-auth");
|
||||
try {
|
||||
(agent as any).markSessionForSignOutRespawn(sessionId, session);
|
||||
} finally {
|
||||
process.argv.splice(process.argv.indexOf("--hide-claude-auth"), 1);
|
||||
}
|
||||
};
|
||||
|
||||
it("lets a prompt after a sign-out wait for the closed process of this agent to end", async () => {
|
||||
await newAgent(["nativeSubagentSessions", "sessionWriterGuard"]);
|
||||
const sessions = (agent as any).sessions;
|
||||
const session = openSession();
|
||||
session.creationParams = { cwd, mcpServers: [] };
|
||||
sessions[sessionId] = session;
|
||||
const teardown = vi.spyOn(agent as any, "teardownSession").mockResolvedValue(undefined);
|
||||
// The process of this agent that the sign-out closes.
|
||||
const closed = await liveProcess();
|
||||
try {
|
||||
signOut(session);
|
||||
let admitted = false;
|
||||
const admission = ((agent as any).admitPromptWriter(sessionId) as Promise<void>).then(
|
||||
() => (admitted = true),
|
||||
);
|
||||
await new Promise((resolve) => setTimeout(resolve, 300));
|
||||
expect(admitted).toBe(false);
|
||||
|
||||
await closed.stop();
|
||||
await admission;
|
||||
expect(teardown).not.toHaveBeenCalled();
|
||||
} finally {
|
||||
await closed.stop();
|
||||
clearTimeout((agent as any).closingHandovers.get(sessionId)?.timer);
|
||||
delete sessions[sessionId];
|
||||
}
|
||||
});
|
||||
|
||||
it("refuses a prompt after a sign-out at once when another process has the session", async () => {
|
||||
await newAgent(["nativeSubagentSessions", "sessionWriterGuard"]);
|
||||
const sessions = (agent as any).sessions;
|
||||
const session = openSession();
|
||||
session.creationParams = { cwd, mcpServers: [] };
|
||||
sessions[sessionId] = session;
|
||||
const teardown = vi.spyOn(agent as any, "teardownSession").mockResolvedValue(undefined);
|
||||
signOut(session);
|
||||
// A terminal resumed the session after the sign-out.
|
||||
const terminal = await liveProcess({ entrypoint: "cli" });
|
||||
try {
|
||||
const startedAt = performance.now();
|
||||
await expect(
|
||||
(agent as any).admitPromptWriter(sessionId) as Promise<void>,
|
||||
).rejects.toMatchObject({ data: { reason: "thread_active_writer" } });
|
||||
expect(performance.now() - startedAt).toBeLessThan(1000);
|
||||
expect(teardown).toHaveBeenCalledWith(sessionId);
|
||||
} finally {
|
||||
await terminal.stop();
|
||||
clearTimeout((agent as any).closingHandovers.get(sessionId)?.timer);
|
||||
delete sessions[sessionId];
|
||||
}
|
||||
});
|
||||
|
||||
/** Waits `ms`, then tells whether `promise` settled: "pending", "resolved" or "rejected". */
|
||||
const stateAfter = async (promise: Promise<unknown>, ms: number) => {
|
||||
let state = "pending";
|
||||
promise.then(
|
||||
() => (state = "resolved"),
|
||||
() => (state = "rejected"),
|
||||
);
|
||||
await new Promise((resolve) => setTimeout(resolve, ms));
|
||||
return state;
|
||||
};
|
||||
|
||||
it("lets a prompt right after a replacement wait for the old process of this agent to end", async () => {
|
||||
await newAgent(["nativeSubagentSessions", "sessionWriterGuard"]);
|
||||
const sessions = (agent as any).sessions;
|
||||
sessions[sessionId] = openSession();
|
||||
const teardown = vi.spyOn(agent as any, "teardownSession").mockResolvedValue(undefined);
|
||||
// The process of this agent that the replacement closes.
|
||||
const old = await liveProcess({ statusUpdatedAt: Date.now() - 1000 });
|
||||
const { end, running } = startReplacement();
|
||||
const fresh = await liveProcess();
|
||||
try {
|
||||
end();
|
||||
await running;
|
||||
// The new query is ready, and the old process has not ended yet.
|
||||
const admission = (agent as any).admitPromptWriter(sessionId) as Promise<void>;
|
||||
expect(await stateAfter(admission, 300)).toBe("pending");
|
||||
|
||||
await old.stop();
|
||||
await admission;
|
||||
expect(teardown).not.toHaveBeenCalled();
|
||||
} finally {
|
||||
end();
|
||||
await old.stop();
|
||||
await fresh.stop();
|
||||
delete sessions[sessionId];
|
||||
}
|
||||
});
|
||||
|
||||
it("lets a load right after a close wait for the closed process of this agent to end", async () => {
|
||||
await newAgent(["nativeSubagentSessions", "sessionWriterGuard"]);
|
||||
const sessions = (agent as any).sessions;
|
||||
sessions[sessionId] = openSession();
|
||||
const own = await liveProcess();
|
||||
stubStart();
|
||||
try {
|
||||
await agent.closeSession({ sessionId });
|
||||
expect(sessions[sessionId]).toBeUndefined();
|
||||
|
||||
const loading = load();
|
||||
expect(await stateAfter(loading, 300)).toBe("pending");
|
||||
|
||||
await own.stop();
|
||||
await expect(loading).rejects.toThrow("the session starts");
|
||||
} finally {
|
||||
await own.stop();
|
||||
}
|
||||
});
|
||||
|
||||
it("lets a prompt after a load with other params wait for the old process of this agent to end", async () => {
|
||||
await newAgent(["nativeSubagentSessions", "sessionWriterGuard"]);
|
||||
const sessions = (agent as any).sessions;
|
||||
// Its params differ from the params of the load, so the load replaces its query.
|
||||
const original = (sessions[sessionId] = openSession());
|
||||
vi.spyOn(agent as any, "validateCwd").mockResolvedValue(undefined);
|
||||
const old = await liveProcess({ statusUpdatedAt: Date.now() - 1000 });
|
||||
let fresh: Awaited<ReturnType<typeof liveProcess>> | undefined;
|
||||
vi.spyOn(agent as any, "startSessionAroundRefusedMcpServers").mockImplementation(async () => {
|
||||
fresh = await liveProcess();
|
||||
sessions[sessionId] = openSession();
|
||||
return { sessionId };
|
||||
});
|
||||
try {
|
||||
await (agent as any).getOrCreateSession({ sessionId, cwd, mcpServers: [] });
|
||||
expect(fresh).toBeDefined();
|
||||
|
||||
const admission = (agent as any).admitPromptWriter(sessionId) as Promise<void>;
|
||||
expect(await stateAfter(admission, 300)).toBe("pending");
|
||||
|
||||
await old.stop();
|
||||
await admission;
|
||||
expect(sessions[sessionId]).not.toBe(original);
|
||||
expect(sessions[sessionId]?.queryClosed).not.toBe(true);
|
||||
} finally {
|
||||
await old.stop();
|
||||
await fresh?.stop();
|
||||
delete sessions[sessionId];
|
||||
}
|
||||
});
|
||||
|
||||
it("names the other process, not the newer record of its own process, in a refusal", async () => {
|
||||
await newAgent(["nativeSubagentSessions", "sessionWriterGuard"]);
|
||||
const sessions = (agent as any).sessions;
|
||||
sessions[sessionId] = mockSessionState({}, agent, sessionId);
|
||||
vi.spyOn(agent as any, "teardownSession").mockResolvedValue(undefined);
|
||||
// The record of its own Claude Code process: the session is not held.
|
||||
await register(process.pid, { entrypoint: "sdk-ts", status: "busy" });
|
||||
await expect(
|
||||
(agent as any).assertSoleWriter(sessionId) as Promise<void>,
|
||||
).resolves.toBeUndefined();
|
||||
const terminal = await liveProcess({
|
||||
entrypoint: "cli",
|
||||
status: "idle",
|
||||
statusUpdatedAt: Date.now() - 5000,
|
||||
});
|
||||
try {
|
||||
// Its own process reports a status after the terminal does.
|
||||
await register(process.pid, {
|
||||
entrypoint: "sdk-ts",
|
||||
status: "busy",
|
||||
statusUpdatedAt: Date.now(),
|
||||
});
|
||||
await expect(
|
||||
(agent as any).admitPromptWriter(sessionId) as Promise<void>,
|
||||
).rejects.toMatchObject({ data: { held: { entrypoint: "cli", status: "idle" } } });
|
||||
} finally {
|
||||
await terminal.stop();
|
||||
delete sessions[sessionId];
|
||||
}
|
||||
});
|
||||
|
||||
it("refuses an idle steer before it reports a new turn when a second process resumed the session", async () => {
|
||||
await newAgent(["nativeSubagentSessions", "sessionWriterGuard"]);
|
||||
const sessions = (agent as any).sessions;
|
||||
sessions[sessionId] = mockSessionState({}, agent, sessionId);
|
||||
const teardown = vi
|
||||
.spyOn(agent as any, "teardownSession")
|
||||
.mockImplementation(async (id: unknown) => {
|
||||
delete sessions[id as string];
|
||||
});
|
||||
const prompt = vi.spyOn(agent, "prompt");
|
||||
await register(process.pid, { entrypoint: "sdk-ts", status: "idle" });
|
||||
const terminal = spawn("sleep", ["30"]);
|
||||
try {
|
||||
await new Promise((resolve) => terminal.once("spawn", resolve));
|
||||
await register(terminal.pid!, { statusUpdatedAt: Date.now() + 1000 });
|
||||
await expect(
|
||||
agent.steer({ sessionId, prompt: [{ type: "text", text: "Hi" }] }),
|
||||
).rejects.toMatchObject(refusal);
|
||||
expect(teardown).toHaveBeenCalledWith(sessionId);
|
||||
expect(prompt).not.toHaveBeenCalled();
|
||||
} finally {
|
||||
terminal.kill();
|
||||
}
|
||||
});
|
||||
|
||||
it("refuses a prompt and closes its own Claude Code process when a second process resumed the session", async () => {
|
||||
await newAgent(["nativeSubagentSessions", "sessionWriterGuard"]);
|
||||
const sessions = (agent as any).sessions;
|
||||
sessions[sessionId] = mockSessionState({}, agent, sessionId);
|
||||
const teardown = vi
|
||||
.spyOn(agent as any, "teardownSession")
|
||||
.mockImplementation(async (id: unknown) => {
|
||||
delete sessions[id as string];
|
||||
});
|
||||
// The record of its own Claude Code process: the session is not held.
|
||||
await register(process.pid, { entrypoint: "sdk-ts", status: "idle" });
|
||||
await expect(
|
||||
(agent as any).assertSoleWriter(sessionId) as Promise<void>,
|
||||
).resolves.toBeUndefined();
|
||||
|
||||
// A terminal resumed the session.
|
||||
const terminal = spawn("sleep", ["30"]);
|
||||
try {
|
||||
await new Promise((resolve) => terminal.once("spawn", resolve));
|
||||
await register(terminal.pid!, { statusUpdatedAt: Date.now() + 1000 });
|
||||
await expect(
|
||||
agent.prompt({ sessionId, prompt: [{ type: "text", text: "Hi" }] }),
|
||||
).rejects.toMatchObject(refusal);
|
||||
expect(teardown).toHaveBeenCalledWith(sessionId);
|
||||
expect(sessions[sessionId]).toBeUndefined();
|
||||
} finally {
|
||||
terminal.kill();
|
||||
}
|
||||
});
|
||||
});
|
||||
@@ -148,9 +148,11 @@ import {
|
||||
AIR_LOAD_REPLAY_END_CAPABILITY,
|
||||
AIR_LOAD_REPLAY_END_KEY,
|
||||
AIR_RECOMMENDED_CONFIG_VALUE_CAPABILITY,
|
||||
AIR_SESSION_WRITER_GUARD_CAPABILITY,
|
||||
clientSupportsAirCapability,
|
||||
withAirMeta,
|
||||
} from "../air-extension.js";
|
||||
import { defaultSessionWriters, type ClosingProcesses } from "./session-writers.js";
|
||||
import * as sessionIndex from "./session-index.js";
|
||||
import type {
|
||||
BatchGetSessionsRequest,
|
||||
@@ -267,6 +269,7 @@ import {
|
||||
type ReplayChild,
|
||||
RfdSubagentReplay,
|
||||
ReplayTranscript,
|
||||
isBackgroundLaunchResult,
|
||||
replaySubagentTerminalState,
|
||||
} from "../subagent-replay.js";
|
||||
import {
|
||||
@@ -1732,6 +1735,9 @@ type SessionCreation = {
|
||||
optionsOnly?: boolean;
|
||||
};
|
||||
|
||||
/** How long a writer check after a close of a query waits for the closed process of this agent to end. */
|
||||
const CLOSING_HANDOVER_MS = 10_000;
|
||||
|
||||
export class ClaudeAcpAgent {
|
||||
sessions: {
|
||||
[key: string]: Session;
|
||||
@@ -1802,6 +1808,28 @@ export class ClaudeAcpAgent {
|
||||
string,
|
||||
Map<string, { model: string; sent: ModelEntry }>
|
||||
>();
|
||||
/** The live processes that write each session (docs/air-extensions.md, "Session writers"). */
|
||||
private readonly sessionWriters = defaultSessionWriters();
|
||||
/**
|
||||
* The starts and replacements of the query of each session that run now:
|
||||
* a load, a resume, a rewind with its recovery, a provider switch, a
|
||||
* sign-out respawn, or a plan restart. During one, the session map
|
||||
* holds no session or the closed one, and the old or the new Claude Code
|
||||
* process of this agent has a live registry record. The writer checks count
|
||||
* the session as run here (see {@link replacingQuery}).
|
||||
*/
|
||||
private readonly queryReplacements = new Map<string, Set<Promise<unknown>>>();
|
||||
/**
|
||||
* The sessions whose query this agent closed in the last
|
||||
* {@link CLOSING_HANDOVER_MS}, with the processes that end: a sign-out, a
|
||||
* replacement of the query, or a teardown. A writer check waits for these
|
||||
* processes to end, and a record of any other process is another writer
|
||||
* at once.
|
||||
*/
|
||||
private readonly closingHandovers = new Map<
|
||||
string,
|
||||
{ timer: ReturnType<typeof setTimeout>; closing: ClosingProcesses }
|
||||
>();
|
||||
/** Counts the prompts `startTurn()` has received, across sessions. */
|
||||
private promptsReceived = 0;
|
||||
/** Per session, the `promptsReceived` count when its last cancel started.
|
||||
@@ -1867,7 +1895,7 @@ export class ClaudeAcpAgent {
|
||||
closeQueryStream: (session) => this.closeQueryStream(session),
|
||||
restartSession: async (params, options) => {
|
||||
const previous = this.sessions[options.publicSessionId];
|
||||
await this.createSession(params, options);
|
||||
await this.replacingQuery(options.publicSessionId, this.createSession(params, options));
|
||||
const session = this.sessions[options.publicSessionId];
|
||||
if (!session) throw new Error("Fresh Claude context was not created");
|
||||
// Remote Control that the user turned off stays off on the fresh query,
|
||||
@@ -2056,6 +2084,7 @@ export class ClaudeAcpAgent {
|
||||
AIR_DIFF_PATCH_CAPABILITY,
|
||||
AIR_PLAN_FILE_CAPABILITY,
|
||||
AIR_BACKGROUND_SUBAGENTS_CAPABILITY,
|
||||
AIR_SESSION_WRITER_GUARD_CAPABILITY,
|
||||
AIR_KNOWN_MODELS_CAPABILITY,
|
||||
...this.sessionIndex.capabilities(),
|
||||
...(clientSupportsAirCapability(
|
||||
@@ -2290,6 +2319,19 @@ export class ClaudeAcpAgent {
|
||||
if (!creationParams || session.queryClosed) {
|
||||
throw RequestError.internalError(undefined, SESSION_ENDED_MESSAGE);
|
||||
}
|
||||
// The mark holds across the replacement and the recovery after a failed one.
|
||||
return this.replacingQuery(
|
||||
sessionId,
|
||||
this.rewindLiveSessionNow(params, session, creationParams),
|
||||
);
|
||||
}
|
||||
|
||||
private rewindLiveSessionNow(
|
||||
params: SessionRewindRequest,
|
||||
session: Session,
|
||||
creationParams: NewSessionRequest,
|
||||
): Promise<SessionRewindResponse> {
|
||||
const { sessionId } = params;
|
||||
return rewindSession(params, {
|
||||
logger: this.logger,
|
||||
clearedContext: session.claudeSessionId !== undefined,
|
||||
@@ -2341,6 +2383,7 @@ export class ClaudeAcpAgent {
|
||||
return this.sessionReads.transition(params.sessionId, "open", async () => {
|
||||
const initial = initialConfigOptions(params.configOptions);
|
||||
while (this.providerUpdate) await this.providerUpdate;
|
||||
await this.assertSoleWriter(params.sessionId);
|
||||
const result = await this.withInitialConfigOptions(
|
||||
await this.getOrCreateSession(params),
|
||||
initial,
|
||||
@@ -2358,6 +2401,7 @@ export class ClaudeAcpAgent {
|
||||
const timing = new SessionTiming(this.logger, "load", params.sessionId);
|
||||
const initial = initialConfigOptions(params.configOptions);
|
||||
while (this.providerUpdate) await this.providerUpdate;
|
||||
await this.assertSoleWriter(params.sessionId);
|
||||
let result: NewSessionResponse;
|
||||
if (this.sessions[params.sessionId]) {
|
||||
const resumedSession = await readResumedSession(params.sessionId, this.logger);
|
||||
@@ -2390,6 +2434,92 @@ export class ClaudeAcpAgent {
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* For a client that declared `sessionWriterGuard`, refuses a second writer
|
||||
* of the session: another live process holds it (see
|
||||
* `SessionWriters.assertWritable`). A client that did not declare it loads
|
||||
* and prompts such a session as before.
|
||||
*/
|
||||
private async assertSoleWriter(sessionId: string): Promise<void> {
|
||||
if (!this.guardsWriters()) return;
|
||||
await this.queryReplacementsEnded(sessionId);
|
||||
await this.sessionWriters.assertWritable(
|
||||
sessionId,
|
||||
this.runsQueryOf(sessionId),
|
||||
this.closingHandovers.get(sessionId)?.closing,
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* Runs `replacement`, a replacement of the query of `sessionId`, and
|
||||
* records it in {@link queryReplacements} until it ends.
|
||||
*/
|
||||
private async replacingQuery<T>(sessionId: string, replacement: Promise<T>): Promise<T> {
|
||||
let running = this.queryReplacements.get(sessionId);
|
||||
if (!running) this.queryReplacements.set(sessionId, (running = new Set()));
|
||||
running.add(replacement);
|
||||
try {
|
||||
return await replacement;
|
||||
} finally {
|
||||
running.delete(replacement);
|
||||
if (running.size === 0 && this.queryReplacements.get(sessionId) === running) {
|
||||
this.queryReplacements.delete(sessionId);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Waits until no replacement of the query of `sessionId` runs. A writer
|
||||
* check then sees the new query of this agent, not the closed one.
|
||||
*/
|
||||
private async queryReplacementsEnded(sessionId: string): Promise<void> {
|
||||
for (let running = this.queryReplacements.get(sessionId); running?.size;) {
|
||||
await Promise.allSettled([...running]);
|
||||
running = this.queryReplacements.get(sessionId);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Whether this agent runs a Claude Code process for `sessionId`: the
|
||||
* session has a query that is not closed. A session whose query closed
|
||||
* keeps its record here, but its process ended, so a live registry record
|
||||
* of the session is of another process.
|
||||
*/
|
||||
private runsQueryOf(sessionId: string): boolean {
|
||||
const session = this.sessions[sessionId];
|
||||
return session !== undefined && !session.queryClosed;
|
||||
}
|
||||
|
||||
/**
|
||||
* For a client that declared `sessionWriterGuard`, refuses a prompt of a
|
||||
* session that another live process holds too. That process is the newer
|
||||
* act of the user, and the agent cannot close it, so the agent closes its
|
||||
* own session before it throws. A prompt and an idle steer both admit
|
||||
* their turn here.
|
||||
*/
|
||||
private async admitPromptWriter(sessionId: string): Promise<void> {
|
||||
if (!this.guardsWriters()) return;
|
||||
try {
|
||||
await this.queryReplacementsEnded(sessionId);
|
||||
await this.sessionWriters.assertWritable(
|
||||
sessionId,
|
||||
this.runsQueryOf(sessionId),
|
||||
this.closingHandovers.get(sessionId)?.closing,
|
||||
);
|
||||
} catch (error) {
|
||||
await this.teardownSession(sessionId);
|
||||
throw error;
|
||||
}
|
||||
}
|
||||
|
||||
/** Whether the client declared `sessionWriterGuard`. */
|
||||
private guardsWriters(): boolean {
|
||||
return clientSupportsAirCapability(
|
||||
this.clientCapabilities,
|
||||
AIR_SESSION_WRITER_GUARD_CAPABILITY,
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* One page of the sessions, newest first. The cursor is the offset of the
|
||||
* page. The SDK then orders the transcripts by their modification time and
|
||||
@@ -2710,6 +2840,13 @@ export class ClaudeAcpAgent {
|
||||
if (!session) {
|
||||
throw RequestError.sessionNotFound(params.sessionId);
|
||||
}
|
||||
// Only a client with the guard awaits here (see the remote control
|
||||
// command below for why a prompt does not await without a reason).
|
||||
if (this.guardsWriters()) {
|
||||
await this.admitPromptWriter(params.sessionId);
|
||||
session = this.sessions[params.sessionId];
|
||||
if (!session) throw RequestError.sessionNotFound(params.sessionId);
|
||||
}
|
||||
// The one re-read per user prompt, fired here and never awaited: a prompt
|
||||
// must not wait on a CLI process, and its result is pushed on change
|
||||
// whenever it lands, mid-turn included. It runs BEFORE the guard on
|
||||
@@ -3089,10 +3226,38 @@ export class ClaudeAcpAgent {
|
||||
`Session ${sessionId}: the identity behind the cached account changed (sign-out, or a probe that found a different login); the query is recreated on the next turn`,
|
||||
);
|
||||
if (options?.endQuery !== false) {
|
||||
// The close hands over the closed process (see `handOverClosingProcess`).
|
||||
// The respawn records a replacement of its own.
|
||||
if (this.sessions[sessionId] !== session) this.handOverClosingProcess(sessionId);
|
||||
this.closeQueryStream(session);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Records that the Claude Code process of this agent for `sessionId` ends
|
||||
* now. Call it before the close. The process can keep its registry record
|
||||
* for a moment, so for {@link CLOSING_HANDOVER_MS} a writer check does not
|
||||
* count that process as another writer. It waits only until that process
|
||||
* ends.
|
||||
*/
|
||||
private handOverClosingProcess(sessionId: string): void {
|
||||
if (!this.guardsWriters()) return;
|
||||
clearTimeout(this.closingHandovers.get(sessionId)?.timer);
|
||||
const timer = setTimeout(() => {
|
||||
if (this.closingHandovers.get(sessionId)?.timer === timer) {
|
||||
this.closingHandovers.delete(sessionId);
|
||||
}
|
||||
}, CLOSING_HANDOVER_MS);
|
||||
timer.unref?.();
|
||||
this.closingHandovers.set(sessionId, {
|
||||
timer,
|
||||
closing: {
|
||||
pids: this.sessionWriters.closingPids(sessionId),
|
||||
until: Date.now() + CLOSING_HANDOVER_MS,
|
||||
},
|
||||
});
|
||||
}
|
||||
|
||||
/** Recreate the query of a signed-out session, keeping the ACP session id and
|
||||
* resuming the Claude session so the history survives. Returns the session
|
||||
* the caller must go on with: the new one, or the argument when no
|
||||
@@ -3132,9 +3297,9 @@ export class ClaudeAcpAgent {
|
||||
}
|
||||
|
||||
private async awaitSignOutRespawn(sessionId: string, session: Session): Promise<Session> {
|
||||
const respawn = (session.signOutRespawn ??= this.recreateSignedOutQuery(
|
||||
const respawn = (session.signOutRespawn ??= this.replacingQuery(
|
||||
sessionId,
|
||||
session,
|
||||
this.recreateSignedOutQuery(sessionId, session),
|
||||
).finally(() => {
|
||||
session.signOutRespawn = undefined;
|
||||
}));
|
||||
@@ -3469,6 +3634,9 @@ export class ClaudeAcpAgent {
|
||||
// "startedNewTurn" for a turn that never started.
|
||||
const subscriptionGuard = this.runClaudeSubscriptionGuard(sessionId, session);
|
||||
if (subscriptionGuard) await subscriptionGuard;
|
||||
// The same for the writer guard: a refusal rejects `steer`, after the
|
||||
// agent closed its session, and no turn starts.
|
||||
if (this.guardsWriters()) await this.admitPromptWriter(sessionId);
|
||||
|
||||
// Preserve the established default for Hosts that do not opt in. This is
|
||||
// intentionally detached for compatibility with the existing contract.
|
||||
@@ -8284,6 +8452,7 @@ export class ClaudeAcpAgent {
|
||||
session.queryClosed = true;
|
||||
for (const [sessionId, candidate] of Object.entries(this.sessions)) {
|
||||
if (candidate !== session) continue;
|
||||
this.handOverClosingProcess(sessionId);
|
||||
// Its list row now shows what the registry and the transcript tell.
|
||||
this.sessionIndex.onOwnSessionChanged(sessionId);
|
||||
}
|
||||
@@ -8594,6 +8763,8 @@ export class ClaudeAcpAgent {
|
||||
const nativeReplayEnabled = form === "air";
|
||||
const replayCompactionUpdates = clientSupportsCompactionUpdates(this.clientCapabilities);
|
||||
const replayTerminalStates = new Map<string, "completed" | "failed" | "cancelled">();
|
||||
// The launches whose tool_result only tells that a background child started.
|
||||
const replayBackgroundLaunches = new Set<string>();
|
||||
const replayChildren = new Map<
|
||||
string,
|
||||
{
|
||||
@@ -8604,9 +8775,14 @@ export class ClaudeAcpAgent {
|
||||
reconstructable: boolean;
|
||||
announced: boolean;
|
||||
terminalState?: "completed" | "failed" | "cancelled";
|
||||
/** Whether the child runs in the background: only its task
|
||||
* notification tells its end. */
|
||||
background?: boolean;
|
||||
/** The state of the last persisted task notification of the child.
|
||||
* It comes after the launch tool_result, so it wins. */
|
||||
notifiedState?: SubagentState;
|
||||
/** The state that the replay sent at the position of a task notification. */
|
||||
sentState?: SubagentState;
|
||||
/** The model id of the child's latest response in its transcript. */
|
||||
responseModel?: string;
|
||||
/** The `model` option entry that the replay sent to the child. */
|
||||
@@ -8654,7 +8830,8 @@ export class ClaudeAcpAgent {
|
||||
"tool_use_id" in block &&
|
||||
typeof block.tool_use_id === "string"
|
||||
) {
|
||||
replayTerminalStates.set(block.tool_use_id, replaySubagentTerminalState(block));
|
||||
if (isBackgroundLaunchResult(block)) replayBackgroundLaunches.add(block.tool_use_id);
|
||||
else replayTerminalStates.set(block.tool_use_id, replaySubagentTerminalState(block));
|
||||
}
|
||||
if (
|
||||
typeof block !== "object" ||
|
||||
@@ -8692,6 +8869,7 @@ export class ClaudeAcpAgent {
|
||||
reconstructable: true,
|
||||
announced: false,
|
||||
terminalState: replayTerminalStates.get(block.id),
|
||||
background: input.run_in_background === true,
|
||||
});
|
||||
}
|
||||
}
|
||||
@@ -8699,6 +8877,10 @@ export class ClaudeAcpAgent {
|
||||
const child = replayChildren.get(toolUseId);
|
||||
if (child) child.terminalState = terminalState;
|
||||
}
|
||||
for (const toolUseId of replayBackgroundLaunches) {
|
||||
const child = replayChildren.get(toolUseId);
|
||||
if (child) child.background = true;
|
||||
}
|
||||
};
|
||||
if (nativeReplayEnabled) registerLaunches(messages);
|
||||
|
||||
@@ -8808,7 +8990,32 @@ export class ClaudeAcpAgent {
|
||||
const toolUse = replayToolUses.get(toolUseId);
|
||||
if (child || (toolUse && isNativeSubagentControlTool(toolUse.name))) {
|
||||
const state = nativeSubagentState(notification.status);
|
||||
if (child && state) child.notifiedState = state;
|
||||
if (!child || !state) return;
|
||||
child.notifiedState = state;
|
||||
// The end goes at the position of the notification, as the live frame
|
||||
// sends it. A follow of a big history then ends each child in order,
|
||||
// and a tail after the cursor gives the end of a background child.
|
||||
// A status read reports the states in its status update, outside the cursor.
|
||||
if (
|
||||
!detached?.subagentStatus &&
|
||||
child.announced &&
|
||||
child.reconstructable &&
|
||||
child.sentState !== state
|
||||
) {
|
||||
child.sentState = state;
|
||||
await publish(
|
||||
asSdkSessionNotification({
|
||||
sessionId: child.parentToolUseId
|
||||
? (replayChildren.get(child.parentToolUseId)?.sessionId ?? sessionId)
|
||||
: sessionId,
|
||||
update: {
|
||||
sessionUpdate: "subagent_state_update",
|
||||
subagentSessionId: child.sessionId,
|
||||
state,
|
||||
},
|
||||
}),
|
||||
);
|
||||
}
|
||||
return;
|
||||
}
|
||||
// Like live, a task that no tool call started stays unknown.
|
||||
@@ -9134,8 +9341,17 @@ export class ClaudeAcpAgent {
|
||||
// state from the launch tool_result. Missing results and malformed or
|
||||
// orphan lineage use the draft protocol's deterministic disconnected state.
|
||||
// A status read reports the states in its status update, outside the cursor.
|
||||
// A background child ends only on its task notification. A detached
|
||||
// replay (a `_session/read`) reads a session that another process can
|
||||
// still run, so such a child without a notification gets no state.
|
||||
for (const child of status ? [] : [...replayChildren.values()].reverse()) {
|
||||
if (!child.announced) continue;
|
||||
const state = child.reconstructable
|
||||
? (child.notifiedState ??
|
||||
child.terminalState ??
|
||||
(child.background && detached ? undefined : "disconnected"))
|
||||
: "disconnected";
|
||||
if (!state) continue;
|
||||
const parentSessionId = child.parentToolUseId
|
||||
? (replayChildren.get(child.parentToolUseId)?.sessionId ?? sessionId)
|
||||
: sessionId;
|
||||
@@ -9145,9 +9361,7 @@ export class ClaudeAcpAgent {
|
||||
update: {
|
||||
sessionUpdate: "subagent_state_update",
|
||||
subagentSessionId: child.sessionId,
|
||||
state: child.reconstructable
|
||||
? (child.notifiedState ?? child.terminalState ?? "disconnected")
|
||||
: "disconnected",
|
||||
state,
|
||||
},
|
||||
}),
|
||||
);
|
||||
@@ -10657,6 +10871,20 @@ export class ClaudeAcpAgent {
|
||||
private createSession(
|
||||
params: NewSessionRequest,
|
||||
creationOpts: SessionCreation = {},
|
||||
): Promise<NewSessionResponse> {
|
||||
// The process of a session with a known id starts here: until the session
|
||||
// is in the map, its registry record is of this agent.
|
||||
const knownId =
|
||||
creationOpts.optionsOnly || creationOpts.forkSession
|
||||
? undefined
|
||||
: (creationOpts.publicSessionId ?? creationOpts.resume);
|
||||
const start = this.startSessionAroundRefusedMcpServers(params, creationOpts);
|
||||
return knownId ? this.replacingQuery(knownId, start) : start;
|
||||
}
|
||||
|
||||
private startSessionAroundRefusedMcpServers(
|
||||
params: NewSessionRequest,
|
||||
creationOpts: SessionCreation,
|
||||
): Promise<NewSessionResponse> {
|
||||
const names = mcpServerNames(
|
||||
params.mcpServers,
|
||||
@@ -11625,6 +11853,19 @@ export class ClaudeAcpAgent {
|
||||
creationParams: NewSessionRequest,
|
||||
resumeAt?: { resumeSessionAt: string; resumeDropsTurn?: string },
|
||||
keepState?: ReplayState,
|
||||
): Promise<void> {
|
||||
await this.replacingQuery(
|
||||
sessionId,
|
||||
this.replaceSessionQueryNow(sessionId, session, creationParams, resumeAt, keepState),
|
||||
);
|
||||
}
|
||||
|
||||
private async replaceSessionQueryNow(
|
||||
sessionId: string,
|
||||
session: Session,
|
||||
creationParams: NewSessionRequest,
|
||||
resumeAt?: { resumeSessionAt: string; resumeDropsTurn?: string },
|
||||
keepState?: ReplayState,
|
||||
): Promise<void> {
|
||||
this.closeQueryStream(session);
|
||||
// Keep the old record visible so closeSession and dispose can mark it torn down.
|
||||
|
||||
156
src/v1/session-writers.ts
Normal file
156
src/v1/session-writers.ts
Normal file
@@ -0,0 +1,156 @@
|
||||
import { RequestError } from "@agentclientprotocol/sdk/unstable";
|
||||
import { LiveSessionRegistry, bySession, type LiveRecord } from "../session-index/live-registry.js";
|
||||
|
||||
/**
|
||||
* Another live process holds the session: a Claude Code process in a terminal,
|
||||
* in another IDE, or one that outlived the IDE that started it. The fields
|
||||
* come from its record in the live registry.
|
||||
*/
|
||||
export type HeldSession = {
|
||||
/** How the process started, such as `cli` or `sdk-ts`. */
|
||||
entrypoint?: string;
|
||||
/** What the process does, such as `busy` or `idle`. */
|
||||
status?: string;
|
||||
};
|
||||
|
||||
/**
|
||||
* The `data.reason` of the error that refuses a second writer. The Codex
|
||||
* adapter gives the same reason, so the AIR client reads both alike.
|
||||
*/
|
||||
export const SESSION_HELD_REASON = "thread_active_writer";
|
||||
|
||||
/**
|
||||
* The writers of a stored session, by the live registry of Claude Code (see
|
||||
* {@link LiveSessionRegistry}). Each Claude Code process writes a record
|
||||
* there with the id of its session. The registry has no parent pid, so
|
||||
* "this agent runs the session" comes from the agent, not from the record.
|
||||
*/
|
||||
export class SessionWriters {
|
||||
/**
|
||||
* The pid of the Claude Code process of this agent for each session that
|
||||
* it runs: the only live record that a writer check saw while the session
|
||||
* ran here. It names the other writer in a refusal.
|
||||
*/
|
||||
private readonly own = new Map<string, number>();
|
||||
|
||||
constructor(private readonly registry: Pick<LiveSessionRegistry, "recordsOf">) {}
|
||||
|
||||
/** The live records of `sessionId`. A registry that cannot be read has none. */
|
||||
private records(sessionId: string): Promise<LiveRecord[]> {
|
||||
return this.registry.recordsOf(sessionId).catch(() => []);
|
||||
}
|
||||
|
||||
/**
|
||||
* Whether another live process holds `sessionId`. A session that this
|
||||
* agent runs (`runsHere`) is never held here: the record of its own Claude
|
||||
* Code process is in the registry too.
|
||||
*/
|
||||
async held(sessionId: string, runsHere: boolean): Promise<HeldSession | undefined> {
|
||||
if (runsHere) return undefined;
|
||||
return heldBy(await this.records(sessionId));
|
||||
}
|
||||
|
||||
/**
|
||||
* Refuses a second writer of `sessionId`. A session that this agent does
|
||||
* not run is refused when one live record has it. A session that this
|
||||
* agent runs is refused when more than one live record has it: its own
|
||||
* Claude Code process has one. A Claude Code version that writes no record
|
||||
* is never refused.
|
||||
*/
|
||||
async assertWritable(
|
||||
sessionId: string,
|
||||
runsHere: boolean,
|
||||
closing?: ClosingProcesses,
|
||||
): Promise<void> {
|
||||
const allowed = runsHere ? 1 : 0;
|
||||
for (;;) {
|
||||
const records = await this.records(sessionId);
|
||||
// A process of this agent that ends now can keep its record for a moment.
|
||||
const pids = closing && Date.now() < closing.until ? await closing.pids : undefined;
|
||||
if (runsHere && records.length === 1 && !pids?.has(records[0]!.pid)) {
|
||||
this.own.set(sessionId, records[0]!.pid);
|
||||
}
|
||||
if (records.length <= allowed) return;
|
||||
const others = pids ? records.filter((record) => !pids.has(record.pid)) : records;
|
||||
if (!pids || others.length > allowed) {
|
||||
throw sessionHeldError(sessionId, this.otherWriter(sessionId, records, pids));
|
||||
}
|
||||
await new Promise((resolve) => setTimeout(resolve, CLOSING_POLL_MS));
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* The newest of `records` that is not a process of this agent: not its
|
||||
* known process of the session and not one of `closing`. When none is
|
||||
* left, the newest of all `records`.
|
||||
*/
|
||||
private otherWriter(
|
||||
sessionId: string,
|
||||
records: LiveRecord[],
|
||||
closing: Set<number> | undefined,
|
||||
): HeldSession {
|
||||
const own = this.own.get(sessionId);
|
||||
const others = records.filter((record) => record.pid !== own && !closing?.has(record.pid));
|
||||
return heldBy(others.length > 0 ? others : records)!;
|
||||
}
|
||||
|
||||
/**
|
||||
* The pids of the Claude Code process of this agent that ends now, as the
|
||||
* agent closes the query of `sessionId`. They are the known process of
|
||||
* the session, or else the live records of the session now. The agent
|
||||
* then has no known process of the session until a writer check sees it.
|
||||
*/
|
||||
async closingPids(sessionId: string): Promise<Set<number>> {
|
||||
const own = this.own.get(sessionId);
|
||||
this.own.delete(sessionId);
|
||||
if (own !== undefined) return new Set([own]);
|
||||
return new Set((await this.records(sessionId)).map((record) => record.pid));
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* The Claude Code processes of this agent that end now: the live records of
|
||||
* the session when the agent closed its query. A writer check waits until
|
||||
* `until` for them to end, and does not count them as other writers.
|
||||
*/
|
||||
export type ClosingProcesses = {
|
||||
pids: Promise<Set<number>>;
|
||||
/** The end of the wait, from `Date.now()`. */
|
||||
until: number;
|
||||
};
|
||||
|
||||
/** How often a writer check reads the registry again while a closing process ends. */
|
||||
const CLOSING_POLL_MS = 100;
|
||||
|
||||
/** The newest of `records`, as a {@link HeldSession}, or undefined when there is none. */
|
||||
function heldBy(records: LiveRecord[]): HeldSession | undefined {
|
||||
const record = [...bySession(records).values()][0];
|
||||
if (!record) return undefined;
|
||||
return {
|
||||
...(record.entrypoint !== undefined ? { entrypoint: record.entrypoint } : {}),
|
||||
...(record.status !== undefined ? { status: record.status } : {}),
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* The refusal of a second writer. It has the form of the Codex adapter:
|
||||
* code -32600, `data.reason` {@link SESSION_HELD_REASON}, and the text
|
||||
* "already has an active writer" in `data.details`.
|
||||
*/
|
||||
export function sessionHeldError(sessionId: string, held: HeldSession): RequestError {
|
||||
return new RequestError(
|
||||
-32600,
|
||||
"This Claude session is in use by another Claude Code process. Close it there, or continue the session there.",
|
||||
{
|
||||
reason: SESSION_HELD_REASON,
|
||||
sessionId,
|
||||
held,
|
||||
details: `session ${sessionId} already has an active writer`,
|
||||
},
|
||||
);
|
||||
}
|
||||
|
||||
/** The writers of the default registry, `<config>/sessions`. */
|
||||
export function defaultSessionWriters(): SessionWriters {
|
||||
return new SessionWriters(new LiveSessionRegistry());
|
||||
}
|
||||
Reference in New Issue
Block a user