@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,1029 @@
1
+ import { randomBytes } from 'node:crypto'
2
+ import { chmodSync, closeSync, constants as fsConstants, existsSync, fstatSync, mkdirSync, openSync, readdirSync, readFileSync, unlinkSync } from 'node:fs'
3
+ import { open } from 'node:fs/promises'
4
+ import { join } from 'node:path'
5
+ import { promisify } from 'node:util'
6
+ import { gunzip, gunzipSync, gzip, gzipSync } from 'node:zlib'
7
+ import { createLogger } from './logger.js'
8
+ import { isWindows, writeFileRestricted } from './platform.js'
9
+ import { pageHistory } from './history-page.js'
10
+ import { SessionMessageHistory } from './session-message-history.js'
11
+ import { SESSION_ARCHIVE_MAX_ENTRIES, savedHasHistory } from './session-archive-limits.js'
12
+
13
+ const log = createLogger('session-archive')
14
+
15
+ const gzipAsync = promisify(gzip)
16
+ const gunzipAsync = promisify(gunzip)
17
+
18
+ /**
19
+ * Provider-neutral session archive.
20
+ *
21
+ * When a session leaves the live set, the history chroxy itself holds (the
22
+ * `history` array of its persisted entry) used to vanish with it. A Claude
23
+ * session can be resumed from the provider's own transcript, but a Codex /
24
+ * Gemini / BYOK session cannot, so for those the content was gone for good.
25
+ * The archive keeps one compressed record per ended session so it stays
26
+ * READABLE (paged, oldest first, through the same bounded reader the
27
+ * failed-restore view uses). It resumes nothing and creates nothing.
28
+ *
29
+ * Storage under `dir`:
30
+ * - `<archiveId>.json.gz` gzip(JSON { version: 1, archivedAt, reason, saved })
31
+ * - `index.json` { version: 1, entries: [meta...], tombstones: [...] }
32
+ * For the ROWS the index is a cache of the record files: a missing or corrupt
33
+ * index is rebuilt from the files, a row whose file is gone is dropped, and a
34
+ * file the index does not know (an index write lost to a crash) is adopted
35
+ * unless a tombstone covers it. The TOMBSTONES (what was deleted or aged out)
36
+ * exist only in the index, so a corrupt or lost index rebuilds with none; a
37
+ * deleted snapshot still present in an older session-state backup could then
38
+ * be archived again. That is a known limit.
39
+ *
40
+ * SECURITY: the archive directory holds transcript content, so files are 0600
41
+ * and the directory 0700. An `archiveId` is a random 128-bit token that this
42
+ * class generates; NO path is ever built from a session id or any other
43
+ * client-supplied string. A client-supplied id must match ARCHIVE_ID_RE AND be
44
+ * present in the index before any filesystem access happens.
45
+ *
46
+ * OUTCOMES. `archiveOutcome()` (synchronous) reports `archived | duplicate |
47
+ * skipped | failed`, so a caller that is about to DROP the only copy of a
48
+ * session (a TTL prune, a dismissed failed restore, a stale boot entry) can
49
+ * keep it when the write `failed`. `archive()` is the meta-or-null shorthand.
50
+ *
51
+ * RUNTIME PATH. A user closing a session must not stall the daemon, so
52
+ * `enqueue()` takes the snapshot's JSON synchronously (the same cost the state
53
+ * persist already pays), then compresses (gzip level 1) and writes on a serial
54
+ * queue off the event loop; `whenIdle()` awaits it and `drainSync()` finishes
55
+ * whatever is queued synchronously (called on shutdown). RESIDUAL WINDOW: a
56
+ * hard kill while a just-closed session is still compressing loses that one
57
+ * archive — the session was being closed anyway, and the clean-exit path
58
+ * drains the queue.
59
+ *
60
+ * DISPOSITIONS. The index also keeps bounded tombstones (sessionId +
61
+ * lastActivityAt + historyLength) of every record removed by delete, delete-all
62
+ * or retention, so a state backup that still carries the source entry cannot
63
+ * resurrect a record the operator deleted or that aged out.
64
+ *
65
+ * SIZE. A record's JSON is bounded by MAX_RECORD_BYTES on write AND read (one
66
+ * constant): when a history would not fit, the OLDEST entries are omitted and
67
+ * counted in `omittedOldest`, rather than writing a record the reader refuses.
68
+ *
69
+ * DURABILITY. A removal (delete, delete-all, retention) writes the index WITH
70
+ * the tombstone first and unlinks the record only after that write succeeded;
71
+ * the synchronous boot-path writes are fsync'd (`durable`) so a record is on
72
+ * disk before the state flush that drops its source.
73
+ *
74
+ * DOCUMENTED LIMITS. The boot paths (stale entries, the failed-restore TTL
75
+ * prune) and `clearFailedRestore` archive SYNCHRONOUSLY, because they need the
76
+ * outcome before they may drop the source, so a very large history stalls the
77
+ * event loop once there. A read still `JSON.parse`s a whole record
78
+ * synchronously after the (asynchronous) read and inflate.
79
+ */
80
+
81
+ const ARCHIVE_ID_RE = /^[0-9a-f]{32}$/
82
+ const RECORD_SUFFIX = '.json.gz'
83
+ const RECORD_FILE_RE = /^([0-9a-f]{32})\.json\.gz$/
84
+ const INDEX_FILE = 'index.json'
85
+ const FORMAT_VERSION = 1
86
+ const DAY_MS = 24 * 60 * 60 * 1000
87
+ const MIB = 1024 * 1024
88
+ // ONE bound on a record's uncompressed JSON, applied by the writer (which omits
89
+ // the oldest entries to fit) and by the reader (gunzip maxOutputLength), so a
90
+ // record that was written can always be read.
91
+ const MAX_RECORD_BYTES = 128 * MIB
92
+ const MAX_TOMBSTONES = 1000
93
+ // Level 1: the archive is about not losing text, not about density, and the
94
+ // default level costs several times the CPU.
95
+ const GZIP_OPTS = Object.freeze({ level: 1 })
96
+
97
+ export { SESSION_ARCHIVE_MAX_ENTRIES }
98
+
99
+ // Opening with O_NOFOLLOW means a symlink planted where the index or a record
100
+ // should be is refused (ELOOP) rather than followed. Absent on win32. O_NONBLOCK
101
+ // keeps a FIFO planted at the path from blocking the open forever (a synchronous
102
+ // open blocks the whole event loop); a regular file is unaffected, and the
103
+ // opened handle is checked to BE a regular file before anything is read.
104
+ const O_NOFOLLOW = typeof fsConstants.O_NOFOLLOW === 'number' ? fsConstants.O_NOFOLLOW : 0
105
+ const O_NONBLOCK = typeof fsConstants.O_NONBLOCK === 'number' ? fsConstants.O_NONBLOCK : 0
106
+ const OPEN_FLAGS = fsConstants.O_RDONLY | O_NOFOLLOW | O_NONBLOCK
107
+ const TMP_FILE_RE = /^(?:[0-9a-f]{32}\.json\.gz|index\.json)\.tmp-.+$/
108
+
109
+ const notRegular = (path) => Object.assign(new Error(`not a regular file: ${path}`), { code: 'ENOTREG' })
110
+
111
+ function readFileNoFollowSync(path) {
112
+ const fd = openSync(path, OPEN_FLAGS)
113
+ try {
114
+ if (!fstatSync(fd).isFile()) throw notRegular(path)
115
+ return readFileSync(fd)
116
+ } finally {
117
+ closeSync(fd)
118
+ }
119
+ }
120
+
121
+ async function readFileNoFollow(path) {
122
+ const handle = await open(path, OPEN_FLAGS)
123
+ try {
124
+ if (!(await handle.stat()).isFile()) throw notRegular(path)
125
+ return await handle.readFile()
126
+ } finally {
127
+ await handle.close()
128
+ }
129
+ }
130
+
131
+ /** A log-safe tag for a read/parse error: never its message, which can quote file content. */
132
+ function errTag(err) {
133
+ return err?.code || err?.name || 'error'
134
+ }
135
+
136
+ export const SESSION_ARCHIVE_DEFAULTS = Object.freeze({
137
+ enabled: true,
138
+ maxEntries: 100,
139
+ maxAgeDays: 30,
140
+ maxMegabytes: 256,
141
+ })
142
+
143
+ export const ARCHIVE_NOT_FOUND_CODE = 'ARCHIVED_SESSION_NOT_FOUND'
144
+ export const ARCHIVE_MAX_RECORD_BYTES = MAX_RECORD_BYTES
145
+
146
+ // Bounds on the strings copied into an index row, so a hand-edited or
147
+ // abnormal saved entry cannot make the roster (sent in one frame) large.
148
+ const MAX_ID_CHARS = 256
149
+ const MAX_NAME_CHARS = 256
150
+ const MAX_PROVIDER_CHARS = 64
151
+ const MAX_CWD_CHARS = 4096
152
+ const MAX_MODEL_CHARS = 256
153
+ const MAX_REASON_CHARS = 64
154
+
155
+ function boundedString(value, max) {
156
+ return typeof value === 'string' ? value.slice(0, max) : null
157
+ }
158
+
159
+ function finiteOrNull(value) {
160
+ return typeof value === 'number' && Number.isFinite(value) ? value : null
161
+ }
162
+
163
+ /**
164
+ * Does the saved entry still name a provider-side conversation it could resume
165
+ * from (#8866)? A Claude-family entry carries `sdkSessionId` (a claude-tui id
166
+ * that was minted but never written to disk is `conversationPersisted: false`);
167
+ * a Codex app-server entry carries `nativeResume`. This only says a locator was
168
+ * RECORDED: whether the transcript / thread still exists is checked when a
169
+ * restore is attempted.
170
+ */
171
+ function savedHasLocator(saved) {
172
+ if (saved?.nativeResume && typeof saved.nativeResume === 'object') return true
173
+ return typeof saved?.sdkSessionId === 'string' && saved.sdkSessionId.length > 0 && saved.conversationPersisted !== false
174
+ }
175
+
176
+ function positiveNumber(value, fallback, name, { integer = false, max = Infinity } = {}) {
177
+ if (value === undefined) return fallback
178
+ const ok = typeof value === 'number' && Number.isFinite(value) && value > 0 && (!integer || Number.isInteger(value))
179
+ if (ok && value > max) {
180
+ log.warn(`sessionArchive.${name}: ${value} is above the maximum — clamped to ${max}`)
181
+ return max
182
+ }
183
+ if (ok) return value
184
+ log.warn(`sessionArchive.${name}: expected a positive ${integer ? 'integer' : 'number'}, got ${JSON.stringify(value)} — using the default (${fallback})`)
185
+ return fallback
186
+ }
187
+
188
+ /**
189
+ * Copy ONLY the typed fields of a roster row from a saved session entry.
190
+ * @returns {object|null} null when the entry has no usable session id
191
+ */
192
+ function metaFrom(saved, { archiveId, reason, archivedAt, bytes, omittedOldest = 0 }) {
193
+ const sessionId = boundedString(saved?.id ?? saved?.sessionId, MAX_ID_CHARS)
194
+ if (!sessionId) return null
195
+ return {
196
+ archiveId,
197
+ sessionId,
198
+ name: boundedString(saved.name, MAX_NAME_CHARS),
199
+ provider: boundedString(saved.provider, MAX_PROVIDER_CHARS),
200
+ cwd: boundedString(saved.cwd, MAX_CWD_CHARS),
201
+ model: boundedString(saved.model, MAX_MODEL_CHARS),
202
+ reason: boundedString(reason, MAX_REASON_CHARS) || 'closed',
203
+ archivedAt: finiteOrNull(archivedAt),
204
+ lastActivityAt: finiteOrNull(saved.lastActivityAt),
205
+ createdAt: finiteOrNull(saved.createdAt),
206
+ historyLength: Array.isArray(saved.history) ? saved.history.length : 0,
207
+ omittedOldest: Number.isInteger(omittedOldest) && omittedOldest > 0 ? omittedOldest : 0,
208
+ bytes: finiteOrNull(bytes) ?? 0,
209
+ // Internal restore hints (#8866); SessionManager folds them into the wire
210
+ // `restore` field and strips them, so the roster never carries these keys.
211
+ locator: savedHasLocator(saved),
212
+ }
213
+ }
214
+
215
+ /** Re-validate an index row read back from disk (it is not trusted either). */
216
+ function metaFromIndexRow(row) {
217
+ if (!row || typeof row !== 'object' || typeof row.archiveId !== 'string' || !ARCHIVE_ID_RE.test(row.archiveId)) return null
218
+ const historyLength = Number.isInteger(row.historyLength) && row.historyLength >= 0 ? row.historyLength : 0
219
+ const meta = metaFrom(
220
+ {
221
+ id: row.sessionId,
222
+ name: row.name,
223
+ provider: row.provider,
224
+ cwd: row.cwd,
225
+ model: row.model,
226
+ lastActivityAt: row.lastActivityAt,
227
+ createdAt: row.createdAt,
228
+ history: [],
229
+ },
230
+ { archiveId: row.archiveId, reason: row.reason, archivedAt: row.archivedAt, bytes: row.bytes, omittedOldest: row.omittedOldest },
231
+ )
232
+ if (!meta) return null
233
+ meta.historyLength = historyLength
234
+ // A row written before #8866 has no hints: `null` = unknown, decided when a
235
+ // restore is attempted, rather than a false "no locator".
236
+ meta.locator = typeof row.locator === 'boolean' ? row.locator : null
237
+ return meta
238
+ }
239
+
240
+ /** Re-validate a tombstone read back from disk. */
241
+ function tombstoneFromIndexRow(row) {
242
+ if (!row || typeof row !== 'object') return null
243
+ const sessionId = boundedString(row.sessionId, MAX_ID_CHARS)
244
+ if (!sessionId) return null
245
+ if (!Number.isInteger(row.historyLength) || row.historyLength < 0) return null
246
+ return {
247
+ sessionId,
248
+ lastActivityAt: finiteOrNull(row.lastActivityAt),
249
+ historyLength: row.historyLength,
250
+ at: finiteOrNull(row.at) ?? 0,
251
+ }
252
+ }
253
+
254
+ /** Source history length of an indexed row (kept entries plus omitted-for-size ones). */
255
+ function rowSourceLength(row) {
256
+ return row.historyLength + (row.omittedOldest || 0)
257
+ }
258
+
259
+ /**
260
+ * Does `existing` already account for the candidate snapshot? Same session and
261
+ * an equal-or-NEWER state: a later `lastActivityAt`, or the same one with at
262
+ * least as much history. That covers a source that outlives its (deleted or
263
+ * evicted) record in a state backup at an OLDER point of the same session —
264
+ * the backup is superseded, not new. When either timestamp is unknown only an
265
+ * exact (timestamp, length) match counts.
266
+ * @param {{sessionId: string, lastActivityAt: number|null, length: number}} existing
267
+ * @param {{sessionId: string, lastActivityAt: number|null, length: number}} candidate
268
+ */
269
+ function snapshotCovers(existing, candidate) {
270
+ if (existing.sessionId !== candidate.sessionId) return false
271
+ const a = existing.lastActivityAt
272
+ const b = candidate.lastActivityAt
273
+ if (typeof a === 'number' && typeof b === 'number') {
274
+ if (a !== b) return a > b
275
+ return existing.length >= candidate.length
276
+ }
277
+ return a === b && existing.length === candidate.length
278
+ }
279
+
280
+ const tombstoneAsSnapshot = (t) => ({ sessionId: t.sessionId, lastActivityAt: t.lastActivityAt, length: t.historyLength })
281
+
282
+ /**
283
+ * Serialise one record's JSON, omitting the OLDEST history entries until it
284
+ * fits `maxBytes`. Each entry is stringified once; the record is assembled from
285
+ * those pieces rather than stringified a second time.
286
+ * @returns {{ json: string, omittedOldest: number, kept: number } | null} null
287
+ * when not even the newest entry fits
288
+ */
289
+ function buildRecordJson(saved, { archivedAt, reason }, maxBytes) {
290
+ const { history, ...rest } = saved
291
+ const parts = history.map((entry) => JSON.stringify(entry) ?? 'null')
292
+ const sizes = parts.map((part) => Buffer.byteLength(part))
293
+ const restJson = JSON.stringify(rest)
294
+ const sep = restJson === '{}' ? '' : ','
295
+ const historyOpen = `${sep}"history":[`
296
+ const prefix = (omitted) => `{"version":${FORMAT_VERSION},"archivedAt":${JSON.stringify(archivedAt)},"reason":${JSON.stringify(reason)},"omittedOldest":${omitted},"saved":`
297
+ const fixed = Buffer.byteLength(restJson) - 1 + Buffer.byteLength(historyOpen) + 3
298
+ let keptBytes = sizes.reduce((sum, n) => sum + n, 0)
299
+ // The EXACT size for each candidate start (the digit width of `omittedOldest`
300
+ // included), so an entry is never discarded on an over-estimate.
301
+ const totalFor = (from) => Buffer.byteLength(prefix(from)) + fixed + keptBytes + Math.max(0, parts.length - from - 1)
302
+ let start = 0
303
+ while (start < parts.length && totalFor(start) > maxBytes) {
304
+ keptBytes -= sizes[start]
305
+ start++
306
+ }
307
+ if (start >= parts.length) return null
308
+ const kept = parts.slice(start)
309
+ const savedJson = `${restJson.slice(0, -1)}${historyOpen}${kept.join(',')}]}`
310
+ return { json: `${prefix(start)}${savedJson}}`, omittedOldest: start, kept: kept.length }
311
+ }
312
+
313
+ export class SessionArchive {
314
+ /**
315
+ * @param {object} options
316
+ * @param {string} options.dir - archive directory (created lazily on first write)
317
+ * @param {boolean} [options.enabled=true] - off switch: stops NEW writes only;
318
+ * retention still runs so old data keeps ageing out
319
+ * @param {number} [options.maxEntries=100] - clamped to SESSION_ARCHIVE_MAX_ENTRIES
320
+ * @param {number} [options.maxAgeDays=30]
321
+ * @param {number} [options.maxMegabytes=256]
322
+ * @param {() => number} [options.now] - clock seam for tests
323
+ * @param {{ truncateEntry: (entry: object) => object }} [options.historyHelper] -
324
+ * the history truncator the pager uses; defaults to a private one
325
+ * @param {number} [options.maxRecordBytes] - test seam for MAX_RECORD_BYTES
326
+ * (NOT a config key)
327
+ * @param {typeof writeFileRestricted} [options.writeFile] - test seam for the
328
+ * atomic file write (NOT a config key)
329
+ */
330
+ constructor({ dir, enabled, maxEntries, maxAgeDays, maxMegabytes, now = () => Date.now(), historyHelper, maxRecordBytes, writeFile = writeFileRestricted } = {}) {
331
+ this._dirValid = typeof dir === 'string' && dir.length > 0
332
+ if (!this._dirValid) log.warn('SessionArchive: no archive directory given — archiving is disabled')
333
+ this._dir = this._dirValid ? dir : null
334
+ if (enabled !== undefined && typeof enabled !== 'boolean') {
335
+ log.warn(`sessionArchive.enabled: expected a boolean, got ${JSON.stringify(enabled)} — using the default (${SESSION_ARCHIVE_DEFAULTS.enabled})`)
336
+ }
337
+ this._enabled = this._dirValid && (typeof enabled === 'boolean' ? enabled : SESSION_ARCHIVE_DEFAULTS.enabled)
338
+ this._maxEntries = positiveNumber(maxEntries, SESSION_ARCHIVE_DEFAULTS.maxEntries, 'maxEntries', { integer: true, max: SESSION_ARCHIVE_MAX_ENTRIES })
339
+ this._maxAgeDays = positiveNumber(maxAgeDays, SESSION_ARCHIVE_DEFAULTS.maxAgeDays, 'maxAgeDays')
340
+ this._maxMegabytes = positiveNumber(maxMegabytes, SESSION_ARCHIVE_DEFAULTS.maxMegabytes, 'maxMegabytes')
341
+ this._maxRecordBytes = typeof maxRecordBytes === 'number' && Number.isFinite(maxRecordBytes) && maxRecordBytes > 0 ? maxRecordBytes : MAX_RECORD_BYTES
342
+ this._now = typeof now === 'function' ? now : () => Date.now()
343
+ this._historyHelper = historyHelper || new SessionMessageHistory({})
344
+ this._writeFile = typeof writeFile === 'function' ? writeFile : writeFileRestricted
345
+ this._tmpSuffix = `.tmp-${process.pid}`
346
+ /** @type {object[]|null} null until a load SUCCEEDS (a failed load is retried) */
347
+ this._index = null
348
+ /** @type {object[]} bounded FIFO of removed records' fingerprints */
349
+ this._tombstones = []
350
+ /** one decoded record, so paging does not gunzip on every page */
351
+ this._cache = null
352
+ /** snapshots taken by enqueue() that are not in the index yet */
353
+ this._pending = []
354
+ this._pumping = null
355
+ }
356
+
357
+ /** @returns {{ enabled: boolean, maxEntries: number, maxAgeDays: number, maxMegabytes: number }} */
358
+ retentionPolicy() {
359
+ return {
360
+ enabled: this._enabled,
361
+ maxEntries: this._maxEntries,
362
+ maxAgeDays: this._maxAgeDays,
363
+ maxMegabytes: this._maxMegabytes,
364
+ }
365
+ }
366
+
367
+ /**
368
+ * Replace the retention policy at runtime and re-run retention so lowered
369
+ * limits take effect now. The caller validates (config.js
370
+ * validateSessionArchivePolicy); `enabled` is still ANDed with the directory.
371
+ * @param {{ enabled: boolean, maxEntries: number, maxAgeDays: number, maxMegabytes: number }} policy
372
+ * @returns {ReturnType<SessionArchive['retentionPolicy']>} the applied policy
373
+ */
374
+ setRetentionPolicy({ enabled, maxEntries, maxAgeDays, maxMegabytes }) {
375
+ this._enabled = this._dirValid && enabled === true
376
+ this._maxEntries = maxEntries
377
+ this._maxAgeDays = maxAgeDays
378
+ this._maxMegabytes = maxMegabytes
379
+ this.prune()
380
+ return this.retentionPolicy()
381
+ }
382
+
383
+ /**
384
+ * Archive one ended session SYNCHRONOUSLY and say what happened. NEVER
385
+ * throws: archiving must not be able to break a teardown.
386
+ *
387
+ * archived a record was written (`meta` is its roster row)
388
+ * duplicate this snapshot (or a newer one of the same session) is already
389
+ * archived, was archived and since removed (tombstone), or is
390
+ * queued — nothing to do
391
+ * skipped nothing to keep: archiving is off, the history is empty, or
392
+ * the record alone is larger than the user's own byte cap (it is
393
+ * not written and NOTHING is evicted to make room)
394
+ * failed the write (or the serialisation, or loading the archive)
395
+ * threw — the caller must NOT drop the only copy of the session
396
+ * if it has a choice
397
+ *
398
+ * The write is fsync'd: this is the path the boot-time callers use, and they
399
+ * drop the source right after.
400
+ *
401
+ * @param {object} saved - a serialized session entry (SessionManager._serializeSessionEntry)
402
+ * @param {string} [reason='closed']
403
+ * @returns {{ status: 'archived'|'duplicate'|'skipped'|'failed', meta?: object }}
404
+ */
405
+ archiveOutcome(saved, reason = 'closed') {
406
+ try {
407
+ const prepared = this._prepare(saved, reason)
408
+ if (!prepared.job) return prepared
409
+ const job = prepared.job
410
+ const gz = gzipSync(job.json, GZIP_OPTS)
411
+ job.done = true
412
+ const meta = this._commit(job, gz, { durable: true })
413
+ return meta ? { status: 'archived', meta } : { status: 'skipped' }
414
+ } catch (err) {
415
+ log.warn(`Failed to archive session: ${err?.message || err}`)
416
+ return { status: 'failed' }
417
+ }
418
+ }
419
+
420
+ /**
421
+ * Archive one ended session (synchronous).
422
+ * @param {object} saved
423
+ * @param {string} [reason='closed']
424
+ * @returns {object|null} the roster row, or null when nothing was archived
425
+ */
426
+ archive(saved, reason = 'closed') {
427
+ const outcome = this.archiveOutcome(saved, reason)
428
+ return outcome.status === 'archived' ? outcome.meta : null
429
+ }
430
+
431
+ /**
432
+ * Queue one ended session for archiving off the event loop. The snapshot's
433
+ * JSON is taken NOW (so the live session can be torn down immediately); the
434
+ * compression and the write happen on a serial queue. NEVER throws.
435
+ * @returns {{ status: 'queued'|'duplicate'|'skipped'|'failed' }}
436
+ */
437
+ enqueue(saved, reason = 'closed') {
438
+ try {
439
+ const prepared = this._prepare(saved, reason)
440
+ if (!prepared.job) return prepared
441
+ this._pending.push(prepared.job)
442
+ this._schedule()
443
+ return { status: 'queued' }
444
+ } catch (err) {
445
+ log.warn(`Failed to queue session for the archive: ${err?.message || err}`)
446
+ return { status: 'failed' }
447
+ }
448
+ }
449
+
450
+ /** Resolves when every queued snapshot has been written (or has failed). */
451
+ async whenIdle() {
452
+ while (this._pumping) await this._pumping
453
+ }
454
+
455
+ /**
456
+ * Finish every queued snapshot synchronously. Called on shutdown so a clean
457
+ * exit does not lose a session that was closed moments ago. NEVER throws.
458
+ */
459
+ drainSync() {
460
+ for (const job of [...this._pending]) {
461
+ if (job.done) continue
462
+ try {
463
+ const gz = gzipSync(job.json, GZIP_OPTS)
464
+ job.done = true
465
+ this._commit(job, gz, { durable: true })
466
+ } catch (err) {
467
+ job.done = true
468
+ log.warn(`Failed to archive a queued session at shutdown: ${err?.message || err}`)
469
+ }
470
+ }
471
+ this._pending = this._pending.filter((job) => !job.done)
472
+ }
473
+
474
+ /**
475
+ * Load the archive and apply retention now, even with archiving turned off.
476
+ * Called at daemon boot and on a timer so records age out without waiting
477
+ * for a new session to end. NEVER throws.
478
+ */
479
+ prune() {
480
+ try {
481
+ this._ensureLoaded()
482
+ this._sweep()
483
+ } catch (err) {
484
+ log.warn(`Failed to prune the session archive: ${err?.message || err}`)
485
+ }
486
+ }
487
+
488
+ /** @returns {object[]} roster rows, newest first */
489
+ list() {
490
+ try {
491
+ this._ensureLoaded()
492
+ this._sweep()
493
+ } catch (err) {
494
+ log.warn(`Failed to load session archive: ${err?.message || err}`)
495
+ return []
496
+ }
497
+ return [...this._index]
498
+ .sort((a, b) => (b.archivedAt ?? 0) - (a.archivedAt ?? 0) || (a.archiveId < b.archiveId ? -1 : 1))
499
+ .map((row) => ({ ...row }))
500
+ }
501
+
502
+ /**
503
+ * One bounded page of an archived session's history, oldest first. The
504
+ * record is read and inflated off the event loop.
505
+ * @param {string} archiveId
506
+ * @param {{ offset?: number, limit?: number }} [opts]
507
+ * @returns {Promise<{ok: true, total: number, offset: number, entries: object[]} | {ok: false, code: string, message: string}>}
508
+ */
509
+ async getHistoryPage(archiveId, { offset, limit } = {}) {
510
+ const notFound = {
511
+ ok: false,
512
+ code: ARCHIVE_NOT_FOUND_CODE,
513
+ message: 'No archived session with that id',
514
+ }
515
+ try {
516
+ this._ensureLoaded()
517
+ this._sweep() // an expired record is never served
518
+ if (!this._knows(archiveId)) return notFound
519
+ const record = await this._readRecord(archiveId)
520
+ // Re-checked AFTER the await on every path, a cache hit included: the
521
+ // record may have been deleted or aged out while this read was in flight.
522
+ if (!record || !this._knows(archiveId)) return notFound
523
+ return { ok: true, ...pageHistory(record.saved?.history, { offset, limit }, this._historyHelper) }
524
+ } catch (err) {
525
+ log.warn(`Failed to read archived session: ${err?.message || err}`)
526
+ return notFound
527
+ }
528
+ }
529
+
530
+ /**
531
+ * The saved session entry of one record, for a restore (#8866). The returned
532
+ * object belongs to the caller (the one-record cache is dropped), because a
533
+ * restore seeds history onto it and must not leave the cached copy mutated.
534
+ * @param {string} archiveId
535
+ * @returns {Promise<{ok: true, saved: object, meta: object} | {ok: false, code: string, message: string}>}
536
+ */
537
+ async getSaved(archiveId) {
538
+ const notFound = { ok: false, code: ARCHIVE_NOT_FOUND_CODE, message: 'No archived session with that id' }
539
+ try {
540
+ this._ensureLoaded()
541
+ this._sweep()
542
+ if (!this._knows(archiveId)) return notFound
543
+ const record = await this._readRecord(archiveId)
544
+ if (!record || !this._knows(archiveId) || !record.saved || typeof record.saved !== 'object') return notFound
545
+ this._invalidate(archiveId)
546
+ const row = this._index.find((r) => r.archiveId === archiveId)
547
+ return { ok: true, saved: record.saved, meta: { ...row } }
548
+ } catch (err) {
549
+ log.warn(`Failed to read archived session for restore: ${err?.message || err}`)
550
+ return notFound
551
+ }
552
+ }
553
+
554
+ /**
555
+ * Remove a record WITHOUT a tombstone: the session it held is live again
556
+ * (#8866), so a later close must be free to archive it afresh. A tombstone
557
+ * would make that archive (and a dismissed failed restore of the same
558
+ * snapshot) dedupe to `duplicate` and drop the only copy.
559
+ *
560
+ * The file goes first: if the index write then fails the row is orphaned and
561
+ * dropped at the next load (its file is gone); the other order would leave a
562
+ * file the next load re-adopts.
563
+ * @param {string} archiveId
564
+ * @returns {'released'|'not_found'|'failed'}
565
+ */
566
+ release(archiveId) {
567
+ try {
568
+ this._ensureLoaded()
569
+ this._sweep()
570
+ if (!this._knows(archiveId)) return 'not_found'
571
+ if (!this._unlinkRecord(archiveId)) return 'failed'
572
+ this._invalidate(archiveId)
573
+ this._index = this._index.filter((row) => row.archiveId !== archiveId)
574
+ this._writeIndex({ durable: true })
575
+ return 'released'
576
+ } catch (err) {
577
+ log.warn(`Failed to release archived session: ${err?.message || err}`)
578
+ return 'failed'
579
+ }
580
+ }
581
+
582
+ /**
583
+ * @param {string} archiveId
584
+ * @returns {'deleted'|'not_found'|'failed'} `failed` means the record could
585
+ * not be removed durably (its tombstone could not be written, or its file
586
+ * could not be unlinked): it is still listed
587
+ */
588
+ delete(archiveId) {
589
+ try {
590
+ this._ensureLoaded()
591
+ this._sweep()
592
+ if (!this._knows(archiveId)) return 'not_found'
593
+ const row = this._index.find((r) => r.archiveId === archiveId)
594
+ const { removed } = this._removeRows([row])
595
+ return removed.length > 0 ? 'deleted' : 'failed'
596
+ } catch (err) {
597
+ log.warn(`Failed to delete archived session: ${err?.message || err}`)
598
+ return 'failed'
599
+ }
600
+ }
601
+
602
+ /**
603
+ * Delete every record, AND cancel every snapshot still queued (a session
604
+ * closed just before the request must not reappear after it).
605
+ * @returns {{ deleted: number, failed: number }} `failed` counts records that
606
+ * are still on disk
607
+ */
608
+ deleteAll() {
609
+ let deleted = 0
610
+ let failed = 0
611
+ try {
612
+ this._ensureLoaded()
613
+ this._sweep()
614
+ const cancelled = this._cancelPending()
615
+ const rows = [...this._index]
616
+ const { removed, failed: stuck } = this._removeRows(rows)
617
+ // Rows were written with the cancelled snapshots' tombstones; with no rows
618
+ // the tombstones still need to reach disk.
619
+ if (cancelled > 0 && rows.length === 0) this._writeIndex({ durable: true, create: true })
620
+ deleted = cancelled + removed.length
621
+ failed = stuck.length
622
+ } catch (err) {
623
+ log.warn(`Failed to delete archived sessions: ${err?.message || err}`)
624
+ failed++
625
+ }
626
+ return { deleted, failed }
627
+ }
628
+
629
+ // -- internals ------------------------------------------------------------
630
+
631
+ /**
632
+ * Everything an archive attempt does BEFORE compression, synchronously:
633
+ * load, retention, the skip rules, the dedupe, and the size-bounded JSON.
634
+ * @returns {{ status: string } | { job: object }}
635
+ */
636
+ _prepare(saved, reason) {
637
+ this._ensureLoaded()
638
+ this._sweep() // the off switch stops new writes; it must not stop old data ageing out
639
+ if (!this._enabled) return { status: 'skipped' }
640
+ if (!savedHasHistory(saved)) return { status: 'skipped' }
641
+ const archivedAt = this._now()
642
+ const probe = metaFrom(saved, { archiveId: '0'.repeat(32), reason, archivedAt, bytes: 0 })
643
+ if (!probe) return { status: 'skipped' }
644
+ // The same snapshot — or an older one of the same session — again: a crash
645
+ // between archive and the state flush, a stale entry seen on two boots, a
646
+ // backup that still carries a source whose archive was since deleted
647
+ // (tombstone), or one still being compressed.
648
+ const candidate = { sessionId: probe.sessionId, lastActivityAt: probe.lastActivityAt, length: probe.historyLength }
649
+ if (this._isKnownSnapshot(candidate)) return { status: 'duplicate' }
650
+
651
+ const built = buildRecordJson(saved, { archivedAt, reason: probe.reason }, this._maxRecordBytes)
652
+ if (!built) throw new Error(`no history entry fits the ${this._maxRecordBytes}-byte record bound`)
653
+ if (built.omittedOldest > 0) {
654
+ log.warn(`Archiving session ${probe.sessionId}: the ${built.omittedOldest} oldest history entries exceed the record size bound and were omitted`)
655
+ }
656
+ const archiveId = randomBytes(16).toString('hex')
657
+ return {
658
+ job: {
659
+ archiveId,
660
+ json: built.json,
661
+ candidate,
662
+ done: false,
663
+ meta: { ...probe, archiveId, historyLength: built.kept, omittedOldest: built.omittedOldest },
664
+ },
665
+ }
666
+ }
667
+
668
+ _isKnownSnapshot(candidate) {
669
+ return this._index.some((row) => snapshotCovers({ sessionId: row.sessionId, lastActivityAt: row.lastActivityAt, length: rowSourceLength(row) }, candidate))
670
+ || this._tombstones.some((t) => snapshotCovers(tombstoneAsSnapshot(t), candidate))
671
+ || this._pending.some((job) => snapshotCovers(job.candidate, candidate))
672
+ }
673
+
674
+ /**
675
+ * Write a prepared job's compressed record and index it. THROWS on a failed
676
+ * write (after removing the temp file the failed write may have left).
677
+ * @returns {object|null} the roster row; null (nothing written, NOTHING
678
+ * evicted) when the record alone exceeds the user's byte cap
679
+ */
680
+ _commit(job, gz, { durable = false } = {}) {
681
+ if (gz.length > this._maxMegabytes * MIB) {
682
+ log.warn(`Not archiving session ${job.meta.sessionId}: its ${gz.length}-byte record alone exceeds the sessionArchive.maxMegabytes cap (${this._maxMegabytes})`)
683
+ return null
684
+ }
685
+ mkdirSync(this._dir, { recursive: true, mode: 0o700 })
686
+ // mkdir's mode only applies to a directory it creates, and is masked by the
687
+ // umask; make the guarantee explicit for one that already existed.
688
+ if (!isWindows) {
689
+ try { chmodSync(this._dir, 0o700) } catch { /* best effort */ }
690
+ }
691
+ const path = this._recordPath(job.archiveId)
692
+ try {
693
+ this._writeFile(path, gz, { tmpSuffix: this._tmpSuffix, durable })
694
+ } catch (err) {
695
+ this._unlinkTemp(path)
696
+ throw err
697
+ }
698
+ const meta = { ...job.meta, bytes: gz.length }
699
+ this._index.push(meta)
700
+ this._enforceRetention(job.archiveId)
701
+ this._writeIndex({ durable })
702
+ return { ...meta }
703
+ }
704
+
705
+ _schedule() {
706
+ if (this._pumping) return
707
+ this._pumping = (async () => {
708
+ try {
709
+ for (;;) {
710
+ const job = this._pending.find((j) => !j.done)
711
+ if (!job) break
712
+ await this._runJob(job)
713
+ }
714
+ } finally {
715
+ this._pumping = null
716
+ }
717
+ })()
718
+ }
719
+
720
+ async _runJob(job) {
721
+ try {
722
+ const gz = await gzipAsync(job.json, GZIP_OPTS)
723
+ if (job.done) return // drainSync() finished it, or deleteAll() cancelled it, while we compressed
724
+ job.done = true
725
+ this._commit(job, gz)
726
+ } catch (err) {
727
+ job.done = true
728
+ log.warn(`Failed to archive a closed session: ${err?.message || err}`)
729
+ } finally {
730
+ this._pending = this._pending.filter((j) => j !== job)
731
+ }
732
+ }
733
+
734
+ /** Cancel every queued snapshot and tombstone it. @returns {number} how many */
735
+ _cancelPending() {
736
+ let cancelled = 0
737
+ for (const job of this._pending) {
738
+ if (job.done) continue
739
+ job.done = true
740
+ this._addTombstone(job.candidate.sessionId, job.candidate.lastActivityAt, job.candidate.length)
741
+ cancelled++
742
+ }
743
+ this._pending = []
744
+ return cancelled
745
+ }
746
+
747
+ /** Apply retention now (it persists the index itself when it drops anything). */
748
+ _sweep() {
749
+ this._enforceRetention()
750
+ }
751
+
752
+ _addTombstone(sessionId, lastActivityAt, length) {
753
+ const tombstone = { sessionId, lastActivityAt, historyLength: length, at: this._now() }
754
+ this._tombstones.push(tombstone)
755
+ if (this._tombstones.length > MAX_TOMBSTONES) this._tombstones.splice(0, this._tombstones.length - MAX_TOMBSTONES)
756
+ return tombstone
757
+ }
758
+
759
+ /**
760
+ * Remove rows DURABLY: the index (without the rows, with their tombstones) is
761
+ * written FIRST and the record files are unlinked only after that succeeded,
762
+ * so a crash or a failed write can never leave a deleted record without its
763
+ * tombstone. A row whose file could not be unlinked is put back (and its
764
+ * tombstone dropped) so it stays visible and is retried.
765
+ * @param {object[]} rows
766
+ * @returns {{ removed: object[], failed: object[] }}
767
+ */
768
+ _removeRows(rows) {
769
+ if (rows.length === 0) return { removed: [], failed: [] }
770
+ const ids = new Set(rows.map((row) => row.archiveId))
771
+ const prevIndex = this._index
772
+ const prevTombstones = this._tombstones
773
+ this._index = prevIndex.filter((row) => !ids.has(row.archiveId))
774
+ this._tombstones = [...prevTombstones]
775
+ const added = new Map()
776
+ for (const row of rows) added.set(row.archiveId, this._addTombstone(row.sessionId, row.lastActivityAt, rowSourceLength(row)))
777
+ if (!this._writeIndex({ durable: true })) {
778
+ this._index = prevIndex
779
+ this._tombstones = prevTombstones
780
+ return { removed: [], failed: rows }
781
+ }
782
+ const removed = []
783
+ const failed = []
784
+ for (const row of rows) {
785
+ if (this._unlinkRecord(row.archiveId)) {
786
+ removed.push(row)
787
+ this._invalidate(row.archiveId)
788
+ } else {
789
+ failed.push(row)
790
+ }
791
+ }
792
+ if (failed.length > 0) {
793
+ const stuck = new Set(failed.map((row) => added.get(row.archiveId)))
794
+ this._index = [...this._index, ...failed]
795
+ this._tombstones = this._tombstones.filter((t) => !stuck.has(t))
796
+ this._writeIndex({ durable: true })
797
+ }
798
+ return { removed, failed }
799
+ }
800
+
801
+ /** A client-supplied id is only ever used after BOTH checks. */
802
+ _knows(archiveId) {
803
+ return typeof archiveId === 'string'
804
+ && ARCHIVE_ID_RE.test(archiveId)
805
+ && this._index.some((row) => row.archiveId === archiveId)
806
+ }
807
+
808
+ _recordPath(archiveId) {
809
+ // Only ever called with an id this class generated or one that passed _knows.
810
+ return join(this._dir, `${archiveId}${RECORD_SUFFIX}`)
811
+ }
812
+
813
+ _invalidate(archiveId) {
814
+ if (this._cache?.archiveId === archiveId) this._cache = null
815
+ }
816
+
817
+ _unlinkTemp(path) {
818
+ try { unlinkSync(`${path}${this._tmpSuffix}`) } catch { /* nothing left to remove */ }
819
+ }
820
+
821
+ /** @returns {boolean} true when the file is gone afterwards */
822
+ _unlinkRecord(archiveId) {
823
+ try {
824
+ unlinkSync(this._recordPath(archiveId))
825
+ return true
826
+ } catch (err) {
827
+ if (err?.code === 'ENOENT') return true
828
+ log.warn(`Failed to remove archive record ${archiveId}: ${err?.message || err}`)
829
+ return false
830
+ }
831
+ }
832
+
833
+ async _readRecord(archiveId) {
834
+ if (this._cache?.archiveId === archiveId) return this._cache.record
835
+ let record
836
+ try {
837
+ const raw = await gunzipAsync(await readFileNoFollow(this._recordPath(archiveId)), { maxOutputLength: this._maxRecordBytes })
838
+ record = JSON.parse(raw.toString('utf8'))
839
+ } catch (err) {
840
+ log.warn(`Unreadable archive record ${archiveId}: ${errTag(err)}`)
841
+ return null
842
+ }
843
+ if (!record || typeof record !== 'object') return null
844
+ // The record may have been deleted or aged out while it was being read.
845
+ if (!this._knows(archiveId)) return null
846
+ this._cache = { archiveId, record }
847
+ return record
848
+ }
849
+
850
+ /**
851
+ * Persist the index and tombstones. The record files are the authority for
852
+ * rows (a lost index is rebuilt), but TOMBSTONES exist nowhere else, so
853
+ * callers that depend on one check the result.
854
+ * @returns {boolean} false when the write failed (its temp file is removed)
855
+ */
856
+ _writeIndex({ durable = false, create = false } = {}) {
857
+ if (!existsSync(this._dir)) {
858
+ if (!create) return true
859
+ try { mkdirSync(this._dir, { recursive: true, mode: 0o700 }) } catch (err) {
860
+ log.warn(`Failed to create the session archive directory: ${err?.message || err}`)
861
+ return false
862
+ }
863
+ }
864
+ const path = join(this._dir, INDEX_FILE)
865
+ try {
866
+ this._writeFile(path, JSON.stringify({ version: FORMAT_VERSION, entries: this._index, tombstones: this._tombstones }), { tmpSuffix: this._tmpSuffix, durable })
867
+ return true
868
+ } catch (err) {
869
+ this._unlinkTemp(path)
870
+ log.warn(`Failed to write the session archive index: ${err?.message || err}`)
871
+ return false
872
+ }
873
+ }
874
+
875
+ /**
876
+ * Read the index, reconcile it with the record files, then apply retention.
877
+ * Only a MISSING directory (or index) means "empty": any other read error
878
+ * THROWS, leaving the archive unloaded so the next call retries, instead of
879
+ * caching an empty index that the next write would persist over real data.
880
+ */
881
+ _ensureLoaded() {
882
+ if (this._index) return
883
+ if (!this._dirValid) {
884
+ this._index = []
885
+ return
886
+ }
887
+ let names
888
+ try {
889
+ names = readdirSync(this._dir)
890
+ } catch (err) {
891
+ // ENOTDIR: a path component is a file, so there is no archive here either.
892
+ if (err?.code === 'ENOENT' || err?.code === 'ENOTDIR') {
893
+ this._index = []
894
+ this._tombstones = []
895
+ return
896
+ }
897
+ throw err
898
+ }
899
+ const onDisk = new Set()
900
+ for (const name of names) {
901
+ const m = RECORD_FILE_RE.exec(name)
902
+ if (m) {
903
+ onDisk.add(m[1])
904
+ } else if (TMP_FILE_RE.test(name)) {
905
+ // A temp left by a write that died mid-way. Load precedes this process's
906
+ // own writes, so it cannot be ours in flight; it can hold transcript bytes.
907
+ try { unlinkSync(join(this._dir, name)) } catch { /* best effort */ }
908
+ }
909
+ }
910
+
911
+ let indexed = []
912
+ let tombstones = []
913
+ let dirty = false
914
+ let indexExisted = true
915
+ try {
916
+ const parsed = JSON.parse(readFileNoFollowSync(join(this._dir, INDEX_FILE)).toString('utf8'))
917
+ if (!parsed || !Array.isArray(parsed.entries)) throw new Error('malformed index')
918
+ const seen = new Set()
919
+ for (const row of parsed.entries) {
920
+ const meta = metaFromIndexRow(row)
921
+ if (!meta || seen.has(meta.archiveId)) { dirty = true; continue }
922
+ seen.add(meta.archiveId)
923
+ indexed.push(meta)
924
+ }
925
+ if (Array.isArray(parsed.tombstones)) {
926
+ const valid = parsed.tombstones.map(tombstoneFromIndexRow).filter(Boolean)
927
+ if (valid.length !== parsed.tombstones.length) dirty = true
928
+ tombstones = valid.slice(-MAX_TOMBSTONES)
929
+ }
930
+ } catch (err) {
931
+ if (err?.code === 'ENOENT') {
932
+ indexExisted = false
933
+ } else if (err?.name === 'SyntaxError' || err?.code === 'ELOOP' || err?.code === 'ENOTREG' || err?.message === 'malformed index') {
934
+ // Corrupt (or a planted symlink): rebuild from the record files. Log the
935
+ // class of error only — a parse message can quote the file's content.
936
+ log.warn(`Session archive index unreadable (${errTag(err)}) — rebuilding from the record files`)
937
+ } else {
938
+ throw err // EACCES, EIO, ...: not "empty" — do not overwrite what we cannot read
939
+ }
940
+ indexed = []
941
+ tombstones = []
942
+ dirty = true
943
+ }
944
+
945
+ // Drop rows whose file is gone.
946
+ const reconciled = indexed.filter((meta) => onDisk.has(meta.archiveId))
947
+ if (reconciled.length !== indexed.length) dirty = true
948
+ // Adopt record files the index does not know — unless a tombstone says the
949
+ // record was deleted (its unlink never ran: a crash between the two).
950
+ const known = new Set(reconciled.map((meta) => meta.archiveId))
951
+ for (const archiveId of onDisk) {
952
+ if (known.has(archiveId)) continue
953
+ const adopted = this._deriveMeta(archiveId)
954
+ if (!adopted) continue
955
+ const candidate = { sessionId: adopted.sessionId, lastActivityAt: adopted.lastActivityAt, length: rowSourceLength(adopted) }
956
+ if (tombstones.some((t) => snapshotCovers(tombstoneAsSnapshot(t), candidate))) {
957
+ this._unlinkRecord(archiveId)
958
+ continue
959
+ }
960
+ reconciled.push(adopted)
961
+ dirty = true
962
+ }
963
+ this._index = reconciled
964
+ this._tombstones = tombstones
965
+ this._enforceRetention()
966
+ // An empty directory with no index is simply empty: do not create a file.
967
+ if (dirty && (indexExisted || this._index.length > 0)) this._writeIndex()
968
+ }
969
+
970
+ /** Derive a roster row from a record file the index does not know. */
971
+ _deriveMeta(archiveId) {
972
+ try {
973
+ const compressed = readFileNoFollowSync(this._recordPath(archiveId))
974
+ const raw = gunzipSync(compressed, { maxOutputLength: this._maxRecordBytes })
975
+ const record = JSON.parse(raw.toString('utf8'))
976
+ if (!record || typeof record !== 'object' || !record.saved || typeof record.saved !== 'object') return null
977
+ return metaFrom(record.saved, {
978
+ archiveId,
979
+ reason: record.reason,
980
+ archivedAt: record.archivedAt,
981
+ bytes: compressed.length,
982
+ omittedOldest: record.omittedOldest,
983
+ })
984
+ } catch (err) {
985
+ log.warn(`Skipping unreadable archive record ${archiveId}: ${errTag(err)}`)
986
+ return null
987
+ }
988
+ }
989
+
990
+ /**
991
+ * Age, then count, then total bytes — oldest first each time — through
992
+ * `_removeRows`, so each dropped row's tombstone is on disk before its file is
993
+ * unlinked. Only as many rows as needed are dropped, and `protectId` (the
994
+ * record being committed) is never evicted to satisfy the COUNT or BYTE cap
995
+ * (a record that is itself past maxAge ages out at the next sweep as usual). A pass whose index write
996
+ * failed drops nothing and is retried by the next one.
997
+ * @param {string} [protectId]
998
+ * @returns {number} how many rows were dropped
999
+ */
1000
+ _enforceRetention(protectId) {
1001
+ if (!this._index || this._index.length === 0) return 0
1002
+ const now = this._now()
1003
+ const maxAgeMs = this._maxAgeDays * DAY_MS
1004
+ const maxBytes = this._maxMegabytes * MIB
1005
+ const oldestFirst = [...this._index].sort((a, b) => (a.archivedAt ?? 0) - (b.archivedAt ?? 0) || (a.archiveId < b.archiveId ? -1 : 1))
1006
+ const drop = new Set()
1007
+ for (const row of oldestFirst) {
1008
+ if (typeof row.archivedAt === 'number' && now - row.archivedAt > maxAgeMs) drop.add(row.archiveId)
1009
+ }
1010
+ const kept = oldestFirst.filter((row) => !drop.has(row.archiveId))
1011
+ const evictable = () => kept.find((row) => row.archiveId !== protectId)
1012
+ while (kept.length > this._maxEntries) {
1013
+ const victim = evictable()
1014
+ if (!victim) break
1015
+ drop.add(victim.archiveId)
1016
+ kept.splice(kept.indexOf(victim), 1)
1017
+ }
1018
+ let total = kept.reduce((sum, row) => sum + (row.bytes || 0), 0)
1019
+ while (total > maxBytes) {
1020
+ const victim = evictable()
1021
+ if (!victim) break
1022
+ drop.add(victim.archiveId)
1023
+ kept.splice(kept.indexOf(victim), 1)
1024
+ total -= victim.bytes || 0
1025
+ }
1026
+ if (drop.size === 0) return 0
1027
+ return this._removeRows(oldestFirst.filter((row) => drop.has(row.archiveId))).removed.length
1028
+ }
1029
+ }