@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
package/CHANGELOG.md CHANGED
@@ -7,6 +7,70 @@ and the measurements. Evidence lives in the LLP, not here. A release groups
7
7
  its bullets under Breaking, Added, Changed and Fixed, breaking first. The
8
8
  released sections below that predate this convention are kept as written.
9
9
 
10
+ ## 0.3.25
11
+
12
+ ### Changed
13
+
14
+ - A Codex resume refused because another app-server still holds the thread ("already
15
+ has an active writer") fails with the new error category `resume_busy`, not
16
+ `resume_failed`: the same resume succeeds once that one lets go. A product that
17
+ matched `resume_failed` retries later on `resume_busy` instead of starting fresh (LLP 0002).
18
+
19
+ ### Fixed
20
+
21
+ - Under Bun, the lifeline shell and the `ps` and `sysctl` the engine runs get its
22
+ `process.env` as it is now, not as Bun was launched: a secret your product, or the
23
+ bin's own `AGENT_SERVER_*_TOKEN`, deleted from `process.env` no longer lives on in
24
+ the lifeline for as long as the engine runs (LLP 0007, The environment a process is given).
25
+ - A cancel that lands after a turn is admitted and before its harness begins it ends
26
+ the turn `cancelled`, where the turn ran to its own end; its answer is still
27
+ `hadTurn: false` (on the wire `unconfirmed`). A scripted `hang` takes `stopTakes`
28
+ also when the cancel came first, so a test can cancel without a sleep (LLP 0001, D9).
29
+ - `AgentServerClient.cancelTurn` for a turn the same client is starting (`runTurn`,
30
+ `startTurn`) is sent after that start's first send: a cancel in the same tick as the
31
+ start ends the turn `cancelled`, where it got `no_active_turn` and the turn ran on
32
+ (LLP 0001, D9).
33
+ - The error classifier no longer reads a status code out of an identifier: a thread
34
+ id holding `-b401-` or `-a429-` no longer makes a failure `auth` or `rate_limit`
35
+ (LLP 0002, Open vocabularies).
36
+ - `credentialRunsOn` takes any `AgentHarness` and answers `{ ok: false, error }` for
37
+ ACP and scripted, which run on no credential a product holds, where it threw a
38
+ `TypeError`; a caller naming Claude or Codex keeps the narrow type (LLP 0012).
39
+
40
+ ## 0.3.24
41
+
42
+ ### Added
43
+
44
+ - The package runs on plain Node, no loader or bundler of yours: every export but
45
+ `./sync/sqlite` loads compiled JavaScript (`default`); Bun loads sources (`bun`).
46
+ The bin: `node node_modules/@zvada/agent-server/dist/server/bin.js`, `--journal`
47
+ on `node:sqlite`; `listen` and `--listen` stay Bun's and say so (LLP 0001, D24).
48
+ - A Claude `toolPolicy` is told an MCP call's `mcp: { server, tool }` in its context,
49
+ as the call's permission request would carry it (a server named with `__` resolves
50
+ to the attached one), so a policy no longer parses `mcp__<server>__<tool>`; none
51
+ for a tool that is no MCP tool (LLP 0002, An MCP tool names its server and tool).
52
+
53
+ ### Changed
54
+
55
+ - `./sync/node-sqlite` loads `node:sqlite` when a journal opens, not on import, so
56
+ it imports under Bun and in a bundle that holds both adapters; a build that
57
+ stubbed or lazy-loaded `node:sqlite` for it can drop that (LLP 0001, D24).
58
+ - A warm Codex session on its home's own login follows a login changed outside the
59
+ engine (`codex login`, another app): once `auth.json` changed, the next turn
60
+ resumes its thread on a new app-server, or fails `auth` after a sign-out. No login
61
+ is read, so a token renewal costs a colder turn about every ten days (LLP 0011).
62
+
63
+ ### Fixed
64
+
65
+ - A hung Claude CLI no longer holds its session: a cancelled turn it has not ended
66
+ by `cancelGraceMs` (10 s) has its process ended, ends `cancelled`, and the next
67
+ turn resumes the conversation. Claude takes the registry's `cancelGraceMs`, and
68
+ answers `cancelled` once its turn ended within `cancelConfirmMs` (LLP 0001, D9).
69
+ - A Codex MCP consent the engine cannot link to one started call (none open, or two
70
+ of the tool and neither with its arguments) carries `mcp` with its server and the
71
+ tool its message names, so a product that consents by `mcp.server` no longer
72
+ refuses it (LLP 0002, An MCP tool names its server and tool).
73
+
10
74
  ## 0.3.23
