@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,905 @@
1
+ /**
2
+ * The daemon-side normalized event journal for agent principals
3
+ * (docs/security/agent-principals.md sections 7.1, 7.2 and 8; #9118, S3 of #9112).
4
+ *
5
+ * `agent-control/events.js` is a CLIENT-side ring that dies with the MCP process (#7859).
6
+ * This is the same normalization (`classifyBroadcast`, its forwarded-type allowlist, its
7
+ * field bounds) held in the daemon, per session, so a supervisor that disconnects or a
8
+ * daemon that restarts does not lose what happened. It never holds raw PTY bytes and it
9
+ * excludes thinking text (both are the classifier's rules, reused as they are).
10
+ *
11
+ * CURSOR AND GAP REASONS. A cursor is `{ sessionId, journalId, seq }`, `seq` being the
12
+ * last event the holder has seen. A cursor that cannot be honored exactly is reported as a
13
+ * gap, never silently resumed:
14
+ * - `evicted` the events after the cursor left the 2000-event window
15
+ * - `journal_reset` the journal was deliberately reset (a new `journalId`)
16
+ * - `restart_loss` a crash lost the unpersisted tail, or a journal could not prove its
17
+ * reservation and was replaced
18
+ * - `unknown_cursor` a journal id (or seq) this daemon never issued
19
+ *
20
+ * SEQ SURVIVES A CRASH BY A CONFIRMED RESERVATION (contract section 7.1, E4, R14). This
21
+ * reuses the IDEA of session-message-history.js (`_nextSeq` / `_seqReserved`, #8259) but
22
+ * NOT its failure handling: `_nextSeq` advances its reservation BEFORE persisting and only
23
+ * logs a failure, so a failed persist still issues the seq. Here the order is the reverse
24
+ * and is the whole guarantee:
25
+ *
26
+ * 1. a seq above `confirmedReserved` is never issued;
27
+ * 2. to go past it, the next reservation is written with the strict durable write
28
+ * (file fsync, rename, directory fsync) and only a `{ durable: true }` verdict
29
+ * raises `confirmedReserved`;
30
+ * 3. if that write throws or is not confirmed, NO event is issued under this
31
+ * `journalId` any more. The journal is `dead` for that id; the next successful start
32
+ * (a retry after a back-off) mints a NEW `journalId`, and a cursor for the old one
33
+ * reports `restart_loss`.
34
+ *
35
+ * On a restart the journal resumes at `reservedThrough + 1` after a crash (the reserved
36
+ * range may all have been issued and delivered) and at `headSeq + 1` after a clean close,
37
+ * so a seq is never reused within one `journalId`. A crash costs a gap flag for the
38
+ * unpersisted tail and nothing else. A journal whose sidecar cannot be trusted (wrong
39
+ * mode, corrupt, inconsistent) cannot prove its reservation: it mints a new `journalId`
40
+ * and every older cursor reports `restart_loss`.
41
+ *
42
+ * PERSISTENCE: a 0600 SIDECAR under the config dir, one pair of files per session
43
+ * (`<hash>.meta.json`: the id, the reservation and the clean flag, written synchronously
44
+ * and strictly; `<hash>.events.json`: the window, written debounced). Not the session
45
+ * state file: that file is one JSON document rewritten wholesale by many writers and read
46
+ * on boot by the restore path, so up to 2000 x 4 KiB per session in it would slow the hot
47
+ * path and put restore at risk, and its lenient writer is not the confirmed-durable write a
48
+ * reservation needs. The sidecar carries the session history's sensitivity (section 13).
49
+ *
50
+ * BOUNDS: 2000 events per session; 4 KiB per event, serialized (an oversize event is
51
+ * truncated and marked `truncated: true`, never dropped). Every stored event is
52
+ * redacted with the shared redactor and DEEP-FROZEN, so it can be handed to any number of
53
+ * subscribers without being copied or changed.
54
+ *
55
+ * FLOOR PROVENANCE (section 8): the result of a tool call whose permission request was
56
+ * floored is replaced by a placeholder. A `permission_request` is floored unless it says
57
+ * `floored: false` (the floor's own fail-closed reading). The frame names the call by
58
+ * `toolUseId` only on one pipeline, so without it the request is matched to the tool calls
59
+ * of the same tool that are open, or the next one that starts: this can over-suppress (a
60
+ * second call of the same tool) and never under-suppress.
61
+ */
62
+ import { createHash, randomUUID } from 'node:crypto'
63
+ import { mkdirSync, readdirSync, unlinkSync } from 'node:fs'
64
+ import { join } from 'node:path'
65
+ import { createLogger } from './logger.js'
66
+ import { writeDurableFile } from './durable-write.js'
67
+ import { readTrustedSecretFile } from './trusted-file-read.js'
68
+ import { sanitizeToolInput, redactWhole } from './redaction.js'
69
+ import { classifyBroadcast, StreamAccumulator, truncateEventData, FORWARDED_TYPES } from './agent-control/events.js'
70
+ import { SEQ_RESERVATION_STEP } from './session-message-history.js'
71
+
72
+ const log = createLogger('principal-journal')
73
+
74
+ export const JOURNAL_MAX_EVENTS = 2000
75
+ export const JOURNAL_EVENT_MAX_BYTES = 4096
76
+ /** A journal file is far smaller than this; a bigger one is not ours. */
77
+ export const JOURNAL_MAX_FILE_BYTES = 32 * 1024 * 1024
78
+ export const JOURNAL_RESERVATION_STEP = SEQ_RESERVATION_STEP
79
+ /** After a failed reservation, wait this long before trying to mint a new journal. */
80
+ export const JOURNAL_RETRY_BACKOFF_MS = 5000
81
+ export const JOURNAL_FLUSH_DELAY_MS = 5000
82
+ export const JOURNAL_GAP_REASONS = Object.freeze(['evicted', 'journal_reset', 'restart_loss', 'unknown_cursor'])
83
+
84
+ /** What a stream the accumulator had to cut is replaced by. */
85
+ export const TRUNCATED_STREAM_PLACEHOLDER = '[text withheld: the stream was longer than the journal can safely redact]'
86
+
87
+ /** What a floored tool call's result is replaced by. */
88
+ export const FLOORED_RESULT_PLACEHOLDER = '[result withheld: the tool call was gated by the permission floor]'
89
+
90
+ const MAX_SUPERSEDED = 8
91
+ const MAX_HOLES = 16
92
+ const MAX_TRACKED_TOOL_CALLS = 256
93
+ const MAX_PENDING_FLOORED = 64
94
+ const FILE_VERSION = 1
95
+
96
+ /** Freeze `value` and everything reachable from it. */
97
+ export function deepFreeze(value) {
98
+ if (value === null || typeof value !== 'object' || Object.isFrozen(value)) return value
99
+ Object.freeze(value)
100
+ for (const key of Object.keys(value)) deepFreeze(value[key])
101
+ return value
102
+ }
103
+
104
+ function byteLength(text) {
105
+ return Buffer.byteLength(text, 'utf8')
106
+ }
107
+
108
+ /**
109
+ * Which tool calls of one session the permission floor gated. In memory only, and held
110
+ * by the journal PER SESSION, outside the journal generation: a recovery that mints a new
111
+ * `journalId` must not forget a floored verdict recorded just before it.
112
+ *
113
+ * It decides, as events arrive, which `tool_result` must be withheld, and it is FAIL
114
+ * CLOSED. A result is let through ONLY when its call is known to have started and to not
115
+ * be floored (`open` and not `outstanding`). Everything else is withheld: a floored call, a
116
+ * call never seen start (it began before journaling, or crossed a restart), a call already
117
+ * retired (a duplicate result), and every call while `latched`.
118
+ *
119
+ * `latched` is set the moment the tracker drops information (a verdict or an open call it
120
+ * has no room for, a pending verdict it must forget). Emptiness proves nothing once
121
+ * information has been dropped, so a latch is cleared ONLY at an authoritative lifecycle
122
+ * boundary: the end of the turn (`result` or `agent_idle`), which proves the turn's calls
123
+ * ended. The same boundary retires everything else the tracker holds (`onTurnEnd`).
124
+ */
125
+ class FloorTracker {
126
+ constructor() {
127
+ /** floored calls that have no result yet */
128
+ this.outstanding = new Set()
129
+ /** @type {{ tool: string }[]} floored requests not yet matched to a call */
130
+ this.pending = []
131
+ /** toolUseId -> tool, calls that started and have no result yet */
132
+ this.open = new Map()
133
+ this.latched = false
134
+ }
135
+
136
+ _mark(id) {
137
+ if (this.outstanding.has(id)) return
138
+ if (this.outstanding.size >= MAX_TRACKED_TOOL_CALLS) {
139
+ this.latched = true // cannot remember one more verdict
140
+ return
141
+ }
142
+ this.outstanding.add(id)
143
+ }
144
+
145
+ onToolStart(msg) {
146
+ const id = msg.toolUseId
147
+ if (typeof id !== 'string') return
148
+ if (!this.open.has(id) && this.open.size >= MAX_TRACKED_TOOL_CALLS) {
149
+ // an open call is about to be forgotten, and with it whether it was floored
150
+ this.open.delete(this.open.keys().next().value)
151
+ this.latched = true
152
+ }
153
+ this.open.set(id, msg.tool)
154
+ const at = this.pending.findIndex((p) => p.tool === msg.tool)
155
+ if (at >= 0) {
156
+ this.pending.splice(at, 1)
157
+ this._mark(id)
158
+ }
159
+ }
160
+
161
+ onPermissionRequest(msg) {
162
+ // Fail closed: only an explicit `false` is "not floored".
163
+ if (msg.floored === false) return
164
+ if (typeof msg.toolUseId === 'string' && msg.toolUseId.length > 0) {
165
+ this._mark(msg.toolUseId)
166
+ return
167
+ }
168
+ for (const [id, tool] of this.open) {
169
+ if (tool === msg.tool) this._mark(id)
170
+ }
171
+ if (this.pending.length >= MAX_PENDING_FLOORED) {
172
+ this.pending.shift()
173
+ this.latched = true
174
+ }
175
+ this.pending.push({ tool: msg.tool })
176
+ }
177
+
178
+ /** Must this call's result be withheld? Anything not KNOWN to be clear is withheld. */
179
+ isFloored(toolUseId) {
180
+ if (this.latched) return true
181
+ if (typeof toolUseId !== 'string') return true
182
+ if (this.outstanding.has(toolUseId)) return true
183
+ return !this.open.has(toolUseId)
184
+ }
185
+
186
+ /** The call is complete: retire it. */
187
+ onToolResult(toolUseId) {
188
+ if (typeof toolUseId !== 'string') return
189
+ this.open.delete(toolUseId)
190
+ this.outstanding.delete(toolUseId)
191
+ }
192
+
193
+ /** The turn ended: every call of it ended. Retire all state and clear the latch. */
194
+ onTurnEnd() {
195
+ this.open.clear()
196
+ this.outstanding.clear()
197
+ this.pending.length = 0
198
+ this.latched = false
199
+ }
200
+ }
201
+
202
+ /**
203
+ * @typedef {object} JournalEntry
204
+ * @property {number} seq
205
+ * @property {number} ts
206
+ * @property {string} type
207
+ * @property {object} data
208
+ * @property {boolean} [truncated]
209
+ */
210
+
211
+ /**
212
+ * @typedef {object} SessionJournal
213
+ * @property {string} sessionId
214
+ * @property {string} journalId
215
+ * @property {number} nextSeq the next seq to issue
216
+ * @property {number} confirmedReserved the highest seq durably reserved; nothing above it is issued
217
+ * @property {JournalEntry[]} events the window, ascending and contiguous within a segment
218
+ * @property {{ from: number, to: number, reason: string }[]} holes ranges lost and never recoverable
219
+ * @property {{ journalId: string, reason: string }[]} superseded ids this session's journal replaced
220
+ * @property {'fresh'|'restart_loss'|'journal_reset'} mintedBy
221
+ * @property {boolean} dead a reservation failed: nothing is issued under this id
222
+ * @property {number} retryAt
223
+ * @property {boolean} dirty events not yet flushed
224
+ * @property {Set<Function>} listeners
225
+ */
226
+
227
+ export class PrincipalJournal {
228
+ /**
229
+ * @param {object} opts
230
+ * @param {string} opts.dir the sidecar directory (0700); each file in it is 0600
231
+ * @param {() => number} [opts.now]
232
+ * @param {(path: string, data: string) => { durable: boolean, unconfirmed: string|null }} [opts.writeDurable]
233
+ * @param {(path: string, opts: object) => object} [opts.readFile] `readTrustedSecretFile`
234
+ * @param {() => string} [opts.newId]
235
+ * @param {() => boolean} [opts.enabled] when false, `record` stores nothing
236
+ * @param {number} [opts.maxEvents]
237
+ * @param {number} [opts.eventMaxBytes]
238
+ * @param {number} [opts.reservationStep]
239
+ * @param {number} [opts.flushDelayMs]
240
+ * @param {number} [opts.retryBackoffMs]
241
+ * @param {{ setTimeout: Function, clearTimeout: Function }} [opts.timers]
242
+ */
243
+ constructor({
244
+ dir, now = Date.now, writeDurable = writeDurableFile, readFile = readTrustedSecretFile,
245
+ newId = () => randomUUID(), enabled = () => true, maxEvents = JOURNAL_MAX_EVENTS,
246
+ eventMaxBytes = JOURNAL_EVENT_MAX_BYTES, reservationStep = JOURNAL_RESERVATION_STEP,
247
+ flushDelayMs = JOURNAL_FLUSH_DELAY_MS, retryBackoffMs = JOURNAL_RETRY_BACKOFF_MS,
248
+ timers = { setTimeout, clearTimeout },
249
+ } = {}) {
250
+ if (typeof dir !== 'string' || dir.length === 0) throw new Error('PrincipalJournal needs a directory')
251
+ this._dir = dir
252
+ this._now = now
253
+ this._writeDurable = writeDurable
254
+ this._readFile = readFile
255
+ this._newId = newId
256
+ this._enabled = enabled
257
+ this._maxEvents = maxEvents
258
+ this._eventMaxBytes = eventMaxBytes
259
+ this._step = reservationStep
260
+ this._flushDelayMs = flushDelayMs
261
+ this._retryBackoffMs = retryBackoffMs
262
+ this._timers = timers
263
+ /** @type {Map<string, SessionJournal>} */
264
+ this._sessions = new Map()
265
+ this._accumulator = new StreamAccumulator()
266
+ /** @type {Map<string, FloorTracker>} per session, deliberately outside the journal generation */
267
+ this._floors = new Map()
268
+ /** is this session currently held by the SessionManager? A frame about one that is not is not journaled. */
269
+ this._live = () => true
270
+ /** bumps on every create or restore of a session id */
271
+ this._incarnations = new Map()
272
+ this._flushTimer = null
273
+ this._dirMade = false
274
+ this._closed = false
275
+ }
276
+
277
+ // -- paths ---------------------------------------------------------------
278
+
279
+ _base(sessionId) {
280
+ return join(this._dir, createHash('sha256').update(sessionId, 'utf8').digest('hex').slice(0, 32))
281
+ }
282
+
283
+ _metaPath(sessionId) { return `${this._base(sessionId)}.meta.json` }
284
+
285
+ _eventsPath(sessionId) { return `${this._base(sessionId)}.events.json` }
286
+
287
+ _ensureDir() {
288
+ if (this._dirMade) return
289
+ mkdirSync(this._dir, { recursive: true, mode: 0o700 })
290
+ this._dirMade = true
291
+ }
292
+
293
+ // -- loading ---------------------------------------------------------------
294
+
295
+ _readJson(path) {
296
+ let read
297
+ try {
298
+ read = this._readFile(path, { mode: 0o600, checkOwner: true, maxSize: JOURNAL_MAX_FILE_BYTES })
299
+ } catch {
300
+ return { status: 'unprovable' }
301
+ }
302
+ if (read.status === 'absent') return { status: 'absent' }
303
+ if (read.status !== 'ok') return { status: 'unprovable' }
304
+ try {
305
+ const value = JSON.parse(read.content)
306
+ if (value === null || typeof value !== 'object' || Array.isArray(value) || value.version !== FILE_VERSION) return { status: 'unprovable' }
307
+ return { status: 'ok', value }
308
+ } catch {
309
+ return { status: 'unprovable' }
310
+ }
311
+ }
312
+
313
+ _fresh(sessionId, mintedBy, superseded = []) {
314
+ return {
315
+ sessionId, journalId: this._newId(), nextSeq: 1, confirmedReserved: 0, events: [], holes: [],
316
+ superseded, mintedBy, dead: false, retryAt: 0, dirty: false, listeners: new Set(),
317
+ }
318
+ }
319
+
320
+ static _validEvents(list) {
321
+ if (!Array.isArray(list)) return null
322
+ let prev = 0
323
+ const out = []
324
+ for (const e of list) {
325
+ if (e === null || typeof e !== 'object' || !Number.isSafeInteger(e.seq) || e.seq <= prev) return null
326
+ if (!Number.isSafeInteger(e.ts) || typeof e.type !== 'string' || e.data === null || typeof e.data !== 'object' || Array.isArray(e.data)) return null
327
+ prev = e.seq
328
+ out.push(deepFreeze({ seq: e.seq, ts: e.ts, type: e.type, data: e.data, ...(e.truncated === true ? { truncated: true } : {}) }))
329
+ }
330
+ return out
331
+ }
332
+
333
+ static _validRanges(list, key) {
334
+ if (!Array.isArray(list)) return null
335
+ const out = []
336
+ for (const r of list) {
337
+ if (r === null || typeof r !== 'object') return null
338
+ if (key === 'holes') {
339
+ if (!Number.isSafeInteger(r.from) || !Number.isSafeInteger(r.to) || r.from < 1 || r.to < r.from || typeof r.reason !== 'string') return null
340
+ out.push({ from: r.from, to: r.to, reason: r.reason })
341
+ } else {
342
+ if (typeof r.journalId !== 'string' || r.journalId.length === 0 || typeof r.reason !== 'string') return null
343
+ out.push({ journalId: r.journalId, reason: r.reason })
344
+ }
345
+ }
346
+ return out
347
+ }
348
+
349
+ /**
350
+ * Does the meta agree with the window and the holes? A clean meta says the window ends AT
351
+ * `headSeq`, so no retained event may be above it; an unclean one is bounded by the
352
+ * reservation. Holes must sit inside the numbered range, must not overlap one another and
353
+ * must not overlap a retained event (a seq is either held or lost, never both).
354
+ */
355
+ static _consistent(m, events, holes) {
356
+ const ceiling = m.clean === true ? m.headSeq : m.reservedThrough
357
+ const top = events.length > 0 ? events[events.length - 1].seq : 0
358
+ if (top > ceiling) return false
359
+ const sorted = [...holes].sort((a, b) => a.from - b.from)
360
+ let prevTo = 0
361
+ for (const h of sorted) {
362
+ if (h.from <= prevTo || h.to > ceiling) return false
363
+ prevTo = h.to
364
+ if (events.some((e) => e.seq >= h.from && e.seq <= h.to)) return false
365
+ }
366
+ return true
367
+ }
368
+
369
+ /** The per-session state, loading it from the sidecar on first touch. */
370
+ _state(sessionId) {
371
+ let state = this._sessions.get(sessionId)
372
+ if (state) return state
373
+ state = this._load(sessionId)
374
+ this._sessions.set(sessionId, state)
375
+ return state
376
+ }
377
+
378
+ _load(sessionId) {
379
+ const meta = this._readJson(this._metaPath(sessionId))
380
+ if (meta.status === 'absent') return this._fresh(sessionId, 'fresh')
381
+ // A sidecar that exists and cannot be trusted cannot prove its reservation.
382
+ const unprovable = () => {
383
+ log.warn(`Principal journal for ${this._base(sessionId)} could not prove its reservation; minting a new journal`)
384
+ return this._fresh(sessionId, 'restart_loss')
385
+ }
386
+ if (meta.status !== 'ok') return unprovable()
387
+ const m = meta.value
388
+ const holes = PrincipalJournal._validRanges(m.holes ?? [], 'holes')
389
+ const superseded = PrincipalJournal._validRanges(m.superseded ?? [], 'superseded')
390
+ if (typeof m.journalId !== 'string' || m.journalId.length === 0 || m.sessionId !== sessionId ||
391
+ !Number.isSafeInteger(m.reservedThrough) || m.reservedThrough < 0 ||
392
+ !Number.isSafeInteger(m.headSeq) || m.headSeq < 0 || m.headSeq > m.reservedThrough ||
393
+ holes === null || superseded === null) {
394
+ return unprovable()
395
+ }
396
+ let events = []
397
+ const file = this._readJson(this._eventsPath(sessionId))
398
+ if (file.status === 'ok' && file.value.journalId === m.journalId && file.value.sessionId === sessionId) {
399
+ events = PrincipalJournal._validEvents(file.value.events) ?? []
400
+ }
401
+ const persistedHead = events.length > 0 ? events[events.length - 1].seq : 0
402
+ if (persistedHead > m.reservedThrough) return unprovable()
403
+ // Cross-validate what the meta CLAIMS against what the sidecar holds. Each file parses
404
+ // on its own, so a doctored or half-written pair can still be inconsistent, and an
405
+ // inconsistent pair could let a seq be issued twice.
406
+ if (!PrincipalJournal._consistent(m, events, holes)) return unprovable()
407
+
408
+ const state = {
409
+ sessionId, journalId: m.journalId, nextSeq: 1, confirmedReserved: 0, events, holes,
410
+ superseded: superseded.slice(-MAX_SUPERSEDED),
411
+ mintedBy: ['fresh', 'restart_loss', 'journal_reset'].includes(m.mintedBy) ? m.mintedBy : 'fresh',
412
+ dead: false, retryAt: 0, dirty: false, listeners: new Set(),
413
+ }
414
+ if (m.clean === true) {
415
+ // A clean close wrote the whole window and the exact head: continue contiguously.
416
+ state.nextSeq = m.headSeq + 1
417
+ state.confirmedReserved = m.headSeq
418
+ const from = Math.max(persistedHead, holeEnd(state)) + 1
419
+ if (from <= m.headSeq) this._addHole(state, from, m.headSeq, 'restart_loss')
420
+ } else {
421
+ // A crash: every seq up to the reservation may have been issued and delivered, so
422
+ // resume above it. What was never flushed is a hole, reported as restart_loss.
423
+ state.nextSeq = m.reservedThrough + 1
424
+ state.confirmedReserved = m.reservedThrough
425
+ const from = Math.max(persistedHead, holeEnd(state)) + 1
426
+ if (from <= m.reservedThrough) this._addHole(state, from, m.reservedThrough, 'restart_loss')
427
+ }
428
+ return state
429
+ }
430
+
431
+ _addHole(state, from, to, reason) {
432
+ state.holes.push({ from, to, reason })
433
+ state.holes.sort((a, b) => a.from - b.from)
434
+ const merged = []
435
+ for (const h of state.holes) {
436
+ const last = merged[merged.length - 1]
437
+ if (last && h.from <= last.to + 1 && h.reason === last.reason) last.to = Math.max(last.to, h.to)
438
+ else merged.push({ ...h })
439
+ }
440
+ state.holes = merged.slice(-MAX_HOLES)
441
+ }
442
+
443
+ // -- persistence -------------------------------------------------------------
444
+
445
+ _metaDoc(state, clean) {
446
+ return JSON.stringify({
447
+ version: FILE_VERSION, sessionId: state.sessionId, journalId: state.journalId,
448
+ reservedThrough: Math.max(state.confirmedReserved, state.nextSeq - 1), headSeq: state.nextSeq - 1,
449
+ clean, mintedBy: state.mintedBy, superseded: state.superseded, holes: state.holes,
450
+ })
451
+ }
452
+
453
+ /** A confirmed durable write of `data` to `path`: true only for a `{ durable: true }` verdict. */
454
+ _confirmedWrite(path, data) {
455
+ try {
456
+ this._ensureDir()
457
+ const verdict = this._writeDurable(path, data)
458
+ return verdict?.durable === true
459
+ } catch (err) {
460
+ log.warn(`Principal journal write failed (${err?.code || err?.message || 'error'})`)
461
+ return false
462
+ }
463
+ }
464
+
465
+ /**
466
+ * Raise `confirmedReserved` to `upTo`, durably. The ONLY place it rises, and only on a
467
+ * confirmed verdict. The meta written here carries `clean: false` BEFORE any seq above the
468
+ * old reservation is issued, so a crash after it can never be mistaken for a clean close.
469
+ */
470
+ _reserve(state, upTo) {
471
+ const before = state.confirmedReserved
472
+ state.confirmedReserved = upTo // the meta below names it; rolled back unless confirmed
473
+ const ok = this._confirmedWrite(this._metaPath(state.sessionId), this._metaDoc(state, false))
474
+ if (!ok) state.confirmedReserved = before
475
+ return ok
476
+ }
477
+
478
+ _scheduleFlush() {
479
+ if (this._flushTimer !== null || this._closed) return
480
+ const timer = this._timers.setTimeout(() => {
481
+ this._flushTimer = null
482
+ this.flush()
483
+ }, this._flushDelayMs)
484
+ timer?.unref?.()
485
+ this._flushTimer = timer
486
+ }
487
+
488
+ /** Write every dirty window. A failure leaves the session dirty for the next flush. */
489
+ flush() {
490
+ for (const state of this._sessions.values()) {
491
+ if (!state.dirty || state.dead) continue
492
+ const doc = JSON.stringify({ version: FILE_VERSION, sessionId: state.sessionId, journalId: state.journalId, events: state.events })
493
+ if (this._confirmedWrite(this._eventsPath(state.sessionId), doc)) state.dirty = false
494
+ }
495
+ }
496
+
497
+ /**
498
+ * Flush, then mark every loaded journal clean so a restart continues contiguously. A
499
+ * journal whose window or meta could not be confirmed stays marked unclean (a restart
500
+ * then treats it as a crash, which is always safe).
501
+ */
502
+ close() {
503
+ if (this._flushTimer !== null) {
504
+ this._timers.clearTimeout(this._flushTimer)
505
+ this._flushTimer = null
506
+ }
507
+ this._closed = true
508
+ this.flush()
509
+ for (const state of this._sessions.values()) {
510
+ if (state.dead || state.dirty || state.nextSeq === 1 && state.confirmedReserved === 0) continue
511
+ this._confirmedWrite(this._metaPath(state.sessionId), this._metaDoc(state, true))
512
+ }
513
+ }
514
+
515
+ // -- the tap -----------------------------------------------------------------
516
+
517
+ /**
518
+ * Feed one server-to-client broadcast. Only session-tagged messages are considered; the
519
+ * classifier decides what is journaled (its allowlist, thinking excluded, raw PTY never).
520
+ * Never throws: a journal fault must not break a broadcast.
521
+ * @param {object} message
522
+ */
523
+ record(message) {
524
+ try {
525
+ if (this._closed || typeof message?.sessionId !== 'string' || message.sessionId.length === 0) return
526
+ if (this._enabled() !== true) return
527
+ const sessionId = message.sessionId
528
+ if (this._live(sessionId) !== true) return
529
+ this._state(sessionId) // load the sidecar on first touch
530
+ const floor = this._floorFor(sessionId)
531
+ const type = message.type
532
+ if (type === 'tool_start') floor.onToolStart(message)
533
+ else if (type === 'permission_request') floor.onPermissionRequest(message)
534
+ let events
535
+ if (type === 'stream_start' || type === 'stream_delta' || type === 'stream_end') {
536
+ events = classifyBroadcast(message, this._accumulator)
537
+ } else if (FORWARDED_TYPES.has(type)) {
538
+ // REDACT BEFORE ANY LOSSY CUT: the classifier clips every string at 4000 characters,
539
+ // which would cut a credential in two and keep its unmasked prefix. The copy is
540
+ // redacted whole first; the frame being broadcast is never touched.
541
+ const safe = this._redactFrame(message)
542
+ events = safe === null ? [] : classifyBroadcast(safe, this._accumulator)
543
+ } else {
544
+ events = []
545
+ }
546
+ for (const event of events) {
547
+ const data = this._scrub(floor, event)
548
+ if (data !== null) this._append(sessionId, event.type, data)
549
+ }
550
+ if (type === 'tool_result') floor.onToolResult(message.toolUseId)
551
+ else if (type === 'result' || type === 'agent_idle') floor.onTurnEnd()
552
+ } catch (err) {
553
+ log.warn(`Principal journal could not record a ${String(message?.type).slice(0, 40)} frame: ${err?.message || err}`)
554
+ }
555
+ }
556
+
557
+ _floorFor(sessionId) {
558
+ let floor = this._floors.get(sessionId)
559
+ if (!floor) {
560
+ floor = new FloorTracker()
561
+ this._floors.set(sessionId, floor)
562
+ }
563
+ return floor
564
+ }
565
+
566
+ /** A redacted deep copy of a frame, or null when it cannot be redacted safely. */
567
+ _redactFrame(message) {
568
+ const safe = sanitizeToolInput(message, { maxChars: 2_000_000 })
569
+ // an over-large frame comes back summarized, which is no longer the frame: drop it
570
+ return safe !== null && typeof safe === 'object' && safe.type === message.type ? safe : null
571
+ }
572
+
573
+ /**
574
+ * What the journal keeps of one classified event (contract section 8). Raw tool INPUTS are
575
+ * never journaled in v1: `tool_start` keeps the tool and its id, `tool_input_delta` is
576
+ * dropped, and a `permission_request` keeps the tool, the floor verdict and, only when
577
+ * the request was NOT floored, its bounded, sanitised description. The result of a floored
578
+ * call is replaced by a placeholder. Returns null for an event that is not kept.
579
+ */
580
+ _scrub(floor, event) {
581
+ const d = event.data ?? {}
582
+ // An explicit allowlist of fields per tool event: `input` (and anything a producer adds
583
+ // later) is never retained.
584
+ const pick = (fields) => Object.fromEntries(fields.filter((f) => d[f] !== undefined).map((f) => [f, d[f]]))
585
+ switch (event.type) {
586
+ case 'tool_input_delta':
587
+ return null
588
+ case 'tool_start':
589
+ return pick(['messageId', 'toolUseId', 'tool'])
590
+ case 'permission_request': {
591
+ const floored = d.floored !== false
592
+ return {
593
+ requestId: d.requestId, tool: d.tool, floored,
594
+ ...(typeof d.toolUseId === 'string' ? { toolUseId: d.toolUseId } : {}),
595
+ ...(typeof d.explicitConsent === 'boolean' ? { explicitConsent: d.explicitConsent } : {}),
596
+ ...(typeof d.nonDelegable === 'boolean' ? { nonDelegable: d.nonDelegable } : {}),
597
+ ...(!floored && typeof d.description === 'string' ? { description: d.description } : {}),
598
+ }
599
+ }
600
+ case 'tool_result':
601
+ return floor.isFloored(d.toolUseId)
602
+ ? { toolUseId: d.toolUseId, result: FLOORED_RESULT_PLACEHOLDER, withheld: 'floored' }
603
+ : pick(['toolUseId', 'result', 'truncated'])
604
+ case 'assistant_text':
605
+ return this._safeStreamText(d)
606
+ default: {
607
+ const { input: _input, ...rest } = d
608
+ return rest
609
+ }
610
+ }
611
+ }
612
+
613
+ /**
614
+ * An accumulated stream. If the accumulator had to cut it, the text is NOT journaled: a
615
+ * credential straddling the cut was never seen whole and no fixed margin can contain one
616
+ * (a JWT is unbounded), so a placeholder, `truncated: true` and the length are kept.
617
+ * Otherwise the whole text is redacted.
618
+ */
619
+ _safeStreamText(d) {
620
+ if (typeof d.text !== 'string') return d
621
+ if (d.truncated === true) {
622
+ return { ...(d.messageId !== undefined ? { messageId: d.messageId } : {}), text: TRUNCATED_STREAM_PLACEHOLDER, truncated: true, length: d.text.length }
623
+ }
624
+ return { ...d, text: redactWhole(d.text).text }
625
+ }
626
+
627
+ /**
628
+ * Append one normalized event. Returns the stored entry, or null when nothing was
629
+ * stored (the journal is dead for lack of a confirmed reservation, or backing off).
630
+ * @param {string} sessionId
631
+ * @param {string} type
632
+ * @param {object} data
633
+ * @returns {JournalEntry|null}
634
+ */
635
+ _append(sessionId, type, data) {
636
+ const state = this._state(sessionId)
637
+ if (state.dead) {
638
+ if (this._now() < state.retryAt) return null
639
+ this._recover(state)
640
+ }
641
+ const seq = state.nextSeq
642
+ if (seq > state.confirmedReserved && !this._reserve(state, seq - 1 + this._step)) {
643
+ this._kill(state)
644
+ return null
645
+ }
646
+ const entry = this._shape(seq, type, data)
647
+ state.nextSeq = seq + 1
648
+ state.events.push(entry)
649
+ while (state.events.length > this._maxEvents) state.events.shift()
650
+ state.dirty = true
651
+ this._scheduleFlush()
652
+ for (const listener of [...state.listeners]) {
653
+ try { listener({ kind: 'event', journalId: state.journalId, entry }) } catch { /* a listener must not break the journal */ }
654
+ }
655
+ return entry
656
+ }
657
+
658
+ /** Redact, bound to the per-event cap, freeze. */
659
+ _shape(seq, type, data) {
660
+ let body
661
+ try {
662
+ body = sanitizeToolInput(data, { maxChars: 1_000_000 })
663
+ if (body === null || typeof body !== 'object' || Array.isArray(body)) body = { value: body }
664
+ } catch {
665
+ body = { note: 'event payload could not be redacted' }
666
+ }
667
+ const envelope = JSON.stringify({ seq: Number.MAX_SAFE_INTEGER, ts: Number.MAX_SAFE_INTEGER, type, truncated: true, data: {} })
668
+ const budget = Math.max(2, this._eventMaxBytes - byteLength(envelope) + 2)
669
+ let truncated = false
670
+ let serialized
671
+ try {
672
+ serialized = JSON.stringify(body)
673
+ } catch {
674
+ serialized = null
675
+ }
676
+ if (typeof serialized !== 'string') {
677
+ body = { truncated: true, originalType: type, note: 'event payload was not JSON-serializable' }
678
+ truncated = true
679
+ } else if (byteLength(serialized) > budget) {
680
+ body = truncateEventData(body, type, budget)
681
+ truncated = true
682
+ }
683
+ let entry = { seq, ts: this._now(), type, data: body, ...(truncated ? { truncated: true } : {}) }
684
+ if (byteLength(JSON.stringify(entry)) > this._eventMaxBytes) {
685
+ entry = { seq, ts: entry.ts, type, data: { truncated: true, originalType: type }, truncated: true }
686
+ }
687
+ return deepFreeze(entry)
688
+ }
689
+
690
+ /** A reservation failed: nothing more is issued under this journalId. */
691
+ _kill(state) {
692
+ state.dead = true
693
+ state.retryAt = this._now() + this._retryBackoffMs
694
+ log.warn('Principal journal could not confirm a seq reservation; it issues no event under this journal id until a new one is minted')
695
+ for (const listener of [...state.listeners]) {
696
+ try { listener({ kind: 'reset', journalId: state.journalId, reason: 'restart_loss' }) } catch { /* ignore */ }
697
+ }
698
+ }
699
+
700
+ /** The next successful start after a dead journal: a new id, the old one remembered. */
701
+ _recover(state) {
702
+ this._supersede(state, 'restart_loss')
703
+ }
704
+
705
+ _supersede(state, reason) {
706
+ state.superseded.push({ journalId: state.journalId, reason })
707
+ state.superseded = state.superseded.slice(-MAX_SUPERSEDED)
708
+ state.journalId = this._newId()
709
+ state.nextSeq = 1
710
+ state.confirmedReserved = 0
711
+ state.events = []
712
+ state.holes = []
713
+ state.mintedBy = reason
714
+ state.dead = false
715
+ state.retryAt = 0
716
+ state.dirty = false
717
+ }
718
+
719
+ // -- reading -----------------------------------------------------------------
720
+
721
+ _windowStart(state) {
722
+ return state.events.length > 0 ? state.events[0].seq : state.nextSeq
723
+ }
724
+
725
+ /**
726
+ * The ranges of seq that exist as numbers but can no longer be served, ascending:
727
+ * lost holes, and everything evicted from the front of the window (holes win overlaps).
728
+ */
729
+ _unavailable(state) {
730
+ const head = state.nextSeq - 1
731
+ const ws = this._windowStart(state)
732
+ const holes = state.holes.filter((h) => h.to >= 1 && h.from <= head).map((h) => ({ from: h.from, to: Math.min(h.to, head), reason: h.reason }))
733
+ const ranges = [...holes]
734
+ if (ws > 1) {
735
+ let cursor = 1
736
+ for (const h of [...holes].sort((a, b) => a.from - b.from)) {
737
+ if (h.from > ws - 1) break
738
+ if (h.from > cursor) ranges.push({ from: cursor, to: h.from - 1, reason: 'evicted' })
739
+ cursor = Math.max(cursor, h.to + 1)
740
+ }
741
+ if (cursor <= ws - 1) ranges.push({ from: cursor, to: ws - 1, reason: 'evicted' })
742
+ }
743
+ return ranges.sort((a, b) => a.from - b.from)
744
+ }
745
+
746
+ /** Tell the journal which sessions currently exist; a frame about any other is not journaled. */
747
+ setLiveness(isLive) {
748
+ this._live = typeof isLive === 'function' ? isLive : () => true
749
+ }
750
+
751
+ /**
752
+ * A new incarnation of a session id (a create, or a restore retry that succeeded): it starts
753
+ * a FRESH journal. Anything held for the id is removed (its subscribers are ended), so the
754
+ * first frame of the new incarnation mints a new `journalId`.
755
+ * @returns {number} the incarnation
756
+ */
757
+ beginIncarnation(sessionId) {
758
+ const n = (this._incarnations.get(sessionId) ?? 0) + 1
759
+ this._incarnations.delete(sessionId)
760
+ this._incarnations.set(sessionId, n)
761
+ while (this._incarnations.size > 4096) this._incarnations.delete(this._incarnations.keys().next().value)
762
+ this.removeSession(sessionId)
763
+ return n
764
+ }
765
+
766
+ incarnation(sessionId) {
767
+ return this._incarnations.get(sessionId) ?? 0
768
+ }
769
+
770
+ /** The journal's current id and head, or null when the session has no journal. */
771
+ head(sessionId) {
772
+ const state = this._state(sessionId)
773
+ return { journalId: state.journalId, headSeq: state.nextSeq - 1, windowStart: this._windowStart(state) }
774
+ }
775
+
776
+ /**
777
+ * Interpret a client cursor against this journal.
778
+ * @param {string} sessionId
779
+ * @param {{ sessionId: string, journalId: string, seq: number }|null|undefined} cursor
780
+ * @returns {{ journalId: string, headSeq: number, afterSeq: number, gap: { reason: string, fromSeq?: number, toSeq?: number }|null }}
781
+ * `afterSeq` is the seq to read after.
782
+ */
783
+ resolveCursor(sessionId, cursor) {
784
+ const state = this._state(sessionId)
785
+ const headSeq = state.nextSeq - 1
786
+ const fromStart = this._windowStart(state) - 1
787
+ const base = { journalId: state.journalId, headSeq }
788
+ if (cursor === null || cursor === undefined) return { ...base, afterSeq: fromStart, gap: null }
789
+ if (typeof cursor !== 'object' || cursor.sessionId !== sessionId || typeof cursor.journalId !== 'string' ||
790
+ !Number.isSafeInteger(cursor.seq) || cursor.seq < 0) {
791
+ return { ...base, afterSeq: fromStart, gap: { reason: 'unknown_cursor' } }
792
+ }
793
+ if (cursor.journalId === state.journalId) {
794
+ if (cursor.seq > headSeq) return { ...base, afterSeq: fromStart, gap: { reason: 'unknown_cursor' } }
795
+ const range = this._unavailable(state).find((r) => r.from <= cursor.seq + 1 && cursor.seq + 1 <= r.to)
796
+ if (range) {
797
+ return { ...base, afterSeq: range.to, gap: { reason: range.reason, fromSeq: cursor.seq + 1, toSeq: range.to } }
798
+ }
799
+ return { ...base, afterSeq: cursor.seq, gap: null }
800
+ }
801
+ // A different journal id. A holder that had seen nothing lost nothing.
802
+ if (cursor.seq === 0) return { ...base, afterSeq: fromStart, gap: null }
803
+ const known = state.superseded.find((s) => s.journalId === cursor.journalId)
804
+ const reason = known ? known.reason : (state.mintedBy === 'restart_loss' ? 'restart_loss' : 'unknown_cursor')
805
+ return { ...base, afterSeq: fromStart, gap: { reason } }
806
+ }
807
+
808
+ /**
809
+ * Read the retained events after `afterSeq`, at most `limit`, never above `maxSeq`. When
810
+ * the next seq is unavailable the unavailable range comes back as `gap` and the read
811
+ * continues after it. A read never spans two segments: it stops before the next hole.
812
+ * @param {string} sessionId
813
+ * @param {number} afterSeq
814
+ * @param {number} limit
815
+ * @param {number} [maxSeq]
816
+ * @returns {{ journalId: string, headSeq: number, events: JournalEntry[], gap: object|null, lastSeq: number }}
817
+ */
818
+ readFrom(sessionId, afterSeq, limit, maxSeq = Number.MAX_SAFE_INTEGER) {
819
+ const state = this._state(sessionId)
820
+ const headSeq = state.nextSeq - 1
821
+ const ranges = this._unavailable(state)
822
+ let after = afterSeq
823
+ let gap = null
824
+ const range = ranges.find((r) => r.from <= after + 1 && after + 1 <= r.to)
825
+ if (range) {
826
+ const to = Math.min(range.to, maxSeq)
827
+ gap = { reason: range.reason, fromSeq: after + 1, toSeq: to }
828
+ after = to
829
+ }
830
+ const upper = Math.min(maxSeq, headSeq, ...ranges.filter((r) => r.from > after).map((r) => r.from - 1))
831
+ const events = []
832
+ for (const e of state.events) {
833
+ if (e.seq <= after) continue
834
+ if (e.seq > upper || events.length >= limit) break
835
+ events.push(e)
836
+ }
837
+ const lastSeq = events.length > 0 ? events[events.length - 1].seq : after
838
+ return { journalId: state.journalId, headSeq, events, gap, lastSeq }
839
+ }
840
+
841
+ /**
842
+ * Observe appends (and resets) for one session. Returns the unsubscribe.
843
+ * @param {string} sessionId
844
+ * @param {(evt: { kind: 'event', journalId: string, entry: JournalEntry } | { kind: 'reset' | 'removed', journalId: string, reason: string }) => void} listener
845
+ */
846
+ onAppend(sessionId, listener) {
847
+ const state = this._state(sessionId)
848
+ state.listeners.add(listener)
849
+ return () => { state.listeners.delete(listener) }
850
+ }
851
+
852
+ // -- lifecycle -----------------------------------------------------------------
853
+
854
+ /** A deliberate reset: a new journal id; cursors for the old one report `journal_reset`. */
855
+ resetSession(sessionId) {
856
+ const state = this._state(sessionId)
857
+ const old = state.journalId
858
+ this._supersede(state, 'journal_reset')
859
+ for (const listener of [...state.listeners]) {
860
+ try { listener({ kind: 'reset', journalId: old, reason: 'journal_reset' }) } catch { /* ignore */ }
861
+ }
862
+ }
863
+
864
+ /**
865
+ * Boot-time sweep: delete the sidecar of every session `isLive` says is gone (destroyed
866
+ * while the daemon was down, or by a path that does not call `removeSession`). Reads
867
+ * only this directory; a file it cannot read is left alone.
868
+ * @param {(sessionId: string) => boolean} isLive
869
+ * @returns {number} how many journals were removed
870
+ */
871
+ prune(isLive) {
872
+ let names
873
+ try { names = readdirSync(this._dir) } catch { return 0 }
874
+ let removed = 0
875
+ for (const name of names) {
876
+ if (!name.endsWith('.meta.json')) continue
877
+ const meta = this._readJson(join(this._dir, name))
878
+ const sessionId = meta.status === 'ok' ? meta.value.sessionId : null
879
+ if (typeof sessionId !== 'string' || isLive(sessionId) !== false) continue
880
+ this.removeSession(sessionId)
881
+ removed++
882
+ }
883
+ return removed
884
+ }
885
+
886
+ /** The session is gone: forget it and delete its sidecar. */
887
+ removeSession(sessionId) {
888
+ const state = this._sessions.get(sessionId)
889
+ if (state) {
890
+ for (const listener of [...state.listeners]) {
891
+ try { listener({ kind: 'removed', journalId: state.journalId, reason: 'removed' }) } catch { /* ignore */ }
892
+ }
893
+ this._sessions.delete(sessionId)
894
+ }
895
+ this._floors.delete(sessionId)
896
+ for (const path of [this._metaPath(sessionId), this._eventsPath(sessionId)]) {
897
+ try { unlinkSync(path) } catch { /* absent */ }
898
+ }
899
+ }
900
+ }
901
+
902
+ /** The last seq a state's holes already cover (0 when none). */
903
+ function holeEnd(state) {
904
+ return state.holes.length > 0 ? state.holes[state.holes.length - 1].to : 0
905
+ }