Compare commits

..

1 Commits

Author SHA1 Message Date
acp-release-bot[bot]
e62d084e9d chore(main): release 0.108.1 (#1650)
🤖 I have created a release *beep* *boop*
---


##
[0.108.1](https://github.com/agentclientprotocol/claude-agent-acp/compare/v0.108.0...v0.108.1)
(2026-11-18)


### Bug Fixes

* answer -32602 on v1 for a request that names a subagent's session
([#1656](https://github.com/agentclientprotocol/claude-agent-acp/issues/1656))
([253cd84](253cd84ed8))
* close a server tool call whose reply Claude Code gave up on, once its
next reply starts
([#1604](https://github.com/agentclientprotocol/claude-agent-acp/issues/1604))
([3205f0b](3205f0bf02))
* end a v1 turn at its result for a client in the subagents RFD form
([#1603](https://github.com/agentclientprotocol/claude-agent-acp/issues/1603))
([c4b64f6](c4b64f628d))
* reject session setup for an incompatible model provider
([#1506](https://github.com/agentclientprotocol/claude-agent-acp/issues/1506))
([90070d6](90070d6cbf))
* start a session without an MCP-over-ACP server whose local endpoint
cannot open
([#1653](https://github.com/agentclientprotocol/claude-agent-acp/issues/1653))
([96dd2bb](96dd2bb10d)),
closes
[#1651](https://github.com/agentclientprotocol/claude-agent-acp/issues/1651)
* update to @agentclientprotocol/sdk 2.8.0
([#1655](https://github.com/agentclientprotocol/claude-agent-acp/issues/1655))
([b6167a8](b6167a82db))

---
This PR was generated with [Release
Please](https://github.com/googleapis/release-please). See
[documentation](https://github.com/googleapis/release-please#release-please).

Co-authored-by: acp-release-bot[bot] <246668977+acp-release-bot[bot]@users.noreply.github.com>
2026-11-18 18:14:55 +01:00
11 changed files with 32 additions and 473 deletions

View File

@@ -1,3 +1,3 @@
{
".": "0.108.0"
".": "0.108.1"
}

View File

@@ -1,5 +1,17 @@
# Changelog
## [0.108.1](https://github.com/agentclientprotocol/claude-agent-acp/compare/v0.108.0...v0.108.1) (2026-11-18)
### Bug Fixes
* answer -32602 on v1 for a request that names a subagent's session ([#1656](https://github.com/agentclientprotocol/claude-agent-acp/issues/1656)) ([253cd84](https://github.com/agentclientprotocol/claude-agent-acp/commit/253cd84ed84efd38fd9d90faaf954690d1610677))
* close a server tool call whose reply Claude Code gave up on, once its next reply starts ([#1604](https://github.com/agentclientprotocol/claude-agent-acp/issues/1604)) ([3205f0b](https://github.com/agentclientprotocol/claude-agent-acp/commit/3205f0bf0211f9346dad8583944f007bd0ef73c2))
* end a v1 turn at its result for a client in the subagents RFD form ([#1603](https://github.com/agentclientprotocol/claude-agent-acp/issues/1603)) ([c4b64f6](https://github.com/agentclientprotocol/claude-agent-acp/commit/c4b64f628d1fad37ed1d56016b91eefc59df5052))
* reject session setup for an incompatible model provider ([#1506](https://github.com/agentclientprotocol/claude-agent-acp/issues/1506)) ([90070d6](https://github.com/agentclientprotocol/claude-agent-acp/commit/90070d6cbf29f5425e4e08828552f91493dd3e59))
* start a session without an MCP-over-ACP server whose local endpoint cannot open ([#1653](https://github.com/agentclientprotocol/claude-agent-acp/issues/1653)) ([96dd2bb](https://github.com/agentclientprotocol/claude-agent-acp/commit/96dd2bb10d838aeb39d75bb0cfde1c7b4eae958a)), closes [#1651](https://github.com/agentclientprotocol/claude-agent-acp/issues/1651)
* update to @agentclientprotocol/sdk 2.8.0 ([#1655](https://github.com/agentclientprotocol/claude-agent-acp/issues/1655)) ([b6167a8](https://github.com/agentclientprotocol/claude-agent-acp/commit/b6167a82dba9864a13dad31a7cad151704badf5e))
## [0.108.0](https://github.com/agentclientprotocol/claude-agent-acp/compare/v0.107.3...v0.108.0) (2026-11-17)

View File

@@ -74,12 +74,9 @@ with replay, which `replay_complete` ends, `session/close`, `session/prompt`, `s
compaction, display terminals for commands, permission requests, elicitation, providers, auth, and
[subagents](docs/subagent-sessions.md). Steering is v1 only for now.
`session/prompt` takes an `idempotencyKey`: a prompt that a client sends again with the same key
is inserted once, and the retry gets the first `messageId`. The key is known for as long as Claude
Code stores the message, also after a restart.
Session cursors are not served yet. The adapter announces none, so `session/fork` with a `cursorId`
fails with `-32602`.
Two parts of the draft are not served yet. `session/prompt` takes an `idempotencyKey` and does not
use it, so a prompt that a client sends again with the same key is inserted again. The adapter
announces no session cursors, so `session/fork` with a `cursorId` fails with `-32602`.
v2 is served by the v2 agent in `src/v2/`, which runs straight on Claude
Code instead of translating to v1. A v2 client that declares JetBrains AIR

4
package-lock.json generated
View File

@@ -1,12 +1,12 @@
{
"name": "@agentclientprotocol/claude-agent-acp",
"version": "0.108.0",
"version": "0.108.1",
"lockfileVersion": 3,
"requires": true,
"packages": {
"": {
"name": "@agentclientprotocol/claude-agent-acp",
"version": "0.108.0",
"version": "0.108.1",
"license": "Apache-2.0",
"dependencies": {
"@agentclientprotocol/sdk": "2.8.0",

View File

@@ -3,7 +3,7 @@
"publishConfig": {
"access": "public"
},
"version": "0.108.0",
"version": "0.108.1",
"description": "An ACP-compatible coding agent powered by the Claude Agent SDK (TypeScript)",
"main": "dist/lib.js",
"types": "dist/lib.d.ts",

View File

@@ -131,29 +131,6 @@ describe.skipIf(!process.env.RUN_INTEGRATION_TESTS)("v2 core with Claude Code",
expect(states(sessionId).at(-1)).toMatchObject({ stopReason: "end_turn" });
}, 180_000);
it("inserts one message for an idempotencyKey, and knows the key after a close and a resume", async () => {
const sessionId = await newSession("default");
const keyed = {
sessionId,
idempotencyKey: "0b6f3c1e-8d2a-4c57-9a41-5e2f7d90c3ab",
prompt: [{ type: "text" as const, text: "Reply with exactly the single word: pong" }],
};
const userMessages = () =>
updates.filter(
({ sessionId: id, update }) => id === sessionId && update.sessionUpdate === "user_message",
);
const { messageId } = await agent.request(v2.methods.agent.session.prompt, keyed);
await until(() => states(sessionId).some((update) => update.state === "idle"));
expect(await agent.request(v2.methods.agent.session.prompt, keyed)).toEqual({ messageId });
// Claude Code stored the message under the uuid that carries the key.
await agent.request(v2.methods.agent.session.close, { sessionId });
await agent.request(v2.methods.agent.session.resume, { sessionId, cwd });
expect(await agent.request(v2.methods.agent.session.prompt, keyed)).toEqual({ messageId });
expect(userMessages()).toHaveLength(1);
expect(states(sessionId).filter((update) => update.state === "running")).toHaveLength(1);
}, 180_000);
// No prompt: it costs no API usage.
it("lists the tools of an MCP server that the client serves over ACP", async () => {
const served: string[] = [];

View File

@@ -673,25 +673,6 @@ describe("ACP v2 core", () => {
});
});
it("keeps the idempotencyKeys of a session across the restart of its query", async () => {
const client = v2Client();
await client.connect(async (agent) => {
const { response, claude } = await openSession(agent);
const keyed = { sessionId: response.sessionId, idempotencyKey: "key-1", prompt: PROMPT };
const first = agent.request(v2.methods.agent.session.prompt, keyed);
claude.send(lifecycle(await claude.prompt(0), "started"));
const { messageId } = await first;
claude.send(result());
await vi.waitFor(() => expect(client.states().at(-1)).toBe("idle"));
await setProvider(agent);
expect(sdk.processes).toHaveLength(2);
// The stored history that the test's SDK returns is empty: the record answers.
expect(await agent.request(v2.methods.agent.session.prompt, keyed)).toEqual({ messageId });
expect(sdk.processes[1].prompts).toHaveLength(0);
});
});
it("sends a prompt of an idle session right after the response to the new query", async () => {
const client = v2Client();
await client.connect(async (agent) => {
@@ -1123,139 +1104,6 @@ describe("ACP v2 core", () => {
});
});
describe("a prompt with an idempotencyKey", () => {
const userMessages = (client: ReturnType<typeof v2Client>) =>
client.sessionUpdates.filter((update) => update.sessionUpdate === "user_message");
it("answers a retry of an inserted prompt with its messageId, and inserts nothing more", async () => {
const client = v2Client();
await client.connect(async (agent) => {
const { response, claude } = await openSession(agent);
const keyed = { sessionId: response.sessionId, idempotencyKey: "key-1" };
const first = agent.request(v2.methods.agent.session.prompt, { ...keyed, prompt: PROMPT });
const prompt = await claude.prompt(0);
claude.send(lifecycle(prompt, "started"));
const { messageId } = await first;
expect(messageId).toBe(prompt.uuid);
// The id is a hash of the key: no update shows the key.
expect(messageId).not.toContain("key-1");
// The prompts of a key are not compared: another one is a retry too.
for (const text of ["Hi", "Hello again"]) {
expect(
await agent.request(v2.methods.agent.session.prompt, {
...keyed,
prompt: [{ type: "text", text }],
}),
).toEqual({ messageId });
}
expect(claude.prompts).toHaveLength(1);
// The same key in another session names another prompt.
const other = await agent.request(v2.methods.agent.session.new, { cwd });
const second = agent.request(v2.methods.agent.session.prompt, {
sessionId: other.sessionId,
idempotencyKey: "key-1",
prompt: PROMPT,
});
const otherPrompt = await sdk.processes[1].prompt(0);
sdk.processes[1].send(lifecycle(otherPrompt, "started"));
expect((await second).messageId).not.toBe(messageId);
});
expect(userMessages(client)).toHaveLength(2);
});
it("answers a retry of a prompt that is not inserted yet with that prompt's outcome", async () => {
const client = v2Client();
await client.connect(async (agent) => {
const { response, claude } = await openSession(agent);
const keyed = { sessionId: response.sessionId, idempotencyKey: "key-1", prompt: PROMPT };
const first = agent.request(v2.methods.agent.session.prompt, keyed);
const prompt = await claude.prompt(0);
const retry = agent.request(v2.methods.agent.session.prompt, keyed);
// The retry reaches the agent while the first prompt waits.
await new Promise((resolve) => setTimeout(resolve, 20));
expect(claude.prompts).toHaveLength(1);
claude.send(lifecycle(prompt, "started"));
expect(await first).toEqual({ messageId: prompt.uuid });
expect(await retry).toEqual({ messageId: prompt.uuid });
});
expect(userMessages(client)).toHaveLength(1);
});
it("leaves the key unused when its prompt fails, and sends the next attempt under another uuid", async () => {
const client = v2Client();
await client.connect(async (agent) => {
const { response, claude } = await openSession(agent);
const sessionId = response.sessionId;
const keyed = { sessionId, idempotencyKey: "key-1", prompt: PROMPT };
const failed = (request: Promise<unknown>) => request.catch((error: unknown) => error);
const first = failed(agent.request(v2.methods.agent.session.prompt, keyed));
const cancelled = await claude.prompt(0);
const retry = failed(agent.request(v2.methods.agent.session.prompt, keyed));
await agent.notify(v2.methods.agent.session.cancel, { sessionId });
expect(await first).toMatchObject({ code: -32800 });
expect(await retry).toMatchObject({ code: -32800 });
await vi.waitFor(() => expect(claude.interrupt).toHaveBeenCalled());
claude.send(lifecycle(cancelled, "cancelled"));
const again = agent.request(v2.methods.agent.session.prompt, keyed);
const prompt = await claude.prompt(1);
// Claude Code ignores a uuid it has seen, and the cancelled prompt may have reached it.
expect(prompt.uuid).not.toBe(cancelled.uuid);
claude.send(lifecycle(prompt, "started"));
expect(await again).toEqual({ messageId: prompt.uuid });
});
expect(userMessages(client)).toHaveLength(1);
});
it.each([
["answers a retry with the messageId of a message that the stored history holds", true],
["inserts a prompt whose key the stored history does not hold", false],
])("after a close and a resume, %s", async (_, stored) => {
const client = v2Client();
await client.connect(async (agent) => {
const { response, claude } = await openSession(agent);
const { sessionId } = response;
const keyed = { sessionId, idempotencyKey: "key-1", prompt: PROMPT };
const first = agent.request(v2.methods.agent.session.prompt, keyed);
claude.send(lifecycle(await claude.prompt(0), "started"));
const { messageId } = await first;
claude.send(result());
await vi.waitFor(() => expect(client.states().at(-1)).toBe("idle"));
// The close drops the session's record: only a stored message keeps its key.
await agent.request(v2.methods.agent.session.close, { sessionId });
await agent.request(v2.methods.agent.session.resume, { sessionId, cwd });
const resumed = sdk.processes[1];
if (stored) {
vi.mocked(getSessionMessages).mockResolvedValueOnce([
{
type: "user",
uuid: messageId,
session_id: sessionId,
parent_tool_use_id: null,
parent_agent_id: null,
message: { role: "user", content: "Hi" },
},
]);
}
const retry = agent.request(v2.methods.agent.session.prompt, keyed);
if (!stored) resumed.send(lifecycle(await resumed.prompt(0), "started"));
expect(await retry).toEqual({ messageId });
expect(resumed.prompts).toHaveLength(stored ? 0 : 1);
});
expect(userMessages(client)).toHaveLength(stored ? 1 : 2);
});
});
it.each([
["discarded", -32603],
["refused", -32603],

View File

@@ -75,7 +75,6 @@ import { modelSwitchHook, SessionConfig } from "./config.js";
import { v2ElicitationRequest } from "./elicitation.js";
import { fileChangePreviewHook } from "./file-preview.js";
import { canUseTool, denyingStoppedWork } from "./permissions.js";
import { PromptKeys } from "./prompt-keys.js";
import { ReplayHolds } from "./replay-hold.js";
import { reportHooks } from "./reports.js";
import { savedSessionStatus } from "../session-status.js";
@@ -174,13 +173,6 @@ class V2Agent implements AgentHandle, SessionConnection {
private readonly resuming = new Map<string, Set<Promise<unknown>>>();
/** What the resumes that replay hold back until their `replay_complete` (see `replay-hold.ts`). */
private readonly replays = new ReplayHolds();
/**
* The `idempotencyKey`s of each session's prompts, from the session's
* start to `session/close` or the end of the connection (see
* `prompt-keys.ts`). A restart of the session's query, and a resume of a
* session whose query ended, keep the record.
*/
private readonly promptKeys = new Map<string, PromptKeys>();
readonly translator = new V2UpdateTranslator();
readonly auth: V2Auth;
/** The `--hide-claude-auth` subscription guard (see `subscription-guard.ts`). */
@@ -700,8 +692,6 @@ class V2Agent implements AgentHandle, SessionConnection {
// its updates go out before the close response.
await this.setupSettled(sessionId);
this.stopped.delete(sessionId);
// A closed session is no longer active here: only its stored messages keep their keys.
this.promptKeys.delete(sessionId);
const session = this.sessions.get(sessionId);
if (session) {
await session.close();
@@ -826,7 +816,6 @@ class V2Agent implements AgentHandle, SessionConnection {
const sessions = [...this.sessions.values()];
this.sessions.clear();
this.stopped.clear();
this.promptKeys.clear();
await Promise.all(sessions.map((session) => session.close()));
}
@@ -956,18 +945,7 @@ class V2Agent implements AgentHandle, SessionConnection {
query: q,
model: { id: models.models.currentModelId, info: models.allowlistedModelInfo },
});
let keys = this.promptKeys.get(sessionId);
if (!keys) {
const { cwd } = opened.request;
keys = new PromptKeys(
sessionId,
() => storedPromptIds(sessionId, cwd, this.logger),
this.logger,
);
this.promptKeys.set(sessionId, keys);
}
keys.queryStarted(resume !== undefined);
session.start(q, config, opened.mcpServers, keys, resume !== undefined);
session.start(q, config, opened.mcpServers, resume !== undefined);
this.sessions.set(sessionId, session);
this.stopped.delete(sessionId);
// A route change during the start did not find this session live.
@@ -1285,22 +1263,6 @@ async function validatedSetup(
return request;
}
/**
* The uuids of the user messages in the stored history of the session
* `sessionId`, as a replay reads it: the messages before each compaction too.
*/
async function storedPromptIds(sessionId: string, cwd: string, logger: Logger): Promise<string[]> {
const messages = await readHistoryAcrossCompactions(
sessionId,
await getSessionMessages(sessionId, { dir: cwd }),
logger,
cwd,
);
return messages.flatMap((message) =>
message.type === "user" && message.uuid ? [message.uuid] : [],
);
}
/** A request of the active `session` names its `cwd`, as `session/resume` must. */
function assertCwdOf(session: V2Session, cwd: string, action: string): void {
if (cwd === session.cwd) return;

View File

@@ -1,174 +0,0 @@
/**
* The `idempotencyKey`s of one session's prompts (ACP v2 `session/prompt`).
*
* A client that lost a prompt's response sends the prompt again with the same
* key. The session then inserts at most one user message for the key:
*
* - A prompt with the key that is not answered yet: the retry gets that
* prompt's outcome, and nothing more goes to Claude Code.
* - A message inserted with the key: the retry gets its `messageId`.
* - A prompt with the key that failed: the key is unused, and the retry is a
* new prompt.
*
* The key is stored as the message's id. A keyed prompt goes to Claude Code
* with a uuid whose first 32 characters are a hash of the session id and the
* key, and whose last 4 hex digits count the attempts. Claude Code keeps that
* uuid in the transcript (`getSessionMessages` returns it, also for a prompt
* that waited in its queue or that it folded into a running turn), so a key
* is recognized for as long as its message is stored, across connections and
* restarts, and no client sees the key: only its hash is in the `messageId`.
* The session id is part of the hash, so the same key in another session, a
* fork too, names another prompt.
*
* Each attempt has its own uuid because Claude Code ignores a prompt whose
* uuid it has seen: it echoes it and starts no turn. A prompt that a
* `session/cancel` answered with -32800 may have reached Claude Code, so the
* next attempt must not reuse its uuid.
*
* A message that Claude Code does not store, such as a local command's, is
* recognized while this record lives: the agent keeps one per session from
* its start to `session/close` or the end of the connection, across restarts
* of the session's query.
*/
import { createHash, type randomUUID } from "node:crypto";
import type * as v2 from "@agentclientprotocol/sdk/experimental/v2/unstable";
import type { Logger } from "../logger.js";
type UUID = ReturnType<typeof randomUUID>;
/** One attempt to insert the prompt of a key. */
export interface KeyedAttempt {
/** The uuid that the prompt goes to Claude Code with, and its `messageId` once inserted. */
uuid: UUID;
/**
* The `messageId` of the message that the session's stored history holds
* for the key, or undefined for none. Absent when the history cannot hold
* one: a session that this connection created has only the messages of
* this record.
*/
stored?: () => Promise<string | undefined>;
}
type KeyRecord = {
/** The attempts so far. The next one's uuid ends in this number. */
attempts: number;
/** The attempt that is not answered yet. */
pending?: Promise<v2.PromptResponse>;
/** The message inserted with the key. */
messageId?: string;
};
/** The characters of a keyed uuid that count its attempts: its last 4 hex digits. */
const ATTEMPT_DIGITS = 4;
export class PromptKeys {
/** The keys seen on this connection, by the uuid prefix of their attempts. */
private readonly keys = new Map<string, KeyRecord>();
/** Whether the session's stored history can hold a message of an earlier connection. */
private resumed = false;
/** The stored history's keyed messages, by uuid prefix, once read. */
private stored: Promise<ReadonlyMap<string, string>> | undefined;
constructor(
private readonly sessionId: string,
/** The uuids of the user messages in the session's stored history, oldest first. */
private readonly readStored: () => Promise<Iterable<string>>,
private readonly logger: Logger,
) {}
/**
* A query of the session started. `resumed`: from a stored conversation,
* which can hold messages that this record does not know, so the next
* lookup reads the history again.
*/
queryStarted(resumed: boolean): void {
if (!resumed) return;
this.resumed = true;
this.stored = undefined;
}
/**
* The response of a prompt with `key`: of the attempt that is not answered
* yet, of the message inserted with the key, or of `submit`, which inserts
* the prompt. `submit` runs at most once at a time for a key, and not at
* all once a message is inserted with it. Its promise is returned as it
* is.
*/
once(
key: string,
submit: (attempt: KeyedAttempt) => Promise<v2.PromptResponse>,
): Promise<v2.PromptResponse> {
const prefix = keyedPrefix(this.sessionId, key);
let record = this.keys.get(prefix);
if (!record) this.keys.set(prefix, (record = { attempts: 0 }));
if (record.messageId !== undefined) return Promise.resolve({ messageId: record.messageId });
if (record.pending) return record.pending;
const known = record;
const attempt = (known.attempts++ % 16 ** ATTEMPT_DIGITS)
.toString(16)
.padStart(ATTEMPT_DIGITS, "0");
const response = submit({
uuid: `${prefix}${attempt}` as UUID,
...(this.resumed ? { stored: () => this.storedMessage(prefix) } : {}),
});
known.pending = response;
response.then(
({ messageId }) => {
known.pending = undefined;
known.messageId = messageId;
},
// An error leaves the key unused: the next prompt with it is a new attempt.
() => {
known.pending = undefined;
},
);
return response;
}
/**
* The `messageId` that the stored history holds for the uuid prefix of a
* key. The history is read once per started query. When reading it fails,
* the key counts as unused, so the session stays usable, and the next
* lookup reads again.
*/
private async storedMessage(prefix: string): Promise<string | undefined> {
if (!this.stored) {
const read: Promise<ReadonlyMap<string, string>> = this.readStored().then(
(uuids) => {
const messages = new Map<string, string>();
// A later attempt's message replaces an earlier one's: only the last attempt was answered.
for (const uuid of uuids) messages.set(uuid.slice(0, -ATTEMPT_DIGITS), uuid);
return messages;
},
(error: unknown) => {
this.logger.error(
`Session ${this.sessionId}: failed to read its history for an idempotencyKey`,
error,
);
if (this.stored === read) this.stored = undefined;
return new Map<string, string>();
},
);
this.stored = read;
}
return (await this.stored).get(prefix);
}
}
/**
* The first 32 characters of the uuids of the prompt `key` of the session
* `sessionId`: a version 8 (custom) UUID of the SHA-256 hash of both, without
* its last 4 hex digits.
*/
function keyedPrefix(sessionId: string, key: string): string {
const hex = createHash("sha256").update(`${sessionId}\n${key}`).digest("hex");
// The variant bits of RFC 9562: `10`.
const variant = ((parseInt(hex[16]!, 16) & 0x3) | 0x8).toString(16);
return [
hex.slice(0, 8),
hex.slice(8, 12),
`8${hex.slice(13, 16)}`,
`${variant}${hex.slice(17, 20)}`,
hex.slice(20, 28),
].join("-");
}

View File

@@ -21,16 +21,8 @@ import { isSupportedBlobMimeType } from "../blob-resources.js";
* Claude cannot read, e.g. an `application/zip` resource: `promptToClaude`
* would drop it. An empty `prompt` fails the same way: v2 requires at least
* one content block.
*
* Without the `idempotencyKey`, which v1 does not have and which the session
* handles (see `prompt-keys.ts`).
*/
export function v1PromptRequest({
prompt,
// eslint-disable-next-line @typescript-eslint/no-unused-vars
idempotencyKey,
...request
}: v2.PromptRequest): PromptRequest {
export function v1PromptRequest({ prompt, ...request }: v2.PromptRequest): PromptRequest {
if (prompt.length === 0) {
throw RequestError.invalidParams({ prompt }, "`prompt` must hold at least one content block");
}

View File

@@ -8,8 +8,7 @@
* - A prompt is pushed to Claude Code at once, with a uuid. Its response is
* the prompt's insertion: the `command_lifecycle` frame `started` for that
* uuid, or the prompt's echo, whichever comes first. `cancelled`,
* `discarded` or `refused` fails the prompt. A prompt with an
* `idempotencyKey` is pushed once per key (see `prompt-keys.ts`).
* `discarded` or `refused` fails the prompt.
* - The foreground work is Claude Code's turn: it starts with a prompt's
* `started` frame or echo, or with the main conversation's output (a
* cycle that Claude Code starts on its own, such as after a background
@@ -82,7 +81,6 @@ import {
TurnReport,
type TurnEnd,
} from "./outcome.js";
import type { KeyedAttempt, PromptKeys } from "./prompt-keys.js";
import { StoppedWork } from "./stopped-work.js";
import { SessionReports } from "./reports.js";
import { SessionElicitations } from "./elicitation.js";
@@ -197,8 +195,6 @@ export class V2Session implements RequestTarget {
private readonly fileChanges: TurnFileChanges | undefined;
config!: SessionConfig;
commands!: SessionCommands;
/** The `idempotencyKey`s of the session's prompts. Set by {@link start}. */
private keys!: PromptKeys;
/** ExitPlanMode's "clear context" option (see {@link ClearContext}). */
readonly clearContext: ClearContext;
/** The `/mcp` prompts not inserted yet, by uuid, and the open turn's (see `SessionCommands`). */
@@ -350,19 +346,11 @@ export class V2Session implements RequestTarget {
/**
* Starts reading the query. Called once, after its initialization.
* `mcpServers` are the servers the query started with, and `keys` the
* record of the session's prompt keys, which outlives this query.
* `mcpServers` are the servers the query started with.
*/
start(
query: Query,
config: SessionConfig,
mcpServers: McpServers,
keys: PromptKeys,
resumed = false,
): void {
start(query: Query, config: SessionConfig, mcpServers: McpServers, resumed = false): void {
this.query = query;
this.config = config;
this.keys = keys;
this.usage = new ResultUsage(resumed);
this.mcpServers = JSON.stringify(mcpServers);
this.commands = new SessionCommands(query);
@@ -429,11 +417,6 @@ export class V2Session implements RequestTarget {
* order, and a cancel or close answers a prompt that waits for it with
* -32800 as any prompt not inserted yet. Its refusal answers the prompt.
* The adapter's `/remote-control` is not guarded.
*
* A prompt with an `idempotencyKey` inserts at most one message for the
* key (see `prompt-keys.ts`): a retry of a prompt that is not answered yet
* gets that prompt's outcome, and a retry of an inserted one its
* `messageId`, and neither goes to Claude Code again.
*/
prompt(
params: v2.PromptRequest,
@@ -444,29 +427,6 @@ export class V2Session implements RequestTarget {
}
// Throws invalid params for content that Claude cannot take.
const request: PromptRequest = v1PromptRequest(params);
const key = params.idempotencyKey;
if (key == null) return this.submit(params, request, guard, { uuid: randomUUID() });
return this.keys.once(key, (attempt) => this.submit(params, request, guard, attempt));
}
/**
* Sends the prompt to Claude Code as the message `attempt.uuid` (see
* {@link prompt}).
*
* `attempt.stored` looks the prompt's key up in the session's stored
* history, where a message of an earlier connection can be. The lookup runs
* in the prompt's turn among the session's prompts. A stored message
* answers the prompt with its `messageId`: nothing is inserted, titled or
* sent. A `session/cancel` during the lookup answers the prompt with
* -32800 like any prompt not inserted yet, also when the message is
* stored: the client's next retry then gets the `messageId`.
*/
private submit(
params: v2.PromptRequest,
request: PromptRequest,
guard: ((query: Query) => Promise<void> | undefined) | undefined,
{ uuid, stored }: KeyedAttempt,
): Promise<v2.PromptResponse> {
const remoteControl = this.remoteControl.mayRun(request.prompt);
const guarded = guard && !remoteControl ? guard : undefined;
// A prompt that the guard refuses titles nothing and sends no notice.
@@ -475,19 +435,15 @@ export class V2Session implements RequestTarget {
// The notice of a mode fallback at the session's start, which sends it at once.
void this.config.promptSent();
};
if (!guarded) sent();
const uuid = randomUUID();
const message = { ...promptToClaude(request), uuid };
/** What a prompt that is new to the session registers before it goes to Claude Code. */
const accept = () => {
if (!guarded) sent();
// Only a prompt that goes to Claude Code gets a file-change report, as
// on v1: the adapter's `/remote-control` registers it once it passes
// the prompt on (below).
if (!remoteControl) this.fileChanges?.requested(uuid, params._meta);
const localCommand = this.commands.localCommand(request.prompt);
if (localCommand) this.localCommands.set(uuid, localCommand);
};
// A prompt whose key the stored history may hold is new only once the lookup says so.
if (!stored) accept();
// Only a prompt that goes to Claude Code gets a file-change report, as on
// v1: the adapter's `/remote-control` registers it once it passes the
// prompt on (below).
if (!remoteControl) this.fileChanges?.requested(uuid, params._meta);
const localCommand = this.commands.localCommand(request.prompt);
if (localCommand) this.localCommands.set(uuid, localCommand);
return new Promise((resolve, reject) => {
const pending: PendingPrompt = { prompt: params.prompt, pushed: false, resolve, reject };
this.pending.set(uuid, pending);
@@ -497,17 +453,6 @@ export class V2Session implements RequestTarget {
.then(() => this.interrupting)
.then(async () => {
if (answered()) return;
if (stored) {
const messageId = await stored();
if (answered()) return;
if (messageId !== undefined) {
this.pending.delete(uuid);
resolve({ messageId });
this.checkBoundary();
return;
}
accept();
}
if (guarded) {
try {
// Set by `start`, which runs before the agent lists the session.