Compare commits

...

2 Commits

Author SHA1 Message Date
Ben Brandt
1dadbfa68a feat: announce session cursors on v2 and fork at a cursor
The session cursors RFD lets an Agent name the positions of a session that a
method can act at, and `session/fork` takes one as `cursorId`. The adapter
announced none and refused every `cursorId`.

On v2, each user message that follows another entry of the conversation now
gets a `cursor_update` right after it, live and in a replay. The cursor is
anchored `before` the message and has the `fork` capability. `session/fork`
with its `cursorId` copies the history before that message, so a client can
edit a message or ask again from there.

- `src/session-cursors.ts` owns the rules. The `cursorId` is derived from
  the uuid of the user message, which Claude Code stores, so it is the same
  live, in every replay and after a restart, and the adapter keeps no
  cursors of its own.
- A fork reads the stored history as a replay reads it, and ends the copy at
  the entry before the cursor's message (`upToMessageId`). Any other
  `cursorId` fails with -32602 before anything is copied.
- The first entry of a history has no cursor: nothing is before it. A slash
  command gets none live, because a replay shows no user message for it. A
  subagent's session gets none: a client cannot fork it.

A v1 client gets no cursors yet. A fork takes a `cursorId` on both versions.
2026-11-18 17:14:11 +01:00
Ben Brandt
437ff12a5f feat: insert one message per idempotencyKey on v2 session/prompt
ACP v2 added an optional `idempotencyKey` to `session/prompt`, which every
agent that advertises `capabilities.session` must support. A client that
lost a prompt's response sends the prompt again with the same key, and the
agent must not insert the message twice. The adapter accepted the field and
ignored it.

`src/v2/prompt-keys.ts` keeps the keys of each session's prompts:

- A retry of a prompt that is not answered yet gets that prompt's outcome.
- A retry of an inserted prompt gets its `messageId`. Neither goes to
  Claude Code again.
- A prompt that failed leaves its key unused.

The key is stored as the message's id. A keyed prompt goes to Claude Code
with a uuid that is a hash of the session id and the key, with the attempt
number in its last four hex digits. Claude Code keeps that uuid in the
transcript, so a key is known for as long as its message is stored, across
connections and restarts, and no update shows the key. The first keyed
prompt after a resume reads the stored history once to look its key up.

Each attempt has its own uuid because Claude Code ignores a prompt whose
uuid it has seen, and a prompt that `session/cancel` answered with -32800
may have reached it.

The agent keeps the record of a session from its start to `session/close`
or the end of the connection, across restarts of the session's query, so a
message that Claude Code does not store, such as a local command's, keeps
its key for that long.
2026-11-18 17:05:07 +01:00
13 changed files with 795 additions and 40 deletions

View File

@@ -74,9 +74,14 @@ 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.
The adapter announces a session cursor (`cursor_update`) before each user message that follows
another entry of the conversation, live and in a replay. `session/fork` with its `cursorId` copies
the history before that message, and fails with `-32602` for any other `cursorId`. A v1 client gets
no cursors yet.
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

