@zvada/agent-server 0.3.23 → 0.3.25

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 (280) hide show
  1. package/CHANGELOG.md +64 -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 +745 -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 +331 -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 +92 -0
  91. package/dist/core/processes/lifeline.js +218 -0
  92. package/dist/core/processes/native-processes.js +299 -0
  93. package/dist/core/processes/process-table.js +164 -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 +29 -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 +437 -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 +339 -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 +142 -0
  141. package/dist/protocol/errors.js +190 -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 +292 -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/client/client.d.ts +6 -1
  207. package/dist/types/client/client.d.ts.map +1 -1
  208. package/dist/types/core/agents/claude-code/approvals.d.ts.map +1 -1
  209. package/dist/types/core/agents/claude-code/claude-agent.d.ts +4 -1
  210. package/dist/types/core/agents/claude-code/claude-agent.d.ts.map +1 -1
  211. package/dist/types/core/agents/claude-code/options.d.ts +28 -11
  212. package/dist/types/core/agents/claude-code/options.d.ts.map +1 -1
  213. package/dist/types/core/agents/claude-code/session.d.ts +8 -0
  214. package/dist/types/core/agents/claude-code/session.d.ts.map +1 -1
  215. package/dist/types/core/agents/codex-app-server/homes.d.ts +6 -0
  216. package/dist/types/core/agents/codex-app-server/homes.d.ts.map +1 -1
  217. package/dist/types/core/agents/codex-app-server/login.d.ts +12 -0
  218. package/dist/types/core/agents/codex-app-server/login.d.ts.map +1 -1
  219. package/dist/types/core/agents/codex-app-server/requests.d.ts.map +1 -1
  220. package/dist/types/core/agents/codex-app-server/session.d.ts +4 -1
  221. package/dist/types/core/agents/codex-app-server/session.d.ts.map +1 -1
  222. package/dist/types/core/agents/process-pool.d.ts +8 -0
  223. package/dist/types/core/agents/process-pool.d.ts.map +1 -1
  224. package/dist/types/core/agents/scripted/scripted-agent.d.ts.map +1 -1
  225. package/dist/types/core/agents/scripted/steps.d.ts +1 -1
  226. package/dist/types/core/presets.d.ts +2 -2
  227. package/dist/types/core/presets.d.ts.map +1 -1
  228. package/dist/types/core/processes/identity.d.ts.map +1 -1
  229. package/dist/types/core/processes/lifeline.d.ts.map +1 -1
  230. package/dist/types/core/processes/process-table.d.ts.map +1 -1
  231. package/dist/types/core/provision/extract.d.ts.map +1 -1
  232. package/dist/types/core/runtime/agent-runtime.d.ts +4 -1
  233. package/dist/types/core/runtime/agent-runtime.d.ts.map +1 -1
  234. package/dist/types/core/runtime/turn.d.ts +12 -7
  235. package/dist/types/core/runtime/turn.d.ts.map +1 -1
  236. package/dist/types/protocol/clis.d.ts +3 -3
  237. package/dist/types/protocol/conversation.d.ts +6 -6
  238. package/dist/types/protocol/credentials.d.ts +13 -1
  239. package/dist/types/protocol/credentials.d.ts.map +1 -1
  240. package/dist/types/protocol/errors.d.ts +6 -4
  241. package/dist/types/protocol/errors.d.ts.map +1 -1
  242. package/dist/types/protocol/lifecycle.d.ts +4 -4
  243. package/dist/types/protocol/wire-api.d.ts +12 -12
  244. package/dist/types/protocol/wire.d.ts +8 -8
  245. package/dist/types/server/bin.d.ts +3 -0
  246. package/dist/types/server/bin.d.ts.map +1 -0
  247. package/dist/types/server/routes.d.ts.map +1 -1
  248. package/dist/types/server/transports.d.ts +2 -1
  249. package/dist/types/server/transports.d.ts.map +1 -1
  250. package/dist/types/sync/node-sqlite.d.ts +4 -1
  251. package/dist/types/sync/node-sqlite.d.ts.map +1 -1
  252. package/docs/consuming.md +56 -7
  253. package/docs/deploy.md +35 -0
  254. package/docs/harnesses.md +30 -5
  255. package/package.json +43 -18
  256. package/src/client/client.ts +114 -44
  257. package/src/core/agents/claude-code/approvals.ts +5 -1
  258. package/src/core/agents/claude-code/claude-agent.ts +32 -5
  259. package/src/core/agents/claude-code/options.ts +28 -11
  260. package/src/core/agents/claude-code/session.ts +13 -0
  261. package/src/core/agents/codex-app-server/homes.ts +11 -2
  262. package/src/core/agents/codex-app-server/login.ts +30 -0
  263. package/src/core/agents/codex-app-server/requests.ts +7 -6
  264. package/src/core/agents/codex-app-server/session.ts +11 -2
  265. package/src/core/agents/process-pool.ts +30 -4
  266. package/src/core/agents/scripted/scripted-agent.ts +2 -1
  267. package/src/core/agents/scripted/steps.ts +1 -1
  268. package/src/core/presets.ts +3 -2
  269. package/src/core/processes/identity.ts +1 -0
  270. package/src/core/processes/lifeline.ts +10 -1
  271. package/src/core/processes/process-table.ts +1 -0
  272. package/src/core/provision/extract.ts +1 -0
  273. package/src/core/runtime/agent-runtime.ts +6 -3
  274. package/src/core/runtime/turn.ts +21 -9
  275. package/src/protocol/credentials.ts +19 -5
  276. package/src/protocol/errors.ts +12 -3
  277. package/src/server/bin.ts +25 -10
  278. package/src/server/routes.ts +3 -2
  279. package/src/server/transports.ts +6 -1
  280. package/src/sync/node-sqlite.ts +19 -3
