@zvada/agent-server 0.3.23 → 0.3.24

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.
Files changed (246) hide show
  1. package/CHANGELOG.md +34 -0
  2. package/README.md +14 -5
  3. package/dist/accounts/chatgpt.js +144 -0
  4. package/dist/accounts/check.js +71 -0
  5. package/dist/accounts/claude.js +80 -0
  6. package/dist/accounts/endpoint.js +104 -0
  7. package/dist/accounts/http.js +58 -0
  8. package/dist/accounts/index.js +9 -0
  9. package/dist/client/client.js +686 -0
  10. package/dist/client/connection.js +338 -0
  11. package/dist/client/history.js +49 -0
  12. package/dist/client/index.js +6 -0
  13. package/dist/client/listeners.js +19 -0
  14. package/dist/client/logins.js +92 -0
  15. package/dist/client/rpc.js +105 -0
  16. package/dist/client/streams.js +432 -0
  17. package/dist/client/transports.js +118 -0
  18. package/dist/client/turns.js +122 -0
  19. package/dist/core/agents/acp/acp-agent.js +425 -0
  20. package/dist/core/agents/acp/adapter.js +231 -0
  21. package/dist/core/agents/acp/client.js +222 -0
  22. package/dist/core/agents/acp/known-agents.js +57 -0
  23. package/dist/core/agents/acp/mappings.js +164 -0
  24. package/dist/core/agents/acp/requests.js +79 -0
  25. package/dist/core/agents/attachments.js +14 -0
  26. package/dist/core/agents/base.js +64 -0
  27. package/dist/core/agents/claude-code/adapter.js +474 -0
  28. package/dist/core/agents/claude-code/approvals.js +245 -0
  29. package/dist/core/agents/claude-code/claude-agent.js +319 -0
  30. package/dist/core/agents/claude-code/credentials.js +142 -0
  31. package/dist/core/agents/claude-code/events.js +11 -0
  32. package/dist/core/agents/claude-code/login.js +217 -0
  33. package/dist/core/agents/claude-code/mcp.js +181 -0
  34. package/dist/core/agents/claude-code/models.js +74 -0
  35. package/dist/core/agents/claude-code/options.js +240 -0
  36. package/dist/core/agents/claude-code/outcome.js +204 -0
  37. package/dist/core/agents/claude-code/results.js +58 -0
  38. package/dist/core/agents/claude-code/sdk-pair.js +59 -0
  39. package/dist/core/agents/claude-code/session.js +593 -0
  40. package/dist/core/agents/claude-code/spawn.js +125 -0
  41. package/dist/core/agents/claude-code/spend.js +118 -0
  42. package/dist/core/agents/claude-code/tools.js +131 -0
  43. package/dist/core/agents/claude-code/turn-usage.js +121 -0
  44. package/dist/core/agents/claude-code/turn.js +199 -0
  45. package/dist/core/agents/codex-app-server/adapter.js +463 -0
  46. package/dist/core/agents/codex-app-server/client.js +338 -0
  47. package/dist/core/agents/codex-app-server/codex-agent.js +294 -0
  48. package/dist/core/agents/codex-app-server/commands.js +184 -0
  49. package/dist/core/agents/codex-app-server/credentials.js +92 -0
  50. package/dist/core/agents/codex-app-server/effort.js +13 -0
  51. package/dist/core/agents/codex-app-server/events.js +18 -0
  52. package/dist/core/agents/codex-app-server/homes.js +118 -0
  53. package/dist/core/agents/codex-app-server/input.js +52 -0
  54. package/dist/core/agents/codex-app-server/items.js +307 -0
  55. package/dist/core/agents/codex-app-server/login.js +183 -0
  56. package/dist/core/agents/codex-app-server/mcp.js +323 -0
  57. package/dist/core/agents/codex-app-server/models.js +160 -0
  58. package/dist/core/agents/codex-app-server/options.js +155 -0
  59. package/dist/core/agents/codex-app-server/plan-approval.js +124 -0
  60. package/dist/core/agents/codex-app-server/protocol.js +38 -0
  61. package/dist/core/agents/codex-app-server/requests.js +250 -0
  62. package/dist/core/agents/codex-app-server/session.js +278 -0
  63. package/dist/core/agents/codex-app-server/subagents.js +260 -0
  64. package/dist/core/agents/codex-app-server/thread-settings.js +214 -0
  65. package/dist/core/agents/codex-app-server/turn-items.js +69 -0
  66. package/dist/core/agents/codex-app-server/turn.js +448 -0
  67. package/dist/core/agents/codex-app-server/user-login.js +78 -0
  68. package/dist/core/agents/config-fingerprint.js +10 -0
  69. package/dist/core/agents/credentials.js +71 -0
  70. package/dist/core/agents/diffs.js +27 -0
  71. package/dist/core/agents/elicitation.js +42 -0
  72. package/dist/core/agents/inherit-config.js +5 -0
  73. package/dist/core/agents/login.js +56 -0
  74. package/dist/core/agents/mcp-config.js +109 -0
  75. package/dist/core/agents/plan.js +6 -0
  76. package/dist/core/agents/process-pool.js +307 -0
  77. package/dist/core/agents/registry.js +49 -0
  78. package/dist/core/agents/scripted/adapter.js +86 -0
  79. package/dist/core/agents/scripted/mcp-call.js +74 -0
  80. package/dist/core/agents/scripted/scripted-agent.js +330 -0
  81. package/dist/core/agents/scripted/scripts.js +154 -0
  82. package/dist/core/agents/scripted/steps.js +87 -0
  83. package/dist/core/agents/session-agent.js +209 -0
  84. package/dist/core/agents/stderr-tail.js +71 -0
  85. package/dist/core/agents/thinking-levels.js +9 -0
  86. package/dist/core/agents/types.js +1 -0
  87. package/dist/core/diagnostics.js +23 -0
  88. package/dist/core/index.js +31 -0
  89. package/dist/core/presets.js +114 -0
  90. package/dist/core/processes/identity.js +91 -0
  91. package/dist/core/processes/lifeline.js +210 -0
  92. package/dist/core/processes/native-processes.js +299 -0
  93. package/dist/core/processes/process-table.js +163 -0
  94. package/dist/core/provision/cache-trust.js +121 -0
  95. package/dist/core/provision/cache-usage.js +61 -0
  96. package/dist/core/provision/checksums.js +22 -0
  97. package/dist/core/provision/extract.js +28 -0
  98. package/dist/core/provision/index.js +4 -0
  99. package/dist/core/provision/install-build.js +99 -0
  100. package/dist/core/provision/npm.js +316 -0
  101. package/dist/core/provision/pins.js +35 -0
  102. package/dist/core/provision/platform.js +65 -0
  103. package/dist/core/provision/provisioner.js +372 -0
  104. package/dist/core/provision/releases.js +68 -0
  105. package/dist/core/provision/tools.js +279 -0
  106. package/dist/core/proxy/anthropic-proxy.js +163 -0
  107. package/dist/core/proxy/api-key-store.js +30 -0
  108. package/dist/core/proxy/index.js +3 -0
  109. package/dist/core/proxy/loopback.js +86 -0
  110. package/dist/core/runtime/agent-runtime.js +434 -0
  111. package/dist/core/runtime/event-processor.js +379 -0
  112. package/dist/core/runtime/event-sink.js +65 -0
  113. package/dist/core/runtime/harness-clis.js +83 -0
  114. package/dist/core/runtime/harness-logins.js +313 -0
  115. package/dist/core/runtime/login-reads.js +71 -0
  116. package/dist/core/runtime/model-lists.js +160 -0
  117. package/dist/core/runtime/permission-policy.js +84 -0
  118. package/dist/core/runtime/request-broker.js +139 -0
  119. package/dist/core/runtime/steering.js +79 -0
  120. package/dist/core/runtime/turn-outcome.js +16 -0
  121. package/dist/core/runtime/turn.js +329 -0
  122. package/dist/core/utils/bounded.js +13 -0
  123. package/dist/core/utils/deadline.js +57 -0
  124. package/dist/core/utils/errors.js +176 -0
  125. package/dist/core/utils/is-record.js +4 -0
  126. package/dist/core/utils/loopback.js +11 -0
  127. package/dist/index.js +4 -0
  128. package/dist/operator/index.js +10 -0
  129. package/dist/operator/mcp.js +139 -0
  130. package/dist/operator/operator.js +499 -0
  131. package/dist/operator/render.js +408 -0
  132. package/dist/operator/view.js +35 -0
  133. package/dist/protocol/account.js +96 -0
  134. package/dist/protocol/async-queue.js +65 -0
  135. package/dist/protocol/auth.js +169 -0
  136. package/dist/protocol/canonical.js +18 -0
  137. package/dist/protocol/clis.js +63 -0
  138. package/dist/protocol/config.js +137 -0
  139. package/dist/protocol/conversation.js +231 -0
  140. package/dist/protocol/credentials.js +141 -0
  141. package/dist/protocol/errors.js +181 -0
  142. package/dist/protocol/execution.js +28 -0
  143. package/dist/protocol/factories.js +231 -0
  144. package/dist/protocol/guards.js +71 -0
  145. package/dist/protocol/harness.js +93 -0
  146. package/dist/protocol/history.js +201 -0
  147. package/dist/protocol/ids.js +37 -0
  148. package/dist/protocol/index.js +36 -0
  149. package/dist/protocol/lifecycle.js +562 -0
  150. package/dist/protocol/meta-keys.js +17 -0
  151. package/dist/protocol/meta.js +13 -0
  152. package/dist/protocol/model-catalog.js +223 -0
  153. package/dist/protocol/models.js +84 -0
  154. package/dist/protocol/part-input.js +94 -0
  155. package/dist/protocol/parts.js +166 -0
  156. package/dist/protocol/plan.js +31 -0
  157. package/dist/protocol/reduce.js +484 -0
  158. package/dist/protocol/selectors.js +136 -0
  159. package/dist/protocol/seq-cursor.js +37 -0
  160. package/dist/protocol/stop-reasons.js +41 -0
  161. package/dist/protocol/thinking.js +31 -0
  162. package/dist/protocol/time.js +21 -0
  163. package/dist/protocol/tokens.js +57 -0
  164. package/dist/protocol/tool-closure.js +70 -0
  165. package/dist/protocol/tool-state.js +153 -0
  166. package/dist/protocol/verify.js +467 -0
  167. package/dist/protocol/vocabulary.js +27 -0
  168. package/dist/protocol/wire-api.js +94 -0
  169. package/dist/protocol/wire.js +669 -0
  170. package/dist/server/acp/binding.js +251 -0
  171. package/dist/server/acp/session-records.js +53 -0
  172. package/dist/server/acp/translate.js +401 -0
  173. package/dist/server/agent-server.js +338 -0
  174. package/dist/server/bin.js +492 -0
  175. package/dist/server/feedback.js +216 -0
  176. package/dist/server/history.js +123 -0
  177. package/dist/server/index.js +8 -0
  178. package/dist/server/install.js +171 -0
  179. package/dist/server/open-parts.js +87 -0
  180. package/dist/server/routes.js +291 -0
  181. package/dist/server/secrets.js +19 -0
  182. package/dist/server/session-gate.js +54 -0
  183. package/dist/server/session-log.js +66 -0
  184. package/dist/server/session-store.js +243 -0
  185. package/dist/server/subscriptions.js +189 -0
  186. package/dist/server/transports.js +214 -0
  187. package/dist/server/wire-error.js +26 -0
  188. package/dist/sync/event-log.js +89 -0
  189. package/dist/sync/fit.js +202 -0
  190. package/dist/sync/history-reader.js +33 -0
  191. package/dist/sync/history-sqlite.js +281 -0
  192. package/dist/sync/history.js +163 -0
  193. package/dist/sync/index.js +5 -0
  194. package/dist/sync/journal-sqlite.js +316 -0
  195. package/dist/sync/journal.js +10 -0
  196. package/dist/sync/live-tails.js +85 -0
  197. package/dist/sync/node-sqlite.js +27 -0
  198. package/dist/sync/projection.js +32 -0
  199. package/dist/sync/recovery.js +117 -0
  200. package/dist/sync/retry.js +45 -0
  201. package/dist/sync/schema.js +73 -0
  202. package/dist/sync/sql.js +94 -0
  203. package/dist/sync/sqlite-file.js +31 -0
  204. package/dist/sync/sqlite.js +18 -0
  205. package/dist/sync/worker.js +212 -0
  206. package/dist/types/core/agents/claude-code/approvals.d.ts.map +1 -1
  207. package/dist/types/core/agents/claude-code/claude-agent.d.ts +4 -1
  208. package/dist/types/core/agents/claude-code/claude-agent.d.ts.map +1 -1
  209. package/dist/types/core/agents/claude-code/options.d.ts +24 -11
  210. package/dist/types/core/agents/claude-code/options.d.ts.map +1 -1
  211. package/dist/types/core/agents/claude-code/session.d.ts +8 -0
  212. package/dist/types/core/agents/claude-code/session.d.ts.map +1 -1
  213. package/dist/types/core/agents/codex-app-server/homes.d.ts +6 -0
  214. package/dist/types/core/agents/codex-app-server/homes.d.ts.map +1 -1
  215. package/dist/types/core/agents/codex-app-server/login.d.ts +12 -0
  216. package/dist/types/core/agents/codex-app-server/login.d.ts.map +1 -1
  217. package/dist/types/core/agents/codex-app-server/requests.d.ts.map +1 -1
  218. package/dist/types/core/agents/codex-app-server/session.d.ts +4 -1
  219. package/dist/types/core/agents/codex-app-server/session.d.ts.map +1 -1
  220. package/dist/types/core/agents/process-pool.d.ts +8 -0
  221. package/dist/types/core/agents/process-pool.d.ts.map +1 -1
  222. package/dist/types/core/presets.d.ts +2 -2
  223. package/dist/types/core/presets.d.ts.map +1 -1
  224. package/dist/types/server/bin.d.ts +3 -0
  225. package/dist/types/server/bin.d.ts.map +1 -0
  226. package/dist/types/server/transports.d.ts +2 -1
  227. package/dist/types/server/transports.d.ts.map +1 -1
  228. package/dist/types/sync/node-sqlite.d.ts +4 -1
  229. package/dist/types/sync/node-sqlite.d.ts.map +1 -1
  230. package/docs/consuming.md +30 -4
  231. package/docs/deploy.md +28 -0
  232. package/docs/harnesses.md +13 -1
  233. package/package.json +43 -18
  234. package/src/core/agents/claude-code/approvals.ts +5 -1
  235. package/src/core/agents/claude-code/claude-agent.ts +32 -5
  236. package/src/core/agents/claude-code/options.ts +24 -11
  237. package/src/core/agents/claude-code/session.ts +13 -0
  238. package/src/core/agents/codex-app-server/homes.ts +11 -2
  239. package/src/core/agents/codex-app-server/login.ts +30 -0
  240. package/src/core/agents/codex-app-server/requests.ts +7 -6
  241. package/src/core/agents/codex-app-server/session.ts +11 -2
  242. package/src/core/agents/process-pool.ts +30 -4
  243. package/src/core/presets.ts +3 -2
  244. package/src/server/bin.ts +25 -10
  245. package/src/server/transports.ts +6 -1
  246. package/src/sync/node-sqlite.ts +19 -3
