@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,279 @@
1
+ import { existsSync, lstatSync, readFileSync, readdirSync, realpathSync, } from "node:fs";
2
+ import { readdir } from "node:fs/promises";
3
+ import { createRequire } from "node:module";
4
+ import { dirname, join, resolve } from "node:path";
5
+ import { pathToFileURL } from "node:url";
6
+ import { CliNotFoundError, CliProvisionError } from "../utils/errors.js";
7
+ import { DEFAULT_PINS } from "./pins.js";
8
+ import { claudePackageSuffix, codexPackageSuffix, findOnPath, } from "./platform.js";
9
+ /**
10
+ * The managed CLIs. Each native harness maps onto exactly one of these; the
11
+ * `acp` harness maps onto none (its agent binaries are arbitrary third-party
12
+ * commands the operator supplies, not something we pin or download), nor does
13
+ * `scripted`, which runs no process.
14
+ */
15
+ export const CLI_TOOLS = ["claude", "codex"];
16
+ /**
17
+ * Which managed CLI a harness runs on — `undefined` for unmanaged harnesses
18
+ * (`acp`, `scripted`). Exhaustive by construction: adding a harness fails to
19
+ * compile here until someone decides whether it is provisioner-managed.
20
+ */
21
+ const TOOL_FOR_HARNESS = {
22
+ "claude-code": "claude",
23
+ "codex-app-server": "codex",
24
+ acp: undefined,
25
+ scripted: undefined,
26
+ };
27
+ export function toolForHarness(harness) {
28
+ return TOOL_FOR_HARNESS[harness];
29
+ }
30
+ /** The first regular file of `binaries` under `dir` (lstat: a symlink could redirect the spawn). */
31
+ export function binaryIn(dir, binaries) {
32
+ for (const candidate of binaries) {
33
+ const path = join(dir, candidate);
34
+ let stat;
35
+ try {
36
+ stat = lstatSync(path);
37
+ }
38
+ catch {
39
+ continue;
40
+ }
41
+ if (stat.isFile())
42
+ return path;
43
+ }
44
+ return undefined;
45
+ }
46
+ /**
47
+ * Locate an installed package by walking `node_modules` upward from `fromDir`,
48
+ * returning its real directory. Deliberately not `require.resolve`: these
49
+ * packages don't export `./package.json`, so exports maps would veto
50
+ * perfectly good installs.
51
+ * The realpath matters under isolated stores (bun): a package's own deps are
52
+ * siblings of its *store* location, not of the symlink consumers see.
53
+ */
54
+ function findPackageDir(name, fromDir) {
55
+ let dir = fromDir;
56
+ while (true) {
57
+ const candidate = join(dir, "node_modules", ...name.split("/"));
58
+ if (existsSync(join(candidate, "package.json"))) {
59
+ try {
60
+ return realpathSync(candidate);
61
+ }
62
+ catch {
63
+ return undefined;
64
+ }
65
+ }
66
+ const parent = dirname(dir);
67
+ if (parent === dir)
68
+ return undefined;
69
+ dir = parent;
70
+ }
71
+ }
72
+ /**
73
+ * Where this package lives on disk — the walk anchor: this module's folder,
74
+ * or a bundle's when bundled (Bun defines `__dirname` in ESM too). Under
75
+ * Node's ESM (tsx, an ESM bundle), which has neither `__dirname` nor
76
+ * `require`, a `require` made from the entry script resolves this package's
77
+ * own manifest (an explicit export; the product's install, or the package
78
+ * itself by self-reference). Anything unresolvable is `undefined`, and pins
79
+ * take over. The walk never starts from the working folder, whose project
80
+ * may hold another Claude SDK than the one that runs. A compiled binary's
81
+ * modules are in `$bunfs`, nowhere on disk. NOTE: this must not mention
82
+ * `import` `.meta` (the meta-property; spelled apart here so the check in
83
+ * `test/core/provision/module-dir.test.ts` holds for comments too) —
84
+ * consumers bundle these sources to CJS, where that token is a parse error
85
+ * (and older bundlers, Bun 1.2.x, don't rewrite it).
86
+ */
87
+ function moduleDir() {
88
+ if (inCompiledBinary())
89
+ return undefined;
90
+ // CJS bundle output: anchor at the bundle location.
91
+ if (typeof __dirname !== "undefined")
92
+ return __dirname;
93
+ try {
94
+ // Bun/ESM provides `require`; Node's ESM gets one from its entry script.
95
+ const entry = process.argv[1];
96
+ const resolver = typeof require !== "undefined"
97
+ ? require
98
+ : entry
99
+ ? createRequire(pathToFileURL(resolve(entry)).href)
100
+ : undefined;
101
+ return resolver && dirname(resolver.resolve("@zvada/agent-server/package.json"));
102
+ }
103
+ catch {
104
+ return undefined;
105
+ }
106
+ }
107
+ /** Inside a binary compiled with `bun build --compile`, whose modules live in `$bunfs`. */
108
+ function inCompiledBinary() {
109
+ const main = globalThis.Bun?.main ?? "";
110
+ return main.startsWith("/$bunfs/") || /^[A-Za-z]:[\\/]~BUN[\\/]/.test(main);
111
+ }
112
+ /** A package manifest's `version`, if it has one. */
113
+ function versionOf(packageDir) {
114
+ return JSON.parse(readFileSync(join(packageDir, "package.json"), "utf8")).version;
115
+ }
116
+ /**
117
+ * The installed Claude SDK, when resolvable on disk. Its version drives both
118
+ * host resolution and the download pin, so the JS ↔ native-CLI pair can
119
+ * never skew. Unresolvable inside compiled binaries — pins take over there.
120
+ */
121
+ export function claudeSdkOnDisk() {
122
+ return claudeSdkFrom(moduleDir());
123
+ }
124
+ function claudeSdkFrom(from) {
125
+ if (!from)
126
+ return undefined;
127
+ try {
128
+ const dir = findPackageDir("@anthropic-ai/claude-agent-sdk", from);
129
+ return dir ? { dir, version: versionOf(dir) } : undefined;
130
+ }
131
+ catch {
132
+ return undefined;
133
+ }
134
+ }
135
+ /** This platform's entry in the SDK's manifest of its CLI: the binary's name and sha256. */
136
+ function claudeManifestBuild(sdkDir, suffix) {
137
+ try {
138
+ const manifest = JSON.parse(readFileSync(join(sdkDir, "manifest.json"), "utf8"));
139
+ return manifest.platforms?.[suffix];
140
+ }
141
+ catch {
142
+ return undefined;
143
+ }
144
+ }
145
+ const CODEX_BINARIES = [join("bin", "codex"), join("bin", "codex.exe")];
146
+ /**
147
+ * The managed CLIs, one entry each: a new tool fails to compile until it says
148
+ * where its builds come from, where its binary sits and how to find one
149
+ * installed.
150
+ */
151
+ export const CLI_TOOL_SPECS = {
152
+ claude: {
153
+ overrideEnv: "CLAUDE_CLI_PATH",
154
+ binaries: ["claude", "claude.exe"],
155
+ platforms: [
156
+ "darwin-arm64",
157
+ "darwin-x64",
158
+ "linux-arm64",
159
+ "linux-x64",
160
+ "linux-arm64-musl",
161
+ "linux-x64-musl",
162
+ "win32-arm64",
163
+ "win32-x64",
164
+ ],
165
+ // The platform packages carry the native CLI matched to the SDK JS.
166
+ package: (platform, version) => {
167
+ const suffix = claudePackageSuffix(platform);
168
+ return { name: `@anthropic-ai/claude-agent-sdk-${suffix}`, registryVersion: version, suffix };
169
+ },
170
+ // The on-disk SDK's version (the pair that actually runs) over the
171
+ // release default, which only decides inside compiled binaries. Even
172
+ // `pinned` follows it: "deterministic" means the tested JS ↔ CLI
173
+ // *pair*, and downloading the release-default CLI under a newer
174
+ // installed SDK would manufacture exactly the skew this module exists
175
+ // to prevent. Operators who want byte-identical fleets pin explicitly
176
+ // (and align the SDK).
177
+ defaultVersion: () => claudeSdkOnDisk()?.version ?? DEFAULT_PINS.claude,
178
+ // @ref LLP 0010#p2--claudes-build-follows-the-sdk-that-runs — a bundled SDK's version is the host's to say
179
+ // The compiled agent-server binary bundles the SDK it pins, so only
180
+ // another product's bundle runs an SDK nothing here can name.
181
+ // Said only as it is: where the engine looked and found none, or that it could not look.
182
+ defaultVersionNote: () => {
183
+ if (inCompiledBinary())
184
+ return undefined;
185
+ const from = moduleDir();
186
+ if (claudeSdkFrom(from))
187
+ return undefined;
188
+ const why = from
189
+ ? `no Claude SDK is installed beside agent-server (looked up from ${from})`
190
+ : "agent-server cannot tell where it runs from here and could not look for a Claude SDK";
191
+ return `claude: ${why}, so this runs the CLI of agent-server's pin ${DEFAULT_PINS.claude}; a product that bundles the SDK sets provision.pins.claude to its version`;
192
+ },
193
+ // The platform package beside the installed Claude SDK: the build that
194
+ // SDK would spawn itself.
195
+ hostInstall: ({ platform }) => {
196
+ const sdk = claudeSdkOnDisk();
197
+ if (!sdk)
198
+ return undefined;
199
+ const suffix = claudePackageSuffix(platform);
200
+ const platformDir = findPackageDir(`@anthropic-ai/claude-agent-sdk-${suffix}`, sdk.dir);
201
+ if (!platformDir)
202
+ return undefined;
203
+ const path = join(platformDir, claudeManifestBuild(sdk.dir, suffix)?.binary ?? "claude");
204
+ return existsSync(path) ? { path, version: sdk.version } : undefined;
205
+ },
206
+ payload: async (extractedRoot) => {
207
+ const dir = join(extractedRoot, "package");
208
+ if (existsSync(dir))
209
+ return dir;
210
+ throw new CliProvisionError("claude tarball has no package/ directory");
211
+ },
212
+ // The SDK on disk names its own CLI's checksum, for a version this
213
+ // release did not pin (a consumer's lockfile moved the SDK).
214
+ localBuild: (suffix, version) => {
215
+ const sdk = claudeSdkOnDisk();
216
+ const sha256 = sdk?.version === version ? claudeManifestBuild(sdk.dir, suffix)?.checksum : undefined;
217
+ return sha256 ? { sha256, vouchedBy: "the installed Claude SDK's manifest" } : undefined;
218
+ },
219
+ },
220
+ codex: {
221
+ overrideEnv: "CODEX_CLI_PATH",
222
+ binaries: CODEX_BINARIES,
223
+ // Its linux builds are static, so there is no musl variant.
224
+ platforms: [
225
+ "darwin-arm64",
226
+ "darwin-x64",
227
+ "linux-arm64",
228
+ "linux-x64",
229
+ "win32-arm64",
230
+ "win32-x64",
231
+ ],
232
+ // Codex publishes its platform builds as version suffixes of one package.
233
+ package: (platform, version) => {
234
+ const suffix = codexPackageSuffix(platform);
235
+ return { name: "@openai/codex", registryVersion: `${version}-${suffix}`, suffix };
236
+ },
237
+ defaultVersion: () => DEFAULT_PINS.codex,
238
+ // @ref LLP 0001#d18--the-engine-installs-the-clis-it-runs-pinned-builds-checked-before-a-turn — a lockfile's build, or in `system` the operator's PATH
239
+ // An installed `@openai/codex` package's build (its platform dependency
240
+ // ships `vendor/<target>/bin/codex`), so a lockfile can pin the CLI the
241
+ // app-server harness runs; then, in `system` mode, a `codex` on PATH.
242
+ hostInstall: ({ platform, env, searchPath }) => {
243
+ try {
244
+ const from = moduleDir();
245
+ const codexDir = from && findPackageDir("@openai/codex", from);
246
+ const suffix = codexPackageSuffix(platform);
247
+ const platformDir = codexDir && findPackageDir(`@openai/codex-${suffix}`, codexDir);
248
+ if (platformDir) {
249
+ const vendor = join(platformDir, "vendor");
250
+ for (const entry of readdirSync(vendor)) {
251
+ const path = binaryIn(join(vendor, entry), CODEX_BINARIES);
252
+ const version = path && versionOf(platformDir)?.replace(`-${suffix}`, "");
253
+ if (path)
254
+ return { path, ...(version ? { version } : {}) };
255
+ }
256
+ }
257
+ }
258
+ catch {
259
+ // No readable vendored build.
260
+ }
261
+ const path = searchPath ? findOnPath("codex", env, platform.platform) : undefined;
262
+ return path ? { path } : undefined;
263
+ },
264
+ // Codex vendors per-target trees: package/vendor/<rust-triple>/bin/codex.
265
+ // Install the whole tree — the CLI expects its vendored rg/zsh siblings.
266
+ payload: async (extractedRoot) => {
267
+ const vendor = join(extractedRoot, "package", "vendor");
268
+ const entries = existsSync(vendor) ? await readdir(vendor) : [];
269
+ for (const entry of entries) {
270
+ const dir = join(vendor, entry);
271
+ if (binaryIn(dir, CODEX_BINARIES))
272
+ return dir;
273
+ }
274
+ throw new CliProvisionError("codex tarball has no vendor/<target>/bin/codex");
275
+ },
276
+ // A bare spawn would just ENOENT.
277
+ notOnHost: () => new CliNotFoundError("codex", 'install it, set $CODEX_CLI_PATH, or use provision mode "auto"'),
278
+ },
279
+ };
@@ -0,0 +1,163 @@
1
+ import { emitDiagnostic } from "../diagnostics.js";
2
+ import { apiKeyStore } from "./api-key-store.js";
3
+ /** Placeholder key handed to the agent subprocess; swapped for the real one here. */
4
+ export const PROXY_PLACEHOLDER_KEY = "sk-proxy-managed";
5
+ /**
6
+ * The `anthropic-beta` capability that must accompany OAuth bearer traffic.
7
+ * Anthropic's gateway guidance: proxies carrying subscription-OAuth requests
8
+ * must advertise this capability or the upstream rejects the bearer token.
9
+ */
10
+ export const ANTHROPIC_OAUTH_BETA = "oauth-2025-04-20";
11
+ /** Append a capability to `anthropic-beta` without clobbering existing ones. */
12
+ function appendAnthropicBeta(headers, capability) {
13
+ const existing = headers.get("anthropic-beta");
14
+ const values = existing
15
+ ? existing
16
+ .split(",")
17
+ .map((value) => value.trim())
18
+ .filter(Boolean)
19
+ : [];
20
+ if (!values.includes(capability))
21
+ values.push(capability);
22
+ headers.set("anthropic-beta", values.join(","));
23
+ }
24
+ /** Headers that belong to one connection, never forwarded. */
25
+ const HOP_BY_HOP = [
26
+ "host",
27
+ "content-length",
28
+ "connection",
29
+ "keep-alive",
30
+ "proxy-connection",
31
+ "transfer-encoding",
32
+ "te",
33
+ "trailer",
34
+ "upgrade",
35
+ ];
36
+ /**
37
+ * A framework-agnostic, Web-standard `(Request) => Promise<Response>` handler
38
+ * implementing the BYOK Anthropic proxy. Mount it in any server (Bun, Hono,
39
+ * Workers, Node 18+). Requests come in at `{prefix}/{sessionId}/{...path}`; the
40
+ * handler looks up the real key for `sessionId`, swaps the `x-api-key` header,
41
+ * and forwards to the configured upstream. Responses are NOT passed through
42
+ * verbatim — two host-runtime bugs require reshaping (both hit Claude Code as
43
+ * its API client, found in agnt's production sidecar):
44
+ * - SSE bodies are pumped through a `TransformStream`: Bun's HTTP server
45
+ * mishandles direct ReadableStream passthrough for SSE and the node
46
+ * client sees a premature "terminated".
47
+ * - Non-SSE responses drop `content-encoding`/`content-length`/
48
+ * `transfer-encoding`: fetch already decompressed the body, so the
49
+ * original headers make the client gunzip plain bytes (ZlibError).
50
+ *
51
+ * Point the agent at it with:
52
+ * ANTHROPIC_BASE_URL=http://localhost:PORT/proxy/anthropic/<sessionId>
53
+ * ANTHROPIC_API_KEY=sk-proxy-managed
54
+ * and register the real key via `apiKeyStore.set(sessionId, realKey)`.
55
+ */
56
+ export function createAnthropicProxy(options = {}) {
57
+ const store = options.store ?? apiKeyStore;
58
+ const prefix = options.pathPrefix ?? "/proxy/anthropic";
59
+ return async function handle(request) {
60
+ const url = new URL(request.url);
61
+ const tail = url.pathname.startsWith(prefix)
62
+ ? url.pathname.slice(prefix.length).replace(/^\//, "")
63
+ : "";
64
+ const slash = tail.indexOf("/");
65
+ const sessionId = slash === -1 ? tail : tail.slice(0, slash);
66
+ const subPath = slash === -1 ? "" : tail.slice(slash);
67
+ const entry = sessionId ? store.get(sessionId) : undefined;
68
+ if (!entry) {
69
+ return new Response(JSON.stringify({
70
+ type: "error",
71
+ error: { type: "authentication_error", message: "unknown proxy session" },
72
+ }), { status: 401, headers: { "content-type": "application/json" } });
73
+ }
74
+ // A body sent twice (a renewed credential's retry) is read first.
75
+ const body = options.renew && request.body ? await request.arrayBuffer() : request.body;
76
+ const forward = (credential) => {
77
+ const headers = new Headers(request.headers);
78
+ // This hop's, not the upstream's: Node's fetch refuses some outright.
79
+ for (const name of HOP_BY_HOP)
80
+ headers.delete(name);
81
+ if (credential.kind === "oauth") {
82
+ // Subscription token: bearer auth + the OAuth capability. The
83
+ // x-api-key the CLI sent carries only the placeholder — it must go,
84
+ // or the upstream sees two conflicting credentials.
85
+ headers.delete("x-api-key");
86
+ headers.set("authorization", `Bearer ${credential.apiKey}`);
87
+ appendAnthropicBeta(headers, ANTHROPIC_OAUTH_BETA);
88
+ }
89
+ else {
90
+ headers.set("x-api-key", credential.apiKey);
91
+ headers.delete("authorization");
92
+ }
93
+ const init = {
94
+ method: request.method,
95
+ headers,
96
+ body,
97
+ redirect: "manual",
98
+ // The CLI going away stops the request upstream.
99
+ signal: request.signal,
100
+ };
101
+ // Required when forwarding a streaming request body on fetch.
102
+ if (body instanceof ReadableStream)
103
+ init.duplex = "half";
104
+ const doFetch = options.fetch ?? globalThis.fetch;
105
+ return doFetch(`${credential.upstreamBaseUrl}${subPath}${url.search}`, init);
106
+ };
107
+ let upstream;
108
+ try {
109
+ upstream = await forward(entry);
110
+ const renewed = upstream.status === 401 && (await options.renew?.(sessionId, entry));
111
+ if (renewed && renewed.apiKey !== entry.apiKey) {
112
+ await upstream.body?.cancel();
113
+ upstream = await forward(renewed);
114
+ }
115
+ }
116
+ catch (error) {
117
+ // An unreachable upstream must surface as a structured API error the
118
+ // agent can classify, not a host-framework 500 with an opaque body.
119
+ return new Response(JSON.stringify({
120
+ type: "error",
121
+ error: {
122
+ type: "api_error",
123
+ message: error instanceof Error ? error.message : "proxy request failed",
124
+ },
125
+ }), { status: 502, headers: { "content-type": "application/json" } });
126
+ }
127
+ if (upstream.status === 401 || upstream.status === 403) {
128
+ emitDiagnostic(options.onDiagnostic, {
129
+ type: "proxyUpstreamAuth",
130
+ sessionId,
131
+ message: `upstream rejected the stored key for session ${sessionId} (${upstream.status})`,
132
+ detail: { status: upstream.status },
133
+ });
134
+ }
135
+ const contentType = upstream.headers.get("content-type") ?? "";
136
+ // Media type only — parameters (charset) stripped, case-insensitive, so
137
+ // `text/event-streamish` or a parameter VALUE never selects SSE handling.
138
+ const mediaType = (contentType.split(";", 1)[0] ?? "").trim().toLowerCase();
139
+ if (mediaType === "text/event-stream" && upstream.body) {
140
+ // Pumped through a fresh stream — see the header comment for why raw
141
+ // passthrough breaks on Bun. pipeTo (not a manual read/write loop) so a
142
+ // downstream disconnect propagates cancellation to the upstream body
143
+ // and the socket is released instead of held open.
144
+ const { readable, writable } = new TransformStream();
145
+ void upstream.body.pipeTo(writable).catch(() => {
146
+ // downstream went away or upstream died — both ends settled by pipeTo
147
+ });
148
+ return new Response(readable, {
149
+ status: upstream.status,
150
+ headers: { "content-type": "text/event-stream", "cache-control": "no-cache" },
151
+ });
152
+ }
153
+ const responseHeaders = new Headers(upstream.headers);
154
+ responseHeaders.delete("content-encoding");
155
+ responseHeaders.delete("content-length");
156
+ responseHeaders.delete("transfer-encoding");
157
+ return new Response(upstream.body, {
158
+ status: upstream.status,
159
+ statusText: upstream.statusText,
160
+ headers: responseHeaders,
161
+ });
162
+ };
163
+ }
@@ -0,0 +1,30 @@
1
+ /**
2
+ * In-memory map of proxy-session → real credentials. The agent subprocess is
3
+ * given a placeholder key and pointed at the local proxy; the proxy swaps in the
4
+ * real credential from this store before forwarding upstream, so it never lives
5
+ * in the subprocess environment.
6
+ * That no-exfiltration property is exactly why subscription OAuth tokens ride
7
+ * the same store instead of the child env: the child keeps the placeholder
8
+ * either way, only the upstream header shape differs.
9
+ */
10
+ export class ApiKeyStore {
11
+ entries = new Map();
12
+ set(sessionId, apiKey, options = {}) {
13
+ this.entries.set(sessionId, {
14
+ apiKey,
15
+ upstreamBaseUrl: options.upstreamBaseUrl ?? "https://api.anthropic.com",
16
+ kind: options.kind ?? "api_key",
17
+ });
18
+ }
19
+ get(sessionId) {
20
+ return this.entries.get(sessionId);
21
+ }
22
+ delete(sessionId) {
23
+ this.entries.delete(sessionId);
24
+ }
25
+ clear() {
26
+ this.entries.clear();
27
+ }
28
+ }
29
+ /** Shared default store used by `createAnthropicProxy` when none is supplied. */
30
+ export const apiKeyStore = new ApiKeyStore();
@@ -0,0 +1,3 @@
1
+ // @zvada/agent-server/core/proxy — optional BYOK Anthropic proxy building block.
2
+ export { ApiKeyStore, apiKeyStore, } from "./api-key-store.js";
3
+ export { ANTHROPIC_OAUTH_BETA, createAnthropicProxy, PROXY_PLACEHOLDER_KEY, } from "./anthropic-proxy.js";
@@ -0,0 +1,86 @@
1
+ import { createServer } from "node:http";
2
+ import { Readable } from "node:stream";
3
+ async function bridge(handle, req, res) {
4
+ // The CLI going away stops what its request started upstream.
5
+ const gone = new AbortController();
6
+ res.once("close", () => gone.abort());
7
+ const body = req.method === "GET" || req.method === "HEAD"
8
+ ? undefined
9
+ : Readable.toWeb(req);
10
+ const headers = new Headers();
11
+ for (const [name, value] of Object.entries(req.headers)) {
12
+ if (typeof value === "string")
13
+ headers.set(name, value);
14
+ else if (value)
15
+ for (const each of value)
16
+ headers.append(name, each);
17
+ }
18
+ const request = new Request(`http://127.0.0.1${req.url ?? "/"}`, {
19
+ method: req.method,
20
+ headers,
21
+ body,
22
+ signal: gone.signal,
23
+ ...(body && { duplex: "half" }),
24
+ });
25
+ const response = await handle(request);
26
+ res.writeHead(response.status, Object.fromEntries(response.headers));
27
+ if (!response.body) {
28
+ res.end();
29
+ return;
30
+ }
31
+ for await (const chunk of response.body) {
32
+ if (gone.signal.aborted)
33
+ break;
34
+ res.write(chunk);
35
+ }
36
+ res.end();
37
+ }
38
+ /**
39
+ * Serve `handle` on 127.0.0.1, on a port of its own: with `Bun.serve` under
40
+ * Bun, whose `node:http` says nothing of a client that left once its request
41
+ * body was read (a stopped turn's request would run on upstream), and with
42
+ * `node:http` under Node.
43
+ */
44
+ export function serveLoopback(handle) {
45
+ const bun = globalThis.Bun;
46
+ if (bun) {
47
+ const server = bun.serve({
48
+ port: 0,
49
+ hostname: "127.0.0.1",
50
+ // A model can think longer than any idle limit between the events it streams.
51
+ idleTimeout: 0,
52
+ fetch: (request) => handle(request).catch(() => new Response(null, { status: 502 })),
53
+ });
54
+ // Nothing on it keeps the process alive.
55
+ server.unref();
56
+ return Promise.resolve({
57
+ url: `http://127.0.0.1:${server.port}`,
58
+ // Not waited for: with a client still connected, Bun's stop can take its time.
59
+ close: async () => {
60
+ server.stop(true);
61
+ },
62
+ });
63
+ }
64
+ const server = createServer((req, res) => {
65
+ bridge(handle, req, res).catch(() => {
66
+ if (!res.headersSent)
67
+ res.writeHead(502);
68
+ res.end();
69
+ });
70
+ });
71
+ return new Promise((resolve, reject) => {
72
+ server.once("error", reject);
73
+ server.listen(0, "127.0.0.1", () => {
74
+ const { port } = server.address();
75
+ // Nothing on it keeps the process alive.
76
+ server.unref();
77
+ resolve({
78
+ url: `http://127.0.0.1:${port}`,
79
+ close: () => new Promise((done) => {
80
+ server.closeAllConnections();
81
+ server.close(() => done());
82
+ }),
83
+ });
84
+ });
85
+ });
86
+ }