@agentclientprotocol/claude-agent-acp 0.108.1-preview.5 → 0.108.2-preview.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/v2/agent.js CHANGED
@@ -18,6 +18,7 @@ import { deleteSession, getSessionMessages, listSessions, query, } from "@anthro
18
18
  import packageJson from "../../package.json" with { type: "json" };
19
19
  import { messageIdForGrouping } from "../sdk-to-acp.js";
20
20
  import { customAgents } from "../session-config-options.js";
21
+ import { restrictedChild } from "../acp-subagents.js";
21
22
  import { claudeCliPath, mcpServersDelivery } from "../claude-cli.js";
22
23
  import { clientSystemPrompt, sessionSystemPrompt } from "../client-system-prompt.js";
23
24
  import { forkSession } from "../fork-session.js";
@@ -46,6 +47,7 @@ import { modelSwitchHook, SessionConfig } from "./config.js";
46
47
  import { v2ElicitationRequest } from "./elicitation.js";
47
48
  import { fileChangePreviewHook } from "./file-preview.js";
48
49
  import { canUseTool, denyingStoppedWork } from "./permissions.js";
50
+ import { PromptKeys } from "./prompt-keys.js";
49
51
  import { ReplayHolds } from "./replay-hold.js";
50
52
  import { reportHooks } from "./reports.js";
51
53
  import { savedSessionStatus } from "../session-status.js";
@@ -53,7 +55,6 @@ import { SessionRestarts } from "./restarts.js";
53
55
  import { V2Session } from "./session.js";
54
56
  import { afterSetupResponse, clientOptions, REPLAY_COMPLETE, replayEndUpdate, sessionModels, withClientHooks, } from "./setup.js";
55
57
  import { SubscriptionGuard } from "./subscription-guard.js";
56
- import { restrictedChild } from "./tasks.js";
57
58
  /** The sessions per `session/list` page. */
58
59
  const SESSION_LIST_PAGE_SIZE = 1000;
59
60
  /** The ACP v2 surface, for one connection. */
