feat: insert one message per idempotencyKey on v2 session/prompt (#1657)

On v2, a `session/prompt` with an `idempotencyKey` now inserts at most
one user message for that key. This is the follow-up that #1655 left
open.

## Why

ACP v2 (schema v2.0.0-alpha.17) added an optional `idempotencyKey` to
`session/prompt`. Every Agent that advertises `capabilities.session`
must support it: a Client that lost a prompt's response sends the prompt
again with the same key, and the Agent answers with the first
`messageId` without inserting a second message.

The adapter accepted the field and ignored it, so a retry was inserted
again and started its work again.

## What a client sees

| The key in this session | Response |
| --- | --- |
| Not seen | The prompt is handled as before. Its `messageId` is
recorded with the key. |
| A prompt with the key is not answered yet | The same outcome as that
prompt, when it is answered. Nothing more goes to Claude Code. |
| A message was inserted with the key | That message's `messageId`. No
update, no new work. |
| A prompt with the key failed, for example with `-32800` after
`session/cancel` | The key is unused. The prompt is handled as a new
one. |

- A key is known for as long as Claude Code stores its message, also
after `session/close`, on a new connection, and after the adapter
restarts.
- A message that Claude Code does not store, such as a local command's,
keeps its key while the session is active on the connection: from its
start to `session/close`, across restarts of the session's query.
- The same key in another session, a fork too, names another prompt.
- Prompts of one key are not compared. A different prompt with a
recorded key is answered as a retry, which the protocol allows.
- The ACP SDK rejects a key that is not a string of 1 to 255 characters
with `-32602` before the adapter sees it.

## How

The protocol suggests storing the key as part of the message's id, and
Claude Code makes that possible: a prompt that the adapter pushes with a
uuid is stored under that uuid.

`src/v2/prompt-keys.ts` owns the keys of one session:

- A keyed prompt gets a version 8 (custom) UUID. Its first 32 characters
are a SHA-256 hash of the session id and the key. Its last 4 hex digits
count the attempts.
- The `messageId` is that uuid, so no update, `session/list` result or
replay shows the key.
- After a resume, the first keyed prompt reads the stored history once
(`getSessionMessages`, with the messages before each compaction, as a
replay reads it) and looks for a user message with the key's prefix. A
session that this connection created needs no read.
- When that read fails, the key counts as unused and the next lookup
reads again. The session stays usable.

`V2Session.prompt` calls `PromptKeys.once`, which returns the pending
attempt's promise, the stored `messageId`, or runs the prompt. The
promise is returned as it is, so the response keeps its order relative
to the turn's `running`.

`V2Agent` keeps one record per session, so a restart of the session's
query (a provider change, new additional directories) keeps the keys.

### Why each attempt has its own uuid

Claude Code ignores a prompt whose uuid it has seen: it echoes it and
starts no turn. A prompt that `session/cancel` answered with `-32800`
may already have reached Claude Code. If the next attempt reused the
uuid, Claude Code could drop it, and the adapter's own record of prompts
that a cancel stopped would take the new attempt for the old one. So an
attempt after a failure gets the next number, and the lookup matches on
the prefix.

## Checked against the real CLI

Bundled Claude Code of `@anthropic-ai/claude-agent-sdk` 0.3.326:

- A pushed version 8 uuid is accepted, echoed, and returned by
`getSessionMessages` as the user message's uuid.
- The same holds for a prompt that waited in Claude Code's queue, and
for one that it folded into a running turn. The raw transcript stores a
folded prompt as a `queued_command` attachment, and `getSessionMessages`
still returns it under the pushed uuid.
- A second push of a uuid gets an echo and an `idle`, with no
`command_lifecycle` frame and no result.

## Not covered

- `$/cancel_request` for a held prompt is still not honored, with or
without a key. The protocol makes it optional.
- A `session/cancel` that arrives while a retry's history lookup runs
answers the retry with `-32800`, also when the message is stored. The
client's next retry gets the `messageId`.
- If Claude Code took in a prompt that a cancel had already answered
with `-32800`, a retry is inserted as a new message. That is today's
behavior for any cancelled prompt.
- v1 has no `idempotencyKey`.

## Tests

- `v2.test.ts`: a retry of an inserted prompt, of a pending one, and
after a failure (with a new uuid). The same key in another session. The
record across a restart of the query. After a close and a resume, a key
that the stored history holds and one that it does not.
- `v2-integration.test.ts` (real CLI, run locally): one message for a
key, and the key is known after `session/close` and `session/resume`.

`npm run build`, `npm run check` and `npm run test:run` pass (4344
tests).
This commit is contained in:
Ben Brandt
2026-11-19 09:32:43 +01:00
committed by GitHub
parent e62d084e9d
commit 1c0792ea8c
7 changed files with 469 additions and 16 deletions

View File

@@ -74,9 +74,12 @@ 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.
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`.
`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`.
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

View File

@@ -131,6 +131,29 @@ 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,6 +673,25 @@ 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) => {
@@ -1104,6 +1123,139 @@ 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,6 +75,7 @@ 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";
@@ -173,6 +174,13 @@ 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`). */
@@ -692,6 +700,8 @@ 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();
@@ -816,6 +826,7 @@ 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()));
}
@@ -945,7 +956,18 @@ class V2Agent implements AgentHandle, SessionConnection {
query: q,
model: { id: models.models.currentModelId, info: models.allowlistedModelInfo },
});
session.start(q, config, opened.mcpServers, resume !== undefined);
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);
this.sessions.set(sessionId, session);
this.stopped.delete(sessionId);
// A route change during the start did not find this session live.
@@ -1263,6 +1285,22 @@ 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;

174
src/v2/prompt-keys.ts Normal file
View File

@@ -0,0 +1,174 @@
/**
* 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,8 +21,16 @@ 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, ...request }: v2.PromptRequest): PromptRequest {
export function v1PromptRequest({
prompt,
// eslint-disable-next-line @typescript-eslint/no-unused-vars
idempotencyKey,
...request
}: v2.PromptRequest): PromptRequest {
if (prompt.length === 0) {
throw RequestError.invalidParams({ prompt }, "`prompt` must hold at least one content block");
}

View File

@@ -8,7 +8,8 @@
* - 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.
* `discarded` or `refused` fails the prompt. A prompt with an
* `idempotencyKey` is pushed once per key (see `prompt-keys.ts`).
* - 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
@@ -81,6 +82,7 @@ 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";
@@ -195,6 +197,8 @@ 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`). */
@@ -346,11 +350,19 @@ export class V2Session implements RequestTarget {
/**
* Starts reading the query. Called once, after its initialization.
* `mcpServers` are the servers the query started with.
* `mcpServers` are the servers the query started with, and `keys` the
* record of the session's prompt keys, which outlives this query.
*/
start(query: Query, config: SessionConfig, mcpServers: McpServers, resumed = false): void {
start(
query: Query,
config: SessionConfig,
mcpServers: McpServers,
keys: PromptKeys,
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);
@@ -417,6 +429,11 @@ 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,
@@ -427,6 +444,29 @@ 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.
@@ -435,15 +475,19 @@ 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 };
// 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);
/** 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();
return new Promise((resolve, reject) => {
const pending: PendingPrompt = { prompt: params.prompt, pushed: false, resolve, reject };
this.pending.set(uuid, pending);
@@ -453,6 +497,17 @@ 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.