11
75
 
12
76
  ### Breaking
package/README.md CHANGED
@@ -54,6 +54,11 @@ bunx @zvada/agent-server --acp # act as an ACP v1 agent (Zed-spawnable
54
54
  bunx @zvada/agent-server install # prefetch pinned claude/codex CLIs
55
55
  ```
56
56
 
57
+ Under Node, run the compiled bin:
58
+ `node node_modules/@zvada/agent-server/dist/server/bin.js --stdio` (or
59
+ `--dial`, `--acp`, `install`). `--listen` needs Bun, and `--journal` uses
60
+ `node:sqlite` there (Node >= 22.16).
61
+
57
62
  A listener answers native clients only: a browser is refused unless
58
63
  `--allow-origin <origin>` names its origin, since any page may open a
59
64
  WebSocket to localhost. Beyond loopback (`--listen 0.0.0.0:4747`) it needs a
@@ -119,11 +124,15 @@ for await (const event of turn.events) conversation = reduceConversation(convers
119
124
 
120
125
  ## Notes
121
126
 
122
- - Ships as TypeScript source (Bun-first; the client and stdio/dial server
123
- transports also run under Node >= 20, where the host bundles the source or
124
- runs it through a TypeScript loader) with declarations: a consumer's `tsc`
125
- reads `dist/types`, so its compiler options, Bun's types and the SDKs of
126
- harnesses it does not run stay out of its build (with `skipLibCheck`).
127
+ - Ships its TypeScript sources, the JavaScript compiled from them, and
128
+ declarations. Bun loads the sources (the `bun` export condition); Node and
129
+ bundlers load the compiled `dist/` (`default`), with no loader or
130
+ transpiling of your own; a consumer's `tsc` reads `dist/types`, so its
131
+ compiler options, Bun's types and the SDKs of harnesses it does not run stay
132
+ out of its build (with `skipLibCheck`). Tested on Bun 1.3 and Node 22.16,
133
+ 22.23 and 24.21. Bun only: `./sync/sqlite` (use `./sync/node-sqlite` under
134
+ Node) and `listen` (under Node serve over stdio, `dial`, or a WebSocket
135
+ server of your own; [deploy](docs/deploy.md#on-node)).
127
136
  - The wire vocabulary tracks the
128
137
  [Agent Client Protocol](https://agentclientprotocol.com) where concepts
129
138
  overlap.
@@ -0,0 +1,144 @@
1
+ import { claimsOf } from "../protocol/credentials.js";
2
+ import { AccountError, call, isRecord, text } from "./http.js";
3
+ // The Codex CLI's own OAuth client, as the `codex` binary carries it, and its
4
+ // device sign-in (codex-rs `login/`). A public client: no secret, the same for
5
+ // every user. The issuer is fixed, so no caller-supplied address ever receives
6
+ // these credentials.
7
+ const ISSUER = "https://auth.openai.com";
8
+ const CLIENT_ID = "app_EMoamEEZ73f0CkXaXp7hrann";
9
+ /** How long a device code waits for its person. */
10
+ const DEVICE_CODE_LIFETIME_MS = 15 * 60_000;
11
+ /** A grant from what OpenAI's token endpoint answered: the account and plan are the id token's. */
12
+ function grantFrom(body, options, previous) {
13
+ const old = previous?.credential.type === "chatgpt" ? previous.credential : undefined;
14
+ const answer = isRecord(body) ? body : {};
15
+ // A renewal answered without a token renewed nothing, and may have spent the refresh token.
16
+ const accessToken = text(answer.access_token);
17
+ const refreshToken = text(answer.refresh_token) ?? previous?.refreshToken;
18
+ const idToken = text(answer.id_token);
19
+ if (!accessToken || !refreshToken) {
20
+ throw new AccountError("OpenAI returned an incomplete login. Sign in again.", true);
21
+ }
22
+ const identity = idToken ? claimsOf(idToken) : {};
23
+ const auth = isRecord(identity["https://api.openai.com/auth"])
24
+ ? identity["https://api.openai.com/auth"]
25
+ : {};
26
+ const accountId = text(auth.chatgpt_account_id) ?? old?.accountId;
27
+ const expiry = claimsOf(accessToken).exp;
28
+ if (!accountId)
29
+ throw new AccountError("OpenAI returned no ChatGPT account. Sign in again.", true);
30
+ if (old && old.accountId !== accountId) {
31
+ throw new AccountError("The ChatGPT account changed. Sign in again.", true);
32
+ }
33
+ const plan = text(auth.chatgpt_plan_type) ?? old?.plan;
34
+ const email = text(identity.email) ?? previous?.email;
35
+ return {
36
+ harness: "codex-app-server",
37
+ credential: {
38
+ type: "chatgpt",
39
+ accessToken,
40
+ accountId,
41
+ ...(plan && { plan }),
42
+ ...(typeof expiry === "number" && { expiresAt: expiry * 1000 }),
43
+ },
44
+ refreshToken,
45
+ ...(email && { email }),
46
+ ...(plan && { plan }),
47
+ obtainedAt: (options.now ?? Date.now)(),
48
+ };
49
+ }
50
+ /**
51
+ * Start a ChatGPT sign-in with a device code, which a person enters on any
52
+ * device: what a hosted product offers, since Codex's browser sign-in calls
53
+ * back to `localhost` only. The account must allow device codes (ChatGPT
54
+ * settings, Security).
55
+ */
56
+ export async function startChatGptLogin(options = {}) {
57
+ const answer = await call(`${ISSUER}/api/accounts/deviceauth/usercode`, {
58
+ method: "POST",
59
+ headers: { "content-type": "application/json" },
60
+ body: JSON.stringify({ client_id: CLIENT_ID }),
61
+ }, options);
62
+ const body = isRecord(answer.body) ? answer.body : {};
63
+ const deviceAuthId = text(body.device_auth_id);
64
+ const userCode = text(body.user_code) ?? text(body.usercode);
65
+ if (!answer.ok || !deviceAuthId || !userCode) {
66
+ throw new AccountError("OpenAI did not start the sign-in. Allow device code sign-in in ChatGPT settings (Security), then try again.");
67
+ }
68
+ const interval = Number(body.interval);
69
+ return {
70
+ deviceAuthId,
71
+ userCode,
72
+ verificationUrl: `${ISSUER}/codex/device`,
73
+ intervalMs: Math.max(Number.isFinite(interval) ? interval : 5, 5) * 1000,
74
+ expiresAt: (options.now ?? Date.now)() + DEVICE_CODE_LIFETIME_MS,
75
+ };
76
+ }
77
+ /**
78
+ * Ask once whether the person approved: the grant once they did, `undefined`
79
+ * while they have not. Poll no faster than `intervalMs`. The approval's code is
80
+ * exchanged once, never retried: a lost answer means sign in again.
81
+ */
82
+ export async function pollChatGptLogin(login, options = {}) {
83
+ if ((options.now ?? Date.now)() > login.expiresAt) {
84
+ throw new AccountError("The sign-in code expired. Start again.");
85
+ }
86
+ const answer = await call(`${ISSUER}/api/accounts/deviceauth/token`, {
87
+ method: "POST",
88
+ headers: { "content-type": "application/json" },
89
+ body: JSON.stringify({ device_auth_id: login.deviceAuthId, user_code: login.userCode }),
90
+ }, options).catch(() => undefined);
91
+ // Waiting, as Codex reads it (403, 404), and a failure worth asking again (429, 5xx).
92
+ if (!answer ||
93
+ answer.status === 403 ||
94
+ answer.status === 404 ||
95
+ answer.status === 429 ||
96
+ answer.status >= 500) {
97
+ return undefined;
98
+ }
99
+ const body = isRecord(answer.body) ? answer.body : {};
100
+ const code = text(body.authorization_code);
101
+ const verifier = text(body.code_verifier);
102
+ if (!answer.ok || !code || !verifier)
103
+ throw new AccountError("OpenAI did not finish the sign-in. Start again.");
104
+ const token = await call(`${ISSUER}/oauth/token`, {
105
+ method: "POST",
106
+ headers: { "content-type": "application/x-www-form-urlencoded" },
107
+ body: new URLSearchParams({
108
+ grant_type: "authorization_code",
109
+ client_id: CLIENT_ID,
110
+ code,
111
+ code_verifier: verifier,
112
+ redirect_uri: `${ISSUER}/deviceauth/callback`,
113
+ }).toString(),
114
+ }, options);
115
+ if (!token.ok)
116
+ throw new AccountError("OpenAI refused this sign-in. Start again.");
117
+ return grantFrom(token.body, options);
118
+ }
119
+ /**
120
+ * Renew a ChatGPT grant: the same account with fresh tokens, which the
121
+ * product stores in its place. One renewal at a time per grant: a renewal
122
+ * whose answer was lost may have happened, and is not tried again here.
123
+ */
124
+ export async function refreshChatGptGrant(grant, options = {}) {
125
+ if (grant.credential.type !== "chatgpt" || !grant.refreshToken) {
126
+ throw new AccountError("This is not a ChatGPT grant that renews.");
127
+ }
128
+ const answer = await call(`${ISSUER}/oauth/token`, {
129
+ method: "POST",
130
+ headers: { "content-type": "application/json" },
131
+ body: JSON.stringify({
132
+ client_id: CLIENT_ID,
133
+ grant_type: "refresh_token",
134
+ refresh_token: grant.refreshToken,
135
+ }),
136
+ }, options);
137
+ if (!answer.ok) {
138
+ const refused = answer.status === 400 || answer.status === 401;
139
+ throw new AccountError(refused
140
+ ? "The ChatGPT login expired or was revoked. Sign in again."
141
+ : "OpenAI did not renew the login. Try again.", refused);
142
+ }
143
+ return grantFrom(answer.body, options, grant);
144
+ }
@@ -0,0 +1,71 @@
1
+ import { credentialRunsOn, } from "../protocol/credentials.js";
2
+ import { AccountError, call } from "./http.js";
3
+ const ANTHROPIC_MODELS = "https://api.anthropic.com/v1/models?limit=1";
4
+ const OPENAI_MODELS = "https://api.openai.com/v1/models";
5
+ const ANTHROPIC_VERSION = "2023-06-01";
6
+ const OK = { ok: true };
7
+ /**
8
+ * Whether a credential works, by one cheap request to its provider (a model
9
+ * list): a key or token the provider refuses is `reconnect`. A ChatGPT token
10
+ * is checked by its expiry only, as no public request takes it, and a
11
+ * gateway's key (`baseUrl`) not at all.
12
+ */
13
+ export async function checkCredential(harness, credential, options = {}) {
14
+ if (harness === "claude-code") {
15
+ const runs = credentialRunsOn(harness, credential);
16
+ return runs.ok ? checkClaude(runs.credential, options) : unrunnable(runs.error);
17
+ }
18
+ if (harness === "codex-app-server") {
19
+ const runs = credentialRunsOn(harness, credential);
20
+ return runs.ok ? checkCodex(runs.credential, options) : unrunnable(runs.error);
21
+ }
22
+ return unrunnable(`${harness} runs on no credential a product holds.`);
23
+ }
24
+ const unrunnable = (error) => ({ ok: false, error, reconnect: true });
25
+ function checkClaude(credential, options) {
26
+ if (credential.type === "oauth_token") {
27
+ return listModels(ANTHROPIC_MODELS, {
28
+ authorization: `Bearer ${credential.accessToken}`,
29
+ "anthropic-version": ANTHROPIC_VERSION,
30
+ "anthropic-beta": "oauth-2025-04-20",
31
+ }, options);
32
+ }
33
+ // A gateway's key: what a person pasted would point this server's
34
+ // requests anywhere, so a product trusts its gateways by its own list.
35
+ if (credential.baseUrl)
36
+ return OK;
37
+ return listModels(ANTHROPIC_MODELS, { "x-api-key": credential.apiKey, "anthropic-version": ANTHROPIC_VERSION }, options);
38
+ }
39
+ function checkCodex(credential, options) {
40
+ if (credential.type === "api_key") {
41
+ return listModels(OPENAI_MODELS, { authorization: `Bearer ${credential.apiKey}` }, options);
42
+ }
43
+ const expired = credential.expiresAt !== undefined && credential.expiresAt <= (options.now ?? Date.now)();
44
+ return expired
45
+ ? { ok: false, error: "The ChatGPT token expired: renew it.", reconnect: false }
46
+ : OK;
47
+ }
48
+ /** One cheap request with the credential: a refusal is `reconnect`. */
49
+ async function listModels(url, headers, options) {
50
+ const answer = await call(url, { headers }, options);
51
+ if (answer.ok)
52
+ return OK;
53
+ const refused = answer.status === 401 || answer.status === 403;
54
+ return {
55
+ ok: false,
56
+ error: refused
57
+ ? "The provider refused this credential."
58
+ : `The provider answered ${answer.status}.`,
59
+ reconnect: refused,
60
+ };
61
+ }
62
+ /**
63
+ * A key or token the person pasted (an API key, a `claude setup-token`
64
+ * token), checked: the grant to store, or why not.
65
+ */
66
+ export async function pastedGrant(harness, credential, options = {}) {
67
+ const check = await checkCredential(harness, credential, options);
68
+ if (!check.ok)
69
+ throw new AccountError(check.error, check.reconnect);
70
+ return { harness, credential, obtainedAt: (options.now ?? Date.now)() };
71
+ }
@@ -0,0 +1,80 @@
1
+ import { pastedSignInCode } from "../protocol/credentials.js";
2
+ import { AccountError, call, challengeOf, isRecord, randomToken, text, } from "./http.js";
3
+ // What `claude setup-token` asks for (Claude Code 2.1.288): Claude Code's own
4
+ // OAuth client, as the `claude` binary carries it (public: no secret, the
5
+ // same for every user), the inference scope alone, a year, and the page that
6
+ // shows a code.
7
+ const CLIENT_ID = "9d1c250a-e61b-44d9-88ed-5944d1962f5e";
8
+ const AUTHORIZE_URL = "https://claude.com/cai/oauth/authorize";
9
+ const TOKEN_URL = "https://platform.claude.com/v1/oauth/token";
10
+ const CODE_PAGE = "https://platform.claude.com/oauth/code/callback";
11
+ const SCOPE = "user:inference";
12
+ const ONE_YEAR_S = 31_536_000;
13
+ /** Start a Claude sign-in whose code is pasted back: it works from any device. */
14
+ export async function startClaudeLogin() {
15
+ const verifier = randomToken();
16
+ const state = randomToken();
17
+ const url = new URL(AUTHORIZE_URL);
18
+ for (const [name, value] of Object.entries({
19
+ code: "true",
20
+ client_id: CLIENT_ID,
21
+ response_type: "code",
22
+ redirect_uri: CODE_PAGE,
23
+ scope: SCOPE,
24
+ code_challenge: await challengeOf(verifier),
25
+ code_challenge_method: "S256",
26
+ state,
27
+ })) {
28
+ url.searchParams.set(name, value);
29
+ }
30
+ return { url: url.toString(), state, verifier };
31
+ }
32
+ /**
33
+ * Finish a Claude sign-in with the code its page showed (`code#state`, the
34
+ * page's address, or the bare code): a one-year inference token, which needs
35
+ * no renewal. A code from another sign-in is refused before it is sent.
36
+ */
37
+ export async function completeClaudeLogin(login, pasted, options = {}) {
38
+ let pastedCode;
39
+ try {
40
+ pastedCode = pastedSignInCode(pasted, login.state);
41
+ }
42
+ catch (error) {
43
+ throw new AccountError(error.message);
44
+ }
45
+ const { code, state } = pastedCode;
46
+ const answer = await call(TOKEN_URL, {
47
+ method: "POST",
48
+ headers: { "content-type": "application/json" },
49
+ body: JSON.stringify({
50
+ grant_type: "authorization_code",
51
+ code,
52
+ redirect_uri: CODE_PAGE,
53
+ client_id: CLIENT_ID,
54
+ code_verifier: login.verifier,
55
+ state,
56
+ expires_in: ONE_YEAR_S,
57
+ }),
58
+ }, options);
59
+ const body = isRecord(answer.body) ? answer.body : {};
60
+ const accessToken = text(body.access_token);
61
+ if (!answer.ok || !accessToken) {
62
+ throw new AccountError(answer.status === 400 || answer.status === 401
63
+ ? "Claude did not accept this code: sign in again, and paste the code the page shows."
64
+ : "Claude did not finish the sign-in. Try again.");
65
+ }
66
+ const now = (options.now ?? Date.now)();
67
+ const expiresIn = Number(body.expires_in);
68
+ const account = isRecord(body.account) ? body.account : {};
69
+ const email = text(account.email_address);
70
+ return {
71
+ harness: "claude-code",
72
+ credential: {
73
+ type: "oauth_token",
74
+ accessToken,
75
+ ...(Number.isFinite(expiresIn) && { expiresAt: now + expiresIn * 1000 }),
76
+ },
77
+ ...(email && { email }),
78
+ obtainedAt: now,
79
+ };
80
+ }
@@ -0,0 +1,104 @@
1
+ import { CredentialRequestSchema, tokenDigest, } from "../protocol/credentials.js";
2
+ import { refreshChatGptGrant } from "./chatgpt.js";
3
+ import { AccountError } from "./http.js";
4
+ const json = (body, status = 200) => new Response(JSON.stringify(body), { status, headers: { "content-type": "application/json" } });
5
+ /**
6
+ * A product's credential endpoint, as a Web-standard handler for any server
7
+ * (a Worker, Bun, Hono, Node 18+): what an engine started with
8
+ * `credentialsFromUrl` (`--credentials-url`) asks before each turn.
9
+ */
10
+ export function createCredentialHandler(options) {
11
+ return async (request) => {
12
+ if (request.method !== "POST")
13
+ return json({ error: "POST a credential request" }, 405);
14
+ const principal = await options.authorize(request);
15
+ if (principal === undefined)
16
+ return json({ error: "not authorized" }, 401);
17
+ const asked = CredentialRequestSchema.safeParse(await request.json().catch(() => undefined));
18
+ if (!asked.success)
19
+ return json({ error: "not a credential request" }, 400);
20
+ try {
21
+ const credential = await options.resolve(asked.data, principal);
22
+ const answer = { credential: credential ?? null };
23
+ return json(answer);
24
+ }
25
+ catch (error) {
26
+ // The product's own words reach the turn; whether the person must sign in again, too.
27
+ if (error instanceof AccountError) {
28
+ return json({ error: error.message, reconnect: error.reconnect }, 409);
29
+ }
30
+ // Any other failure's words stay here: its message may hold what it failed on.
31
+ return json({ error: "no credential" }, 502);
32
+ }
33
+ };
34
+ }
35
+ /**
36
+ * A credential endpoint's `resolve` over the product's store: the grant's
37
+ * credential, renewed first when it expires within five minutes or the
38
+ * harness refused the very token it holds, and the renewal written back. One
39
+ * renewal at a time per grant in this process, deciding on the grant as read
40
+ * inside it; across processes, the store decides which write wins (a
41
+ * revision it compares before writing).
42
+ */
43
+ export function credentialsFrom(store, options = {}) {
44
+ const renewals = new Map();
45
+ const now = () => (options.now ?? Date.now)();
46
+ return async (request, principal) => {
47
+ const grant = await store.read(request, principal);
48
+ if (!grant)
49
+ return undefined;
50
+ if (!grant.refreshToken) {
51
+ // Nothing renews a key or a one-year token: one the harness refused needs the person.
52
+ if (await refused(grant, request)) {
53
+ throw new AccountError("The provider refused this credential. Sign in again.", true);
54
+ }
55
+ return grant.credential;
56
+ }
57
+ if (!(await needsRenewal(grant, request, now())))
58
+ return grant.credential;
59
+ // Keyed by the refresh token it spends: every ask that read this grant waits on one renewal.
60
+ const key = grant.refreshToken;
61
+ let renewal = renewals.get(key);
62
+ if (!renewal) {
63
+ renewal = (async () => {
64
+ // Read again: a renewal that finished meanwhile spent this refresh token.
65
+ const current = await store.read(request, principal);
66
+ if (!current || !(await needsRenewal(current, request, now())))
67
+ return current;
68
+ const renewed = await renew(current, options);
69
+ await store.write(renewed, request, principal);
70
+ return renewed;
71
+ })().finally(() => renewals.delete(key));
72
+ renewals.set(key, renewal);
73
+ }
74
+ return (await renewal)?.credential;
75
+ };
76
+ }
77
+ /** What renews a grant: only a ChatGPT login's refresh token does. */
78
+ function renew(grant, options) {
79
+ if (grant.credential.type === "chatgpt")
80
+ return refreshChatGptGrant(grant, options);
81
+ throw new AccountError(`Nothing renews a ${grant.credential.type} credential.`);
82
+ }
83
+ /** A ChatGPT token is renewed this long before it expires. */
84
+ const RENEW_BEFORE_MS = 5 * 60_000;
85
+ /**
86
+ * Whether to renew a grant before answering: it expires within five
87
+ * minutes, or the harness refused the very token it holds. A refusal of an
88
+ * older token than the one held is answered with the one held.
89
+ */
90
+ export async function needsRenewal(grant, request, now = Date.now()) {
91
+ if (!grant.refreshToken)
92
+ return false;
93
+ if (await refused(grant, request))
94
+ return true;
95
+ const { credential } = grant;
96
+ const expiresAt = credential.type === "api_key" ? undefined : credential.expiresAt;
97
+ return expiresAt !== undefined && expiresAt - now < RENEW_BEFORE_MS;
98
+ }
99
+ /** Whether the harness refused the very token the grant holds, not an older one. */
100
+ async function refused(grant, request) {
101
+ const { credential } = grant;
102
+ const token = credential.type === "api_key" ? credential.apiKey : credential.accessToken;
103
+ return (request.rejectedSha256 !== undefined && request.rejectedSha256 === (await tokenDigest(token)));
104
+ }
@@ -0,0 +1,58 @@
1
+ /**
2
+ * Why an account operation failed, in words for the person: `reconnect`
3
+ * means the account must be signed in again (a refused or revoked grant), as
4
+ * opposed to a failure worth trying again.
5
+ */
6
+ export class AccountError extends Error {
7
+ reconnect;
8
+ constructor(message, reconnect = false) {
9
+ super(message);
10
+ this.reconnect = reconnect;
11
+ this.name = "AccountError";
12
+ }
13
+ }
14
+ /**
15
+ * One request to a provider's fixed endpoint: no redirect followed, a
16
+ * deadline, the body as JSON. A request that never answered throws: after a
17
+ * token exchange or renewal it may have happened, so it is never retried here.
18
+ */
19
+ export async function call(url, init, options) {
20
+ const doFetch = options.fetch ?? globalThis.fetch;
21
+ let response;
22
+ try {
23
+ response = await doFetch(url, {
24
+ ...init,
25
+ redirect: "manual",
26
+ signal: AbortSignal.timeout(options.timeoutMs ?? 8_000),
27
+ });
28
+ }
29
+ catch {
30
+ throw new AccountError(`Could not reach ${new URL(url).host}. Try again.`);
31
+ }
32
+ const text = await response.text().catch(() => "");
33
+ let body;
34
+ try {
35
+ body = text ? JSON.parse(text) : undefined;
36
+ }
37
+ catch {
38
+ body = undefined;
39
+ }
40
+ return { ok: response.ok, status: response.status, body };
41
+ }
42
+ export const isRecord = (value) => typeof value === "object" && value !== null && !Array.isArray(value);
43
+ export const text = (value) => typeof value === "string" && value.length > 0 ? value : undefined;
44
+ /** Random bytes as base64url: a PKCE verifier, a state. */
45
+ export function randomToken(bytes = 32) {
46
+ return base64Url(crypto.getRandomValues(new Uint8Array(bytes)));
47
+ }
48
+ function base64Url(bytes) {
49
+ let binary = "";
50
+ for (const byte of bytes)
51
+ binary += String.fromCharCode(byte);
52
+ return btoa(binary).replace(/\+/g, "-").replace(/\//g, "_").replace(/=+$/, "");
53
+ }
54
+ /** A PKCE challenge (S256) for a verifier. */
55
+ export async function challengeOf(verifier) {
56
+ const digest = await crypto.subtle.digest("SHA-256", new TextEncoder().encode(verifier));
57
+ return base64Url(new Uint8Array(digest));
58
+ }
@@ -0,0 +1,9 @@
1
+ // @zvada/agent-server/accounts — a product's side of durable credentials
2
+ // (LLP 0012): sign a person's subscription in for a credential the product
3
+ // stores, renew it, check a key, and answer an engine's credential requests.
4
+ // Only `fetch` and Web Crypto: it runs in a Worker as on a server.
5
+ export { checkCredential, pastedGrant } from "./check.js";
6
+ export { pollChatGptLogin, refreshChatGptGrant, startChatGptLogin, } from "./chatgpt.js";
7
+ export { completeClaudeLogin, startClaudeLogin } from "./claude.js";
8
+ export { createCredentialHandler, credentialsFrom, } from "./endpoint.js";
9
+ export { AccountError } from "./http.js";