@chroxy/server 0.11.0 → 0.11.11

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 (386) hide show
  1. package/CONFIG.md +206 -18
  2. package/README.md +2 -2
  3. package/hooks/claude-native-route-check.mjs +17 -0
  4. package/hooks/permission-hook.sh +166 -11
  5. package/package.json +16 -12
  6. package/sidecar/Dockerfile +1 -1
  7. package/sidecar/PROTOCOL.md +9 -1
  8. package/sidecar/agent.js +102 -10
  9. package/sidecar/package-lock.json +3 -3
  10. package/src/acp-config.js +206 -0
  11. package/src/acp-session.js +958 -0
  12. package/src/activity-registry.js +110 -5
  13. package/src/agent-connections.js +304 -0
  14. package/src/agent-control/client.js +1645 -0
  15. package/src/agent-control/events.js +551 -0
  16. package/src/agent-control/local-connection.js +293 -0
  17. package/src/agent-control/mcp-server.js +547 -0
  18. package/src/anthropic-compatible-config.js +30 -4
  19. package/src/anthropic-compatible-session.js +15 -6
  20. package/src/anthropic-gemini-shim.js +444 -0
  21. package/src/anthropic-gemini-translate.js +1030 -0
  22. package/src/anthropic-openai-shim.js +0 -1
  23. package/src/archive-continuation.js +164 -0
  24. package/src/assistant-response.js +24 -0
  25. package/src/auth-probes.js +120 -13
  26. package/src/background-shell-tracker.js +27 -0
  27. package/src/base-session.js +1520 -36
  28. package/src/bearer-recheck.js +49 -0
  29. package/src/billing-budget.js +19 -0
  30. package/src/billing-class.js +40 -7
  31. package/src/binary-provenance-trust.js +11 -5
  32. package/src/bound-client-policy.js +291 -0
  33. package/src/built-in-tools/bash-exec.js +46 -7
  34. package/src/built-in-tools/file-ops.js +69 -5
  35. package/src/built-in-tools/tool-transforms.js +1113 -13
  36. package/src/byok-compose-state.js +6 -9
  37. package/src/byok-credentials.js +2 -3
  38. package/src/byok-mcp-client.js +92 -7
  39. package/src/byok-mcp-config.js +633 -122
  40. package/src/byok-mcp-fleet.js +49 -7
  41. package/src/byok-mcp-oauth-store.js +18 -16
  42. package/src/byok-mcp-trust.js +37 -23
  43. package/src/byok-session.js +707 -179
  44. package/src/byok-tool-executor.js +2742 -26
  45. package/src/byok-tools.js +9 -2
  46. package/src/channels/chroxy-channel-server.js +2 -3
  47. package/src/checkpoint-manager.js +64 -46
  48. package/src/claude-channel-session.js +16 -10
  49. package/src/claude-model-catalog.js +131 -16
  50. package/src/claude-model-refresh.js +385 -0
  51. package/src/claude-model-request.js +103 -0
  52. package/src/claude-setting-sources.js +74 -0
  53. package/src/claude-stream-parser.js +53 -3
  54. package/src/claude-tui/diagnostic-tail.js +83 -0
  55. package/src/claude-tui/form-driver.js +44 -7
  56. package/src/claude-tui/model-error.js +41 -0
  57. package/src/claude-tui/pty-driver.js +215 -88
  58. package/src/claude-tui/sanitize-question-payload.js +109 -0
  59. package/src/claude-tui/usage-limit.js +239 -0
  60. package/src/claude-tui-session.js +3563 -284
  61. package/src/claude-tui-tool-response.js +300 -0
  62. package/src/cli/agent-cmd.js +236 -0
  63. package/src/cli/agent-control-cmd.js +65 -0
  64. package/src/cli/config-cmd.js +4 -4
  65. package/src/cli/config-dir-cmd.js +234 -0
  66. package/src/cli/connection-state.js +54 -0
  67. package/src/cli/deploy-cmd.js +45 -10
  68. package/src/cli/doctor-cmd.js +7 -3
  69. package/src/cli/freshness-cmd.js +53 -0
  70. package/src/cli/init-cmd.js +15 -16
  71. package/src/cli/pages-cmd.js +6 -4
  72. package/src/cli/pair-code-cmd.js +7 -6
  73. package/src/cli/pair-discord-cmd.js +7 -6
  74. package/src/cli/providers-cmd.js +3 -3
  75. package/src/cli/schedule-cmd.js +91 -40
  76. package/src/cli/server-cmd.js +54 -1
  77. package/src/cli/service-cmd.js +33 -10
  78. package/src/cli/session-cmd.js +227 -74
  79. package/src/cli/shared.js +162 -11
  80. package/src/cli/shell-cmd.js +7 -4
  81. package/src/cli/status-cmd.js +19 -5
  82. package/src/cli/tokens-cmd.js +4 -5
  83. package/src/cli/tunnel-cmd.js +255 -24
  84. package/src/cli/worktree-gc-cmd.js +2 -2
  85. package/src/cli-session.js +1250 -126
  86. package/src/cli.js +8 -0
  87. package/src/codex-app-server-client.js +36 -3
  88. package/src/codex-app-server-session.js +1517 -81
  89. package/src/codex-bundled-client.js +66 -0
  90. package/src/codex-error-text.js +114 -0
  91. package/src/codex-model-catalog.js +548 -0
  92. package/src/codex-model-rejections.js +87 -0
  93. package/src/codex-native-resume.js +104 -0
  94. package/src/codex-protocol-capabilities.js +188 -0
  95. package/src/codex-session.js +450 -27
  96. package/src/config-dir-migration.js +449 -0
  97. package/src/config-dir.js +108 -0
  98. package/src/config.js +306 -26
  99. package/src/connection-authority.js +48 -0
  100. package/src/connection-info.js +78 -23
  101. package/src/connection-locality.js +60 -0
  102. package/src/container-liveness-monitor.js +189 -0
  103. package/src/continuation-metadata-worker.js +17 -0
  104. package/src/continuations.js +227 -0
  105. package/src/control-room/host-prune.js +5 -0
  106. package/src/control-room/integrations.js +7 -20
  107. package/src/control-room/skills-inventory.js +2 -2
  108. package/src/conversation-scanner.js +42 -39
  109. package/src/conversation-scope.js +59 -39
  110. package/src/conversation-search.js +28 -39
  111. package/src/credential-store.js +23 -19
  112. package/src/daemon-commit.js +92 -0
  113. package/src/daemon-idle-state.js +171 -0
  114. package/src/daemon-update-status.js +314 -0
  115. package/src/dashboard-build.js +70 -0
  116. package/src/declared-status.js +90 -0
  117. package/src/deepseek-credentials.js +2 -3
  118. package/src/dev-preview.js +170 -182
  119. package/src/device-preferences.js +2 -2
  120. package/src/diff-parser.js +87 -0
  121. package/src/discord-credentials.js +2 -3
  122. package/src/docker-byok-pool.js +3 -1
  123. package/src/docker-byok-session.js +678 -78
  124. package/src/docker-image-allowlist.js +23 -1
  125. package/src/docker-sdk-session.js +172 -3
  126. package/src/docker-session.js +294 -11
  127. package/src/doctor.js +781 -64
  128. package/src/durable-write.js +35 -0
  129. package/src/edited-input.js +264 -0
  130. package/src/environment-manager.js +175 -36
  131. package/src/environments/authority.js +101 -0
  132. package/src/environments/backends/container-claude-spawn.js +94 -0
  133. package/src/environments/backends/docker.js +31 -10
  134. package/src/environments/backends/k8s.js +49 -24
  135. package/src/environments/destroy-with-sessions.js +142 -0
  136. package/src/event-ingest.js +118 -13
  137. package/src/event-normalizer.js +186 -235
  138. package/src/folder-trust-wire.js +137 -0
  139. package/src/folder-trust-worker.js +17 -0
  140. package/src/folder-trust.js +1572 -0
  141. package/src/freshness/activity-meter.js +101 -0
  142. package/src/freshness/adapter.js +199 -0
  143. package/src/freshness/checks.js +239 -0
  144. package/src/freshness/config.js +98 -0
  145. package/src/freshness/core.js +185 -0
  146. package/src/freshness/derive.js +680 -0
  147. package/src/freshness/exchange.js +305 -0
  148. package/src/freshness/file-ledger.js +400 -0
  149. package/src/freshness/grade.js +81 -0
  150. package/src/freshness/hash.js +45 -0
  151. package/src/freshness/inbox.js +163 -0
  152. package/src/freshness/index.js +20 -0
  153. package/src/freshness/investigation.js +474 -0
  154. package/src/freshness/keys.js +177 -0
  155. package/src/freshness/ledger.js +122 -0
  156. package/src/freshness/outbox.js +131 -0
  157. package/src/freshness/policy.js +599 -0
  158. package/src/freshness/queue.js +843 -0
  159. package/src/freshness/read-errors.js +23 -0
  160. package/src/freshness/render.js +153 -0
  161. package/src/freshness/runtime.js +113 -0
  162. package/src/freshness/session-registry-adapter.js +161 -0
  163. package/src/freshness/state-file-adapter.js +167 -0
  164. package/src/freshness-runner/build-info.js +139 -0
  165. package/src/freshness-runner/cli.js +105 -0
  166. package/src/freshness-runner/run-tick.js +109 -0
  167. package/src/freshness-runner/stamp.js +57 -0
  168. package/src/freshness-sources/claude-transcript-adapter.js +211 -0
  169. package/src/freshness-sources/codex-transcript-adapter.js +33 -0
  170. package/src/freshness-sources/index.js +8 -0
  171. package/src/gemini-byok-session.js +292 -0
  172. package/src/gemini-credentials.js +67 -0
  173. package/src/gemini-key-safety.js +246 -0
  174. package/src/gemini-models.js +386 -0
  175. package/src/gemini-session.js +81 -5
  176. package/src/handler-utils.js +540 -80
  177. package/src/handlers/checkpoint-handlers.js +47 -4
  178. package/src/handlers/control-room-handlers.js +51 -11
  179. package/src/handlers/conversation-handlers.js +469 -56
  180. package/src/handlers/daemon-update-handlers.js +81 -0
  181. package/src/handlers/evaluator-handlers.js +14 -1
  182. package/src/handlers/feature-handlers.js +186 -69
  183. package/src/handlers/file-handlers.js +57 -13
  184. package/src/handlers/folder-trust-handlers.js +90 -0
  185. package/src/handlers/input-handlers.js +714 -48
  186. package/src/handlers/orchestration-handlers.js +3 -3
  187. package/src/handlers/principal-admin-handlers.js +229 -0
  188. package/src/handlers/principal-handlers.js +262 -0
  189. package/src/handlers/scheduler-handlers.js +92 -18
  190. package/src/handlers/session-handlers.js +551 -20
  191. package/src/handlers/session-pr-status-handlers.js +283 -0
  192. package/src/handlers/session-pr-threads-handlers.js +247 -0
  193. package/src/handlers/settings-handlers.js +372 -50
  194. package/src/handlers/skills-handlers.js +20 -4
  195. package/src/handlers/summarize-handlers.js +32 -1
  196. package/src/handlers/survey-throttle.js +380 -0
  197. package/src/health-proof.js +40 -0
  198. package/src/history-page.js +112 -0
  199. package/src/http-routes.js +127 -8
  200. package/src/ide/search.js +24 -6
  201. package/src/ide/symbols.js +20 -6
  202. package/src/input-context.js +117 -0
  203. package/src/instruction-policy-compiler.js +229 -0
  204. package/src/instruction-policy.js +250 -0
  205. package/src/jsonl-reader.js +378 -91
  206. package/src/jsonl-subprocess-session.js +96 -9
  207. package/src/keychain.js +1 -1
  208. package/src/logger.js +166 -30
  209. package/src/mailbox-route.js +113 -22
  210. package/src/message-wire.js +386 -0
  211. package/src/model-discovery.js +43 -3
  212. package/src/models.js +1276 -174
  213. package/src/notification-prefs.js +27 -4
  214. package/src/notifications/discord-billing-sink.js +22 -5
  215. package/src/notifications/discord-ci-sink.js +243 -0
  216. package/src/notifications/discord-webhook-client.js +71 -0
  217. package/src/notifications/discord-webhook-sink.js +64 -23
  218. package/src/notifications/expo-push-sink.js +85 -6
  219. package/src/notifications/ready-body.js +16 -5
  220. package/src/ollama-session.js +34 -2
  221. package/src/orchestration/build-manager.js +9 -2
  222. package/src/orchestration/git-ops.js +41 -7
  223. package/src/orchestration/orchestration-manager.js +112 -36
  224. package/src/orchestration/permission-gate.js +17 -2
  225. package/src/orchestration/run-model.js +2 -1
  226. package/src/orchestration/run-record.js +11 -0
  227. package/src/orchestration/turn-driver.js +185 -43
  228. package/src/orphan-reaper.js +470 -0
  229. package/src/outgoing-policy.js +189 -0
  230. package/src/pairing.js +92 -13
  231. package/src/path-hash-trust-ledger.js +642 -25
  232. package/src/permission-deadlines.js +82 -0
  233. package/src/permission-floor.js +1410 -43
  234. package/src/permission-hook.js +180 -69
  235. package/src/permission-manager.js +737 -89
  236. package/src/permission-mode-support.js +35 -0
  237. package/src/permission-resolved-by.js +89 -0
  238. package/src/permission-resolver.js +126 -8
  239. package/src/permission-scope.js +43 -0
  240. package/src/platform.js +315 -47
  241. package/src/preview-ingress.js +54 -0
  242. package/src/preview-target.js +213 -0
  243. package/src/principal-audit.js +189 -0
  244. package/src/principal-binding.js +25 -0
  245. package/src/principal-brakes.js +21 -0
  246. package/src/principal-effect.js +101 -0
  247. package/src/principal-journal.js +905 -0
  248. package/src/principal-kill-switch.js +183 -0
  249. package/src/principal-label.js +5 -0
  250. package/src/principal-pending-permissions.js +177 -0
  251. package/src/principal-policy.js +1094 -0
  252. package/src/principal-sessions-snapshot.js +208 -0
  253. package/src/principal-store.js +488 -0
  254. package/src/principal-subscriptions.js +283 -0
  255. package/src/prompt-evaluator.js +34 -4
  256. package/src/provider-customization.js +180 -0
  257. package/src/providers.js +209 -4
  258. package/src/push.js +30 -4
  259. package/src/question-route-map.js +130 -0
  260. package/src/redaction.js +531 -20
  261. package/src/roster-broadcast.js +186 -0
  262. package/src/scheduled-task-store.js +330 -26
  263. package/src/scheduler.js +368 -11
  264. package/src/sdk-session.js +2114 -188
  265. package/src/server-cli/preview-shutdown.js +22 -0
  266. package/src/server-cli/push-notification-handler.js +17 -3
  267. package/src/server-cli/server-orchestrator.js +28 -5
  268. package/src/server-cli-child.js +33 -18
  269. package/src/server-cli.js +553 -38
  270. package/src/server-identity.js +15 -11
  271. package/src/service.js +396 -25
  272. package/src/session-archive-limits.js +15 -0
  273. package/src/session-archive.js +1029 -0
  274. package/src/session-busy-state.js +72 -0
  275. package/src/session-ci-watcher.js +1099 -0
  276. package/src/session-context.js +7 -2
  277. package/src/session-manager.js +4062 -312
  278. package/src/session-message-history.js +841 -16
  279. package/src/session-name-allocator.js +685 -0
  280. package/src/session-pr-status.js +654 -0
  281. package/src/session-pr-threads.js +271 -0
  282. package/src/session-preset-trust.js +3 -3
  283. package/src/session-preset.js +10 -5
  284. package/src/session-state-persistence.js +94 -17
  285. package/src/session-timeout-manager.js +20 -0
  286. package/src/session-token-store.js +17 -8
  287. package/src/session-wake.js +240 -0
  288. package/src/shell-approval-info.js +2 -2
  289. package/src/shell-approval-store.js +3 -1
  290. package/src/skills-loader.js +7 -4
  291. package/src/skills-manager.js +2 -2
  292. package/src/skills-trust.js +95 -13
  293. package/src/skills-usage.js +2 -3
  294. package/src/snapshots-store.js +2 -3
  295. package/src/statusline.js +100 -29
  296. package/src/summarize-session.js +53 -4
  297. package/src/supervisor.js +22 -11
  298. package/src/sweep-stale-provider-dirs.js +95 -0
  299. package/src/thinking-level-wire.js +39 -0
  300. package/src/thinking-stream.js +179 -0
  301. package/src/tool-result.js +61 -0
  302. package/src/transcript-sources.js +109 -0
  303. package/src/transcript-tasks.js +372 -25
  304. package/src/trusted-file-read.js +302 -0
  305. package/src/tunnel/base.js +0 -8
  306. package/src/tunnel/cloudflare.js +34 -31
  307. package/src/tunnel/index.js +9 -0
  308. package/src/tunnel/preview.js +64 -0
  309. package/src/turn-outcome.js +140 -0
  310. package/src/usage-normalize.js +9 -5
  311. package/src/user-shell-session.js +59 -5
  312. package/src/utils/agent-sdk-version.js +107 -0
  313. package/src/utils/argv-safety.js +770 -0
  314. package/src/utils/auth-cause.js +60 -0
  315. package/src/utils/binary-package-manifest.js +639 -0
  316. package/src/utils/binary-version.js +224 -0
  317. package/src/utils/bounded-regex-worker.js +29 -0
  318. package/src/utils/bounded-regex.js +162 -0
  319. package/src/utils/claude-binary.js +43 -0
  320. package/src/utils/claude-config-dir.js +245 -0
  321. package/src/utils/claude-login-command.js +16 -0
  322. package/src/utils/claude-native-route.js +81 -0
  323. package/src/utils/componentwise-resolver.js +133 -37
  324. package/src/utils/deploy-control-files.js +87 -0
  325. package/src/utils/exec-failure-reason.js +21 -0
  326. package/src/utils/git-repo.js +42 -0
  327. package/src/utils/is-entry-point.js +137 -0
  328. package/src/utils/node-pty-probe.js +95 -0
  329. package/src/utils/node-pty-support.js +118 -0
  330. package/src/utils/opened-file-path.js +167 -0
  331. package/src/utils/path-containment.js +165 -0
  332. package/src/utils/permission-mode-sidecar.js +51 -0
  333. package/src/utils/pid-liveness.js +47 -0
  334. package/src/utils/preflight.js +360 -16
  335. package/src/utils/read-limiter.js +217 -0
  336. package/src/utils/regular-file.js +375 -0
  337. package/src/utils/safe-regex.js +113 -0
  338. package/src/utils/small-file.js +129 -0
  339. package/src/utils/spawn-env.js +189 -4
  340. package/src/utils/stale-session-dirs.js +182 -0
  341. package/src/utils/stat-identity.js +43 -0
  342. package/src/utils/verify-provenance.js +406 -13
  343. package/src/web-task-manager.js +297 -16
  344. package/src/worktree-gc.js +202 -6
  345. package/src/ws-auth.js +163 -31
  346. package/src/ws-broadcaster.js +49 -5
  347. package/src/ws-client-manager.js +24 -1
  348. package/src/ws-client-sender.js +7 -0
  349. package/src/ws-file-ops/browser.js +363 -58
  350. package/src/ws-file-ops/common.js +320 -14
  351. package/src/ws-file-ops/git.js +395 -42
  352. package/src/ws-file-ops/index.js +2 -0
  353. package/src/ws-file-ops/memory.js +137 -35
  354. package/src/ws-file-ops/open-nofollow.js +354 -0
  355. package/src/ws-file-ops/reader.js +571 -113
  356. package/src/ws-forwarding.js +349 -39
  357. package/src/ws-handler-context.js +88 -2
  358. package/src/ws-history.js +1010 -175
  359. package/src/ws-message-handlers.js +25 -1
  360. package/src/ws-permissions.js +307 -37
  361. package/src/ws-schemas.js +5 -0
  362. package/src/ws-server.js +885 -98
  363. package/sidecar/node_modules/.package-lock.json +0 -29
  364. package/sidecar/node_modules/ws/LICENSE +0 -20
  365. package/sidecar/node_modules/ws/README.md +0 -548
  366. package/sidecar/node_modules/ws/browser.js +0 -8
  367. package/sidecar/node_modules/ws/index.js +0 -22
  368. package/sidecar/node_modules/ws/lib/buffer-util.js +0 -131
  369. package/sidecar/node_modules/ws/lib/constants.js +0 -19
  370. package/sidecar/node_modules/ws/lib/event-target.js +0 -292
  371. package/sidecar/node_modules/ws/lib/extension.js +0 -203
  372. package/sidecar/node_modules/ws/lib/limiter.js +0 -55
  373. package/sidecar/node_modules/ws/lib/permessage-deflate.js +0 -528
  374. package/sidecar/node_modules/ws/lib/receiver.js +0 -706
  375. package/sidecar/node_modules/ws/lib/sender.js +0 -602
  376. package/sidecar/node_modules/ws/lib/stream.js +0 -161
  377. package/sidecar/node_modules/ws/lib/subprotocol.js +0 -62
  378. package/sidecar/node_modules/ws/lib/validation.js +0 -152
  379. package/sidecar/node_modules/ws/lib/websocket-server.js +0 -554
  380. package/sidecar/node_modules/ws/lib/websocket.js +0 -1393
  381. package/sidecar/node_modules/ws/package.json +0 -70
  382. package/sidecar/node_modules/ws/wrapper.mjs +0 -21
  383. package/src/dashboard-next/dist/assets/index-C2ipeGlq.js +0 -111
  384. package/src/dashboard-next/dist/assets/index-DM-_dISG.css +0 -1
  385. package/src/dashboard-next/dist/index.html +0 -13
  386. package/src/dashboard-next/node_modules/.vite/vitest/da39a3ee5e6b4b0d3255bfef95601890afd80709/results.json +0 -1