@@ -0,0 +1,593 @@
1
+ import { AsyncQueue, generateUUIDv7 } from "../../../protocol/index.js";
2
+ import { onAbort, untilAborted, withTimeout } from "../../utils/deadline.js";
3
+ import { SessionResumeError } from "../../utils/errors.js";
4
+ import { CANCEL_CONFIRM_MS } from "../base.js";
5
+ import { IDLE_TIMEOUT_MS, ProcessPool, } from "../process-pool.js";
6
+ import { createCanUseTool, createOnElicitation, startQuery } from "./approvals.js";
7
+ import { commandStarted } from "./events.js";
8
+ import { claudeLoginStore } from "./login.js";
9
+ import { ClaudeMcpConnections } from "./mcp.js";
10
+ import { buildClaudeOptions, claudeSpawnKey, fromSdkPermissionMode, toSdkPermissionMode, } from "./options.js";
11
+ import { planUsedUp } from "./outcome.js";
12
+ import { notePairedReleases } from "./sdk-pair.js";
13
+ import { withStderr } from "./spawn.js";
14
+ import { ClaudeSpend } from "./spend.js";
15
+ import { ClaudeTurn } from "./turn.js";
16
+ /** Claude repeats a message it was sent, where it reads it (`--replay-user-messages`). */
17
+ function isReplay(event) {
18
+ return event.type === "user" && "isReplay" in event && event.isReplay === true;
19
+ }
20
+ /** The messages a frame says its query consumed. */
21
+ function consumed(event) {
22
+ return ("user_message_uuids" in event && event.user_message_uuids) || [];
23
+ }
24
+ /** Why the pool ended a session, in the reasons `onSessionEnd` has always given. */
25
+ function endReason(reason) {
26
+ if (reason === "idle" || reason === "shutdown")
27
+ return reason;
28
+ return reason?.startsWith("replaced:") ? "replaced" : "released";
29
+ }
30
+ /**
31
+ * Wraps one long-lived Claude `query()` call. The prompt input is an AsyncQueue
32
+ * that stays open across turns, so the same subprocess (and its context) is
33
+ * reused turn to turn. A background loop reads SDK output, learns what it says
34
+ * of the session (`observe`) and hands it to the running turn (`route`); the
35
+ * `result` answering the turn ends it.
36
+ *
37
+ * Lifecycle: starting → idle ⇄ busy → terminated. To the process pool it is
38
+ * both the process and its client: `closed` once its end began, from any
39
+ * state; `close` ends it whatever it is doing, a running turn with it.
40
+ */
41
+ export class ClaudeSession {
42
+ id;
43
+ settings;
44
+ onTerminated;
45
+ pooling;
46
+ state = "starting";
47
+ /** What the session runs with; its MCP servers are `mcp`'s. */
48
+ config;
49
+ /** What the process was started with and cannot change (`claudeSpawnKey`). */
50
+ spawnKey;
51
+ mcp;
52
+ /** What the conversation has spent, across the processes that ran it. */
53
+ spend;
54
+ promptQueue = new AsyncQueue();
55
+ query;
56
+ nativeSessionId = null;
57
+ /** Set by the CLI's first message; until then it has begun no turn. */
58
+ cliStarted = false;
59
+ startupError;
60
+ /** The operator's `sdkOptions` set the effort or thinking, not the engine. */
61
+ thinkingOverridden = false;
62
+ /** The running turn: where its events go, and what its requests ask. */
63
+ turn = null;
64
+ /** The CLI can drop queued messages with its interrupt (`interrupt_cancel_queued_v1`). */
65
+ cancelsQueued = false;
66
+ /** A query has begun in this process: before one, nothing of Claude's own can run. */
67
+ queryBegun = false;
68
+ /**
69
+ * Each plan window's last report. Claude repeats a rejection only when it
70
+ * changes, so a turn after a used-up window starts from that report.
71
+ */
72
+ planWindows = new Map();
73
+ /** The `claude` process the engine started for it; none under an operator's spawner. */
74
+ native;
75
+ /** Its end, once it began: settles when its process is stopped. */
76
+ ending;
77
+ closeHandlers = new Set();
78
+ constructor(id, config, settings, onTerminated, pooling) {
79
+ this.id = id;
80
+ this.settings = settings;
81
+ this.onTerminated = onTerminated;
82
+ this.pooling = pooling;
83
+ const { mcpServers, ...spawn } = config;
84
+ this.config = spawn;
85
+ this.spawnKey = claudeSpawnKey(config);
86
+ this.mcp = new ClaudeMcpConnections(mcpServers, () => pooling?.hostResumed() ?? false);
87
+ this.spend = config.resumeSessionId ? ClaudeSpend.unknown() : ClaudeSpend.fresh();
88
+ }
89
+ /** The pool's process is its own client. */
90
+ get client() {
91
+ return this;
92
+ }
93
+ get closed() {
94
+ return this.state === "terminated";
95
+ }
96
+ close(reason) {
97
+ void this.terminate(endReason(reason));
98
+ }
99
+ onClose(handler) {
100
+ this.closeHandlers.add(handler);
101
+ return () => this.closeHandlers.delete(handler);
102
+ }
103
+ /** Settles once its process is stopped and its end reported. */
104
+ gone() {
105
+ return this.ending ?? Promise.resolve();
106
+ }
107
+ get currentState() {
108
+ return this.state;
109
+ }
110
+ get currentSessionId() {
111
+ return this.nativeSessionId;
112
+ }
113
+ get currentConfig() {
114
+ return this.config;
115
+ }
116
+ /** Whether the operator's `sdkOptions` chose the thinking settings this session runs. */
117
+ get operatorThinking() {
118
+ return this.thinkingOverridden;
119
+ }
120
+ /** Hot-swap the model without losing context (Claude `setModel`). */
121
+ async setModel(model) {
122
+ if (this.state === "terminated" || !this.query)
123
+ return;
124
+ await this.query.setModel(model);
125
+ this.config = { ...this.config, model };
126
+ }
127
+ /**
128
+ * Switch the permission mode without a restart (plan, default, accept edits,
129
+ * don't ask). Bypass needs its flag at spawn, so the pool restarts for it.
130
+ */
131
+ async setPermissionMode(mode) {
132
+ if (this.state === "terminated" || !this.query)
133
+ return;
134
+ await this.query.setPermissionMode(toSdkPermissionMode(mode) ?? "default");
135
+ this.config = { ...this.config, permissionMode: mode };
136
+ }
137
+ /**
138
+ * Hot-swap the wire-configured MCP servers on the LIVE session (no restart,
139
+ * context intact). In-process servers are re-merged so a swap can never drop
140
+ * the host's own tools. A text-only session stays tool-free.
141
+ */
142
+ setMcpServers(servers) {
143
+ return this.mcp.update(servers, () => this.config.disableTools || this.state === "terminated" ? undefined : this.query);
144
+ }
145
+ // @ref LLP 0013#f13-a-live-change-held-a-claude-turn-a-cancel-could-not-end — a cancel ends the change, and the process
146
+ /**
147
+ * Switch what the live process can switch for the turn: its model, its
148
+ * permission mode, its MCP servers. All else is in its spawn key, so this
149
+ * never asks for a new process. The SDK gives these control requests no
150
+ * deadline: the turn's cancel (`signal`) ends the wait for each, and the
151
+ * process, since what it applied is not known; the session's next turn
152
+ * resumes the conversation on a new one.
153
+ */
154
+ async applyLiveChange(next, signal) {
155
+ try {
156
+ if (next.model !== this.config.model)
157
+ await untilAborted(this.setModel(next.model), signal);
158
+ if ((next.permissionMode ?? "default") !== (this.config.permissionMode ?? "default")) {
159
+ await untilAborted(this.setPermissionMode(next.permissionMode), signal);
160
+ }
161
+ // Text-only sessions must stay tool-free when the MCP configuration changes.
162
+ if (!next.disableTools && this.mcp.needsUpdate(next.mcpServers)) {
163
+ await untilAborted(this.setMcpServers(next.mcpServers ?? {}), signal);
164
+ }
165
+ }
166
+ catch (error) {
167
+ if (signal.aborted)
168
+ void this.terminate("replaced");
169
+ throw error;
170
+ }
171
+ return true;
172
+ }
173
+ async start() {
174
+ if (this.state !== "starting")
175
+ throw new Error(`Cannot start in state: ${this.state}`);
176
+ const sdk = await import("@anthropic-ai/claude-agent-sdk");
177
+ const spawn = { sessionId: this.id, cwd: this.config.cwd };
178
+ const hostServers = await this.settings.sdkMcpServers?.(spawn);
179
+ this.mcp.useHostServers(hostServers);
180
+ const overrides = await this.settings.sdkOptions?.(spawn);
181
+ this.thinkingOverridden = Boolean(overrides && ("effort" in overrides || "thinking" in overrides));
182
+ const options = buildClaudeOptions(this.config, hostServers, overrides, {
183
+ processes: this.settings.processes,
184
+ sessionId: this.id,
185
+ onSpawned: (native) => {
186
+ this.native = native;
187
+ },
188
+ });
189
+ if (this.settings.hooks) {
190
+ options.hooks = this.settings.hooks({
191
+ sessionId: this.id,
192
+ currentTurnId: () => this.turn?.id,
193
+ });
194
+ }
195
+ // The SDK's callbacks are fixed at spawn: each asks the turn running when
196
+ // it is called, so a turn's brokers never answer for another.
197
+ const turn = () => this.turn;
198
+ options.canUseTool = createCanUseTool({
199
+ sessionId: this.id,
200
+ policy: this.settings.toolPolicy,
201
+ turn,
202
+ mcpServers: () => this.mcp.names,
203
+ });
204
+ options.onElicitation = createOnElicitation(turn);
205
+ // Release/shutdown may finish while an async options/tool factory is
206
+ // pending. Never create a query after its owner has already terminated.
207
+ if (this.currentState === "terminated")
208
+ throw new Error("Session terminated during startup");
209
+ this.query = startQuery(options.permissionMode, () => sdk.query({ prompt: this.promptQueue, options }));
210
+ // Right after `query()`, which names the SDK that ran it.
211
+ notePairedReleases(this.config.cliPath, this.settings.onDiagnostic, this.id);
212
+ const events = this.consumeEvents();
213
+ if (!this.config.disableTools && Object.keys(this.mcp.servers).length) {
214
+ try {
215
+ // Every wire server gets one owner: it is attached here, before the
216
+ // first prompt, never at spawn (`buildClaudeOptions`).
217
+ await this.setMcpServers(this.mcp.servers);
218
+ }
219
+ catch (error) {
220
+ // A CLI that fails its startup while the servers attach (a
221
+ // conversation it cannot load) says why in a result the SDK delivers
222
+ // only after it rejected the attach: close, and read to the end, so
223
+ // that reason wins.
224
+ await this.terminate();
225
+ await events;
226
+ throw this.startupError ?? error;
227
+ }
228
+ }
229
+ if (this.startupError)
230
+ throw this.startupError;
231
+ // TypeScript retains the pre-query narrowing across await; termination can
232
+ // happen while the initial MCP attachment is in flight.
233
+ if (this.state === "terminated")
234
+ throw new Error("Session terminated during startup");
235
+ this.state = "idle";
236
+ }
237
+ /**
238
+ * Send a turn's prompt: the turn's events stream until its result. One turn
239
+ * runs at a time (LLP 0001, D10): a turn's generator stops its native turn
240
+ * before it releases the session, so the session is idle here.
241
+ */
242
+ sendMessage(content, start) {
243
+ if (this.state === "terminated")
244
+ throw this.startupError ?? new Error("Session is terminated");
245
+ if (this.state !== "idle")
246
+ throw new Error(`Claude session is ${this.state}, not idle`);
247
+ // A host resume can land during preparation. Never enqueue a prompt on a
248
+ // process whose network pool predates suspension.
249
+ if (this.mcp.respawnRequired || (!this.config.disableTools && this.mcp.uncertain)) {
250
+ throw new Error("MCP network connections changed during turn preparation; session is not ready");
251
+ }
252
+ this.state = "busy";
253
+ const prompt = this.userMessage(content);
254
+ const turn = new ClaudeTurn(start, prompt.uuid);
255
+ this.turn = turn;
256
+ for (const report of this.rejectedWindowReports())
257
+ turn.events.push(report);
258
+ this.promptQueue.push(prompt);
259
+ return turn;
260
+ }
261
+ // @ref LLP 0002#steering — Claude reads a steer at its next step, or runs it next
262
+ /**
263
+ * Send more input into the running turn. Claude reads it after the step it
264
+ * is on (the tool it runs), or, when it was already giving its final
265
+ * answer, runs it as its next query; the turn lasts until that query ends.
266
+ * False when no turn takes input.
267
+ */
268
+ steer(content, steerId) {
269
+ if (this.state !== "busy" || !this.turn)
270
+ return false;
271
+ const message = this.userMessage(content);
272
+ this.turn.sendSteer(message.uuid, steerId);
273
+ this.promptQueue.push(message);
274
+ return true;
275
+ }
276
+ /** The last report of each plan window still used up, and not past its reset. */
277
+ *rejectedWindowReports() {
278
+ const now = Date.now() / 1000;
279
+ for (const [id, report] of this.planWindows) {
280
+ const info = report.rate_limit_info;
281
+ if (!info || !planUsedUp(info))
282
+ continue;
283
+ if (info.resetsAt !== undefined && info.resetsAt <= now)
284
+ this.planWindows.delete(id);
285
+ else
286
+ yield report;
287
+ }
288
+ }
289
+ /** A uuid-stamped user message: Claude names it when it replays or consumes it. */
290
+ userMessage(content) {
291
+ return {
292
+ type: "user",
293
+ message: { role: "user", content },
294
+ parent_tool_use_id: null,
295
+ // A UUIDv7 is a UUID: the SDK types it as `crypto.randomUUID()`'s.
296
+ uuid: generateUUIDv7(),
297
+ ...(this.nativeSessionId ? { session_id: this.nativeSessionId } : {}),
298
+ };
299
+ }
300
+ /** How long Claude has to confirm an interrupt before the turn counts as still running. */
301
+ get confirmMs() {
302
+ return this.settings.cancelConfirmMs ?? CANCEL_CONFIRM_MS;
303
+ }
304
+ /**
305
+ * Stop the in-flight turn without killing the session. Returns whether the
306
+ * interrupt was CONFIRMED: true when there was nothing to interrupt or the
307
+ * SDK acknowledged it; false when the round-trip timed out or failed — the
308
+ * subprocess may still be running its turn and the caller must report that
309
+ * honestly instead of assuming a clean cancel.
310
+ *
311
+ * A session still starting, or whose CLI has sent nothing yet, is terminated
312
+ * instead: it has begun no turn, an interrupt would wait out its startup, and
313
+ * a prompt the CLI has not dequeued survives an interrupt and runs anyway.
314
+ */
315
+ interruptTurn(timeoutMs = this.confirmMs) {
316
+ const turn = this.turn;
317
+ if (!turn)
318
+ return this.interrupt(undefined, timeoutMs);
319
+ return turn.interruptOnce(() => this.interrupt(turn, timeoutMs));
320
+ }
321
+ /**
322
+ * Stop `turn` unless it ended, for a generator that stopped reading it before
323
+ * its result (a transformer that threw, a sink that failed): interrupt it,
324
+ * and end the process when the turn has not ended within the interrupt
325
+ * timeout. The session is idle or terminated when this returns.
326
+ */
327
+ async stopTurn(turn, timeoutMs = this.confirmMs) {
328
+ if (this.turn !== turn)
329
+ return;
330
+ await Promise.all([this.interruptTurn(timeoutMs), withTimeout(turn.ended, timeoutMs)]);
331
+ if (this.turn === turn)
332
+ await this.terminate("replaced");
333
+ }
334
+ // @ref LLP 0001#d9--the-wire-is-quick-ack-json-rpc-requests-flow-one-way — cancelGraceMs: an agent that has not stopped is ended
335
+ /**
336
+ * End the process of a cancelled `turn` that has not ended within
337
+ * `graceMs`: Claude did not stop it (a frozen or hung CLI), and nothing
338
+ * else would. The turn's events end, so it ends cancelled, and the pool
339
+ * hears `replaced` (`onSessionEnd`); the next turn resumes on a new
340
+ * process. A turn that ended, and any turn after it, is left alone.
341
+ */
342
+ async endUnstopped(turn, graceMs) {
343
+ if ((await withTimeout(turn.ended, graceMs)) === undefined && this.turn === turn)
344
+ await this.terminate("replaced");
345
+ }
346
+ async interrupt(turn, timeoutMs) {
347
+ if (this.state === "idle" || this.state === "terminated")
348
+ return true;
349
+ if (this.state === "starting" || !this.cliStarted || !this.query) {
350
+ await this.terminate();
351
+ return true;
352
+ }
353
+ if (turn?.mustDropQueued(this.queryBegun))
354
+ return await this.interruptQueued(turn, timeoutMs);
355
+ try {
356
+ return (await withTimeout(this.query.interrupt(), timeoutMs)) !== undefined;
357
+ }
358
+ catch {
359
+ return false; // best-effort dispatched, unconfirmed
360
+ }
361
+ }
362
+ /**
363
+ * Interrupt and drop the turn's queued messages with the CLI's queue cancel
364
+ * (`ClaudeTurn.mustDropQueued` says why a plain interrupt would not do).
365
+ * Until its receipt they stay tracked, so one Claude reads meanwhile is
366
+ * still shown where it read it, and the turn's end waits. A CLI that cannot
367
+ * cancel queued messages, or does not account for every one, is replaced:
368
+ * the next turn resumes the conversation without them.
369
+ */
370
+ async interruptQueued(turn, timeoutMs) {
371
+ if (!this.cancelsQueued || !this.query) {
372
+ await this.terminate("replaced");
373
+ return true;
374
+ }
375
+ turn.dropQueued();
376
+ const verdict = turn.dropped(await this.cancelQueued(this.query, timeoutMs));
377
+ // The turn ended meanwhile, or the session with it.
378
+ if (this.turn !== turn)
379
+ return true;
380
+ if (verdict === "replace")
381
+ await this.terminate("replaced");
382
+ else if (verdict === "end")
383
+ this.endTurn();
384
+ return true;
385
+ }
386
+ /** The queue cancel's receipt; undefined when none came in time. */
387
+ async cancelQueued(query, timeoutMs) {
388
+ // The SDK sends `{ cancelQueued }` (0.3.288) but types `interrupt()` without it.
389
+ const cancel = query;
390
+ try {
391
+ return (await withTimeout(cancel.interrupt({ cancelQueued: true }), timeoutMs))?.value;
392
+ }
393
+ catch {
394
+ return undefined;
395
+ }
396
+ }
397
+ /**
398
+ * End the session: close its query, and stop its process with its tool
399
+ * sessions and MCP servers. Settles once they are gone (at most the grace);
400
+ * every call shares that end, and the first one's reason is reported.
401
+ */
402
+ terminate(reason = "released") {
403
+ if (!this.ending) {
404
+ this.ending = this.end(reason);
405
+ // Once `gone()` has its answer: the pool waits on it from its handler.
406
+ for (const handler of this.closeHandlers)
407
+ handler();
408
+ this.closeHandlers.clear();
409
+ }
410
+ return this.ending;
411
+ }
412
+ async end(reason) {
413
+ this.state = "terminated";
414
+ const query = this.query;
415
+ this.query = undefined;
416
+ this.promptQueue.end();
417
+ this.turn?.end();
418
+ this.turn = null;
419
+ try {
420
+ // The SDK documents close() as the forceful subprocess/MCP cleanup path.
421
+ query?.close();
422
+ // @ref LLP 0007#turn-ownership-d10 — the session is released once its process is gone
423
+ // close() ends its stdin, which Claude reads as "finish, then exit",
424
+ // and signals it two seconds later. SIGTERM now: Claude stops its own
425
+ // tools and MCP servers on it, and the next process to resume the
426
+ // conversation never meets this one still working.
427
+ await this.native?.stop();
428
+ }
429
+ finally {
430
+ try {
431
+ this.onTerminated?.(reason);
432
+ }
433
+ catch {
434
+ // Observer failures (incl. the host's onSessionEnd) must never make
435
+ // terminate() reject: the pool's idle timer ends it unawaited.
436
+ }
437
+ }
438
+ }
439
+ async consumeEvents() {
440
+ if (!this.query)
441
+ return;
442
+ try {
443
+ for await (const event of this.query) {
444
+ this.cliStarted = true;
445
+ this.observe(event);
446
+ this.route(event);
447
+ }
448
+ }
449
+ catch (thrown) {
450
+ // The SDK words an exit from its own spawner with the CLI's stderr; ours keeps that tail.
451
+ const err = withStderr(thrown, this.native?.stderrTail ?? "");
452
+ if (this.turn)
453
+ this.turn.fail(err);
454
+ else
455
+ this.startupError = err;
456
+ }
457
+ finally {
458
+ await this.terminate();
459
+ }
460
+ }
461
+ /** What an event says of the session: its native id, its mode, plan windows, spend, steers read. */
462
+ observe(event) {
463
+ if (event.type === "system" && event.subtype === "init") {
464
+ this.queryBegun = true;
465
+ if (event.session_id)
466
+ this.nativeSessionId = event.session_id;
467
+ this.cancelsQueued = (event.capabilities ?? []).includes("interrupt_cancel_queued_v1");
468
+ // An older CLI may leave the list out.
469
+ if (Array.isArray(event.mcp_servers))
470
+ this.mcp.sawLoaded(event.mcp_servers.map((server) => server.name));
471
+ }
472
+ // The mode Claude runs in now: approving a plan switches it mid-turn,
473
+ // so the next turn compares against this, not the mode it asked for.
474
+ if (event.type === "system" && event.subtype === "status") {
475
+ const mode = fromSdkPermissionMode(event.permissionMode);
476
+ if (mode)
477
+ this.config = { ...this.config, permissionMode: mode };
478
+ }
479
+ if (event.type === "rate_limit_event")
480
+ this.planWindows.set(event.rate_limit_info?.rateLimitType ?? "plan", event);
481
+ if (event.type === "conversation_reset")
482
+ this.spend.reset();
483
+ // Claude takes a message: a frame names it as started.
484
+ const taken = commandStarted(event);
485
+ if (taken !== undefined)
486
+ this.turn?.took(taken);
487
+ // Claude replays each message it was sent where it reads it: a steer's
488
+ // replay marks the steer's place. A frame naming the messages its query
489
+ // consumed marks a steer read too, in case its replay never came.
490
+ this.turn?.read(isReplay(event) ? [event.uuid] : consumed(event));
491
+ }
492
+ /** Hand an event to the running turn; a result answering it settles the turn. */
493
+ route(event) {
494
+ // A replay repeats what the session sent; `observe` took its place.
495
+ if (isReplay(event))
496
+ return;
497
+ const turn = this.turn;
498
+ if (event.type !== "result") {
499
+ turn?.events.push(event);
500
+ return;
501
+ }
502
+ if (!turn) {
503
+ this.settleUnshown(event);
504
+ return;
505
+ }
506
+ // @ref LLP 0001#d14--nothing-the-agent-does-is-off-the-stream — a query Claude began itself
507
+ // Claude answers a finished background task with a query of its own. Its
508
+ // result is not this turn's end, and its cost stays in the turn whose
509
+ // stream showed it.
510
+ if (!turn.answeredBy(event))
511
+ return;
512
+ switch (turn.settle(event, this.spend.charge(event))) {
513
+ case "end":
514
+ this.endTurn();
515
+ break;
516
+ case "await-steers":
517
+ // The turn ends without them if their query never begins, and a new
518
+ // process keeps them out of the next.
519
+ turn.awaitSteerQuery(() => void this.terminate("replaced"));
520
+ break;
521
+ case "hold":
522
+ // The interrupt's receipt decides (`interruptQueued`).
523
+ break;
524
+ }
525
+ }
526
+ /**
527
+ * A result while no turn runs: Claude failed its startup, or answered a
528
+ * query it began itself between turns. Its spend counts in no turn.
529
+ */
530
+ settleUnshown(result) {
531
+ if (result.subtype !== "success" && result.origin === undefined) {
532
+ const reason = result.errors.join("; ") || "Claude failed during startup";
533
+ throw this.config.resumeSessionId
534
+ ? new SessionResumeError(this.config.resumeSessionId, reason, {
535
+ cause: new Error(reason),
536
+ })
537
+ : new Error(reason);
538
+ }
539
+ this.spend.charge(result);
540
+ if (this.state === "idle")
541
+ this.pooling?.betweenTurns();
542
+ }
543
+ endTurn() {
544
+ this.turn?.end();
545
+ this.turn = null;
546
+ this.state = "idle";
547
+ }
548
+ }
549
+ /**
550
+ * An agent's Claude sessions. Claude decides of a warm process only whether
551
+ * its spawn key is the turn's and what it switches live; the pool decides
552
+ * the rest (LLP 0001, D10).
553
+ */
554
+ export function claudeSessionPool(settings) {
555
+ const pool = new ProcessPool({
556
+ // @ref LLP 0011#a-login-change-starts-the-next-turn-on-a-new-cli — only the store it changed in
557
+ store: ({ config }) => claudeLoginStore(config.env),
558
+ resumeOf: ({ config }) => config.resumeSessionId || undefined,
559
+ // Claude may rekey a conversation it resumed: the id it started on still names it.
560
+ conversationsOf: (session) => [session.currentSessionId, session.currentConfig.resumeSessionId].filter((id) => Boolean(id)),
561
+ fits: (session, { config }) => session.spawnKey === claudeSpawnKey(config),
562
+ applyLiveChange: (session, { config }, signal) => session.applyLiveChange(config, signal),
563
+ spawn: async (turn, own, signal, replacing) => {
564
+ const { sessionId, config } = turn;
565
+ const session = new ClaudeSession(sessionId, config, settings, (reason) => settings.onSessionEnd?.(sessionId, reason), {
566
+ hostResumed: () => pool.startedBeforeResume(session),
567
+ betweenTurns: () => pool.touch(sessionId, session),
568
+ });
569
+ // The same native conversation continues in a new process, and so
570
+ // does its running cost: the new process restores the total the old one saved.
571
+ if (replacing?.currentSessionId && replacing.currentSessionId === config.resumeSessionId)
572
+ session.spend.continueFrom(replacing.spend);
573
+ own(session);
574
+ turn.spawned = true;
575
+ // A cancel ends a start under way: it has begun no turn, and an
576
+ // interrupt would wait out its startup.
577
+ const offAbort = onAbort(signal, () => void session.terminate());
578
+ try {
579
+ await session.start();
580
+ return session;
581
+ }
582
+ catch (error) {
583
+ // Never leave a half-started session: it could serve no turn.
584
+ await session.terminate();
585
+ throw error;
586
+ }
587
+ finally {
588
+ offAbort();
589
+ }
590
+ },
591
+ }, { idleMs: settings.idleTimeoutMs ?? IDLE_TIMEOUT_MS });
592
+ return pool;
593
+ }