@@ -9,7 +9,8 @@ import {
type SessionStoreEntry,
} from "@anthropic-ai/claude-agent-sdk";
import { createHash } from "node:crypto";
import { loadFullSessionHistory } from "./resumed-session.js";
import { loadFullSessionHistory, readHistoryAcrossCompactions } from "./resumed-session.js";
import { forkPointOf } from "./session-cursors.js";
import { assistantMessageText } from "./session-failure-extension.js";
import { SessionTiming } from "./session-timing.js";
@@ -177,22 +178,18 @@ function isUnknownSessionError(error: unknown, sessionId: string): boolean {
}
/**
* Copies the transcript of `params.sessionId` into a new session.
* Copies the transcript of `params.sessionId` into a new session: all of it,
* or with a `cursorId` the history before that session cursor (see
* `session-cursors.ts`).
*
* Fails with invalid params (-32602) for a `cursorId`: the agent sends no
* `cursor_update`, so it issued no cursor, and ACP forbids forking the whole
* session in its place.
* Fails with invalid params (-32602) for a `cursorId` that is no cursor of
* the session's stored history. ACP forbids forking the whole session, or at
* another position, in its place.
*/
export async function forkSession(
params: ForkSessionRequest,
dependencies: ForkSessionDependencies,
): Promise<ForkSessionResponse> {
if (params.cursorId != null) {
throw RequestError.invalidParams(
{ cursorId: params.cursorId },
`Session ${params.sessionId} has no cursor ${params.cursorId}: this agent announces no session cursors. Send the request without \`cursorId\` to fork the whole session.`,
);
}
try {
return await forkTranscript(params, dependencies);
} catch (error) {
@@ -208,6 +205,24 @@ async function forkTranscript(
dependencies: ForkSessionDependencies,
): Promise<ForkSessionResponse> {
const timing = new SessionTiming(dependencies.logger, "fork", params.sessionId);
if (params.cursorId != null) {
// The history as a replay reads it, which announces the cursors.
const history = await readHistoryAcrossCompactions(
params.sessionId,
await getSessionMessages(params.sessionId),
);
const upToMessageId = forkPointOf(params.cursorId, history);
timing.phase("cursor", ` resolution=${upToMessageId ? "found" : "missing"}`);
if (upToMessageId === undefined) {
throw RequestError.invalidParams(
{ cursorId: params.cursorId },
`Session ${params.sessionId} has no cursor ${params.cursorId} that a fork can start at. Use a cursor that the session announced with the \`fork\` capability, or send the request without \`cursorId\` to fork the whole session.`,
);
}
const forked = await forkClaudeSession(params.sessionId, { upToMessageId });
timing.phase("sdk-fork");
return { sessionId: forked.sessionId };
}
const point = forkPoint(params._meta);
// SDK `dir` scopes source lookup, not the fork's working directory. Search
// all projects: params.cwd can name a different workspace for the new session.

84
src/session-cursors.ts Normal file
View File

@@ -0,0 +1,84 @@
/**
* Session cursors (the unstable session cursors RFD): the positions of a
* session that a method can act at.
*
* The adapter announces one kind: the position before a user message that the
* session's history stores, with the `fork` capability. `session/fork` with
* its `cursorId` copies the history before that message, so a client can edit
* the message or ask again from there. The first entry of a history has no
* cursor: nothing is before it, and Claude Code forks at an entry, not before
* the first one.
*
* A `cursorId` is derived from the uuid of its user message, which Claude Code
* stores. So it is the same live, in every replay and after a restart, and
* the adapter keeps no cursors of its own: a fork finds the position in the
* stored history.
*/
import type { SessionMessage } from "@anthropic-ai/claude-agent-sdk";
import { isCompactSummaryMessage } from "./context-compaction.js";
import { isReplayHiddenMetaMessage, stripLocalCommandMetadata } from "./message-filters.js";
/** What the cursor ids start with. The rest is the uuid of the user message. */
const BEFORE_MESSAGE = "before:";
/** The `cursor_update` of the cursor before the user message `messageId`. */
export function forkCursorUpdate(messageId: string) {
return {
sessionUpdate: "cursor_update" as const,
cursorId: `${BEFORE_MESSAGE}${messageId}`,
capabilities: { fork: {} },
anchor: { type: "user_message" as const, messageId, position: "before" as const },
};
}
/**
* Whether a prompt with this content gets a cursor when it is inserted live.
* A slash command does not: Claude Code stores a command as command metadata
* or not at all, so a replay shows no user message for it and a fork finds no
* cursor (see {@link hasForkCursor}). Text that only starts like a command
* gets its cursor in the next replay.
*/
export function promptGetsCursor(prompt: ReadonlyArray<{ type: string; text?: unknown }>): boolean {
const first = prompt.find((block) => block.type === "text");
return !(typeof first?.text === "string" && first.text.trimStart().startsWith("/"));
}
/**
* Whether the entry `index` of the stored history `messages` is a user
* message with a cursor before it: one that a replay shows as a user message
* under its uuid, and that follows an entry that a fork can end with. A
* replay announces the cursor of each such message, and a fork accepts no
* other.
*/
export function hasForkCursor(messages: readonly SessionMessage[], index: number): boolean {
const message = messages[index];
if (!message || message.type !== "user" || !message.uuid) return false;
if (!messages[index - 1]?.uuid) return false;
if (message.parent_tool_use_id !== null) return false;
if (isReplayHiddenMetaMessage(message) || isCompactSummaryMessage(message)) return false;
// `null`: the message was command metadata alone, which a replay does not show.
const content = stripLocalCommandMetadata(
(message.message as { content?: unknown } | undefined)?.content,
);
if (typeof content === "string") return content.length > 0;
// A message of tool results alone is no user message.
return (
Array.isArray(content) &&
content.some((block) => (block as { type?: unknown } | null)?.type !== "tool_result")
);
}
/**
* The uuid of the entry that a fork at `cursorId` ends with: the entry before
* the cursor's user message in the stored history `messages`. Undefined for
* an id that is no cursor of that history (see {@link hasForkCursor}).
*/
export function forkPointOf(
cursorId: string,
messages: readonly SessionMessage[],
): string | undefined {
if (!cursorId.startsWith(BEFORE_MESSAGE)) return undefined;
const messageId = cursorId.slice(BEFORE_MESSAGE.length);
const index = messages.findIndex((message) => message.uuid === messageId);
return hasForkCursor(messages, index) ? messages[index - 1]!.uuid : undefined;
}

View File

@@ -15,6 +15,7 @@
{"kind":"notification","method":"session/update","payload":{"sessionId":"<session>","update":{"_meta":{"_claude/model":"claude-sonnet-4-6"},"cost":{"amount":0,"currency":"USD"},"sessionUpdate":"usage_update","size":200000,"used":2}}}
{"kind":"notification","method":"session/update","payload":{"sessionId":"<session>","update":{"_meta":{"quota":{"model_usage":[],"token_count":{"cachedInputTokens":0,"cachedWriteTokens":0,"inputTokens":0,"outputTokens":0,"reasoningOutputTokens":0,"totalTokens":0}}},"background":[],"sessionUpdate":"state_update","state":"idle","stopReason":"end_turn","usage":{"cachedReadTokens":0,"cachedWriteTokens":0,"inputTokens":0,"outputTokens":0,"totalTokens":0}}}}
{"kind":"notification","method":"session/update","payload":{"sessionId":"<session>","update":{"content":[{"text":"prompt 2","type":"text"}],"messageId":"<id-2>","sessionUpdate":"user_message"}}}
{"kind":"notification","method":"session/update","payload":{"sessionId":"<session>","update":{"anchor":{"messageId":"<id-2>","position":"before","type":"user_message"},"capabilities":{"fork":{}},"cursorId":"before:<id-2>","sessionUpdate":"cursor_update"}}}
{"kind":"response","method":"session/prompt","payload":{"messageId":"<id-2>"}}
{"kind":"notification","method":"session/update","payload":{"sessionId":"<session>","update":{"background":[],"sessionUpdate":"state_update","state":"running"}}}
{"kind":"notification","method":"session/update","payload":{"sessionId":"<session>","update":{"_meta":{"_claude/model":"claude-sonnet-4-6"},"sessionUpdate":"usage_update","size":200000,"used":2}}}

View File

@@ -187,17 +187,43 @@ describe.each(["same directory", "different directory"])("fork into %s", (direct
});
});
it("rejects a cursorId without forking the whole session", async () => {
const projectDir = path.dirname(sourceFile);
await expect(
forkSession(
{ sessionId, cwd: sourceCwd, mcpServers: [], cursorId: "cur_9f2c41" },
describe("fork at a session cursor", () => {
/** The entries of the source transcript, as `getSessionMessages` returns its active chain. */
const history = () => getSessionMessages(sessionId, { dir: sourceCwd });
it("copies the history before the cursor's user message", async () => {
const [, firstAnswer, followup] = await history();
const response = await forkSession(
{ sessionId, cwd: destinationCwd, mcpServers: [], cursorId: `before:${followup!.uuid}` },
{ messageIdForGrouping },
),
).rejects.toMatchObject({
code: -32602,
data: { cursorId: "cur_9f2c41" },
message: expect.stringContaining("this agent announces no session cursors"),
);
const forked = await getSessionMessages(response.sessionId);
expect(forked.map((message) => message.message)).toEqual([
{ role: "user", content: "First prompt" },
expect.objectContaining({ id: "msg_first" }),
]);
expect(firstAnswer!.message).toMatchObject({ id: "msg_first" });
expect(await fs.readFile(sourceFile, "utf8")).toBe(transcript);
});
it.each([
["an id that the session did not announce", () => "cur_9f2c41"],
// Nothing is before the first entry.
["the first entry of the history", async () => `before:${(await history())[0]!.uuid}`],
["an entry that is no user message", async () => `before:${(await history())[1]!.uuid}`],
])("rejects %s without forking anything", async (_, cursor) => {
const cursorId = await cursor();
await expect(
forkSession(
{ sessionId, cwd: sourceCwd, mcpServers: [], cursorId },
{ messageIdForGrouping },
),
).rejects.toMatchObject({
code: -32602,
data: { cursorId },
message: expect.stringContaining("that a fork can start at"),
});
expect(await fs.readdir(path.dirname(sourceFile))).toEqual([path.basename(sourceFile)]);
});
expect(await fs.readdir(projectDir)).toEqual([path.basename(sourceFile)]);
});

View File

@@ -2790,6 +2790,8 @@ describe("ACP v2 prompts", () => {
expect.objectContaining({ currentValue: "claude-haiku-4-5" }),
expect.objectContaining({ currentValue: "claude-sonnet-4-6" }),
]);
// The client cannot fork a child, so the messages a child received get no cursor.
expect(client.updates("cursor_update")).toEqual([]);
});
it("ends a resume with replay with one end event after replay_complete for a client with loadReplayEnd", async () => {

View File

@@ -131,6 +131,65 @@ 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);
it("forks at the cursor before a prompt, with the history that came before it", async () => {
const sessionId = await newSession("default");
const kinds = (id: string, kind: string) =>
updates.flatMap(({ sessionId: session, update }) =>
session === id && update.sessionUpdate === kind ? [update] : [],
);
const idles = () => states(sessionId).filter((update) => update.state === "idle").length;
await prompt(sessionId, "Reply with exactly the single word: one");
await until(() => idles() === 1);
const second = await prompt(sessionId, "Reply with exactly the single word: two");
await until(() => idles() === 2);
// The first prompt has nothing before it: only the second has a cursor.
const [cursor, ...others] = kinds(sessionId, "cursor_update") as v2.CursorUpdate[];
expect(others).toEqual([]);
expect(cursor).toMatchObject({
capabilities: { fork: {} },
anchor: { type: "user_message", messageId: second.messageId, position: "before" },
});
const fork = await agent.request(v2.methods.agent.session.fork, {
sessionId,
cwd,
cursorId: cursor!.cursorId,
});
await agent.request(v2.methods.agent.session.close, { sessionId: fork.sessionId });
await agent.request(v2.methods.agent.session.resume, {
sessionId: fork.sessionId,
cwd,
replayFrom: { type: "start" },
});
const replayedPrompts = kinds(fork.sessionId, "user_message_chunk").map(
(update) => (update as { content: { text?: string } }).content.text,
);
expect(replayedPrompts).toEqual(["Reply with exactly the single word: one"]);
expect(kinds(fork.sessionId, "agent_message_chunk")).not.toEqual([]);
}, 240_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],
@@ -2439,6 +2591,117 @@ describe("ACP v2 core", () => {
]);
});
describe("session cursors", () => {
const stored = (type: "user" | "assistant", uuid: string, message: unknown) => ({
type,
uuid,
session_id: "s",
parent_tool_use_id: null,
parent_agent_id: null,
message,
});
/** Two turns: a fork can start before the second prompt, and not before the first. */
const twoTurns = [
stored("user", "u1", { role: "user", content: "Build it" }),
stored("assistant", "a1", {
id: "msg_a",
role: "assistant",
content: [{ type: "text", text: "Built." }],
}),
stored("user", "u2", { role: "user", content: "Test it" }),
] as never;
const cursorOf = (messageId: string) => ({
sessionUpdate: "cursor_update",
cursorId: `before:${messageId}`,
capabilities: { fork: {} },
anchor: { type: "user_message", messageId, position: "before" },
});
it("announces a cursor before a prompt that follows another, and none for a slash command", async () => {
const client = v2Client();
const ids = await client.connect(async (agent) => {
const { response, claude } = await openSession(agent);
const ids: string[] = [];
for (const [index, text] of ["Build it", "Test it", "/context"].entries()) {
const answer = agent.request(v2.methods.agent.session.prompt, {
sessionId: response.sessionId,
prompt: [{ type: "text", text }],
});
claude.send(lifecycle(await claude.prompt(index), "started"));
ids.push((await answer).messageId);
claude.send(result());
await vi.waitFor(() =>
expect(client.states().filter((state) => state === "idle")).toHaveLength(index + 1),
);
}
return ids;
});
const kinds = client.sessionUpdates.filter((update) =>
["user_message", "cursor_update"].includes(update.sessionUpdate),
);
// The first prompt has nothing before it. The cursor follows its message.
expect(kinds).toEqual([
expect.objectContaining({ sessionUpdate: "user_message", messageId: ids[0] }),
expect.objectContaining({ sessionUpdate: "user_message", messageId: ids[1] }),
cursorOf(ids[1]!),
expect.objectContaining({ sessionUpdate: "user_message", messageId: ids[2] }),
]);
});
it("replays the cursor of each user message after it, with the id of the live one", async () => {
vi.mocked(getSessionMessages).mockResolvedValueOnce(twoTurns);
const client = v2Client();
await client.connect(async (agent) => {
await agent.request(v2.methods.agent.initialize, {
protocolVersion: v2.PROTOCOL_VERSION,
info: { name: "v2-test-client", version: "1.0.0" },
capabilities: {},
});
await agent.request(v2.methods.agent.session.resume, {
sessionId: randomUUID(),
cwd,
replayFrom: { type: "start" },
});
});
const replayed = client.sessionUpdates.slice(
0,
client.sessionUpdates.findIndex((update) => update.sessionUpdate === "replay_complete"),
);
expect(replayed.map((update) => update.sessionUpdate)).toEqual([
"user_message",
"user_message_chunk",
"agent_message",
"agent_message_chunk",
"user_message",
"user_message_chunk",
"cursor_update",
]);
expect(replayed.at(-1)).toEqual(cursorOf("u2"));
});
it.each([
["forks the history before a cursor's message", "before:u2", { upToMessageId: "a1" }],
["rejects a cursor that the history does not have", "before:u9", undefined],
])("%s", async (_, cursorId, forkedAt) => {
const client = v2Client();
await client.connect(async (agent) => {
const { response } = await openSession(agent);
const { sessionId } = response;
vi.mocked(getSessionMessages).mockResolvedValueOnce(twoTurns);
const fork = agent.request(v2.methods.agent.session.fork, { sessionId, cwd, cursorId });
if (forkedAt) {
await fork;
expect(forkSession).toHaveBeenCalledExactlyOnceWith(sessionId, forkedAt);
} else {
await expect(fork).rejects.toMatchObject({ code: -32602, data: { cursorId } });
expect(forkSession).not.toHaveBeenCalled();
}
});
});
});
it("ends the replay of an empty history with replay_complete, and sends none without replayFrom", async () => {
const client = v2Client();
await client.connect(async (agent) => {

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
@@ -67,6 +68,7 @@ import type { UnservedMcpServer } from "../mcp-servers.js";
import { modelRefusalFallback, noticeUpdate } from "../session-notices.js";
import { planModeUpdate } from "../exit-plan.js";
import { resetPlanUpdates } from "../plans.js";
import { forkCursorUpdate, promptGetsCursor } from "../session-cursors.js";
import type { ClearContextReset } from "../clear-context-coordinator.js";
import { agentFileChangeReportMeta } from "../file-change-audit.js";
import type { AirSupport } from "./air.js";
@@ -81,6 +83,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";
@@ -177,6 +180,12 @@ export class V2Session implements RequestTarget {
private lifecycleFrames = false;
/** What the open turn's assistant messages reported about its end (see {@link TurnReport}). */
private readonly turnReport = new TurnReport();
/**
* Whether the conversation holds an entry: the query resumed a stored one,
* or a prompt of this session was inserted. A prompt that follows one gets
* a session cursor (see {@link inserted}).
*/
private hasHistory = false;
/** Set by `session/close`, or when the query ends: nothing more goes out. */
private closed = false;
private closing: Promise<void> | undefined;
@@ -195,6 +204,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,12 +357,21 @@ 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.hasHistory = resumed;
this.mcpServers = JSON.stringify(mcpServers);
this.commands = new SessionCommands(query);
void this.consume(query);
@@ -417,6 +437,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 +452,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 +483,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 +505,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.
@@ -1143,12 +1206,22 @@ export class V2Session implements RequestTarget {
this.openTurn(uuid);
}
/**
* The prompt `uuid` is inserted: its `user_message` goes out, and its
* response. A prompt that follows an entry of the conversation also gets
* its session cursor, which `session/fork` takes to copy the history
* before the prompt (see `session-cursors.ts`). The cursor is announced at
* once, and a fork finds it once Claude Code stored the message. A slash
* command gets none.
*/
private inserted(uuid: string): void {
const prompt = this.pending.get(uuid);
if (!prompt) return;
this.pending.delete(uuid);
this.fileChanges?.promptStarted(uuid);
this.send({ sessionUpdate: "user_message", messageId: uuid, content: prompt.prompt });
if (this.hasHistory && promptGetsCursor(prompt.prompt)) this.send(forkCursorUpdate(uuid));
this.hasHistory = true;
prompt.resolve({ messageId: uuid });
}

View File

@@ -46,6 +46,7 @@ import { UnansweredServerToolCalls } from "../tool-calls/server-tool-calls.js";
import { AcpToolCallRenderer, progressToolCallId, V2_CANCELLED } from "../tool-calls/renderer.js";
import { changedTaskPlanEntries, unregisterHookCallback, type TaskState } from "../tools.js";
import { recordStreamedDelta, unstreamedRemainder, type StreamedBlock } from "../streamed-text.js";
import { forkCursorUpdate, hasForkCursor } from "../session-cursors.js";
import { replayClear, type V2UpdateTranslator } from "./update-translator.js";
/** Every v2 client gets the same tool call reports: v2 diffs and display terminals. */
@@ -406,7 +407,9 @@ export class SessionOutput {
* messages and its tool calls, as the live session sent them. Subagent
* transcripts are left out, as live. The client may hold the replayed
* messages already, so each message is cleared before its first chunk.
* `hooks` replays the subagents' own histories to their sessions.
* `hooks` replays the subagents' own histories to their sessions. Each
* user message of the root session that a fork can start before gets its
* session cursor right after it (see `session-cursors.ts`).
*
* A replayed tool call that the history gives no result, such as one that
* ran when Claude Code was killed, ends `failed` after the replay, as v2
@@ -425,7 +428,7 @@ export class SessionOutput {
this.replayHooks = hooks;
const unfinished = (this.replayUnfinished = new Set());
try {
for (const message of messages) {
for (const [index, message] of messages.entries()) {
if (message.parent_tool_use_id !== null || isReplayHiddenMetaMessage(message)) continue;
// Claude Code's sign-in message, which the live session did not show either.
if (message.type === "assistant" && isSyntheticLoginMessage(message.message)) continue;
@@ -457,6 +460,10 @@ export class SessionOutput {
{ messageId: message.uuid, replay: true },
running,
);
// The client cannot fork a subagent's session, so a child gets no cursors.
if (!this.subagent && hasForkCursor(messages, index)) {
this.send(forkCursorUpdate(message.uuid));
}
}
hooks?.replayed(message);
}