@@ -0,0 +1,685 @@
1
+ /**
2
+ * Project-scoped incrementing session names ("chroxy 7") — the durable allocator.
3
+ *
4
+ * NOT WIRED INTO ANYTHING (slice N1). `SessionManager.createSession` is
5
+ * synchronous, so this module is synchronous end to end.
6
+ *
7
+ * ## No lock. Compare-and-swap on generations.
8
+ *
9
+ * State lives in numbered generations, each with a primary and a mirror copy:
10
+ *
11
+ * <dir>/session-names.g<12-digit gen>.json (primary)
12
+ * <dir>/session-names.g<12-digit gen>.mirror.json (mirror)
13
+ *
14
+ * Each file is `{ version: 1, gen, body, sha256 }`; `sha256` covers a canonical
15
+ * (sorted-key) serialization of `{ version, gen, body }`. Nothing else in the
16
+ * directory is ever parsed.
17
+ *
18
+ * A writer OWNS generation g+1 only if it creates BOTH names itself:
19
+ * 1. write the full text (every byte, short writes looped) to two unique temp
20
+ * files (`session-names.tmp.<pid>.<token>.a|b`, outside the generation
21
+ * pattern) and fsync each;
22
+ * 2. `linkSync(tmpA, primary)` then `linkSync(tmpB, mirror)` — each an atomic
23
+ * create-if-absent. EEXIST on EITHER means another writer owns g+1: unlink
24
+ * whichever of the two names THIS writer created, reload, retry. (A rename
25
+ * would overwrite and let a stale writer reclaim a generation whose other
26
+ * copy was lost.)
27
+ * 3. fsync the directory once, unlink the temps;
28
+ * 4. re-list the directory: if a generation GREATER than g+1 exists, this
29
+ * writer's view was stale (the store moved on and pruned g+1 — an ABA).
30
+ * Unlink our two names and retry; never issue;
31
+ * 5. issue the number only when both links succeeded and the directory fsync
32
+ * was confirmed. Otherwise the number may already be persisted as `next`:
33
+ * it becomes a gap, never a reuse.
34
+ * Contention is bounded (`maxAttempts`, default 8) and returns `contended`.
35
+ * No sleeps, no lock file, no wall clock in mutual exclusion. A filesystem
36
+ * without hard links returns `unsupported_fs` (non-closing, nothing issued).
37
+ * Every outcome after a load (issued, lost, failed) prunes: generations below
38
+ * top-2 and temp files older than 10 minutes are removed; the top three
39
+ * generations are never touched.
40
+ *
41
+ * Two consequences of the two-link publish, both on the safe side:
42
+ * - between a writer's two links a concurrent reader can see two valid copies
43
+ * with different sha256 and fail closed `inconsistent` for that one call;
44
+ * - a crash inside that window, in the lost-copy case, leaves a permanent
45
+ * `inconsistent`: no duplicate is possible, and operator recovery applies.
46
+ *
47
+ * ## Load
48
+ *
49
+ * Every call re-reads the directory (no cache). The highest generation that has
50
+ * any file is the state:
51
+ * - no naming files at all -> fresh (gen 0)
52
+ * - either copy valid -> use it (primary preferred)
53
+ * - both valid, different sha256 -> fail closed: 'inconsistent'
54
+ * - at least one copy present but bad, none valid -> fail closed: 'evidence_lost'
55
+ * - both copies ENOENT after listing (pruned under us) -> re-list, retry
56
+ * - any other read error (EIO, EMFILE, EACCES) -> 'io_error' (non-closing)
57
+ * An older generation is NEVER a fallback. Failing closed returns
58
+ * `{ ok: false, reason }` from allocate and bind and WRITES NOTHING, so corrupt
59
+ * evidence keeps the allocator closed across restarts (callers use their legacy
60
+ * names). Naming files are opened O_RDONLY|O_NONBLOCK|O_NOFOLLOW, fstat'd, and
61
+ * must be regular files of at most MAX_STORE_BYTES, so a FIFO planted at a
62
+ * naming path cannot block the daemon.
63
+ *
64
+ * ## Guarantee (narrowed on purpose)
65
+ *
66
+ * A number issued for a key is never issued again for that key while at least
67
+ * one durable copy of the generation that recorded it, or of any later
68
+ * generation, survives intact. If both copies of the highest generation are
69
+ * invalid, numbered allocation fails closed (callers use legacy names) and the
70
+ * allocator writes nothing until an operator removes the naming files. If all
71
+ * naming files are deleted, that is indistinguishable from first use: numbering
72
+ * restarts above the highest number in LIVE session names, and numbers that
73
+ * belonged only to deleted sessions or unused allocations may be issued again —
74
+ * this case is outside the guarantee.
75
+ *
76
+ * On win32 the guarantee holds across process crashes and restarts; durability
77
+ * of directory entries against POWER LOSS is not confirmed (the directory fsync
78
+ * is skipped there, and `writeFileRestricted` assumes rename is write-through).
79
+ *
80
+ * ## Operator recovery from a fail-closed state
81
+ *
82
+ * Stop the daemon and remove every `session-names.*` file in the config dir,
83
+ * then start it again. Accepted cost: numbers may repeat those of sessions that
84
+ * no longer exist. There is no lock and no stale-lock state to clean up.
85
+ *
86
+ * ## Other behaviour
87
+ *
88
+ * - Live floor: n = max(stored next, highest live "<key> <n>" + 1). Live
89
+ * numbers that are not safe integers or exceed 1,000,000 are ignored, so a
90
+ * user-typed "chroxy 99999999999" cannot exhaust a project.
91
+ * - Idempotency records (<= 512, <= 24 h by `now`, ordered by a persisted
92
+ * monotonic `seq`, never by wall clock) store key, canonical root, number and
93
+ * bound session. A retry of an unbound key returns the same number but ONLY
94
+ * after a new generation carrying it was published and confirmed. A key reused
95
+ * for a different project or root is refused, never remapped. Expiry (24 h) is
96
+ * applied BEFORE lookup, so a retry of an expired key is a new key; a clock
97
+ * that moves backwards never drops a fresh record.
98
+ * - The serialized size is checked BEFORE publishing against MAX_STORE_BYTES.
99
+ * Over budget: idempotency records are evicted oldest-seq first (never the
100
+ * current one); still over -> 'store_full' (non-closing, nothing written).
101
+ * - Numbers stop at MAX_SAFE_INTEGER - 1, and generations at 999999999999
102
+ * ('exhausted', nothing written).
103
+ * - `body.projects` is deliberately unbounded: after roughly 3,000 distinct
104
+ * projects, new projects get `store_full` while existing ones keep allocating.
105
+ * - A candidate name is checked against every live name; collisions are skipped
106
+ * (at most 64) and then fail with `live_collision` (non-closing).
107
+ * - Cost: every call is SYNCHRONOUS disk work on the caller's thread. Measured on a laptop:
108
+ * about 15 ms per allocation against an empty store, about 28 ms near the size budget, and
109
+ * 27-57 ms for a create that carries an idempotency key, because the follow-up `bind` publishes
110
+ * a second generation. A bind is not folded into the allocation's own publish on purpose: a
111
+ * record must only become "bound" once the session really exists, or a retry of a create that
112
+ * failed in between would burn a fresh number instead of reusing its reservation.
113
+ * - Nothing here throws for I/O or corruption problems; those return
114
+ * `{ ok: false, reason }`. Only bad arguments throw (programming errors).
115
+ */
116
+
117
+ import { createHash, randomBytes } from 'node:crypto'
118
+ import {
119
+ closeSync, constants as fsConstants, fstatSync, fsyncSync, linkSync, mkdirSync, openSync, readdirSync,
120
+ readSync, statSync, unlinkSync, writeSync,
121
+ } from 'node:fs'
122
+ import { join } from 'node:path'
123
+ import { canonicalProjectForCwd } from '@chroxy/protocol/project'
124
+ import { configDir } from './config-dir.js'
125
+
126
+ export const MAX_STORE_BYTES = 1024 * 1024
127
+
128
+ const VERSION = 1
129
+ const MAX_LABEL_CODE_POINTS = 64
130
+ const MAX_ROOT_CODE_POINTS = 512
131
+ const MAX_SESSION_ID_LEN = 128
132
+ const MAX_IDEM_KEY_LEN = 256
133
+ const MAX_KEYS = 512
134
+ const KEY_TTL_MS = 24 * 60 * 60 * 1000
135
+ const MAX_LIVE_NUMBER = 1_000_000
136
+ const DEFAULT_MAX_ATTEMPTS = 8
137
+ const KEEP_GENERATIONS = 3
138
+ const TMP_PREFIX = 'session-names.tmp.'
139
+ const TMP_STALE_MS = 10 * 60 * 1000
140
+ const FILE_RE = /^session-names\.g(\d{12})(\.mirror)?\.json$/
141
+ const MAX_GEN = 999_999_999_999
142
+ const MAX_LIVE_SKIPS = 64
143
+
144
+ const O_NONBLOCK = fsConstants.O_NONBLOCK ?? 0
145
+ const O_NOFOLLOW = fsConstants.O_NOFOLLOW ?? 0
146
+
147
+
148
+ const genName = (gen, mirror) => `session-names.g${String(gen).padStart(12, '0')}${mirror ? '.mirror' : ''}.json`
149
+
150
+ /** Read a naming file without ever blocking; non-regular or oversized files are refused. */
151
+ function defaultReadFile(path, maxBytes = MAX_STORE_BYTES) {
152
+ const fd = openSync(path, fsConstants.O_RDONLY | O_NONBLOCK | O_NOFOLLOW)
153
+ try {
154
+ const st = fstatSync(fd)
155
+ if (!st.isFile() || st.size > maxBytes) {
156
+ const err = new Error('naming file is not a regular file or is oversized')
157
+ err.code = 'ECHROXY_BADFILE'
158
+ throw err
159
+ }
160
+ const buf = Buffer.alloc(st.size)
161
+ let off = 0
162
+ while (off < st.size) {
163
+ const n = readSync(fd, buf, off, st.size - off, off)
164
+ if (n <= 0) break
165
+ off += n
166
+ }
167
+ return buf.subarray(0, off).toString('utf8')
168
+ } finally {
169
+ closeSync(fd)
170
+ }
171
+ }
172
+
173
+ /** fsync a directory so a new entry survives power loss. Not possible on win32. */
174
+ function defaultSyncDir(dir) {
175
+ if (process.platform === 'win32') return
176
+ const fd = openSync(dir, fsConstants.O_RDONLY)
177
+ try {
178
+ fsyncSync(fd)
179
+ } finally {
180
+ closeSync(fd)
181
+ }
182
+ }
183
+
184
+ /** Sorted-key JSON, so the digest does not depend on property order. */
185
+ function canonicalJson(value) {
186
+ if (Array.isArray(value)) return `[${value.map(canonicalJson).join(',')}]`
187
+ if (value && typeof value === 'object') {
188
+ return `{${Object.keys(value).sort().map((k) => `${JSON.stringify(k)}:${canonicalJson(value[k])}`).join(',')}}`
189
+ }
190
+ return JSON.stringify(value)
191
+ }
192
+
193
+ function digest(version, gen, body) {
194
+ return createHash('sha256').update(canonicalJson({ version, gen, body })).digest('hex')
195
+ }
196
+
197
+ /** Label normalization: NFC, whitespace collapsed, control chars stripped, 64 code-point cap. */
198
+ export function normalizeLabel(raw) {
199
+ if (typeof raw !== 'string') return ''
200
+ let s = raw.normalize('NFC').replace(/\s+/gu, ' ')
201
+ s = s.replace(/\p{Cc}/gu, '')
202
+ s = Array.from(s.trim()).slice(0, MAX_LABEL_CODE_POINTS).join('')
203
+ return s.trim().normalize('NFC')
204
+ }
205
+
206
+ /**
207
+ * Is `name` an allocator-style name ("<label> <n>") for the project that `cwd` belongs to?
208
+ * Used to tell a name this module handed out from one a person typed.
209
+ */
210
+ export function isAllocatorNameForCwd(name, cwd) {
211
+ if (typeof name !== 'string' || typeof cwd !== 'string' || cwd.length === 0) return false
212
+ let project
213
+ try {
214
+ project = canonicalProjectForCwd(cwd)
215
+ } catch {
216
+ return false
217
+ }
218
+ if (!project) return false
219
+ const label = normalizeLabel(project.label)
220
+ if (!label) return false
221
+ const key = keyForLabel(label)
222
+ return new RegExp(`^${escapeRegExp(key)} \\d+$`).test(name.normalize('NFC').toLowerCase())
223
+ }
224
+
225
+ export function keyForLabel(label) {
226
+ return label.normalize('NFC').toLowerCase()
227
+ }
228
+
229
+ function escapeRegExp(s) {
230
+ return s.replace(/[.*+?^${}()|[\]\\]/g, '\\$&')
231
+ }
232
+
233
+ const isInt = (v) => Number.isSafeInteger(v) && v >= 1
234
+ const isObj = (v) => v !== null && typeof v === 'object' && !Array.isArray(v)
235
+
236
+ function validBody(body) {
237
+ if (!isObj(body) || !isObj(body.projects) || !isObj(body.keys)) return false
238
+ if (!Number.isSafeInteger(body.seq) || body.seq < 0) return false
239
+ for (const [k, p] of Object.entries(body.projects)) {
240
+ if (k.length > MAX_LABEL_CODE_POINTS * 2) return false
241
+ if (!isObj(p) || typeof p.label !== 'string' || typeof p.root !== 'string' || !isInt(p.next)) return false
242
+ }
243
+ for (const [id, e] of Object.entries(body.keys)) {
244
+ if (id.length > MAX_IDEM_KEY_LEN) return false
245
+ if (!isObj(e) || typeof e.key !== 'string' || !/^[0-9a-f]{64}$/.test(e.rootId) || !isInt(e.n)) return false
246
+ if (!(e.sessionId === null || (typeof e.sessionId === 'string' && e.sessionId.length <= MAX_SESSION_ID_LEN))) return false
247
+ if (typeof e.at !== 'number' || !Number.isFinite(e.at) || !Number.isSafeInteger(e.seq) || e.seq < 0) return false
248
+ }
249
+ return true
250
+ }
251
+
252
+ /** Reasons a naming path is "present but not usable" (as opposed to a transient I/O error). */
253
+ const BAD_FILE_CODES = new Set(['ECHROXY_BADFILE', 'ELOOP', 'EISDIR'])
254
+
255
+ /** @returns {{state:'absent'}|{state:'error'}|{state:'invalid'}|{state:'valid',gen:number,sha256:string,body:object}} */
256
+ function readCopy(path, gen, readFile) {
257
+ let text
258
+ try {
259
+ text = readFile(path, MAX_STORE_BYTES)
260
+ } catch (err) {
261
+ if (err?.code === 'ENOENT') return { state: 'absent' }
262
+ return BAD_FILE_CODES.has(err?.code) ? { state: 'invalid' } : { state: 'error' }
263
+ }
264
+ try {
265
+ const doc = JSON.parse(text)
266
+ if (!isObj(doc) || doc.version !== VERSION || doc.gen !== gen || typeof doc.sha256 !== 'string') return { state: 'invalid' }
267
+ if (!validBody(doc.body)) return { state: 'invalid' }
268
+ if (digest(doc.version, doc.gen, doc.body) !== doc.sha256) return { state: 'invalid' }
269
+ return { state: 'valid', gen: doc.gen, sha256: doc.sha256, body: doc.body }
270
+ } catch {
271
+ return { state: 'invalid' }
272
+ }
273
+ }
274
+
275
+ const emptyBody = () => ({ projects: {}, keys: {}, seq: 0 })
276
+ const own = (obj, k) => Object.prototype.hasOwnProperty.call(obj, k)
277
+ // Plain `obj[k] = v` with k === '__proto__' would rewrite the prototype, not add a key.
278
+ const setOwn = (obj, k, v) => Object.defineProperty(obj, k, { value: v, enumerable: true, writable: true, configurable: true })
279
+
280
+ /**
281
+ * @param {object} opts
282
+ * @param {string} [opts.dir] defaults to the config dir (honours CHROXY_CONFIG_DIR)
283
+ * @param {() => string[]} [opts.liveNames] names of sessions that exist right now
284
+ * @param {() => number} [opts.now] wall clock (idempotency TTL only)
285
+ * @param {{warn?:Function,error?:Function,info?:Function}} [opts.log]
286
+ * @param {number} [opts.maxAttempts] bound on CAS retries
287
+ * @param {object} [opts.deps] test seams: readFile, readdir, linkSync, syncDir, writeSync, onSerialize,
288
+ * afterLoad, maxBytes
289
+ */
290
+ export function createSessionNameAllocator({
291
+ dir = configDir(),
292
+ liveNames = () => [],
293
+ now = Date.now,
294
+ log = {},
295
+ maxAttempts = DEFAULT_MAX_ATTEMPTS,
296
+ deps = {},
297
+ } = {}) {
298
+ const readFile = deps.readFile ?? defaultReadFile
299
+ const link = deps.linkSync ?? linkSync
300
+ const syncDir = deps.syncDir ?? defaultSyncDir
301
+ const writeBytes = deps.writeSync ?? ((fd, buf, off, len) => writeSync(fd, buf, off, len))
302
+ const listDir = deps.readdir ?? readdirSync
303
+ const afterLoad = deps.afterLoad ?? null
304
+ // The budget can be tightened for tests but never loosened past what a load will accept.
305
+ const maxBytes = Math.min(deps.maxBytes ?? MAX_STORE_BYTES, MAX_STORE_BYTES)
306
+
307
+ // A refused git config makes the project fall back to legacy names: say so once per root.
308
+ const onRefuse = ({ reason, dir: where }) => {
309
+ const k = `${where}\u0000${reason}`
310
+ if (loggedRefusals.has(k)) return
311
+ loggedRefusals.add(k)
312
+ emit('warn', `session names: ${where} fell back to legacy naming (${reason}); its git config is outside the supported subset`, { reason, dir: where })
313
+ }
314
+
315
+ // Once per allocator per (dir, reason): a closed allocator is polled on every create.
316
+ const loggedFailClosed = new Set()
317
+ const loggedRefusals = new Set()
318
+
319
+ const emit = (level, msg, fields) => {
320
+ try {
321
+ log?.[level]?.(msg, fields)
322
+ } catch { /* a broken logger must not break allocation */ }
323
+ }
324
+
325
+ const listGens = () => {
326
+ const gens = new Map()
327
+ for (const name of listDir(dir)) {
328
+ const m = FILE_RE.exec(name)
329
+ if (!m) continue
330
+ const g = Number(m[1])
331
+ if (!Number.isSafeInteger(g) || g < 1) continue
332
+ const slot = gens.get(g) ?? { primary: false, mirror: false }
333
+ if (m[2]) slot.mirror = true
334
+ else slot.primary = true
335
+ gens.set(g, slot)
336
+ }
337
+ return gens
338
+ }
339
+
340
+ // ---- evidence -------------------------------------------------------
341
+ const load = () => {
342
+ let gens
343
+ try {
344
+ gens = listGens()
345
+ } catch (err) {
346
+ if (err?.code === 'ENOENT') return { kind: 'ok', gen: 0, body: emptyBody() }
347
+ return { kind: 'error', reason: 'io_error' }
348
+ }
349
+ if (gens.size === 0) return { kind: 'ok', gen: 0, body: emptyBody() }
350
+ const top = Math.max(...gens.keys())
351
+ const a = readCopy(join(dir, genName(top, false)), top, readFile)
352
+ const b = readCopy(join(dir, genName(top, true)), top, readFile)
353
+ // Both gone: the store advanced and pruned this generation after we listed. Not corruption.
354
+ if (a.state === 'absent' && b.state === 'absent') return { kind: 'retry' }
355
+ const valid = [a, b].filter((c) => c.state === 'valid')
356
+ if (valid.length === 0) {
357
+ if (a.state === 'error' || b.state === 'error') return { kind: 'error', reason: 'io_error' }
358
+ return { kind: 'closed', reason: 'evidence_lost' }
359
+ }
360
+ if (valid.length === 2 && a.sha256 !== b.sha256) return { kind: 'closed', reason: 'inconsistent' }
361
+ return { kind: 'ok', gen: top, body: structuredClone(valid[0].body) }
362
+ }
363
+
364
+ const failClosed = (reason) => {
365
+ const k = `${dir}\u0000${reason}`
366
+ if (!loggedFailClosed.has(k)) {
367
+ loggedFailClosed.add(k)
368
+ emit('error', `session-name allocator closed (${reason}); numbered names disabled until the session-names.* files in ${dir} are removed`, { reason })
369
+ }
370
+ return { ok: false, reason }
371
+ }
372
+
373
+ const serialize = (gen, body) => {
374
+ deps.onSerialize?.()
375
+ return JSON.stringify({ version: VERSION, gen, body, sha256: digest(VERSION, gen, body) })
376
+ }
377
+
378
+ /**
379
+ * Fit the serialized store into the budget by evicting idempotency records, oldest seq first,
380
+ * never `keep`. The excess is worked out from per-record sizes and ONE batch is evicted, then
381
+ * the exact size is checked once (a re-serialization of a near-cap store costs tens of ms, so
382
+ * it must not happen once per evicted record). Returns the final text, or null (store_full).
383
+ */
384
+ const fitBudget = (gen, body, keep) => {
385
+ let text = serialize(gen, body)
386
+ let size = Buffer.byteLength(text)
387
+ if (size <= maxBytes) return text
388
+ const victims = Object.entries(body.keys)
389
+ .filter(([id]) => id !== keep)
390
+ .sort((x, y) => x[1].seq - y[1].seq)
391
+ .map(([id, e]) => ({ id, bytes: Buffer.byteLength(JSON.stringify(id)) + Buffer.byteLength(JSON.stringify(e)) + 2 }))
392
+ let next = 0
393
+ while (size > maxBytes) {
394
+ if (next >= victims.length) return null
395
+ let excess = size - maxBytes
396
+ while (excess > 0 && next < victims.length) {
397
+ const v = victims[next++]
398
+ delete body.keys[v.id]
399
+ excess -= v.bytes
400
+ }
401
+ // `excess` is an estimate (separators, the digest is fixed width): confirm exactly, and
402
+ // if it fell short the loop evicts a further batch.
403
+ text = serialize(gen, body)
404
+ size = Buffer.byteLength(text)
405
+ }
406
+ return text
407
+ }
408
+
409
+ const tryUnlink = (p) => {
410
+ try { unlinkSync(p) } catch { /* ignore */ }
411
+ }
412
+
413
+ /** Write every byte (looping over short writes) to a fresh file and fsync it. */
414
+ const writeTemp = (path, buf) => {
415
+ let fd
416
+ try {
417
+ fd = openSync(path, 'wx', 0o600)
418
+ let off = 0
419
+ while (off < buf.length) {
420
+ const n = writeBytes(fd, buf, off, buf.length - off)
421
+ if (!Number.isInteger(n) || n <= 0 || n > buf.length - off) throw new Error('incomplete write')
422
+ off += n
423
+ }
424
+ fsyncSync(fd)
425
+ const done = fd
426
+ fd = undefined
427
+ closeSync(done)
428
+ } catch (err) {
429
+ if (fd !== undefined) try { closeSync(fd) } catch { /* ignore */ }
430
+ tryUnlink(path)
431
+ throw err
432
+ }
433
+ }
434
+
435
+ /**
436
+ * Publish `text` as generation `gen` by creating BOTH names. Returns 'won' | 'lost'
437
+ * (another writer owns it, or a stale view) | 'unsupported' | 'error'.
438
+ */
439
+ const publish = (gen, text) => {
440
+ const buf = Buffer.from(text)
441
+ const primary = join(dir, genName(gen, false))
442
+ const mirror = join(dir, genName(gen, true))
443
+ const token = `${process.pid}.${randomBytes(6).toString('hex')}`
444
+ const tmpA = join(dir, `${TMP_PREFIX}${token}.a`)
445
+ const tmpB = join(dir, `${TMP_PREFIX}${token}.b`)
446
+ const dropTemps = () => {
447
+ tryUnlink(tmpA)
448
+ tryUnlink(tmpB)
449
+ }
450
+ try {
451
+ writeTemp(tmpA, buf)
452
+ writeTemp(tmpB, buf)
453
+ } catch (err) {
454
+ emit('warn', `session-name temp write failed: ${err?.message ?? err}`, { reason: 'write_unconfirmed' })
455
+ dropTemps()
456
+ return 'error'
457
+ }
458
+ const classify = (err) => {
459
+ if (err?.code === 'EEXIST') return 'lost'
460
+ if (err?.code === 'EPERM' || err?.code === 'ENOTSUP' || err?.code === 'EOPNOTSUPP' || err?.code === 'ENOSYS') return 'unsupported'
461
+ emit('warn', `session-name publish failed: ${err?.message ?? err}`, { reason: 'write_unconfirmed' })
462
+ return 'error'
463
+ }
464
+ try {
465
+ link(tmpA, primary)
466
+ } catch (err) {
467
+ dropTemps()
468
+ return classify(err)
469
+ }
470
+ try {
471
+ link(tmpB, mirror)
472
+ } catch (err) {
473
+ dropTemps()
474
+ // EEXIST: another writer owns this generation's mirror, so our primary is a loser's debris
475
+ // and is retracted. Any OTHER failure leaves the primary where it is: it may already have
476
+ // been read (and built upon) by a concurrent writer, and retracting a visible generation
477
+ // lets a stale writer re-create it and issue a number the later generation never saw. A
478
+ // primary-only generation is valid under the load rules; the number becomes a gap.
479
+ if (err?.code === 'EEXIST') tryUnlink(primary)
480
+ return classify(err)
481
+ }
482
+ dropTemps()
483
+ try {
484
+ syncDir(dir)
485
+ } catch (err) {
486
+ emit('warn', `session-name directory fsync failed: ${err?.message ?? err}`, { reason: 'write_unconfirmed' })
487
+ return 'error'
488
+ }
489
+ // ABA guard: a newer generation means our view was stale and g+1 had been pruned.
490
+ try {
491
+ if (Math.max(...listGens().keys()) > gen) {
492
+ tryUnlink(primary)
493
+ tryUnlink(mirror)
494
+ return 'lost'
495
+ }
496
+ } catch {
497
+ // Both names exist and may be visible: never retract them. Unconfirmed; the number is a gap.
498
+ return 'error'
499
+ }
500
+ return 'won'
501
+ }
502
+
503
+ /** Remove generations below top-2 and stale temp files. Never touches the top three. */
504
+ const prune = () => {
505
+ try {
506
+ const names = readdirSync(dir)
507
+ let top = 0
508
+ for (const name of names) {
509
+ const m = FILE_RE.exec(name)
510
+ if (m) top = Math.max(top, Number(m[1]))
511
+ }
512
+ for (const name of names) {
513
+ const m = FILE_RE.exec(name)
514
+ if (m) {
515
+ if (Number(m[1]) < top - (KEEP_GENERATIONS - 1)) tryUnlink(join(dir, name))
516
+ } else if (name.startsWith(TMP_PREFIX)) {
517
+ try {
518
+ if (Date.now() - statSync(join(dir, name)).mtimeMs > TMP_STALE_MS) tryUnlink(join(dir, name))
519
+ } catch { /* ignore */ }
520
+ }
521
+ }
522
+ } catch { /* ignore */ }
523
+ }
524
+
525
+ /**
526
+ * The CAS loop. `step(state)` returns { done: result } to stop without writing, or
527
+ * { body, keep, result } to publish body as the next generation and return result once durable.
528
+ */
529
+ const transact = (step) => {
530
+ try {
531
+ mkdirSync(dir, { recursive: true, mode: 0o700 })
532
+ } catch {
533
+ return { ok: false, reason: 'io_error' }
534
+ }
535
+ for (let attempt = 0; attempt < maxAttempts; attempt++) {
536
+ const state = load()
537
+ if (state.kind === 'retry') continue
538
+ if (state.kind === 'closed') return failClosed(state.reason)
539
+ if (state.kind === 'error') return { ok: false, reason: state.reason }
540
+ afterLoad?.({ gen: state.gen, attempt })
541
+ const plan = step(state)
542
+ if (plan.done) return plan.done
543
+ const gen = state.gen + 1
544
+ if (gen > MAX_GEN) return { ok: false, reason: 'exhausted' }
545
+ const text = fitBudget(gen, plan.body, plan.keep)
546
+ if (text === null) return { ok: false, reason: 'store_full' }
547
+ const outcome = publish(gen, text)
548
+ prune()
549
+ if (outcome === 'lost') continue
550
+ if (outcome === 'unsupported') return { ok: false, reason: 'unsupported_fs' }
551
+ if (outcome === 'error') return { ok: false, reason: 'write_unconfirmed' }
552
+ return plan.result
553
+ }
554
+ return { ok: false, reason: 'contended' }
555
+ }
556
+
557
+ /** TTL expiry (by wall clock, applied before lookup). Backwards clocks never expire anything. */
558
+ const expire = (body) => {
559
+ const t = now()
560
+ for (const [id, e] of Object.entries(body.keys)) {
561
+ if (t - e.at > KEY_TTL_MS) delete body.keys[id]
562
+ }
563
+ }
564
+
565
+ /** Keep the newest MAX_KEYS records by seq, always retaining `keep`. */
566
+ const capKeys = (body, keep) => {
567
+ const ids = Object.keys(body.keys)
568
+ if (ids.length <= MAX_KEYS) return
569
+ const victims = ids.filter((id) => id !== keep).sort((x, y) => body.keys[x].seq - body.keys[y].seq)
570
+ for (const id of victims.slice(0, ids.length - MAX_KEYS)) delete body.keys[id]
571
+ }
572
+
573
+ // ---- API ------------------------------------------------------------
574
+ function allocate({ cwd, idempotencyKey } = {}) {
575
+ if (typeof cwd !== 'string' || cwd.length === 0) throw new TypeError('allocate: cwd must be a non-empty string')
576
+ if (idempotencyKey !== undefined && (typeof idempotencyKey !== 'string' || idempotencyKey.length === 0 || idempotencyKey.length > MAX_IDEM_KEY_LEN)) {
577
+ throw new TypeError('allocate: idempotencyKey must be a non-empty string up to 256 chars')
578
+ }
579
+ let project
580
+ try {
581
+ project = canonicalProjectForCwd(cwd, undefined, onRefuse)
582
+ } catch {
583
+ project = null
584
+ }
585
+ if (!project) return { ok: false, reason: 'non_project' }
586
+ const label = normalizeLabel(project.label)
587
+ if (!label) return { ok: false, reason: 'non_project' }
588
+ const key = keyForLabel(label)
589
+ const root = Array.from(project.root).slice(0, MAX_ROOT_CODE_POINTS).join('')
590
+ // Identity of the FULL realpath: two roots sharing a 512-code-point prefix must not collide.
591
+ const rootId = createHash('sha256').update(project.root).digest('hex')
592
+
593
+ try {
594
+ return transact((state) => {
595
+ let live
596
+ try {
597
+ live = Array.from(liveNames() ?? [], (n) => String(n).normalize('NFC').toLowerCase())
598
+ } catch {
599
+ return { done: { ok: false, reason: 'live_names_failed' } }
600
+ }
601
+ const liveSet = new Set(live)
602
+ const re = new RegExp(`^${escapeRegExp(key)} (\\d+)$`)
603
+ let floor = 0
604
+ for (const name of live) {
605
+ const m = re.exec(name)
606
+ if (!m) continue
607
+ const v = Number(m[1])
608
+ if (!Number.isSafeInteger(v) || v > MAX_LIVE_NUMBER) continue // a typed-in huge number must not exhaust the project
609
+ if (v > floor) floor = v
610
+ }
611
+
612
+ const body = state.body
613
+ expire(body)
614
+ const result = (n) => ({ ok: true, name: `${label} ${n}`, label, number: n, key })
615
+ const entry = idempotencyKey !== undefined && own(body.keys, idempotencyKey) ? body.keys[idempotencyKey] : null
616
+ // The same key for another project or root is a conflict only while the reservation is
617
+ // still open. A BOUND record is spent: the key is simply reused (agent-control retries
618
+ // across reconnects with one requestId), and the record is replaced like any other.
619
+ const differs = entry && (entry.key !== key || entry.rootId !== rootId)
620
+ if (differs && entry.sessionId === null) {
621
+ return { done: { ok: false, reason: 'idempotency_key_conflict' } }
622
+ }
623
+
624
+ if (entry && !differs) {
625
+ const held = liveSet.has(`${key} ${entry.n}`)
626
+ if (entry.sessionId === null && !held) {
627
+ // A retry of a create whose number was never bound: same number, but only after
628
+ // a fresh generation carrying it is confirmed durable in both copies.
629
+ return { body, keep: idempotencyKey, result: result(entry.n) }
630
+ }
631
+ emit('warn', `duplicate_create_request: idempotency key already ${entry.sessionId !== null ? 'bound to a session' : 'held by a live session'}; allocating a fresh number`, {
632
+ reason: 'duplicate_create_request', key, n: entry.n,
633
+ })
634
+ }
635
+
636
+ const stored = own(body.projects, key) ? body.projects[key].next : 1
637
+ let n = Math.max(stored, floor + 1)
638
+ // The floor ignores huge live numbers, but the name itself must still never duplicate a live one.
639
+ let skips = 0
640
+ while (liveSet.has(`${key} ${n}`)) {
641
+ if (++skips > MAX_LIVE_SKIPS) return { done: { ok: false, reason: 'live_collision' } }
642
+ n += 1
643
+ }
644
+ if (n >= Number.MAX_SAFE_INTEGER) return { done: { ok: false, reason: 'exhausted' } }
645
+ setOwn(body.projects, key, { label, root, next: n + 1 })
646
+ if (idempotencyKey !== undefined) {
647
+ body.seq += 1
648
+ setOwn(body.keys, idempotencyKey, { key, rootId, n, sessionId: null, at: now(), seq: body.seq })
649
+ capKeys(body, idempotencyKey)
650
+ }
651
+ return { body, keep: idempotencyKey, result: result(n) }
652
+ })
653
+ } catch (err) {
654
+ emit('error', `session-name allocator internal error: ${err?.message ?? err}`, { reason: 'internal_error' })
655
+ return { ok: false, reason: 'internal_error' }
656
+ }
657
+ }
658
+
659
+ function bind(idempotencyKey, sessionId, { number } = {}) {
660
+ if (typeof idempotencyKey !== 'string' || idempotencyKey.length === 0) throw new TypeError('bind: idempotencyKey must be a non-empty string')
661
+ if (typeof sessionId !== 'string' || sessionId.length === 0 || sessionId.length > MAX_SESSION_ID_LEN) {
662
+ throw new TypeError('bind: sessionId must be a non-empty string up to 128 chars')
663
+ }
664
+ if (!isInt(number)) throw new TypeError('bind: { number } (the reserved number being bound) is required')
665
+ try {
666
+ return transact((state) => {
667
+ const body = state.body
668
+ expire(body)
669
+ if (!own(body.keys, idempotencyKey)) return { done: { ok: false, reason: 'unknown_key' } }
670
+ const entry = body.keys[idempotencyKey]
671
+ // A delayed bind must not attach to a replacement reservation for the same key.
672
+ if (entry.n !== number) return { done: { ok: false, reason: 'stale_reservation' } }
673
+ if (entry.sessionId !== null && entry.sessionId !== sessionId) return { done: { ok: false, reason: 'already_bound' } }
674
+ // Same-session retries publish too: `ok` is only ever reported behind a confirmed write.
675
+ entry.sessionId = sessionId
676
+ return { body, keep: idempotencyKey, result: { ok: true } }
677
+ })
678
+ } catch (err) {
679
+ emit('error', `session-name allocator internal error: ${err?.message ?? err}`, { reason: 'internal_error' })
680
+ return { ok: false, reason: 'internal_error' }
681
+ }
682
+ }
683
+
684
+ return { allocate, bind }
685
+ }