@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,23 @@
1
+ /**
2
+ * Which read error codes describe one file that was read, and which describe
3
+ * the source. The only classifier: every consumer asks `isFileLevelReadError`.
4
+ *
5
+ * A code is listed only if it describes one file in every adapter that emits it
6
+ * (`shape_changed` is not: the state-file and registry adapters report it for the
7
+ * whole source). An allowlist, so it fails safe: a code that is not named here (an unknown or
8
+ * future code, a missing one, `unreadable`, `source_missing`, `unsupported`,
9
+ * `adapter_fault`) counts as describing the source, as every error did before
10
+ * the split. The docs guide lists the same codes and a test holds the two
11
+ * lists equal.
12
+ */
13
+ export const FILE_LEVEL_READ_ERRORS = Object.freeze(new Set(['window_exhausted', 'tail_too_small', 'corrupt', 'bad_timestamp']))
14
+
15
+ /** Whether an error code describes the one file that was read, not the source. */
16
+ export function isFileLevelReadError(code) {
17
+ return typeof code === 'string' && FILE_LEVEL_READ_ERRORS.has(code)
18
+ }
19
+
20
+ /** Whether a check state (`outcome`, `errorCode`) is an error that describes the source. */
21
+ export function isSourceLevelError(check) {
22
+ return Boolean(check) && check.outcome === 'error' && !isFileLevelReadError(check.errorCode)
23
+ }
@@ -0,0 +1,153 @@
1
+ /**
2
+ * Templates for the outbox: what an item, the digest, an echo and an alert
3
+ * say. No model writes any of it. Every sentence is fixed here, and the only
4
+ * values put into one are the item's declared-status fields (state, what it is
5
+ * blocked on, the decision, the next step, the owner it names, its time) and
6
+ * the session's source and id, each cleaned and cut to a length first.
7
+ *
8
+ * Nothing here reads a clock: a text names absolute times only, so the same
9
+ * item in the same state renders the same text and an unchanged item is never
10
+ * "updated". Pure functions over the derived state.
11
+ */
12
+
13
+ import { H } from './hash.js'
14
+ import { effectiveState } from './derive.js'
15
+
16
+ const KEY_LEN = 32
17
+
18
+ /** The outbox key of an item's episode: stable, and the same on every restart. */
19
+ export function itemKey(itemId, episode) {
20
+ return H('outbox_key', itemId, episode).slice(0, KEY_LEN)
21
+ }
22
+
23
+ /** The id of one outbox record, from what it is made of. */
24
+ export function recId(...parts) {
25
+ return H('outbox_rec', ...parts).slice(0, KEY_LEN)
26
+ }
27
+
28
+ export const DIGEST_KEY = H('outbox_digest').slice(0, KEY_LEN)
29
+
30
+ export const HEX_ID = new RegExp(`^[0-9a-f]{${KEY_LEN}}$`)
31
+
32
+ /** A value put in a text: one line, no control characters, cut to `max` characters. */
33
+ export function clean(value, max) {
34
+ if (value === null || value === undefined) return ''
35
+ // Control characters and every Unicode format character (bidi overrides and
36
+ // isolates, zero-width characters) become a space.
37
+ // That includes ZWJ and the soft hyphen, so an emoji ZWJ sequence splits: by design,
38
+ // safety in operator-visible text wins over emoji rendering.
39
+ const flat = String(value).replace(/[\u0000-\u001f\u007f-\u009f\u2028\u2029\p{Cf}]+/gu, ' ').replace(/\s+/g, ' ').trim()
40
+ // Cut by code point, so a surrogate pair is never split.
41
+ const points = Array.from(flat)
42
+ return points.length > max ? points.slice(0, Math.max(0, max - 1)).join('') + '…' : flat
43
+ }
44
+
45
+ function iso(ms) {
46
+ return Number.isFinite(ms) ? new Date(ms).toISOString() : 'unknown time'
47
+ }
48
+
49
+ function who(session, max) {
50
+ return session ? `session ${clean(session.source, 64)}/${clean(session.native_id, max)}` : 'a session'
51
+ }
52
+
53
+ function reportOf(state, id) {
54
+ return id ? (state.reports.get(id)?.body ?? null) : null
55
+ }
56
+
57
+ function field(label, value, max) {
58
+ const v = clean(value, max)
59
+ return v ? `${label}: ${v}` : null
60
+ }
61
+
62
+ /** One short line naming an item. */
63
+ export function headline(item, max = 240) {
64
+ const w = who(item.session, max)
65
+ switch (item.origin) {
66
+ case 'owner':
67
+ return `${w} needs the owner`
68
+ case 'attention':
69
+ return `${w} has an old status report`
70
+ case 'gone':
71
+ return `${w} is no longer listed`
72
+ case 'outage':
73
+ return `source ${clean(item.source, 64)} cannot be read`
74
+ case 'seed':
75
+ return `a seed to paste for ${clean(item.seed?.scope, max)}`
76
+ default:
77
+ return `${clean(item.kind, 64)} for ${w}`
78
+ }
79
+ }
80
+
81
+ function ownerLines(state, item, max) {
82
+ const lines = []
83
+ const declared = item.asks.get('declared')
84
+ if (declared) {
85
+ const rep = reportOf(state, declared.report_id)
86
+ lines.push(field('Blocked on', rep?.declared_blocked_on, max), field('Decision', rep?.decision, max), field('Next', rep?.next, max), field('Reported', rep ? iso(rep.last_report_at) : null, max))
87
+ }
88
+ if (item.asks.has('prompt')) lines.push('A prompt is waiting for an answer.')
89
+ return lines
90
+ }
91
+
92
+ function conditionLines(item, max) {
93
+ return item.carried.map((c) => `Also: the status report went stale (${clean(c.trigger, 64)}), since ${iso(c.since)}.`).slice(0, 3).map((l) => clean(l, max * 2))
94
+ }
95
+
96
+ /**
97
+ * The text of an open or closed item, and whether it is open. `title` is
98
+ * the headline the item was first rendered under, kept for the closed text.
99
+ */
100
+ export function renderItem(state, item, { max, title = null, unconfirmed = false } = {}) {
101
+ if (!item.open) {
102
+ const how = item.closedAs ? ` (${clean(item.closedAs.replace(':', ' '), 64)})` : ''
103
+ return { text: `Closed${how}: ${clean(title ?? headline(item, max), max * 2)}`, status: 'closed' }
104
+ }
105
+ const lines = [`${clean(headline(item, max), max * 2)}.`]
106
+ if (item.origin === 'owner') lines.push(...ownerLines(state, item, max), ...conditionLines(item, max))
107
+ else if (item.origin === 'attention' || item.origin === 'gone') {
108
+ const rep = reportOf(state, item.reportId)
109
+ lines.push(field('Last report', rep ? iso(rep.last_report_at) : null, max), field('State', rep?.state, max), field('Trigger', item.condition?.trigger, max))
110
+ } else if (item.origin === 'seed') {
111
+ lines.push(field('Written', item.seed ? iso(item.seed.written_at) : null, max))
112
+ }
113
+ if (item.state === 'acknowledged') lines.push('Marked done; it closes when the next check agrees.')
114
+ if (item.state === 'deferred') lines.push(`Deferred until ${iso(item.deferUntil)}.`)
115
+ if (item.state === 'exhausted') lines.push('No more reminders will be sent.')
116
+ if (unconfirmed) lines.push('Delivery of an earlier message was not confirmed.')
117
+ return { text: lines.filter(Boolean).join('\n'), status: 'open' }
118
+ }
119
+
120
+ /** The line a further delivery of an item starts with. */
121
+ export function stepLine(step, n) {
122
+ if (step === 'reminded') return `Reminder ${n}.`
123
+ if (step === 'returned') return 'Marked done earlier, but the latest status still shows it open.'
124
+ return null
125
+ }
126
+
127
+ /** The digest: one line per open item, in a stable order, cut to `maxItems`. */
128
+ export function renderDigest(state, now, { max, maxItems }) {
129
+ const open = [...state.items.values()].filter((it) => it.open).sort((a, b) => (a.orderTime ?? 0) - (b.orderTime ?? 0) || (a.itemId < b.itemId ? -1 : 1))
130
+ if (open.length === 0) return { text: 'No open items.', count: 0 }
131
+ const lines = [`Open items: ${open.length}.`]
132
+ for (const it of open.slice(0, maxItems)) lines.push(`- ${effectiveState(it, now)}: ${clean(headline(it, max), max * 2)}`)
133
+ if (open.length > maxItems) lines.push(`and ${open.length - maxItems} more.`)
134
+ return { text: lines.join('\n'), count: open.length }
135
+ }
136
+
137
+ export const ECHO = Object.freeze({
138
+ done: (title) => `Noted: marked done, ${title}. It closes when the next check agrees.`,
139
+ dismiss: (title) => `Noted: dismissed, ${title}.`,
140
+ defer: (title, until) => `Noted: deferred until ${iso(until)}, ${title}.`,
141
+ capped: (title) => `Further lines about this item were not applied (too many): ${title}.`,
142
+ refused: (title, reason) => `Not applied (${reason}): ${title}.`,
143
+ })
144
+
145
+ export const ALERT = (title) => `Marked done, but the latest status still shows it open: ${title}. The item stays open.`
146
+
147
+ export const REFUSAL_TEXT = Object.freeze({
148
+ too_long: 'longer than the longest deferral allowed',
149
+ too_many: 'more deferrals than allowed for this item',
150
+ until_not_in_future: 'the time is not in the future',
151
+ not_active: 'the item is not the one waiting for an answer',
152
+ not_dismissable: 'this kind of item cannot be dismissed',
153
+ })
@@ -0,0 +1,113 @@
1
+ /**
2
+ * The driver half of the freshness model: a model context, the `run` loop
3
+ * that executes a planner against it, the configuration record and the list
4
+ * of sessions a tick tracks.
5
+ *
6
+ * A model context is `{ ledger, state, policy }`: the ledger is the durable
7
+ * part, `state` is derived from it (derive.js) and is discarded on a restart,
8
+ * and `policy` is the rule set (policy.js). Planners are generators that
9
+ * yield operations; `run()` executes them against the context. Every
10
+ * outward effect is an operation the driver hands to the caller's `deliver`
11
+ * function; the code here performs none.
12
+ *
13
+ * This is the one implementation. The model tests (tests/freshness) and the
14
+ * file-backed reconciler (core.js) both import it.
15
+ */
16
+
17
+ import { canonical, H } from './hash.js'
18
+ import { deriveState, foldRecord, sessionsOf } from './derive.js'
19
+ import { put } from './checks.js'
20
+ import { append, createLedger, loadLedger } from './ledger.js'
21
+ import { DEFAULT_POLICY } from './policy.js'
22
+ import { configKey, sessionKey } from './keys.js'
23
+
24
+ /** A fresh model context. */
25
+ export function createModel({ ledgerId, policy = DEFAULT_POLICY }) {
26
+ const ledger = createLedger({ ledgerId })
27
+ return { ledger, state: deriveState([], policy), policy }
28
+ }
29
+
30
+ /**
31
+ * Rebuild a context from ledger records alone, as after a crash: the
32
+ * ledger's index and every derived value are recomputed; nothing survives
33
+ * from the previous process.
34
+ */
35
+ export function restoreModel({ ledgerId, records, policy = DEFAULT_POLICY }) {
36
+ const ledger = loadLedger({ ledgerId, records: records.slice() })
37
+ return { ledger, state: deriveState(ledger.records, policy), policy }
38
+ }
39
+
40
+ /**
41
+ * Execute a planner against a context. `deliver(effect)` performs a send
42
+ * and returns 'delivered' or 'failed'. Returns { sends, value }.
43
+ *
44
+ * `appendRecord(draft, at)` is the one place a record is written. It
45
+ * defaults to the in-memory ledger; the file-backed reconciler passes one
46
+ * that also makes the record durable.
47
+ */
48
+ export function run(ctx, gen, { deliver = () => 'delivered', appendRecord = (draft, at) => append(ctx.ledger, draft, at) } = {}) {
49
+ const sends = []
50
+ let res = gen.next()
51
+ while (!res.done) {
52
+ const op = res.value
53
+ let reply
54
+ if (op.op === 'append') {
55
+ reply = appendRecord(op.record, op.at)
56
+ if (reply.record) foldRecord(ctx.state, reply.record)
57
+ } else if (op.op === 'send') {
58
+ sends.push(op.effect)
59
+ reply = deliver(op.effect)
60
+ } else {
61
+ throw new Error(`run: unknown op ${op.op}`)
62
+ }
63
+ res = gen.next(reply)
64
+ }
65
+ return { sends, value: res.value }
66
+ }
67
+
68
+ /** Plan a configuration record. The full values are stored (the DESIGN-GAP note below). */
69
+ export function* planConfig(ctx, { config, now }) {
70
+ const st = ctx.state
71
+ const configHash = H(config)
72
+ const previous = st.lastConfigId
73
+ const id = configKey(previous, configHash)
74
+ if (st.index.has(id)) return { configRef: st.configRef }
75
+ const configRef = 'cfg_' + configHash.slice(0, 12)
76
+ const prevValues = st.config
77
+ const changed = prevValues ? Object.keys(config).filter((k) => canonical(config[k]) !== canonical(prevValues[k])) : Object.keys(config)
78
+ yield put(
79
+ {
80
+ kind: 'config',
81
+ id,
82
+ body: {
83
+ config_ref: configRef,
84
+ previous_config_ref: st.configRef,
85
+ config_hash: configHash,
86
+ changed_fields: changed,
87
+ // DESIGN-GAP: the `config` body carries only a hash and the names of
88
+ // the changed fields, so the thresholds a check was graded under are
89
+ // not derivable from the ledger alone. The model stores the values.
90
+ values: config,
91
+ },
92
+ },
93
+ now,
94
+ )
95
+ return { configRef }
96
+ }
97
+
98
+ /**
99
+ * The sessions a tick of `source` reads: every session the ledger already
100
+ * tracks plus every session the source lists now, in key order. A tracked
101
+ * session the source no longer lists is `listed: false`; when the source
102
+ * cannot be listed at all (`list` returned null) `listed` is null and the
103
+ * session is read anyway, so the read reports the failure.
104
+ */
105
+ export function trackedSessions(ctx, source, world) {
106
+ const listed = world.list(source)
107
+ const out = new Map()
108
+ for (const s of sessionsOf(ctx.state, source)) out.set(s.sk, { session: s.session, scope: s.scope, listed: listed == null ? null : false })
109
+ if (listed) {
110
+ for (const e of listed) out.set(sessionKey(e.session), { session: e.session, scope: e.scope ?? null, listed: true })
111
+ }
112
+ return [...out.entries()].sort((a, b) => (a[0] < b[0] ? -1 : 1)).map(([, v]) => v)
113
+ }
@@ -0,0 +1,161 @@
1
+ /**
2
+ * Adapter over the Claude Code command-line tool's local registry of live
3
+ * sessions: a directory holding one JSON file per live process, named for the
4
+ * process id (`<pid>.json`). It is activity evidence only.
5
+ *
6
+ * A registry row says a session is live and whether it is busy. It is not a
7
+ * status report: this adapter never returns a report, so a session it reads is
8
+ * graded `unknown` (no status line) and can never be `fresh`, whatever the
9
+ * row's time. What it does return is native activity: whether a turn is in
10
+ * flight, and a `registry_busy` or `registry_idle` event timed at the row's
11
+ * `statusUpdatedAt`, with the host application in the event's `ref`.
12
+ *
13
+ * The registry is not a documented interface, so every read is shape-checked
14
+ * and a shape it does not know is `error`, never `idle` and never `no_report`:
15
+ *
16
+ * - only files named `<digits>.json` are read; every other file in the
17
+ * directory is ignored without being opened;
18
+ * - such a file must be a regular file of bounded size holding a JSON object
19
+ * with a `sessionId` (a short token), a `cwd` string, a `status` of `busy`
20
+ * or `idle`, a `statusUpdatedAt` in epoch milliseconds and an `entrypoint`
21
+ * string. Any other value in those fields, an unreadable file or a
22
+ * duplicate `sessionId` makes the whole registry unreadable for that tick;
23
+ * - extra keys are expected (the format is not ours) and ignored.
24
+ *
25
+ * Only `sessionId`, the last path segment of `cwd` (the project), `status`,
26
+ * `statusUpdatedAt` and `entrypoint` are carried out of a row. The session
27
+ * title (`name`) and every other field are never read into a value this module
28
+ * returns, so they cannot reach the ledger. An `entrypoint` that is not a short
29
+ * lowercase token is recorded as `other`; the raw string is not kept.
30
+ *
31
+ * The directory is only read, never written. `list()` takes one snapshot and
32
+ * the `read()` calls that follow answer from it. A directory with no
33
+ * row files is a registry with no live sessions, unless it holds a regular `*.json`
34
+ * file under another name, which is a changed format and reads as `error`.
35
+ *
36
+ * Time: `statusUpdatedAt` is the time the row's status last changed
37
+ * (`report_time_basis` is `none`: there is no report). A row dated further in
38
+ * the future than `MAX_FUTURE_MS` is `error: clock_skew`.
39
+ */
40
+
41
+ import fs from 'node:fs'
42
+ import path from 'node:path'
43
+ import { validSourceName } from './adapter.js'
44
+
45
+ /** The source name the reconciler's configuration must give capabilities for. */
46
+ export const REGISTRY_SOURCE = 'claude-session-registry'
47
+
48
+ /** The capabilities `coreConfig` registers for the registry source: native activity and scope, no report. */
49
+ export const REGISTRY_CAPS = Object.freeze({ native_in_read: true, activity_read: false, scope: true, can_confirm_gone: true, report_time_basis: 'none' })
50
+
51
+ export const REGISTRY_BASES = Object.freeze({ busy: 'registry_busy', idle: 'registry_idle' })
52
+
53
+ const DEFAULT_MAX_FILES = 2000
54
+ const DEFAULT_MAX_FILE_BYTES = 64 * 1024
55
+ const MAX_FUTURE_MS = 5 * 60 * 1000
56
+ // Epoch milliseconds are far above this; epoch seconds are far below it.
57
+ const MIN_EPOCH_MS = 1e11
58
+ const SESSION_ID_RE = /^[A-Za-z0-9][A-Za-z0-9._:-]{0,127}$/
59
+ const ROW_FILE_RE = /^[0-9]{1,10}\.json$/
60
+
61
+ function isPlain(v) {
62
+ return v !== null && typeof v === 'object' && !Array.isArray(v)
63
+ }
64
+
65
+ /** The project a working directory maps to: its last path segment, made safe to store. */
66
+ function projectOf(cwd) {
67
+ const seg = cwd.split(/[\\/]/).filter(Boolean).pop() ?? ''
68
+ const safe = seg.replace(/[^A-Za-z0-9._@+ -]/g, '_').slice(0, 64)
69
+ return safe === '' ? 'root' : safe
70
+ }
71
+
72
+ /** The host application an entrypoint names, or `other`. */
73
+ function appOf(entrypoint) {
74
+ const t = entrypoint.toLowerCase()
75
+ return validSourceName(t) ? t : 'other'
76
+ }
77
+
78
+ /** One row, validated and cut down to the fields this module uses, or null when the shape is not known. */
79
+ function parseRow(doc) {
80
+ if (!isPlain(doc)) return null
81
+ const { sessionId, cwd, status, statusUpdatedAt, entrypoint } = doc
82
+ if (typeof sessionId !== 'string' || !SESSION_ID_RE.test(sessionId)) return null
83
+ if (typeof cwd !== 'string' || cwd === '' || cwd.length > 4096) return null
84
+ if (status !== 'busy' && status !== 'idle') return null
85
+ if (!Number.isSafeInteger(statusUpdatedAt) || statusUpdatedAt < MIN_EPOCH_MS) return null
86
+ if (typeof entrypoint !== 'string' || entrypoint === '' || entrypoint.length > 200) return null
87
+ return { id: sessionId, project: projectOf(cwd), busy: status === 'busy', since: statusUpdatedAt, app: appOf(entrypoint) }
88
+ }
89
+
90
+ /**
91
+ * Take one snapshot of the registry directory: `{ rows }` (a Map from session
92
+ * id to `{ id, project, busy, since, app }`) or `{ error }` with a code.
93
+ */
94
+ export function loadRegistry(dir, { maxFiles = DEFAULT_MAX_FILES, maxFileBytes = DEFAULT_MAX_FILE_BYTES } = {}) {
95
+ let entries
96
+ try {
97
+ entries = fs.readdirSync(dir, { withFileTypes: true })
98
+ } catch (err) {
99
+ if (err?.code === 'ENOTDIR') return { error: 'shape_changed' }
100
+ return { error: err?.code === 'ENOENT' ? 'source_missing' : 'unreachable' }
101
+ }
102
+ const candidates = entries.filter((e) => ROW_FILE_RE.test(e.name))
103
+ if (candidates.length > maxFiles) return { error: 'too_large' }
104
+ // Rows under a name this module does not know are a changed format, not an empty registry.
105
+ if (candidates.length === 0 && entries.some((e) => e.isFile() && e.name.endsWith('.json'))) return { error: 'shape_changed' }
106
+ const rows = new Map()
107
+ for (const e of candidates.sort((a, b) => (a.name < b.name ? -1 : 1))) {
108
+ if (!e.isFile()) return { error: 'shape_changed' }
109
+ let text
110
+ try {
111
+ const file = path.join(dir, e.name)
112
+ if (fs.statSync(file).size > maxFileBytes) return { error: 'too_large' }
113
+ text = fs.readFileSync(file, 'utf8')
114
+ } catch (err) {
115
+ // The process ended between the listing and the read: the row is gone.
116
+ if (err?.code === 'ENOENT') continue
117
+ return { error: 'unreachable' }
118
+ }
119
+ let doc
120
+ try {
121
+ doc = JSON.parse(text)
122
+ } catch {
123
+ return { error: 'parse_failed' }
124
+ }
125
+ const row = parseRow(doc)
126
+ if (row === null || rows.has(row.id)) return { error: 'shape_changed' }
127
+ rows.set(row.id, row)
128
+ }
129
+ return { rows }
130
+ }
131
+
132
+ /**
133
+ * @param {object} opts
134
+ * @param {string} opts.dir the registry directory
135
+ * @param {string} [opts.source] source name (default `claude-session-registry`)
136
+ * @param {number} [opts.maxFiles] refuse a registry with more rows than this
137
+ * @param {number} [opts.maxFileBytes] refuse a larger row file
138
+ */
139
+ export function createSessionRegistryAdapter({ dir, source = REGISTRY_SOURCE, maxFiles, maxFileBytes }) {
140
+ if (typeof dir !== 'string' || dir === '') throw new TypeError('createSessionRegistryAdapter: dir is required')
141
+ if (!validSourceName(source)) throw new TypeError('createSessionRegistryAdapter: source must be a short lowercase name')
142
+ const limits = { maxFiles, maxFileBytes }
143
+ let snapshot = null
144
+ return {
145
+ source,
146
+ list() {
147
+ snapshot = loadRegistry(dir, limits)
148
+ if (snapshot.error) return null
149
+ return [...snapshot.rows.values()].map((r) => ({ session: { source, native_id: r.id, incarnation: null }, scope: r.project }))
150
+ },
151
+ read(session, now) {
152
+ if (!snapshot) snapshot = loadRegistry(dir, limits)
153
+ if (snapshot.error) return { outcome: 'error', error_code: snapshot.error }
154
+ const row = snapshot.rows.get(session.native_id)
155
+ if (!row) return { listed: false }
156
+ if (Number.isFinite(now) && row.since - now > MAX_FUTURE_MS) return { outcome: 'error', error_code: 'clock_skew' }
157
+ const basis = row.busy ? REGISTRY_BASES.busy : REGISTRY_BASES.idle
158
+ return { outcome: 'no_report', native: { turn_in_flight: row.busy, events: [{ basis, ref: row.app, activity_at: row.since }] } }
159
+ },
160
+ }
161
+ }
@@ -0,0 +1,167 @@
1
+ /**
2
+ * Adapter over the daemon's persisted session-state file
3
+ * (`~/.chroxy/session-state.json`, written by `SessionStatePersistence`).
4
+ *
5
+ * It reads declared-status fields and nothing else. Of each persisted session
6
+ * it takes the `id` and the `declaredStatus` object, and of that object the
7
+ * `state`, `next`, `blockedOn`, `decision`, `updatedAt` and `source` fields.
8
+ * Everything else the file holds (names, working directories, history,
9
+ * usage, `summary` text) is never read into a value this module returns, so
10
+ * it cannot reach the ledger.
11
+ *
12
+ * The file is opened read-only and never written. Every read is shape-checked:
13
+ *
14
+ * - the file must be a JSON object with `version: 1` and a `sessions` array
15
+ * whose entries are objects with a unique non-empty string `id`;
16
+ * - a session's `declaredStatus`, when present, must satisfy the daemon's
17
+ * own strict `DeclaredStatusSchema` (an unknown key is a changed shape);
18
+ * - an entry with no `declaredStatus` must still look like one the daemon
19
+ * wrote (it always writes `sdkSessionId` and `conversationId`) and must
20
+ * not carry a declaration-shaped object under another key. An entry that
21
+ * fails either is a changed shape, so a renamed or restructured field
22
+ * reads as an error. What cannot be told apart is a declaration dropped
23
+ * from an otherwise intact entry: that is a session that never declared.
24
+ *
25
+ * A file that fails the first check cannot be listed (`list()` is null, and
26
+ * every tracked session's read is `error: shape_changed`). A session whose
27
+ * declaration fails the second reads as `error: shape_changed`. A changed
28
+ * shape is therefore always an error, never `idle`, never `no_report`.
29
+ *
30
+ * `list()` takes one snapshot of the file; the `read()` calls that follow
31
+ * answer from it, so one tick sees one consistent file.
32
+ *
33
+ * Time: the daemon stamps `updatedAt` when the declaration changes, so the
34
+ * report time is a changed-at time (README: `report_time_basis: changed_at`).
35
+ * A decision carried by such a declaration may be inherited from an earlier
36
+ * one, so it is recorded `possibly_inherited`, never `stated`.
37
+ */
38
+
39
+ import fs from 'node:fs'
40
+ import { DeclaredStatusSchema } from '@chroxy/protocol'
41
+ import { extractDeclaredStatus } from '../declared-status.js'
42
+
43
+ /** The source name the reconciler's configuration must give capabilities for. */
44
+ export const STATE_FILE_SOURCE = 'chroxy-state-file'
45
+
46
+ /** The capabilities `coreConfig` registers for the state-file source. */
47
+ export const STATE_FILE_CAPS = Object.freeze({ native_in_read: false, activity_read: false, scope: false, can_confirm_gone: true, report_time_basis: 'changed_at' })
48
+
49
+ const DEFAULT_MAX_BYTES = 64 * 1024 * 1024
50
+ const DECLARED_VIA = { marker: 'marker', api: 'api', hook: 'hook' }
51
+
52
+ function isPlain(v) {
53
+ return v !== null && typeof v === 'object' && !Array.isArray(v)
54
+ }
55
+
56
+ /** The name after `OWNER:` in a next-step line, or null. */
57
+ function ownerOf(next) {
58
+ if (typeof next !== 'string') return null
59
+ const m = /\bOWNER:\s*(\S.*)$/i.exec(next)
60
+ return m ? m[1].trim() : null
61
+ }
62
+
63
+ /**
64
+ * Map one validated declared status (the daemon's own object) to a report.
65
+ * The same mapping serves a declaration parsed from message text with
66
+ * `extractDeclaredStatus`, which yields the same fields.
67
+ */
68
+ export function reportFromDeclared(declared, { updatedAt, via }) {
69
+ const relayed = via === 'api' || via === 'hook'
70
+ const decision = typeof declared.decision === 'string' && declared.decision !== '' ? declared.decision : null
71
+ return {
72
+ state: declared.state,
73
+ last_report_at: updatedAt,
74
+ declared_via: via,
75
+ next: declared.next ?? null,
76
+ declared_blocked_on: declared.blockedOn ?? null,
77
+ decision: relayed ? null : decision,
78
+ decision_basis: relayed || decision == null ? 'none' : via === 'transcript' ? 'stated' : 'possibly_inherited',
79
+ owner_named: relayed ? null : ownerOf(declared.next),
80
+ seed_ref: null,
81
+ time_trusted: true,
82
+ }
83
+ }
84
+
85
+ /**
86
+ * Parse a status block from one completed message with the daemon's parser
87
+ * (`extractDeclaredStatus`) and map it to a report timed `updatedAt`, or null
88
+ * when the text carries no valid declaration. Used by sources that hold message
89
+ * text rather than the daemon's parsed object.
90
+ */
91
+ export function reportFromText(text, { updatedAt }) {
92
+ const declared = extractDeclaredStatus(text)
93
+ return declared ? reportFromDeclared(declared, { updatedAt, via: 'transcript' }) : null
94
+ }
95
+
96
+ const DECLARATION_STATES = new Set(['running', 'idle', 'blocked', 'stalled', 'done', 'unknown'])
97
+ const SHAPE_CHANGED = Symbol('shape_changed')
98
+
99
+ /** Does this entry carry an object shaped like a declaration under a key other than `declaredStatus`? */
100
+ function hasMisplacedDeclaration(entry) {
101
+ return Object.entries(entry).some(([k, v]) => k !== 'declaredStatus' && isPlain(v) && DECLARATION_STATES.has(v.state) && typeof v.summary === 'string' && typeof v.updatedAt === 'number')
102
+ }
103
+
104
+ /** What the daemon's entry for a session with no declaration looks like. */
105
+ function looksLikeDaemonEntry(entry) {
106
+ return 'sdkSessionId' in entry && 'conversationId' in entry
107
+ }
108
+
109
+ function loadSnapshot(path, maxBytes) {
110
+ let text
111
+ try {
112
+ const st = fs.statSync(path)
113
+ if (!st.isFile()) return { error: 'shape_changed' }
114
+ if (st.size > maxBytes) return { error: 'too_large' }
115
+ text = fs.readFileSync(path, 'utf8')
116
+ } catch (err) {
117
+ return { error: err?.code === 'ENOENT' ? 'source_missing' : 'unreachable' }
118
+ }
119
+ let doc
120
+ try {
121
+ doc = JSON.parse(text)
122
+ } catch {
123
+ return { error: 'parse_failed' }
124
+ }
125
+ if (!isPlain(doc) || doc.version !== 1 || !Array.isArray(doc.sessions)) return { error: 'shape_changed' }
126
+ const byId = new Map()
127
+ for (const entry of doc.sessions) {
128
+ if (!isPlain(entry) || typeof entry.id !== 'string' || entry.id === '' || entry.id.length > 256 || byId.has(entry.id)) {
129
+ return { error: 'shape_changed' }
130
+ }
131
+ // Only the declaration is carried forward; the rest of the entry is dropped here.
132
+ if (entry.declaredStatus !== undefined) byId.set(entry.id, entry.declaredStatus)
133
+ else byId.set(entry.id, looksLikeDaemonEntry(entry) && !hasMisplacedDeclaration(entry) ? undefined : SHAPE_CHANGED)
134
+ }
135
+ return { byId }
136
+ }
137
+
138
+ /**
139
+ * @param {object} opts
140
+ * @param {string} opts.path path of the daemon's session-state file
141
+ * @param {string} [opts.source] source name (default `chroxy-state-file`)
142
+ * @param {number} [opts.maxBytes] refuse a larger file
143
+ */
144
+ export function createStateFileAdapter({ path, source = STATE_FILE_SOURCE, maxBytes = DEFAULT_MAX_BYTES }) {
145
+ if (typeof path !== 'string' || path === '') throw new TypeError('createStateFileAdapter: path is required')
146
+ let snapshot = null
147
+ return {
148
+ source,
149
+ list() {
150
+ snapshot = loadSnapshot(path, maxBytes)
151
+ if (snapshot.error) return null
152
+ return [...snapshot.byId.keys()].map((id) => ({ session: { source, native_id: id, incarnation: null }, scope: null }))
153
+ },
154
+ read(session) {
155
+ if (!snapshot) snapshot = loadSnapshot(path, maxBytes)
156
+ if (snapshot.error) return { outcome: 'error', error_code: snapshot.error }
157
+ if (!snapshot.byId.has(session.native_id)) return { listed: false }
158
+ const raw = snapshot.byId.get(session.native_id)
159
+ if (raw === SHAPE_CHANGED) return { outcome: 'error', error_code: 'shape_changed' }
160
+ if (raw === undefined) return { outcome: 'no_report' }
161
+ const parsed = DeclaredStatusSchema.safeParse(raw)
162
+ if (!parsed.success) return { outcome: 'error', error_code: 'shape_changed' }
163
+ const d = parsed.data
164
+ return { outcome: 'ok', report: reportFromDeclared(d, { updatedAt: d.updatedAt, via: DECLARED_VIA[d.source] }) }
165
+ },
166
+ }
167
+ }