@@ -0,0 +1,142 @@
1
+ import { tokenDigest, } from "../../../protocol/index.js";
2
+ import { PROXY_PLACEHOLDER_KEY, createAnthropicProxy, } from "../../proxy/anthropic-proxy.js";
3
+ import { ApiKeyStore } from "../../proxy/api-key-store.js";
4
+ import { serveLoopback } from "../../proxy/loopback.js";
5
+ import { credentialFor } from "../credentials.js";
6
+ /**
7
+ * The flags by which Claude Code picks another provider (Claude Code 2.1.288),
8
+ * each of which the server's or a turn's env could set: any would win over
9
+ * the placeholder. An empty one is off.
10
+ */
11
+ const PROVIDER_FLAGS = [
12
+ "CLAUDE_CODE_USE_BEDROCK",
13
+ "CLAUDE_CODE_USE_VERTEX",
14
+ "CLAUDE_CODE_USE_FOUNDRY",
15
+ "CLAUDE_CODE_USE_ANTHROPIC_AWS",
16
+ "CLAUDE_CODE_USE_ANTHROPIC_GOOGLE_CLOUD",
17
+ "CLAUDE_CODE_USE_MANTLE",
18
+ "CLAUDE_CODE_USE_GATEWAY",
19
+ ];
20
+ /**
21
+ * What Claude Code holds behind the proxy, whoever's credential is there: a
22
+ * placeholder key, over what a turn's own env says (a product that blanks
23
+ * `ANTHROPIC_API_KEY`), and nothing that outranks it. Its model list depends
24
+ * on this alone: the CLI lists by the kind of credential it holds, asking the
25
+ * API nothing (Claude Code 2.1.288), so a listing needs no credential.
26
+ */
27
+ export const ON_PLACEHOLDER = {
28
+ apiKey: PROXY_PLACEHOLDER_KEY,
29
+ env: {
30
+ ANTHROPIC_API_KEY: PROXY_PLACEHOLDER_KEY,
31
+ ANTHROPIC_AUTH_TOKEN: "",
32
+ CLAUDE_CODE_OAUTH_TOKEN: "",
33
+ ...Object.fromEntries(PROVIDER_FLAGS.map((flag) => [flag, ""])),
34
+ },
35
+ };
36
+ // @ref LLP 0012#what-the-engine-holds-for-the-third — the token never enters the CLI's environment
37
+ /**
38
+ * Claude Code on credentials the product holds: each goes to the engine's
39
+ * own Anthropic proxy on loopback, and the CLI gets a placeholder key and the
40
+ * proxy's address, so what its tools can read holds no credential. A session
41
+ * keeps one address across its turns, as its CLI keeps the one it started
42
+ * with, and the credential behind it is held only while a turn runs. A
43
+ * credential refused upstream is asked for again, once, and the request sent
44
+ * with the fresher one.
45
+ */
46
+ export class ClaudeCredentials {
47
+ source;
48
+ fetch;
49
+ store = new ApiKeyStore();
50
+ /** Each session's address: unguessable, since anything on this machine reaches loopback. */
51
+ addresses = new Map();
52
+ /** Whose credential each address holds now: a renewal is kept only while it does. */
53
+ holders = new Map();
54
+ loopback;
55
+ constructor(source,
56
+ /** How the proxy reaches Anthropic (a test's stand-in). */
57
+ fetch) {
58
+ this.source = source;
59
+ this.fetch = fetch;
60
+ }
61
+ /** Hold the turn's credential until `endTurn`: none runs the turn on the CLI's own login. */
62
+ async forTurn(sessionId, turnId, signal) {
63
+ const request = { harness: "claude-code", sessionId, ...(turnId && { turnId }) };
64
+ const credential = await credentialFor(this.source, request, signal);
65
+ if (!credential)
66
+ return undefined;
67
+ const proxyId = this.addresses.get(sessionId) ?? crypto.randomUUID();
68
+ this.addresses.set(sessionId, proxyId);
69
+ this.hold(proxyId, request, credential);
70
+ return this.delivery(proxyId);
71
+ }
72
+ /** The turn ended: the session's address holds nothing until its next turn. */
73
+ endTurn(sessionId) {
74
+ const proxyId = this.addresses.get(sessionId);
75
+ if (proxyId)
76
+ this.drop(proxyId);
77
+ }
78
+ /** Forget the session: its address answers no more. */
79
+ release(sessionId) {
80
+ this.endTurn(sessionId);
81
+ this.addresses.delete(sessionId);
82
+ }
83
+ async close() {
84
+ this.store.clear();
85
+ this.holders.clear();
86
+ this.addresses.clear();
87
+ const loopback = this.loopback;
88
+ this.loopback = undefined;
89
+ await (await loopback?.catch(() => undefined))?.close();
90
+ }
91
+ hold(proxyId, holder, credential) {
92
+ this.holders.set(proxyId, holder);
93
+ this.put(proxyId, credential);
94
+ }
95
+ drop(proxyId) {
96
+ this.store.delete(proxyId);
97
+ this.holders.delete(proxyId);
98
+ }
99
+ put(proxyId, credential) {
100
+ if (credential.type === "api_key") {
101
+ const baseUrl = credential.baseUrl?.replace(/\/+$/, "");
102
+ this.store.set(proxyId, credential.apiKey, { ...(baseUrl && { upstreamBaseUrl: baseUrl }) });
103
+ }
104
+ else {
105
+ this.store.set(proxyId, credential.accessToken, { kind: "oauth" });
106
+ }
107
+ return this.store.get(proxyId);
108
+ }
109
+ /** The placeholder, and the session's address on the proxy. */
110
+ async delivery(proxyId) {
111
+ const { url } = await this.serve();
112
+ return {
113
+ apiKey: ON_PLACEHOLDER.apiKey,
114
+ env: { ...ON_PLACEHOLDER.env, ANTHROPIC_BASE_URL: `${url}/proxy/anthropic/${proxyId}` },
115
+ };
116
+ }
117
+ serve() {
118
+ this.loopback ??= serveLoopback(createAnthropicProxy({
119
+ store: this.store,
120
+ ...(this.fetch && { fetch: this.fetch }),
121
+ renew: (proxyId, rejected) => this.renew(proxyId, rejected),
122
+ }));
123
+ // A start that failed is tried again by the next turn.
124
+ this.loopback.catch(() => {
125
+ this.loopback = undefined;
126
+ });
127
+ return this.loopback;
128
+ }
129
+ /** Upstream refused an address's credential: a fresher one, kept only while the same holder has it. */
130
+ async renew(proxyId, rejected) {
131
+ const holder = this.holders.get(proxyId);
132
+ if (!holder)
133
+ return undefined;
134
+ const fresher = await credentialFor(this.source, {
135
+ ...holder,
136
+ rejectedSha256: await tokenDigest(rejected.apiKey),
137
+ }).catch(() => undefined);
138
+ if (!fresher || this.holders.get(proxyId) !== holder)
139
+ return undefined;
140
+ return this.put(proxyId, fresher);
141
+ }
142
+ }
@@ -0,0 +1,11 @@
1
+ /**
2
+ * The message Claude Code took, from its `command_lifecycle` "started" frame,
3
+ * which the SDK does not type. A query beginning does not say so: Claude also
4
+ * begins queries of its own.
5
+ */
6
+ export function commandStarted(event) {
7
+ const frame = event;
8
+ return frame.type === "command_lifecycle" && frame.state === "started"
9
+ ? frame.command_uuid
10
+ : undefined;
11
+ }
@@ -0,0 +1,217 @@
1
+ import { AsyncQueue, pastedSignInCode } from "../../../protocol/index.js";
2
+ import { onAbort } from "../../utils/deadline.js";
3
+ import { InvalidRequestError } from "../../utils/errors.js";
4
+ import { isRecord } from "../../utils/is-record.js";
5
+ import { loginMethod, runAuthCommand, terminalMethod, } from "../login.js";
6
+ import { buildClaudeOptions, claudeEnv } from "./options.js";
7
+ /** The logins Claude Code runs itself; `claudeAuthenticate` takes whether it is the subscription one. */
8
+ const LOGINS = [
9
+ { id: "claudeai", kind: "browser", label: "Claude subscription", credential: "subscription" },
10
+ {
11
+ id: "console",
12
+ kind: "browser",
13
+ label: "Anthropic Console (API usage billing)",
14
+ credential: "api_key",
15
+ },
16
+ ];
17
+ /** What each of `auth status`'s `authMethod`s runs on, and where it comes from. */
18
+ const AUTH_METHODS = {
19
+ "claude.ai": { credential: "subscription", source: "login" },
20
+ // A token (`CLAUDE_CODE_OAUTH_TOKEN`) is a subscription's, from the environment.
21
+ oauth_token: { credential: "subscription", source: "environment" },
22
+ api_key: { credential: "api_key" },
23
+ api_key_helper: { credential: "api_key" },
24
+ third_party: { credential: "cloud", source: "environment" },
25
+ };
26
+ /** Where `auth status` says a key comes from (`apiKeySource`). */
27
+ const KEY_SOURCES = {
28
+ ANTHROPIC_API_KEY: "environment",
29
+ apiKeyHelper: "settings",
30
+ "/login managed key": "login",
31
+ };
32
+ /**
33
+ * A login as Claude Code says it (`claude auth status --json`): the
34
+ * credential its turns run with, which the environment's beats the login's,
35
+ * as the CLI decides it.
36
+ */
37
+ export function claudeLoginStatus(raw) {
38
+ if (!raw.loggedIn)
39
+ return { state: "signed_out" };
40
+ const runsOn = AUTH_METHODS[raw.authMethod ?? ""];
41
+ const keySource = runsOn?.credential === "api_key" && KEY_SOURCES[raw.apiKeySource ?? ""];
42
+ const provider = raw.apiProvider === "firstParty" ? "anthropic" : raw.apiProvider;
43
+ return {
44
+ state: "signed_in",
45
+ ...runsOn,
46
+ ...(keySource && { source: keySource }),
47
+ ...(provider && { provider }),
48
+ ...(raw.email && { email: raw.email }),
49
+ ...(raw.orgName && { organization: raw.orgName }),
50
+ ...(raw.subscriptionType && { plan: raw.subscriptionType }),
51
+ };
52
+ }
53
+ const REFUSED = "Claude did not accept this code: log in again, and paste the code the page shows.";
54
+ function httpsUrl(value) {
55
+ if (typeof value !== "string" || !value.startsWith("https://")) {
56
+ throw new Error("Claude Code answered no sign-in address.");
57
+ }
58
+ return value;
59
+ }
60
+ /** The variable that picks Claude Code's login store. */
61
+ const STORE_VARIABLE = "CLAUDE_CONFIG_DIR";
62
+ /** The login store a turn or a login with this `env` uses: its `CLAUDE_CONFIG_DIR`, empty when unset. */
63
+ export function claudeLoginStore(env) {
64
+ return env?.[STORE_VARIABLE] ?? "";
65
+ }
66
+ /** Claude Code's login: `claude auth status`, its OAuth flows over the SDK, `claude auth logout`. */
67
+ export class ClaudeCliLogin {
68
+ options;
69
+ constructor(options) {
70
+ this.options = options;
71
+ }
72
+ store(env) {
73
+ return claudeLoginStore(env);
74
+ }
75
+ /** The CLI to run a command of: the one turns run, else `$CLAUDE_CLI_PATH`, else `claude` on PATH. */
76
+ async commandPath() {
77
+ return (await this.options.resolveCliPath?.()) ?? process.env.CLAUDE_CLI_PATH ?? "claude";
78
+ }
79
+ /** The environment a turn with this `env` runs Claude Code in: whose login it is. */
80
+ env(options) {
81
+ return claudeEnv({
82
+ ...(options.env && { env: options.env }),
83
+ inheritConfig: this.options.inheritConfig,
84
+ });
85
+ }
86
+ async methods(options) {
87
+ const cliPath = await this.commandPath();
88
+ return [
89
+ ...LOGINS,
90
+ terminalMethod([cliPath, "auth", "login"], this.env(options), STORE_VARIABLE),
91
+ ];
92
+ }
93
+ async status(options) {
94
+ const { code, stdout, stderr } = await runAuthCommand(this.options.processes, {
95
+ command: await this.commandPath(),
96
+ args: ["auth", "status", "--json"],
97
+ env: this.env(options),
98
+ harness: "claude-code",
99
+ signal: options.signal,
100
+ });
101
+ // Logged out exits 1, and still answers.
102
+ let raw;
103
+ try {
104
+ raw = JSON.parse(stdout);
105
+ }
106
+ catch {
107
+ return { state: "unknown", error: stderr || `claude auth status exited ${code}` };
108
+ }
109
+ return isRecord(raw)
110
+ ? claudeLoginStatus(raw)
111
+ : { state: "unknown", error: "claude auth status answered no status" };
112
+ }
113
+ async start(id, options) {
114
+ const method = loginMethod(LOGINS, id);
115
+ const sdk = await import("@anthropic-ai/claude-agent-sdk");
116
+ // The CLI turns run: the provisioner's, else the SDK's own.
117
+ const cliPath = await this.options.resolveCliPath?.();
118
+ const query = this.options.query ?? sdk.query;
119
+ // An open prompt that never yields: the CLI starts and waits, its
120
+ // control channel open.
121
+ const prompt = new AsyncQueue();
122
+ // A turn's options, so the login lands where turns look; no tool, hook or MCP server runs.
123
+ const sdkOptions = buildClaudeOptions({
124
+ cwd: process.cwd(),
125
+ ...(options.env && { env: options.env }),
126
+ ...(cliPath && { cliPath }),
127
+ inheritConfig: this.options.inheritConfig,
128
+ maxTurns: 1,
129
+ }, undefined, undefined, { processes: this.options.processes });
130
+ sdkOptions.strictMcpConfig = true;
131
+ sdkOptions.settings = { disableAllHooks: true };
132
+ const session = query({ prompt, options: sdkOptions });
133
+ const close = () => {
134
+ prompt.end();
135
+ session.close();
136
+ };
137
+ void (async () => {
138
+ try {
139
+ for await (const _ of session) {
140
+ // Nothing it says is used; read so it keeps reading.
141
+ }
142
+ }
143
+ catch {
144
+ // A closed session ends its stream with an error.
145
+ }
146
+ })();
147
+ const { claudeAuthenticate, claudeOAuthCallback, claudeOAuthWaitForCompletion } = session;
148
+ if (!claudeAuthenticate || !claudeOAuthCallback || !claudeOAuthWaitForCompletion) {
149
+ close();
150
+ throw new Error("This Claude Code cannot log in from here: run `claude auth login` in a terminal.");
151
+ }
152
+ let url;
153
+ let codeUrl;
154
+ // A start the engine gave up on stops its CLI.
155
+ const offAbort = onAbort(options.signal, close);
156
+ try {
157
+ const urls = await claudeAuthenticate.call(session, method.id === "claudeai");
158
+ url = httpsUrl(urls.automaticUrl);
159
+ codeUrl = httpsUrl(urls.manualUrl);
160
+ }
161
+ catch (error) {
162
+ close();
163
+ throw error;
164
+ }
165
+ finally {
166
+ offAbort();
167
+ }
168
+ const state = new URL(codeUrl).searchParams.get("state") ?? "";
169
+ let codeSent = false;
170
+ let succeeded = false;
171
+ const done = claudeOAuthWaitForCompletion
172
+ .call(session)
173
+ .then(() => {
174
+ succeeded = true;
175
+ }, (error) => {
176
+ // The CLI answers a refused code with the token endpoint's own words.
177
+ throw codeSent ? new Error(REFUSED, { cause: error }) : error;
178
+ })
179
+ .finally(close);
180
+ // A caller that only cancels has nothing to hear.
181
+ done.catch(() => { });
182
+ return {
183
+ url,
184
+ codeUrl,
185
+ done,
186
+ complete: async (pasted) => {
187
+ let answer;
188
+ try {
189
+ answer = pastedSignInCode(pasted, state);
190
+ }
191
+ catch (error) {
192
+ throw new InvalidRequestError([{ path: "code", message: error.message }]);
193
+ }
194
+ codeSent = true;
195
+ try {
196
+ await claudeOAuthCallback.call(session, answer.code, answer.state);
197
+ }
198
+ catch (error) {
199
+ // Closing after a finished flow cuts off the callback's own reply.
200
+ if (!succeeded)
201
+ throw new Error(REFUSED, { cause: error });
202
+ }
203
+ },
204
+ cancel: close,
205
+ };
206
+ }
207
+ async logout(options) {
208
+ const { code, stdout, stderr } = await runAuthCommand(this.options.processes, {
209
+ command: await this.commandPath(),
210
+ args: ["auth", "logout"],
211
+ env: this.env(options),
212
+ harness: "claude-code",
213
+ });
214
+ if (code !== 0)
215
+ throw new Error(stderr || stdout.trim() || `claude auth logout exited ${code}`);
216
+ }
217
+ }
@@ -0,0 +1,181 @@
1
+ import { configFingerprint } from "../config-fingerprint.js";
2
+ import { UnavailableMcpServers, mcpConnectionErrors, nativeMcpServer, settleMcpFailures, snapshotMcpServers, } from "../mcp-config.js";
3
+ function remoteMcpServer(server) {
4
+ return server.type === "http" || server.type === "sse";
5
+ }
6
+ /** Connection setup only: never retry a model turn or a tool invocation. */
7
+ function transientMcpError(error) {
8
+ return /socket connection was closed unexpectedly|\bECONNRESET\b|\bEPIPE\b|\bETIMEDOUT\b/i.test(error);
9
+ }
10
+ /**
11
+ * A Claude session's MCP servers: the turn's wire servers it runs with, the
12
+ * host's in-process ones, and what is known of their connections. Every
13
+ * update goes through one chain, so explicit swaps and turn preparation never
14
+ * interleave on the CLI's control channel.
15
+ */
16
+ export class ClaudeMcpConnections {
17
+ hostResumed;
18
+ wire;
19
+ host = {};
20
+ loaded = [];
21
+ updates = Promise.resolve();
22
+ /**
23
+ * Set while an update has not finished, with the servers that failed in it.
24
+ * A failed SDK update is not transactional: it can cache the new config
25
+ * with a failed client, then return errors:{} for the identical retry. The
26
+ * uncertainty holds until a verified reattachment succeeds.
27
+ */
28
+ failed;
29
+ /** Servers not required that could not connect: the session's turns go on without them. */
30
+ unavailable = new UnavailableMcpServers();
31
+ /**
32
+ * `servers`: the spawning turn's, attached before its prompt.
33
+ * `hostResumed`: whether a host resume came since the process began to
34
+ * start (the pool's `startedBeforeResume`).
35
+ */
36
+ constructor(servers, hostResumed = () => false) {
37
+ this.hostResumed = hostResumed;
38
+ this.wire = snapshotMcpServers(servers);
39
+ }
40
+ /** The wire servers the session runs with: the last update's, or the spawning turn's. */
41
+ get servers() {
42
+ return this.wire;
43
+ }
44
+ /**
45
+ * Every server name the session knows: the wire's, the host's, and those
46
+ * Claude loaded from the person's configuration (above `inheritConfig:
47
+ * "none"`), which its `system/init` lists. A tool name is matched against them.
48
+ */
49
+ get names() {
50
+ return [...new Set([...Object.keys(this.wire), ...Object.keys(this.host), ...this.loaded])];
51
+ }
52
+ /** The servers Claude's `system/init` listed. */
53
+ sawLoaded(names) {
54
+ this.loaded = [...names];
55
+ }
56
+ /** The last update did not finish: what the CLI holds now is not known. */
57
+ get uncertain() {
58
+ return this.failed !== undefined;
59
+ }
60
+ /**
61
+ * The process must be replaced: host suspension invalidated its
62
+ * subprocess-wide HTTP pool, which replacing MCP clients cannot clear. A
63
+ * thawed VM can retain clients whose sockets still appear connected, so it
64
+ * holds until the process is replaced, whatever an update says after.
65
+ */
66
+ get respawnRequired() {
67
+ return this.hostResumed();
68
+ }
69
+ /** The host's in-process servers, resolved at spawn: every update keeps them, and they win a name. */
70
+ useHostServers(servers) {
71
+ this.host = { ...servers };
72
+ }
73
+ /** Whether a turn asking for `servers` must update the connections before its prompt. */
74
+ needsUpdate(servers) {
75
+ return (this.uncertain ||
76
+ this.respawnRequired ||
77
+ // A server the last turn went without is tried again once due, or at
78
+ // once when this turn requires it.
79
+ this.unavailable.retryNow(servers ?? {}).length > 0 ||
80
+ configFingerprint(servers ?? {}) !== configFingerprint(this.wire));
81
+ }
82
+ /**
83
+ * Attach `servers` after the updates before it. `control` is asked for the
84
+ * live query when the update's turn comes; none (a session that ended, or
85
+ * runs without tools) skips it.
86
+ */
87
+ update(servers, control) {
88
+ // Snapshot before queuing: callers may reuse and mutate their config.
89
+ const snapshot = snapshotMcpServers(servers);
90
+ const update = this.updates.then(() => {
91
+ const query = control();
92
+ return query && this.apply(query, snapshot);
93
+ });
94
+ this.updates = update.then(() => { }, () => { });
95
+ return update;
96
+ }
97
+ async apply(query, servers) {
98
+ if (this.respawnRequired)
99
+ throw new Error("Claude process must resume after host suspension");
100
+ const reconnect = this.failed !== undefined;
101
+ // What failed last time stays uncertain through this update, with what fails in it.
102
+ const failed = new Set(this.failed);
103
+ this.failed = failed;
104
+ // A server the last turn went without gets a fresh connection once due,
105
+ // or at once when this turn requires it: the SDK keeps a failed client
106
+ // for an identical configuration, and its old failure must not decide.
107
+ const retry = new Set(this.unavailable.retryNow(servers));
108
+ const resetNames = Object.keys(servers).filter((name) => failed.has(name) || retry.has(name));
109
+ const native = Object.fromEntries(Object.entries(servers).map(([name, server]) => [name, nativeMcpServer(server)]));
110
+ const desired = { ...native, ...this.host };
111
+ const added = new Set();
112
+ const removed = new Set();
113
+ const applyDesired = async () => {
114
+ const result = await query.setMcpServers(desired);
115
+ for (const name of result.added)
116
+ added.add(name);
117
+ for (const name of result.removed)
118
+ removed.add(name);
119
+ return result;
120
+ };
121
+ // A required server's failure fails the turn; the others it goes on without.
122
+ const check = (errors) => {
123
+ for (const name of Object.keys(errors))
124
+ failed.add(name);
125
+ return settleMcpFailures(errors, servers);
126
+ };
127
+ const reattach = async (names) => {
128
+ const detached = { ...desired };
129
+ for (const name of names) {
130
+ if (!this.host[name])
131
+ delete detached[name];
132
+ }
133
+ check((await query.setMcpServers(detached)).errors ?? {});
134
+ return applyDesired();
135
+ };
136
+ // A socket failure is transient; anything else fails for good, at once.
137
+ const lasting = (errors) => Object.fromEntries(Object.entries(errors).filter(([, error]) => !transientMcpError(error)));
138
+ // After a fresh attach, a remote server's transient failure gets one repair.
139
+ const repairable = (errors) => Object.keys(errors).filter((name) => transientMcpError(errors[name]) &&
140
+ servers[name] &&
141
+ remoteMcpServer(servers[name]) &&
142
+ !this.host[name]);
143
+ let result = await applyDesired();
144
+ let retried = false;
145
+ /** What each server that went down said first: a later status says less. */
146
+ const said = {};
147
+ // What failed last time gets a fresh connection: after a failed update,
148
+ // and for a server the last turn went without, once due.
149
+ if (reconnect || resetNames.length) {
150
+ Object.assign(said, check(lasting(result.errors ?? {})));
151
+ retried = Object.keys(result.errors ?? {}).length > 0;
152
+ result = await reattach([...new Set([...resetNames, ...Object.keys(result.errors ?? {})])]);
153
+ }
154
+ const repairs = retried ? [] : repairable(result.errors ?? {});
155
+ if (repairs.length) {
156
+ // A required server's lasting failure names its own cause first.
157
+ Object.assign(said, check(lasting(result.errors ?? {})));
158
+ // reconnectMcpServer(name) can restore the CLI's STARTUP credentials.
159
+ // Removing and adding uses this turn's exact configuration instead.
160
+ result = await reattach(repairs);
161
+ }
162
+ const unavailable = check(result.errors ?? {});
163
+ // In-process SDK servers initialize lazily at the first prompt and are
164
+ // absent from startup status. This barrier checks external connections.
165
+ const external = Object.keys(desired).filter((name) => desired[name]?.type !== "sdk");
166
+ if (external.length) {
167
+ const statuses = await query.mcpServerStatus();
168
+ // The setup's own error names the cause better than a status does.
169
+ for (const [name, cause] of Object.entries(check(mcpConnectionErrors(external, statuses))))
170
+ unavailable[name] ??= said[name] ?? cause;
171
+ }
172
+ this.wire = servers;
173
+ this.failed = undefined;
174
+ this.unavailable.record(unavailable, (name) => resetNames.includes(name) || added.has(name));
175
+ return {
176
+ added: [...added],
177
+ removed: [...removed],
178
+ errors: result.errors,
179
+ };
180
+ }
181
+ }
@@ -0,0 +1,74 @@
1
+ import { AsyncQueue, clampThinkingLevel, } from "../../../protocol/index.js";
2
+ import { onAbort } from "../../utils/deadline.js";
3
+ import { knownThinkingLevels } from "../thinking-levels.js";
4
+ import { buildClaudeOptions } from "./options.js";
5
+ /**
6
+ * Claude Code's model rows in the shared shape. `default` (the account's
7
+ * default model) is a model id Claude accepts, so it stays a row of its own.
8
+ * A row Claude marks disabled is not selectable and is left out.
9
+ */
10
+ export function claudeModelDescriptors(models) {
11
+ return models
12
+ .filter((model) => !model.disabled)
13
+ .map((model) => ({
14
+ id: model.value,
15
+ harness: "claude-code",
16
+ label: model.displayName || model.value,
17
+ ...(model.description && { description: model.description }),
18
+ ...(model.resolvedModel &&
19
+ model.resolvedModel !== model.value && { resolvedId: model.resolvedModel }),
20
+ ...(model.value === "default" && { isDefault: true }),
21
+ thinking: { levels: knownThinkingLevels(model.supportedEffortLevels ?? []) },
22
+ }));
23
+ }
24
+ /**
25
+ * The level to start Claude with, and the level it then runs. Claude Code
26
+ * lowers a level its model lacks on its own and does not say so (`max` and
27
+ * `xhigh` become `high`), so the level is fitted here, where the model's levels
28
+ * are known. `off` is sent as it is: some models do not let thinking be
29
+ * disabled, and Claude Code then thinks at its default effort; Haiku, which
30
+ * Claude Code otherwise starts thinking, does not think with it. A model known
31
+ * to have no effort levels (`levels: []`, Haiku) is sent no other level, so it
32
+ * is not started on adaptive thinking at an effort it has no control for; a
33
+ * model whose levels are unknown (`undefined`) is sent the level as asked.
34
+ */
35
+ export function fitClaudeThinking(level, levels) {
36
+ if (level === undefined)
37
+ return {};
38
+ if (level === "off" || levels === undefined)
39
+ return { send: level };
40
+ if (!levels.length)
41
+ return {};
42
+ const fitted = clampThinkingLevel(level, levels) ?? level;
43
+ return { send: fitted, applied: fitted };
44
+ }
45
+ /**
46
+ * Ask Claude Code which models it offers. Starts the CLI the way a turn would
47
+ * (same folder settings, as the operator's `inheritConfig` loads them, same
48
+ * environment and credentials, which decide the list) but sends no prompt,
49
+ * loads no MCP server and runs no hook. Answers from the CLI's
50
+ * initialization: under a second, no tokens.
51
+ */
52
+ export async function readClaudeModels(config, processes, signal) {
53
+ const sdk = await import("@anthropic-ai/claude-agent-sdk");
54
+ signal?.throwIfAborted();
55
+ // No in-process servers, and `strictMcpConfig` keeps the folder's own out.
56
+ // Held by the lifeline, and not recorded: no session waits on it.
57
+ const options = buildClaudeOptions({ ...config, maxTurns: 1 }, undefined, undefined, {
58
+ processes,
59
+ });
60
+ options.strictMcpConfig = true;
61
+ options.settings = { disableAllHooks: true };
62
+ // An open prompt stream that never yields: the CLI initializes and waits.
63
+ const prompt = new AsyncQueue();
64
+ const query = sdk.query({ prompt, options });
65
+ const offAbort = onAbort(signal, () => query.close());
66
+ try {
67
+ return await query.supportedModels();
68
+ }
69
+ finally {
70
+ offAbort();
71
+ prompt.end();
72
+ query.close();
73
+ }
74
+ }