diff --git a/README.md b/README.md index f5e9b0ab..a74645cf 100644 --- a/README.md +++ b/README.md @@ -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 diff --git a/src/tests/v2/v2-integration.test.ts b/src/tests/v2/v2-integration.test.ts index 6587fbed..fb92e4f9 100644 --- a/src/tests/v2/v2-integration.test.ts +++ b/src/tests/v2/v2-integration.test.ts @@ -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[] = []; diff --git a/src/tests/v2/v2.test.ts b/src/tests/v2/v2.test.ts index ac40b9e5..81650d67 100644 --- a/src/tests/v2/v2.test.ts +++ b/src/tests/v2/v2.test.ts @@ -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) => + 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) => 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], diff --git a/src/v2/agent.ts b/src/v2/agent.ts index 2d3067e1..651b0ec7 100644 --- a/src/v2/agent.ts +++ b/src/v2/agent.ts @@ -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>>(); /** 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(); 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 { + 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; diff --git a/src/v2/prompt-keys.ts b/src/v2/prompt-keys.ts new file mode 100644 index 00000000..01bcbce3 --- /dev/null +++ b/src/v2/prompt-keys.ts @@ -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; + +/** 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; +} + +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; + /** 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(); + /** 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> | undefined; + + constructor( + private readonly sessionId: string, + /** The uuids of the user messages in the session's stored history, oldest first. */ + private readonly readStored: () => Promise>, + 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, + ): Promise { + 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 { + if (!this.stored) { + const read: Promise> = this.readStored().then( + (uuids) => { + const messages = new Map(); + // 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(); + }, + ); + 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("-"); +} diff --git a/src/v2/prompt.ts b/src/v2/prompt.ts index 810d0bf0..4662e095 100644 --- a/src/v2/prompt.ts +++ b/src/v2/prompt.ts @@ -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"); } diff --git a/src/v2/session.ts b/src/v2/session.ts index 0365d364..34ca1c68 100644 --- a/src/v2/session.ts +++ b/src/v2/session.ts @@ -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 | undefined) | undefined, + { uuid, stored }: KeyedAttempt, + ): Promise { 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.