@@ -117,6 +118,13 @@ class V2Agent {
117
118
  resuming = new Map();
118
119
  /** What the resumes that replay hold back until their `replay_complete` (see `replay-hold.ts`). */
119
120
  replays = new ReplayHolds();
121
+ /**
122
+ * The `idempotencyKey`s of each session's prompts, from the session's
123
+ * start to `session/close` or the end of the connection (see
124
+ * `prompt-keys.ts`). A restart of the session's query, and a resume of a
125
+ * session whose query ended, keep the record.
126
+ */
127
+ promptKeys = new Map();
120
128
  translator = new V2UpdateTranslator();
121
129
  auth;
122
130
  /** The `--hide-claude-auth` subscription guard (see `subscription-guard.ts`). */
@@ -580,6 +588,8 @@ class V2Agent {
580
588
  // its updates go out before the close response.
581
589
  await this.setupSettled(sessionId);
582
590
  this.stopped.delete(sessionId);
591
+ // A closed session is no longer active here: only its stored messages keep their keys.
592
+ this.promptKeys.delete(sessionId);
583
593
  const session = this.sessions.get(sessionId);
584
594
  if (session) {
585
595
  await session.close();
@@ -696,6 +706,7 @@ class V2Agent {
696
706
  const sessions = [...this.sessions.values()];
697
707
  this.sessions.clear();
698
708
  this.stopped.clear();
709
+ this.promptKeys.clear();
699
710
  await Promise.all(sessions.map((session) => session.close()));
700
711
  }
701
712
  // --- Session setup -----------------------------------------------------------
@@ -800,7 +811,14 @@ class V2Agent {
800
811
  query: q,
801
812
  model: { id: models.models.currentModelId, info: models.allowlistedModelInfo },
802
813
  });
803
- session.start(q, config, opened.mcpServers, resume !== undefined);
814
+ let keys = this.promptKeys.get(sessionId);
815
+ if (!keys) {
816
+ const { cwd } = opened.request;
817
+ keys = new PromptKeys(sessionId, () => storedPromptIds(sessionId, cwd, this.logger), this.logger);
818
+ this.promptKeys.set(sessionId, keys);
819
+ }
820
+ keys.queryStarted(resume !== undefined);
821
+ session.start(q, config, opened.mcpServers, keys, resume !== undefined);
804
822
  this.sessions.set(sessionId, session);
805
823
  this.stopped.delete(sessionId);
806
824
  // A route change during the start did not find this session live.
@@ -1065,6 +1083,14 @@ async function validatedSetup(params) {
1065
1083
  }
1066
1084
  return request;
1067
1085
  }
1086
+ /**
1087
+ * The uuids of the user messages in the stored history of the session
1088
+ * `sessionId`, as a replay reads it: the messages before each compaction too.
1089
+ */
1090
+ async function storedPromptIds(sessionId, cwd, logger) {
1091
+ const messages = await readHistoryAcrossCompactions(sessionId, await getSessionMessages(sessionId, { dir: cwd }), logger, cwd);
1092
+ return messages.flatMap((message) => message.type === "user" && message.uuid ? [message.uuid] : []);
1093
+ }
1068
1094
  /** A request of the active `session` names its `cwd`, as `session/resume` must. */
1069
1095
  function assertCwdOf(session, cwd, action) {
1070
1096
  if (cwd === session.cwd)
@@ -0,0 +1,86 @@
1
+ /**
2
+ * The `idempotencyKey`s of one session's prompts (ACP v2 `session/prompt`).
3
+ *
4
+ * A client that lost a prompt's response sends the prompt again with the same
5
+ * key. The session then inserts at most one user message for the key:
6
+ *
7
+ * - A prompt with the key that is not answered yet: the retry gets that
8
+ * prompt's outcome, and nothing more goes to Claude Code.
9
+ * - A message inserted with the key: the retry gets its `messageId`.
10
+ * - A prompt with the key that failed: the key is unused, and the retry is a
11
+ * new prompt.
12
+ *
13
+ * The key is stored as the message's id. A keyed prompt goes to Claude Code
14
+ * with a uuid whose first 32 characters are a hash of the session id and the
15
+ * key, and whose last 4 hex digits count the attempts. Claude Code keeps that
16
+ * uuid in the transcript (`getSessionMessages` returns it, also for a prompt
17
+ * that waited in its queue or that it folded into a running turn), so a key
18
+ * is recognized for as long as its message is stored, across connections and
19
+ * restarts, and no client sees the key: only its hash is in the `messageId`.
20
+ * The session id is part of the hash, so the same key in another session, a
21
+ * fork too, names another prompt.
22
+ *
23
+ * Each attempt has its own uuid because Claude Code ignores a prompt whose
24
+ * uuid it has seen: it echoes it and starts no turn. A prompt that a
25
+ * `session/cancel` answered with -32800 may have reached Claude Code, so the
26
+ * next attempt must not reuse its uuid.
27
+ *
28
+ * A message that Claude Code does not store, such as a local command's, is
29
+ * recognized while this record lives: the agent keeps one per session from
30
+ * its start to `session/close` or the end of the connection, across restarts
31
+ * of the session's query.
32
+ */
33
+ import { type randomUUID } from "node:crypto";
34
+ import type * as v2 from "@agentclientprotocol/sdk/experimental/v2/unstable";
35
+ import type { Logger } from "../logger.js";
36
+ type UUID = ReturnType<typeof randomUUID>;
37
+ /** One attempt to insert the prompt of a key. */
38
+ export interface KeyedAttempt {
39
+ /** The uuid that the prompt goes to Claude Code with, and its `messageId` once inserted. */
40
+ uuid: UUID;
41
+ /**
42
+ * The `messageId` of the message that the session's stored history holds
43
+ * for the key, or undefined for none. Absent when the history cannot hold
44
+ * one: a session that this connection created has only the messages of
45
+ * this record.
46
+ */
47
+ stored?: () => Promise<string | undefined>;
48
+ }
49
+ export declare class PromptKeys {
50
+ private readonly sessionId;
51
+ /** The uuids of the user messages in the session's stored history, oldest first. */
52
+ private readonly readStored;
53
+ private readonly logger;
54
+ /** The keys seen on this connection, by the uuid prefix of their attempts. */
55
+ private readonly keys;
56
+ /** Whether the session's stored history can hold a message of an earlier connection. */
57
+ private resumed;
58
+ /** The stored history's keyed messages, by uuid prefix, once read. */
59
+ private stored;
60
+ constructor(sessionId: string,
61
+ /** The uuids of the user messages in the session's stored history, oldest first. */
62
+ readStored: () => Promise<Iterable<string>>, logger: Logger);
63
+ /**
64
+ * A query of the session started. `resumed`: from a stored conversation,
65
+ * which can hold messages that this record does not know, so the next
66
+ * lookup reads the history again.
67
+ */
68
+ queryStarted(resumed: boolean): void;
69
+ /**
70
+ * The response of a prompt with `key`: of the attempt that is not answered
71
+ * yet, of the message inserted with the key, or of `submit`, which inserts
72
+ * the prompt. `submit` runs at most once at a time for a key, and not at
73
+ * all once a message is inserted with it. Its promise is returned as it
74
+ * is.
75
+ */
76
+ once(key: string, submit: (attempt: KeyedAttempt) => Promise<v2.PromptResponse>): Promise<v2.PromptResponse>;
77
+ /**
78
+ * The `messageId` that the stored history holds for the uuid prefix of a
79
+ * key. The history is read once per started query. When reading it fails,
80
+ * the key counts as unused, so the session stays usable, and the next
81
+ * lookup reads again.
82
+ */
83
+ private storedMessage;
84
+ }
85
+ export {};
86
+ //# sourceMappingURL=prompt-keys.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"prompt-keys.d.ts","sourceRoot":"","sources":["../../src/v2/prompt-keys.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;;;;;;;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a prompt's response sends the prompt again with the same
5
+ * key. The session then inserts at most one user message for the key:
6
+ *
7
+ * - A prompt with the key that is not answered yet: the retry gets that
8
+ * prompt's outcome, and nothing more goes to Claude Code.
9
+ * - A message inserted with the key: the retry gets its `messageId`.
10
+ * - A prompt with the key that failed: the key is unused, and the retry is a
11
+ * new prompt.
12
+ *
13
+ * The key is stored as the message's id. A keyed prompt goes to Claude Code
14
+ * with a uuid whose first 32 characters are a hash of the session id and the
15
+ * key, and whose last 4 hex digits count the attempts. Claude Code keeps that
16
+ * uuid in the transcript (`getSessionMessages` returns it, also for a prompt
17
+ * that waited in its queue or that it folded into a running turn), so a key
18
+ * is recognized for as long as its message is stored, across connections and
19
+ * restarts, and no client sees the key: only its hash is in the `messageId`.
20
+ * The session id is part of the hash, so the same key in another session, a
21
+ * fork too, names another prompt.
22
+ *
23
+ * Each attempt has its own uuid because Claude Code ignores a prompt whose
24
+ * uuid it has seen: it echoes it and starts no turn. A prompt that a
25
+ * `session/cancel` answered with -32800 may have reached Claude Code, so the
26
+ * next attempt must not reuse its uuid.
27
+ *
28
+ * A message that Claude Code does not store, such as a local command's, is
29
+ * recognized while this record lives: the agent keeps one per session from
30
+ * its start to `session/close` or the end of the connection, across restarts
31
+ * of the session's query.
32
+ */
33
+ import { createHash } from "node:crypto";
34
+ /** The characters of a keyed uuid that count its attempts: its last 4 hex digits. */
35
+ const ATTEMPT_DIGITS = 4;
36
+ export class PromptKeys {
37
+ sessionId;
38
+ readStored;
39
+ logger;
40
+ /** The keys seen on this connection, by the uuid prefix of their attempts. */
41
+ keys = new Map();
42
+ /** Whether the session's stored history can hold a message of an earlier connection. */
43
+ resumed = false;
44
+ /** The stored history's keyed messages, by uuid prefix, once read. */
45
+ stored;
46
+ constructor(sessionId,
47
+ /** The uuids of the user messages in the session's stored history, oldest first. */
48
+ readStored, logger) {
49
+ this.sessionId = sessionId;
50
+ this.readStored = readStored;
51
+ this.logger = logger;
52
+ }
53
+ /**
54
+ * A query of the session started. `resumed`: from a stored conversation,
55
+ * which can hold messages that this record does not know, so the next
56
+ * lookup reads the history again.
57
+ */
58
+ queryStarted(resumed) {
59
+ if (!resumed)
60
+ return;
61
+ this.resumed = true;
62
+ this.stored = undefined;
63
+ }
64
+ /**
65
+ * The response of a prompt with `key`: of the attempt that is not answered
66
+ * yet, of the message inserted with the key, or of `submit`, which inserts
67
+ * the prompt. `submit` runs at most once at a time for a key, and not at
68
+ * all once a message is inserted with it. Its promise is returned as it
69
+ * is.
70
+ */
71
+ once(key, submit) {
72
+ const prefix = keyedPrefix(this.sessionId, key);
73
+ let record = this.keys.get(prefix);
74
+ if (!record)
75
+ this.keys.set(prefix, (record = { attempts: 0 }));
76
+ if (record.messageId !== undefined)
77
+ return Promise.resolve({ messageId: record.messageId });
78
+ if (record.pending)
79
+ return record.pending;
80
+ const known = record;
81
+ const attempt = (known.attempts++ % 16 ** ATTEMPT_DIGITS)
82
+ .toString(16)
83
+ .padStart(ATTEMPT_DIGITS, "0");
84
+ const response = submit({
85
+ uuid: `${prefix}${attempt}`,
86
+ ...(this.resumed ? { stored: () => this.storedMessage(prefix) } : {}),
87
+ });
88
+ known.pending = response;
89
+ response.then(({ messageId }) => {
90
+ known.pending = undefined;
91
+ known.messageId = messageId;
92
+ },
93
+ // An error leaves the key unused: the next prompt with it is a new attempt.
94
+ () => {
95
+ known.pending = undefined;
96
+ });
97
+ return response;
98
+ }
99
+ /**
100
+ * The `messageId` that the stored history holds for the uuid prefix of a
101
+ * key. The history is read once per started query. When reading it fails,
102
+ * the key counts as unused, so the session stays usable, and the next
103
+ * lookup reads again.
104
+ */
105
+ async storedMessage(prefix) {
106
+ if (!this.stored) {
107
+ const read = this.readStored().then((uuids) => {
108
+ const messages = new Map();
109
+ // A later attempt's message replaces an earlier one's: only the last attempt was answered.
110
+ for (const uuid of uuids)
111
+ messages.set(uuid.slice(0, -ATTEMPT_DIGITS), uuid);
112
+ return messages;
113
+ }, (error) => {
114
+ this.logger.error(`Session ${this.sessionId}: failed to read its history for an idempotencyKey`, error);
115
+ if (this.stored === read)
116
+ this.stored = undefined;
117
+ return new Map();
118
+ });
119
+ this.stored = read;
120
+ }
121
+ return (await this.stored).get(prefix);
122
+ }
123
+ }
124
+ /**
125
+ * The first 32 characters of the uuids of the prompt `key` of the session
126
+ * `sessionId`: a version 8 (custom) UUID of the SHA-256 hash of both, without
127
+ * its last 4 hex digits.
128
+ */
129
+ function keyedPrefix(sessionId, key) {
130
+ const hex = createHash("sha256").update(`${sessionId}\n${key}`).digest("hex");
131
+ // The variant bits of RFC 9562: `10`.
132
+ const variant = ((parseInt(hex[16], 16) & 0x3) | 0x8).toString(16);
133
+ return [
134
+ hex.slice(0, 8),
135
+ hex.slice(8, 12),
136
+ `8${hex.slice(13, 16)}`,
137
+ `${variant}${hex.slice(17, 20)}`,
138
+ hex.slice(20, 28),
139
+ ].join("-");
140
+ }
@@ -13,7 +13,10 @@ import * as v2 from "@agentclientprotocol/sdk/experimental/v2/unstable";
13
13
  * Claude cannot read, e.g. an `application/zip` resource: `promptToClaude`
14
14
  * would drop it. An empty `prompt` fails the same way: v2 requires at least
15
15
  * one content block.
16
+ *
17
+ * Without the `idempotencyKey`, which v1 does not have and which the session
18
+ * handles (see `prompt-keys.ts`).
16
19
  */
17
- export declare function v1PromptRequest({ prompt, ...request }: v2.PromptRequest): PromptRequest;
20
+ export declare function v1PromptRequest({ prompt, idempotencyKey, ...request }: v2.PromptRequest): PromptRequest;
18
21
  export declare function v1ContentBlock(block: v2.ContentBlock): ContentBlock;
19
22
  //# sourceMappingURL=prompt.d.ts.map
@@ -1 +1 @@
1
- {"version":3,"file":"prompt.d.ts","sourceRoot":"","sources":["../../src/v2/prompt.ts"],"names":[],"mappings":"AAAA;;;GAGG;AACH,OAAO,EAGL,KAAK,YAAY,EACjB,KAAK,aAAa,EAEnB,MAAM,mCAAmC,CAAC;AAC3C,OAAO,KAAK,EAAE,MAAM,mDAAmD,CAAC;AAGxE;;;;;;;;;GASG;AACH,wBAAgB,eAAe,CAAC,EAAE,MAAM,EAAE,GAAG,OAAO,EAAE,EAAE,EAAE,CAAC,aAAa,GAAG,aAAa,CAqBvF;AAED,wBAAgB,cAAc,CAAC,KAAK,EAAE,EAAE,CAAC,YAAY,GAAG,YAAY,CAcnE"}
1
+ {"version":3,"file":"prompt.d.ts","sourceRoot":"","sources":["../../src/v2/prompt.ts"],"names":[],"mappings":"AAAA;;;GAGG;AACH,OAAO,EAGL,KAAK,YAAY,EACjB,KAAK,aAAa,EAEnB,MAAM,mCAAmC,CAAC;AAC3C,OAAO,KAAK,EAAE,MAAM,mDAAmD,CAAC;AAGxE;;;;;;;;;;;;GAYG;AACH,wBAAgB,eAAe,CAAC,EAC9B,MAAM,EAEN,cAAc,EACd,GAAG,OAAO,EACX,EAAE,EAAE,CAAC,aAAa,GAAG,aAAa,CAqBlC;AAED,wBAAgB,cAAc,CAAC,KAAK,EAAE,EAAE,CAAC,YAAY,GAAG,YAAY,CAcnE"}
package/dist/v2/prompt.js CHANGED
@@ -14,8 +14,13 @@ import { isSupportedBlobMimeType } from "../blob-resources.js";
14
14
  * Claude cannot read, e.g. an `application/zip` resource: `promptToClaude`
15
15
  * would drop it. An empty `prompt` fails the same way: v2 requires at least
16
16
  * one content block.
17
+ *
18
+ * Without the `idempotencyKey`, which v1 does not have and which the session
19
+ * handles (see `prompt-keys.ts`).
17
20
  */
18
- export function v1PromptRequest({ prompt, ...request }) {
21
+ export function v1PromptRequest({ prompt,
22
+ // eslint-disable-next-line @typescript-eslint/no-unused-vars
23
+ idempotencyKey, ...request }) {
19
24
  if (prompt.length === 0) {
20
25
  throw RequestError.invalidParams({ prompt }, "`prompt` must hold at least one content block");
21
26
  }
@@ -11,6 +11,7 @@ import type { AirSupport } from "./air.js";
11
11
  import { ClearContext } from "./clear-context.js";
12
12
  import { SessionCommands } from "./commands.js";
13
13
  import type { SessionConfig } from "./config.js";
14
+ import type { PromptKeys } from "./prompt-keys.js";
14
15
  import { StoppedWork } from "./stopped-work.js";
15
16
  import { SessionReports } from "./reports.js";
16
17
  import { SessionElicitations } from "./elicitation.js";
@@ -82,6 +83,12 @@ export declare class V2Session implements RequestTarget {
82
83
  private lifecycleFrames;
83
84
  /** What the open turn's assistant messages reported about its end (see {@link TurnReport}). */
84
85
  private readonly turnReport;
86
+ /**
87
+ * Whether the conversation holds an entry: the query resumed a stored one,
88
+ * or a prompt of this session was inserted. A prompt that follows one gets
89
+ * a session cursor (see {@link inserted}).
90
+ */
91
+ private hasHistory;
85
92
  /** Set by `session/close`, or when the query ends: nothing more goes out. */
86
93
  private closed;
87
94
  private closing;
@@ -100,6 +107,8 @@ export declare class V2Session implements RequestTarget {
100
107
  private readonly fileChanges;
101
108
  config: SessionConfig;
102
109
  commands: SessionCommands;
110
+ /** The `idempotencyKey`s of the session's prompts. Set by {@link start}. */
111
+ private keys;
103
112
  /** ExitPlanMode's "clear context" option (see {@link ClearContext}). */
104
113
  readonly clearContext: ClearContext;
105
114
  /** The `/mcp` prompts not inserted yet, by uuid, and the open turn's (see `SessionCommands`). */
@@ -124,9 +133,10 @@ export declare class V2Session implements RequestTarget {
124
133
  workspaceDirectories?: readonly string[]);
125
134
  /**
126
135
  * Starts reading the query. Called once, after its initialization.
127
- * `mcpServers` are the servers the query started with.
136
+ * `mcpServers` are the servers the query started with, and `keys` the
137
+ * record of the session's prompt keys, which outlives this query.
128
138
  */
129
- start(query: Query, config: SessionConfig, mcpServers: McpServers, resumed?: boolean): void;
139
+ start(query: Query, config: SessionConfig, mcpServers: McpServers, keys: PromptKeys, resumed?: boolean): void;
130
140
  /** Sends the session's commands in an update, read again from Claude Code. */
131
141
  sendCommands(): Promise<void>;
132
142
  /**
@@ -161,8 +171,26 @@ export declare class V2Session implements RequestTarget {
161
171
  * order, and a cancel or close answers a prompt that waits for it with
162
172
  * -32800 as any prompt not inserted yet. Its refusal answers the prompt.
163
173
  * The adapter's `/remote-control` is not guarded.
174
+ *
175
+ * A prompt with an `idempotencyKey` inserts at most one message for the
176
+ * key (see `prompt-keys.ts`): a retry of a prompt that is not answered yet
177
+ * gets that prompt's outcome, and a retry of an inserted one its
178
+ * `messageId`, and neither goes to Claude Code again.
164
179
  */
165
180
  prompt(params: v2.PromptRequest, guard?: (query: Query) => Promise<void> | undefined): Promise<v2.PromptResponse>;
181
+ /**
182
+ * Sends the prompt to Claude Code as the message `attempt.uuid` (see
183
+ * {@link prompt}).
184
+ *
185
+ * `attempt.stored` looks the prompt's key up in the session's stored
186
+ * history, where a message of an earlier connection can be. The lookup runs
187
+ * in the prompt's turn among the session's prompts. A stored message
188
+ * answers the prompt with its `messageId`: nothing is inserted, titled or
189
+ * sent. A `session/cancel` during the lookup answers the prompt with
190
+ * -32800 like any prompt not inserted yet, also when the message is
191
+ * stored: the client's next retry then gets the `messageId`.
192
+ */
193
+ private submit;
166
194
  /**
167
195
  * Whether no turn is open and no prompt waits in Claude Code's queue. With
168
196
  * `restart`, for a restart of the query (see `restarts.ts`), also no
@@ -305,6 +333,14 @@ export declare class V2Session implements RequestTarget {
305
333
  * nothing (see {@link StoppedWork}).
306
334
  */
307
335
  private promptStarted;
336
+ /**
337
+ * The prompt `uuid` is inserted: its `user_message` goes out, and its
338
+ * response. A prompt that follows an entry of the conversation also gets
339
+ * its session cursor, which `session/fork` takes to copy the history
340
+ * before the prompt (see `session-cursors.ts`). The cursor is announced at
341
+ * once, and a fork finds it once Claude Code stored the message. A slash
342
+ * command gets none.
343
+ */
308
344
  private inserted;
309
345
  /**
310
346
  * Output of the main conversation while no turn is open starts a cycle
@@ -1 +1 @@
1
- {"version":3,"file":"session.d.ts","sourceRoot":"","sources":["../../src/v2/session.ts"],"names":[],"mappings":"AAkCA,OAAO,EAEL,KAAK,+BAA+B,EACpC,KAAK,wBAAwB,EAC7B,KAAK,yBAAyB,EAE9B,KAAK,cAAc,EACpB,MAAM,mCAAmC,CAAC;AAC3C,OAAO,KAAK,KAAK,EAAE,MAAM,mDAAmD,CAAC;AAC7E,OAAO,KAAK,EAGV,cAAc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,CAAC,gBAAgB;IAaxB;;;;;;;;OAQG;IACH,OAAO,CAAC,iBAAiB;YAiBX,OAAO;IAoBrB;;;;OAIG;IACH,OAAO,CAAC,iBAAiB;IAMzB,OAAO,CAAC,WAAW;IAenB;;;;OAIG;IACH,OAAO,CAAC,MAAM;IAyHd;;;OAGG;IACH,OAAO,CAAC,MAAM;IAqBd,OAAO,CAAC,SAAS;IAsCjB;;;;;OAKG;IACH,OAAO,CAAC,aAAa;IAUrB;;;;;;;OAOG;IACH,OAAO,CAAC,QAAQ;IAWhB;;;;;OAKG;IACH,OAAO,CAAC,YAAY;IAQpB,OAAO,CAAC,MAAM;IAkEd;;;;OAIG;IACH,OAAO,CAAC,OAAO;IAQf;;;;;OAKG;IACH,OAAO,CAAC,kBAAkB;IAK1B;;;;;OAKG;IACH,OAAO,CAAC,cAAc;IAOtB;;;;OAIG;IACH,OAAO,CAAC,cAAc;IAUtB,+EAA+E;IAC/E,OAAO,CAAC,cAAc;IAMtB,8EAA8E;IAC9E,OAAO,CAAC,KAAK;IAwCb,oFAAoF;IACpF,OAAO,CAAC,UAAU;IAQlB;;;OAGG;IACH,OAAO,CAAC,QAAQ;IAmBhB;;;;OAIG;IACH,OAAO,CAAC,SAAS;IAkCjB;;;;OAIG;IACH,OAAO,CAAC,eAAe;IAMvB;;;;OAIG;IACH,OAAO,CAAC,WAAW;IAgBnB,OAAO,CAAC,WAAW;IAoBnB,OAAO,CAAC,IAAI;IAIZ,gFAAgF;IAChF,OAAO,CAAC,gBAAgB;IAKxB,yFAAyF;IACzF,OAAO,CAAC,UAAU;IAWlB,OAAO,CAAC,WAAW;CAGpB"}
@@ -8,7 +8,8 @@
8
8
  * - A prompt is pushed to Claude Code at once, with a uuid. Its response is
9
9
  * the prompt's insertion: the `command_lifecycle` frame `started` for that
10
10
  * uuid, or the prompt's echo, whichever comes first. `cancelled`,
11
- * `discarded` or `refused` fails the prompt.
11
+ * `discarded` or `refused` fails the prompt. A prompt with an
12
+ * `idempotencyKey` is pushed once per key (see `prompt-keys.ts`).
12
13
  * - The foreground work is Claude Code's turn: it starts with a prompt's
13
14
  * `started` frame or echo, or with the main conversation's output (a
14
15
  * cycle that Claude Code starts on its own, such as after a background
@@ -43,6 +44,7 @@ import { MODEL_CONFIG_ID } from "../session-model.js";
43
44
  import { modelRefusalFallback, noticeUpdate } from "../session-notices.js";
44
45
  import { planModeUpdate } from "../exit-plan.js";
45
46
  import { resetPlanUpdates } from "../plans.js";
47
+ import { forkCursorUpdate, promptGetsCursor } from "../session-cursors.js";
46
48
  import { agentFileChangeReportMeta } from "../file-change-audit.js";
47
49
  import { ClearContext } from "./clear-context.js";
48
50
  import { TurnFileChanges } from "./file-changes.js";
@@ -100,6 +102,12 @@ export class V2Session {
100
102
  lifecycleFrames = false;
101
103
  /** What the open turn's assistant messages reported about its end (see {@link TurnReport}). */
102
104
  turnReport = new TurnReport();
105
+ /**
106
+ * Whether the conversation holds an entry: the query resumed a stored one,
107
+ * or a prompt of this session was inserted. A prompt that follows one gets
108
+ * a session cursor (see {@link inserted}).
109
+ */
110
+ hasHistory = false;
103
111
  /** Set by `session/close`, or when the query ends: nothing more goes out. */
104
112
  closed = false;
105
113
  closing;
@@ -118,6 +126,8 @@ export class V2Session {
118
126
  fileChanges;
119
127
  config;
120
128
  commands;
129
+ /** The `idempotencyKey`s of the session's prompts. Set by {@link start}. */
130
+ keys;
121
131
  /** ExitPlanMode's "clear context" option (see {@link ClearContext}). */
122
132
  clearContext;
123
133
  /** The `/mcp` prompts not inserted yet, by uuid, and the open turn's (see `SessionCommands`). */
@@ -247,12 +257,15 @@ export class V2Session {
247
257
  }
248
258
  /**
249
259
  * Starts reading the query. Called once, after its initialization.
250
- * `mcpServers` are the servers the query started with.
260
+ * `mcpServers` are the servers the query started with, and `keys` the
261
+ * record of the session's prompt keys, which outlives this query.
251
262
  */
252
- start(query, config, mcpServers, resumed = false) {
263
+ start(query, config, mcpServers, keys, resumed = false) {
253
264
  this.query = query;
254
265
  this.config = config;
266
+ this.keys = keys;
255
267
  this.usage = new ResultUsage(resumed);
268
+ this.hasHistory = resumed;
256
269
  this.mcpServers = JSON.stringify(mcpServers);
257
270
  this.commands = new SessionCommands(query);
258
271
  void this.consume(query);
@@ -312,6 +325,11 @@ export class V2Session {
312
325
  * order, and a cancel or close answers a prompt that waits for it with
313
326
  * -32800 as any prompt not inserted yet. Its refusal answers the prompt.
314
327
  * The adapter's `/remote-control` is not guarded.
328
+ *
329
+ * A prompt with an `idempotencyKey` inserts at most one message for the
330
+ * key (see `prompt-keys.ts`): a retry of a prompt that is not answered yet
331
+ * gets that prompt's outcome, and a retry of an inserted one its
332
+ * `messageId`, and neither goes to Claude Code again.
315
333
  */
316
334
  prompt(params, guard) {
317
335
  if (this.closed) {
@@ -319,6 +337,24 @@ export class V2Session {
319
337
  }
320
338
  // Throws invalid params for content that Claude cannot take.
321
339
  const request = v1PromptRequest(params);
340
+ const key = params.idempotencyKey;
341
+ if (key == null)
342
+ return this.submit(params, request, guard, { uuid: randomUUID() });
343
+ return this.keys.once(key, (attempt) => this.submit(params, request, guard, attempt));
344
+ }
345
+ /**
346
+ * Sends the prompt to Claude Code as the message `attempt.uuid` (see
347
+ * {@link prompt}).
348
+ *
349
+ * `attempt.stored` looks the prompt's key up in the session's stored
350
+ * history, where a message of an earlier connection can be. The lookup runs
351
+ * in the prompt's turn among the session's prompts. A stored message
352
+ * answers the prompt with its `messageId`: nothing is inserted, titled or
353
+ * sent. A `session/cancel` during the lookup answers the prompt with
354
+ * -32800 like any prompt not inserted yet, also when the message is
355
+ * stored: the client's next retry then gets the `messageId`.
356
+ */
357
+ submit(params, request, guard, { uuid, stored }) {
322
358
  const remoteControl = this.remoteControl.mayRun(request.prompt);
323
359
  const guarded = guard && !remoteControl ? guard : undefined;
324
360
  // A prompt that the guard refuses titles nothing and sends no notice.
@@ -327,18 +363,23 @@ export class V2Session {
327
363
  // The notice of a mode fallback at the session's start, which sends it at once.
328
364
  void this.config.promptSent();
329
365
  };
330
- if (!guarded)
331
- sent();
332
- const uuid = randomUUID();
333
366
  const message = { ...promptToClaude(request), uuid };
334
- // Only a prompt that goes to Claude Code gets a file-change report, as on
335
- // v1: the adapter's `/remote-control` registers it once it passes the
336
- // prompt on (below).
337
- if (!remoteControl)
338
- this.fileChanges?.requested(uuid, params._meta);
339
- const localCommand = this.commands.localCommand(request.prompt);
340
- if (localCommand)
341
- this.localCommands.set(uuid, localCommand);
367
+ /** What a prompt that is new to the session registers before it goes to Claude Code. */
368
+ const accept = () => {
369
+ if (!guarded)
370
+ sent();
371
+ // Only a prompt that goes to Claude Code gets a file-change report, as
372
+ // on v1: the adapter's `/remote-control` registers it once it passes
373
+ // the prompt on (below).
374
+ if (!remoteControl)
375
+ this.fileChanges?.requested(uuid, params._meta);
376
+ const localCommand = this.commands.localCommand(request.prompt);
377
+ if (localCommand)
378
+ this.localCommands.set(uuid, localCommand);
379
+ };
380
+ // A prompt whose key the stored history may hold is new only once the lookup says so.
381
+ if (!stored)
382
+ accept();
342
383
  return new Promise((resolve, reject) => {
343
384
  const pending = { prompt: params.prompt, pushed: false, resolve, reject };
344
385
  this.pending.set(uuid, pending);
@@ -349,6 +390,18 @@ export class V2Session {
349
390
  .then(async () => {
350
391
  if (answered())
351
392
  return;
393
+ if (stored) {
394
+ const messageId = await stored();
395
+ if (answered())
396
+ return;
397
+ if (messageId !== undefined) {
398
+ this.pending.delete(uuid);
399
+ resolve({ messageId });
400
+ this.checkBoundary();
401
+ return;
402
+ }
403
+ accept();
404
+ }
352
405
  if (guarded) {
353
406
  try {
354
407
  // Set by `start`, which runs before the agent lists the session.
@@ -991,6 +1044,14 @@ export class V2Session {
991
1044
  this.inserted(uuid);
992
1045
  this.openTurn(uuid);
993
1046
  }
1047
+ /**
1048
+ * The prompt `uuid` is inserted: its `user_message` goes out, and its
1049
+ * response. A prompt that follows an entry of the conversation also gets
1050
+ * its session cursor, which `session/fork` takes to copy the history
1051
+ * before the prompt (see `session-cursors.ts`). The cursor is announced at
1052
+ * once, and a fork finds it once Claude Code stored the message. A slash
1053
+ * command gets none.
1054
+ */
994
1055
  inserted(uuid) {
995
1056
  const prompt = this.pending.get(uuid);
996
1057
  if (!prompt)
@@ -998,6 +1059,9 @@ export class V2Session {
998
1059
  this.pending.delete(uuid);
999
1060
  this.fileChanges?.promptStarted(uuid);
1000
1061
  this.send({ sessionUpdate: "user_message", messageId: uuid, content: prompt.prompt });
1062
+ if (this.hasHistory && promptGetsCursor(prompt.prompt))
1063
+ this.send(forkCursorUpdate(uuid));
1064
+ this.hasHistory = true;
1001
1065
  prompt.resolve({ messageId: uuid });
1002
1066
  }
1003
1067
  /**
@@ -176,7 +176,9 @@ export declare class SessionOutput {
176
176
  * messages and its tool calls, as the live session sent them. Subagent
177
177
  * transcripts are left out, as live. The client may hold the replayed
178
178
  * messages already, so each message is cleared before its first chunk.
179
- * `hooks` replays the subagents' own histories to their sessions.
179
+ * `hooks` replays the subagents' own histories to their sessions. Each
180
+ * user message of the root session that a fork can start before gets its
181
+ * session cursor right after it (see `session-cursors.ts`).
180
182
  *
181
183
  * A replayed tool call that the history gives no result, such as one that
182
184
  * ran when Claude Code was killed, ends `failed` after the replay, as v2