omnicell-router 0.8.4 → 0.10.0

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 (363) hide show
  1. package/README.md +26 -7
  2. package/README.zh-CN.md +18 -5
  3. package/backend/dist/capture/recorder.d.ts +4 -10
  4. package/backend/dist/capture/recorder.js +6 -58
  5. package/backend/dist/cli/clients/base.d.ts +36 -11
  6. package/backend/dist/cli/clients/base.js +31 -15
  7. package/backend/dist/cli/clients/claude.d.ts +9 -0
  8. package/backend/dist/cli/clients/claude.js +6 -0
  9. package/backend/dist/cli/clients/codex.d.ts +8 -0
  10. package/backend/dist/cli/clients/codex.js +5 -0
  11. package/backend/dist/cli/clients/core-adapters.d.ts +1 -1
  12. package/backend/dist/cli/clients/core-adapters.js +1 -1
  13. package/backend/dist/cli/clients/dsh.d.ts +8 -0
  14. package/backend/dist/cli/clients/dsh.js +5 -0
  15. package/backend/dist/cli/clients/grok.d.ts +15 -1
  16. package/backend/dist/cli/clients/grok.js +16 -2
  17. package/backend/dist/cli/clients/index.d.ts +13 -1
  18. package/backend/dist/cli/clients/index.js +97 -19
  19. package/backend/dist/cli/clients/kimi.d.ts +6 -0
  20. package/backend/dist/cli/clients/kimi.js +3 -0
  21. package/backend/dist/cli/clients/launcher.d.ts +1 -1
  22. package/backend/dist/cli/clients/model-meta.js +6 -3
  23. package/backend/dist/cli/clients/omp.d.ts +6 -0
  24. package/backend/dist/cli/clients/omp.js +3 -0
  25. package/backend/dist/cli/clients/openclaw.d.ts +6 -0
  26. package/backend/dist/cli/clients/openclaw.js +3 -0
  27. package/backend/dist/cli/clients/opencode.d.ts +8 -0
  28. package/backend/dist/cli/clients/opencode.js +5 -0
  29. package/backend/dist/cli/clients/pi.d.ts +6 -0
  30. package/backend/dist/cli/clients/pi.js +3 -0
  31. package/backend/dist/cli/clients/update-check.d.ts +37 -0
  32. package/backend/dist/cli/clients/update-check.js +309 -0
  33. package/backend/dist/cli/clients/workbuddy.d.ts +19 -0
  34. package/backend/dist/cli/clients/workbuddy.js +66 -0
  35. package/backend/dist/cli/index.js +5 -4
  36. package/backend/dist/cli/paths.js +8 -0
  37. package/backend/dist/cli/types.d.ts +92 -16
  38. package/backend/dist/config/comments-en.js +31 -26
  39. package/backend/dist/config/comments-zh.js +29 -24
  40. package/backend/dist/config/defaults.d.ts +194 -33
  41. package/backend/dist/config/defaults.js +193 -32
  42. package/backend/dist/config/env.d.ts +10 -0
  43. package/backend/dist/config/env.js +3 -2
  44. package/backend/dist/config/index.d.ts +7 -0
  45. package/backend/dist/config/index.js +184 -43
  46. package/backend/dist/config/migrations/v0-to-v1.d.ts +2 -2
  47. package/backend/dist/config/migrations/v10-to-v11.d.ts +38 -0
  48. package/backend/dist/config/migrations/v10-to-v11.js +43 -0
  49. package/backend/dist/config/migrations/v6-to-v7.d.ts +45 -0
  50. package/backend/dist/config/migrations/v6-to-v7.js +97 -0
  51. package/backend/dist/config/migrations/v7-to-v8.d.ts +36 -0
  52. package/backend/dist/config/migrations/v7-to-v8.js +43 -0
  53. package/backend/dist/config/migrations/v8-to-v9.d.ts +38 -0
  54. package/backend/dist/config/migrations/v8-to-v9.js +43 -0
  55. package/backend/dist/config/migrations/v9-to-v10.d.ts +51 -0
  56. package/backend/dist/config/migrations/v9-to-v10.js +71 -0
  57. package/backend/dist/config/runtime.js +1 -1
  58. package/backend/dist/config/schema.d.ts +3 -3
  59. package/backend/dist/config/schema.js +14 -4
  60. package/backend/dist/config/types.d.ts +167 -38
  61. package/backend/dist/egress-proxy/asset-download.d.ts +54 -0
  62. package/backend/dist/egress-proxy/asset-download.js +420 -0
  63. package/backend/dist/egress-proxy/manual-node-spec.d.ts +92 -0
  64. package/backend/dist/egress-proxy/manual-node-spec.js +408 -0
  65. package/backend/dist/egress-proxy/mihomo-binary.d.ts +54 -0
  66. package/backend/dist/egress-proxy/mihomo-binary.js +278 -0
  67. package/backend/dist/egress-proxy/mihomo-client.d.ts +94 -0
  68. package/backend/dist/egress-proxy/mihomo-client.js +308 -0
  69. package/backend/dist/egress-proxy/mihomo-config.d.ts +40 -0
  70. package/backend/dist/egress-proxy/mihomo-config.js +161 -0
  71. package/backend/dist/egress-proxy/mihomo-geo.d.ts +87 -0
  72. package/backend/dist/egress-proxy/mihomo-geo.js +213 -0
  73. package/backend/dist/egress-proxy/mihomo-logs.d.ts +43 -0
  74. package/backend/dist/egress-proxy/mihomo-logs.js +84 -0
  75. package/backend/dist/egress-proxy/mihomo-pac.d.ts +37 -0
  76. package/backend/dist/egress-proxy/mihomo-pac.js +75 -0
  77. package/backend/dist/egress-proxy/mihomo-rules-import.d.ts +43 -0
  78. package/backend/dist/egress-proxy/mihomo-rules-import.js +193 -0
  79. package/backend/dist/egress-proxy/mihomo-sidecar.d.ts +81 -0
  80. package/backend/dist/egress-proxy/mihomo-sidecar.js +637 -0
  81. package/backend/dist/forward-proxy/egress.d.ts +50 -11
  82. package/backend/dist/forward-proxy/egress.js +50 -17
  83. package/backend/dist/forward-proxy/h2-forward.js +36 -10
  84. package/backend/dist/forward-proxy/index.d.ts +11 -8
  85. package/backend/dist/forward-proxy/index.js +22 -60
  86. package/backend/dist/forward-proxy/interceptor.d.ts +3 -2
  87. package/backend/dist/forward-proxy/interceptor.js +4 -4
  88. package/backend/dist/forward-proxy/relay.js +3 -3
  89. package/backend/dist/forward-proxy/rules.d.ts +4 -4
  90. package/backend/dist/forward-proxy/rules.js +25 -4
  91. package/backend/dist/forward-proxy/server.d.ts +0 -16
  92. package/backend/dist/forward-proxy/server.js +124 -156
  93. package/backend/dist/harness/host/hosts.js +3 -2
  94. package/backend/dist/index.js +53 -18
  95. package/backend/dist/ingress-proxy/access-log.d.ts +176 -0
  96. package/backend/dist/ingress-proxy/access-log.js +774 -0
  97. package/backend/dist/ingress-proxy/ca-inventory.d.ts +106 -0
  98. package/backend/dist/ingress-proxy/ca-inventory.js +525 -0
  99. package/backend/dist/ingress-proxy/ca-trust.d.ts +96 -0
  100. package/backend/dist/ingress-proxy/ca-trust.js +315 -0
  101. package/backend/dist/ingress-proxy/ca.d.ts +104 -0
  102. package/backend/dist/ingress-proxy/ca.js +273 -0
  103. package/backend/dist/ingress-proxy/data-dir.d.ts +28 -0
  104. package/backend/dist/ingress-proxy/data-dir.js +45 -0
  105. package/backend/dist/ingress-proxy/egress.d.ts +151 -0
  106. package/backend/dist/ingress-proxy/egress.js +364 -0
  107. package/backend/dist/ingress-proxy/h2-forward.d.ts +66 -0
  108. package/backend/dist/ingress-proxy/h2-forward.js +561 -0
  109. package/backend/dist/ingress-proxy/index.d.ts +24 -0
  110. package/backend/dist/ingress-proxy/index.js +144 -0
  111. package/backend/dist/ingress-proxy/interceptor.d.ts +25 -0
  112. package/backend/dist/ingress-proxy/interceptor.js +52 -0
  113. package/backend/dist/ingress-proxy/ordered-relay.d.ts +29 -0
  114. package/backend/dist/ingress-proxy/ordered-relay.js +46 -0
  115. package/backend/dist/ingress-proxy/relay.d.ts +54 -0
  116. package/backend/dist/ingress-proxy/relay.js +188 -0
  117. package/backend/dist/ingress-proxy/rules.d.ts +195 -0
  118. package/backend/dist/ingress-proxy/rules.js +348 -0
  119. package/backend/dist/ingress-proxy/server.d.ts +153 -0
  120. package/backend/dist/ingress-proxy/server.js +2065 -0
  121. package/backend/dist/ingress-proxy/sni.d.ts +35 -0
  122. package/backend/dist/ingress-proxy/sni.js +124 -0
  123. package/backend/dist/ingress-proxy/status.d.ts +32 -0
  124. package/backend/dist/ingress-proxy/status.js +15 -0
  125. package/backend/dist/ingress-proxy/system-proxy.d.ts +112 -0
  126. package/backend/dist/ingress-proxy/system-proxy.js +481 -0
  127. package/backend/dist/ingress-proxy/traffic-delete.d.ts +21 -0
  128. package/backend/dist/ingress-proxy/traffic-delete.js +64 -0
  129. package/backend/dist/ingress-proxy/traffic-delete.worker.d.ts +44 -0
  130. package/backend/dist/ingress-proxy/traffic-delete.worker.js +228 -0
  131. package/backend/dist/ingress-proxy/traffic-files.d.ts +10 -0
  132. package/backend/dist/ingress-proxy/traffic-files.js +10 -0
  133. package/backend/dist/ingress-proxy/upstream-tls.d.ts +46 -0
  134. package/backend/dist/ingress-proxy/upstream-tls.js +105 -0
  135. package/backend/dist/ingress-proxy/ws-frames.d.ts +45 -0
  136. package/backend/dist/ingress-proxy/ws-frames.js +153 -0
  137. package/backend/dist/ir/adapters/anthropic-messages-stream.js +6 -1
  138. package/backend/dist/ir/adapters/anthropic-messages.js +12 -5
  139. package/backend/dist/ir/adapters/google-gemini-stream.js +7 -2
  140. package/backend/dist/ir/adapters/google-gemini.js +5 -2
  141. package/backend/dist/ir/adapters/openai-chat-stream.js +5 -1
  142. package/backend/dist/ir/adapters/openai-chat.d.ts +25 -0
  143. package/backend/dist/ir/adapters/openai-chat.js +45 -3
  144. package/backend/dist/ir/adapters/openai-responses-output.d.ts +1 -0
  145. package/backend/dist/ir/adapters/openai-responses-output.js +67 -21
  146. package/backend/dist/ir/adapters/openai-responses-stream.d.ts +13 -0
  147. package/backend/dist/ir/adapters/openai-responses-stream.js +34 -1
  148. package/backend/dist/ir/adapters/openai-responses.d.ts +82 -24
  149. package/backend/dist/ir/adapters/openai-responses.js +146 -37
  150. package/backend/dist/ir/media.d.ts +20 -0
  151. package/backend/dist/ir/media.js +41 -0
  152. package/backend/dist/ir/tool-identity.d.ts +35 -0
  153. package/backend/dist/ir/tool-identity.js +40 -0
  154. package/backend/dist/ir/types.d.ts +9 -1
  155. package/backend/dist/local/build-jobs.d.ts +66 -0
  156. package/backend/dist/local/build-jobs.js +243 -0
  157. package/backend/dist/local/detect.d.ts +32 -0
  158. package/backend/dist/local/detect.js +145 -0
  159. package/backend/dist/local/draft-match.d.ts +58 -0
  160. package/backend/dist/local/draft-match.js +124 -0
  161. package/backend/dist/local/engine-runtime.d.ts +522 -0
  162. package/backend/dist/local/engine-runtime.js +1 -0
  163. package/backend/dist/local/engines.d.ts +241 -0
  164. package/backend/dist/local/engines.js +651 -0
  165. package/backend/dist/local/gguf.d.ts +35 -0
  166. package/backend/dist/local/gguf.js +314 -0
  167. package/backend/dist/local/hf.d.ts +120 -0
  168. package/backend/dist/local/hf.js +304 -0
  169. package/backend/dist/local/install.d.ts +90 -0
  170. package/backend/dist/local/install.js +421 -0
  171. package/backend/dist/local/llamacpp.d.ts +55 -0
  172. package/backend/dist/local/llamacpp.js +177 -0
  173. package/backend/dist/local/local-provider.d.ts +81 -0
  174. package/backend/dist/local/local-provider.js +301 -0
  175. package/backend/dist/local/machine-stats.d.ts +87 -0
  176. package/backend/dist/local/machine-stats.js +332 -0
  177. package/backend/dist/local/model-store.d.ts +347 -0
  178. package/backend/dist/local/model-store.js +1215 -0
  179. package/backend/dist/local/part-sweep.d.ts +32 -0
  180. package/backend/dist/local/part-sweep.js +156 -0
  181. package/backend/dist/local/plan.d.ts +65 -0
  182. package/backend/dist/local/plan.js +146 -0
  183. package/backend/dist/local/resources.d.ts +49 -0
  184. package/backend/dist/local/resources.js +64 -0
  185. package/backend/dist/local/run-stats.d.ts +95 -0
  186. package/backend/dist/local/run-stats.js +195 -0
  187. package/backend/dist/local/runner.d.ts +235 -0
  188. package/backend/dist/local/runner.js +1392 -0
  189. package/backend/dist/local/settings.d.ts +79 -0
  190. package/backend/dist/local/settings.js +180 -0
  191. package/backend/dist/local/strata-catalog.d.ts +30 -0
  192. package/backend/dist/local/strata-catalog.js +511 -0
  193. package/backend/dist/local/strata-drafting.d.ts +46 -0
  194. package/backend/dist/local/strata-drafting.js +265 -0
  195. package/backend/dist/local/strata.d.ts +278 -0
  196. package/backend/dist/local/strata.js +1392 -0
  197. package/backend/dist/local/tar.d.ts +20 -0
  198. package/backend/dist/local/tar.js +367 -0
  199. package/backend/dist/local/transport.d.ts +35 -0
  200. package/backend/dist/local/transport.js +89 -0
  201. package/backend/dist/local/tune.d.ts +58 -0
  202. package/backend/dist/local/tune.js +324 -0
  203. package/backend/dist/observability/http-exchange.d.ts +2 -2
  204. package/backend/dist/opencode/catalog/auto-pull.d.ts +14 -3
  205. package/backend/dist/opencode/catalog/auto-pull.js +276 -70
  206. package/backend/dist/opencode/catalog/ocr-store.js +3 -1
  207. package/backend/dist/opencode/catalog/overrides-store.d.ts +10 -1
  208. package/backend/dist/opencode/catalog/overrides-store.js +6 -0
  209. package/backend/dist/opencode/catalog/reasoning-declaration.d.ts +35 -0
  210. package/backend/dist/opencode/catalog/reasoning-declaration.js +66 -0
  211. package/backend/dist/opencode/catalog/repository.js +25 -2
  212. package/backend/dist/opencode/catalog/sources/models-dev.js +13 -3
  213. package/backend/dist/opencode/catalog/types.d.ts +35 -3
  214. package/backend/dist/opencode/catalog/types.js +38 -1
  215. package/backend/dist/opencode/credentials/ocr-store.js +11 -2
  216. package/backend/dist/opencode/credentials/sync.js +12 -3
  217. package/backend/dist/opencode/credentials/types.d.ts +31 -4
  218. package/backend/dist/opencode/credentials/types.js +25 -0
  219. package/backend/dist/opencode/probe.d.ts +21 -4
  220. package/backend/dist/opencode/probe.js +34 -10
  221. package/backend/dist/pipeline/directives.d.ts +9 -4
  222. package/backend/dist/pipeline/directives.js +14 -10
  223. package/backend/dist/pipeline/orchestrator.d.ts +42 -13
  224. package/backend/dist/pipeline/orchestrator.js +497 -165
  225. package/backend/dist/plugins/environment-ack.d.ts +51 -0
  226. package/backend/dist/plugins/environment-ack.js +81 -0
  227. package/backend/dist/plugins/gateways.d.ts +6 -6
  228. package/backend/dist/plugins/gateways.js +2 -2
  229. package/backend/dist/plugins/host.d.ts +98 -14
  230. package/backend/dist/plugins/host.js +622 -87
  231. package/backend/dist/plugins/install-run.d.ts +27 -0
  232. package/backend/dist/plugins/install-run.js +99 -0
  233. package/backend/dist/plugins/manifest.d.ts +84 -32
  234. package/backend/dist/plugins/manifest.js +149 -45
  235. package/backend/dist/plugins/market-install.d.ts +18 -0
  236. package/backend/dist/plugins/market-install.js +111 -0
  237. package/backend/dist/plugins/market-source.d.ts +100 -0
  238. package/backend/dist/plugins/market-source.js +449 -0
  239. package/backend/dist/plugins/market-updates.d.ts +70 -0
  240. package/backend/dist/plugins/market-updates.js +97 -0
  241. package/backend/dist/plugins/market.d.ts +677 -0
  242. package/backend/dist/plugins/market.js +2113 -0
  243. package/backend/dist/plugins/source-index.d.ts +155 -0
  244. package/backend/dist/plugins/source-index.js +217 -0
  245. package/backend/dist/plugins/types.d.ts +402 -37
  246. package/backend/dist/projects/worktrees.d.ts +88 -0
  247. package/backend/dist/projects/worktrees.js +220 -0
  248. package/backend/dist/providers/boot-direct.d.ts +41 -7
  249. package/backend/dist/providers/boot-direct.js +252 -36
  250. package/backend/dist/providers/compat/tool-markup-recovery.js +31 -6
  251. package/backend/dist/providers/executors/dispatch.d.ts +17 -7
  252. package/backend/dist/providers/executors/dispatch.js +28 -9
  253. package/backend/dist/providers/executors/openai-chat.js +14 -2
  254. package/backend/dist/providers/executors/plugin-adapter.d.ts +23 -1
  255. package/backend/dist/providers/executors/plugin-adapter.js +59 -3
  256. package/backend/dist/providers/member-match.d.ts +32 -9
  257. package/backend/dist/providers/member-match.js +65 -21
  258. package/backend/dist/providers/model-resolution.d.ts +62 -0
  259. package/backend/dist/providers/model-resolution.js +62 -0
  260. package/backend/dist/providers/price-order.d.ts +51 -0
  261. package/backend/dist/providers/price-order.js +54 -0
  262. package/backend/dist/providers/provider-takedown.d.ts +5 -2
  263. package/backend/dist/providers/registry.d.ts +84 -25
  264. package/backend/dist/providers/registry.js +209 -114
  265. package/backend/dist/providers/selection.d.ts +91 -0
  266. package/backend/dist/providers/selection.js +158 -0
  267. package/backend/dist/providers/virtual-meta.d.ts +33 -2
  268. package/backend/dist/providers/virtual-meta.js +74 -18
  269. package/backend/dist/quota/cli-login.d.ts +25 -4
  270. package/backend/dist/quota/cli-login.js +35 -5
  271. package/backend/dist/quota/coverage-generation.d.ts +24 -0
  272. package/backend/dist/quota/coverage-generation.js +29 -0
  273. package/backend/dist/quota/declarations.js +8 -4
  274. package/backend/dist/quota/engine.js +2 -2
  275. package/backend/dist/quota/prober.d.ts +43 -2
  276. package/backend/dist/quota/prober.js +97 -22
  277. package/backend/dist/ratelimit/rate-limiter.d.ts +1 -1
  278. package/backend/dist/resilience/error-classifier.js +29 -0
  279. package/backend/dist/router/index.d.ts +1 -1
  280. package/backend/dist/router/index.js +17 -1
  281. package/backend/dist/router/layer2-decision.d.ts +1 -1
  282. package/backend/dist/router/layer2-decision.js +2 -2
  283. package/backend/dist/routes/console.js +928 -310
  284. package/backend/dist/routes/environments.js +1 -1
  285. package/backend/dist/routes/local-models.d.ts +2 -0
  286. package/backend/dist/routes/local-models.js +1414 -0
  287. package/backend/dist/routes/mihomo.d.ts +2 -2
  288. package/backend/dist/routes/mihomo.js +20 -11
  289. package/backend/dist/routes/projects.js +121 -0
  290. package/backend/dist/server.js +318 -13
  291. package/backend/dist/session/session-manager.d.ts +42 -5
  292. package/backend/dist/session/session-manager.js +64 -11
  293. package/backend/dist/session/session-row.d.ts +29 -8
  294. package/backend/dist/session/session-row.js +18 -13
  295. package/backend/dist/snapshot/bundle.d.ts +40 -0
  296. package/backend/dist/snapshot/bundle.js +177 -0
  297. package/backend/dist/snapshot/handoff/compress.d.ts +46 -0
  298. package/backend/dist/snapshot/handoff/compress.js +77 -0
  299. package/backend/dist/snapshot/handoff/index.d.ts +119 -0
  300. package/backend/dist/snapshot/handoff/index.js +160 -0
  301. package/backend/dist/snapshot/handoff/jsonl-writer.d.ts +78 -0
  302. package/backend/dist/snapshot/handoff/jsonl-writer.js +175 -0
  303. package/backend/dist/snapshot/handoff/opencode-writer.d.ts +51 -0
  304. package/backend/dist/snapshot/handoff/opencode-writer.js +214 -0
  305. package/backend/dist/snapshot/handoff/summarize.d.ts +39 -0
  306. package/backend/dist/snapshot/handoff/summarize.js +118 -0
  307. package/backend/dist/snapshot/handoff/transcript.d.ts +71 -0
  308. package/backend/dist/snapshot/handoff/transcript.js +167 -0
  309. package/backend/dist/snapshot/media-fs.d.ts +10 -0
  310. package/backend/dist/snapshot/media-fs.js +50 -0
  311. package/backend/dist/snapshot/media.d.ts +32 -0
  312. package/backend/dist/snapshot/media.js +87 -0
  313. package/backend/dist/snapshot/store.d.ts +226 -0
  314. package/backend/dist/snapshot/store.js +887 -0
  315. package/backend/dist/snapshot/tree.d.ts +112 -0
  316. package/backend/dist/snapshot/tree.js +207 -0
  317. package/backend/dist/snapshot/types.d.ts +212 -0
  318. package/backend/dist/snapshot/types.js +14 -0
  319. package/backend/dist/snapshot/view.d.ts +19 -0
  320. package/backend/dist/snapshot/view.js +57 -0
  321. package/backend/dist/snapshot/write-worker.d.ts +67 -0
  322. package/backend/dist/snapshot/write-worker.js +129 -0
  323. package/backend/dist/surfaces/body-admission.d.ts +67 -2
  324. package/backend/dist/surfaces/body-admission.js +218 -13
  325. package/backend/dist/surfaces/chat-pipeline.js +8 -0
  326. package/backend/dist/surfaces/decision-pipeline.js +10 -7
  327. package/backend/dist/surfaces/gateway-catalog.d.ts +26 -0
  328. package/backend/dist/surfaces/gateway-catalog.js +202 -0
  329. package/backend/dist/surfaces/gateway-chat.d.ts +7 -11
  330. package/backend/dist/surfaces/gateway-chat.js +50 -12
  331. package/backend/dist/surfaces/ocr-headers.d.ts +6 -4
  332. package/backend/dist/surfaces/ocr-headers.js +11 -7
  333. package/backend/dist/surfaces/systemone.js +1 -1
  334. package/backend/dist/surfaces/transport-fastify.js +32 -5
  335. package/backend/dist/surfaces/transport-node-http.d.ts +9 -3
  336. package/backend/dist/surfaces/transport-node-http.js +6 -19
  337. package/backend/dist/surfaces/types.d.ts +11 -3
  338. package/backend/dist/trace/persist.js +21 -1
  339. package/backend/dist/trace/tracker.d.ts +35 -3
  340. package/backend/dist/trace/tracker.js +23 -0
  341. package/backend/dist/types/openai.d.ts +8 -0
  342. package/backend/dist/types/router.d.ts +17 -6
  343. package/backend/dist/types/router.js +14 -2
  344. package/backend/dist/utils/client-families.d.ts +66 -0
  345. package/backend/dist/utils/client-families.js +127 -0
  346. package/backend/dist/utils/event-ring.d.ts +1 -1
  347. package/backend/dist/utils/event-ring.js +1 -1
  348. package/backend/dist/utils/proxy-node.js +1 -1
  349. package/backend/dist/utils/proxy.d.ts +135 -11
  350. package/backend/dist/utils/proxy.js +144 -29
  351. package/backend/dist/utils/run-command.d.ts +21 -1
  352. package/backend/dist/utils/run-command.js +64 -4
  353. package/backend/dist/utils/server-liveness.d.ts +3 -2
  354. package/backend/dist/utils/server-liveness.js +3 -2
  355. package/backend/dist/utils/session-file.d.ts +28 -0
  356. package/backend/dist/utils/session-file.js +34 -0
  357. package/frontend/dist/assets/antigravity.color-DXFfVr6X.svg +39 -0
  358. package/frontend/dist/assets/gemini-cli.color-BfquLd1p.svg +1 -0
  359. package/frontend/dist/assets/index-CTZNvn1d.js +1707 -0
  360. package/frontend/dist/assets/{index-KI1OW5x6.css → index-CqDSOPQ0.css} +1 -1
  361. package/frontend/dist/index.html +2 -2
  362. package/package.json +3 -1
  363. package/frontend/dist/assets/index-Dk76uc7e.js +0 -1522
@@ -0,0 +1,887 @@
1
+ import fs from 'node:fs';
2
+ import path from 'node:path';
3
+ import { Worker } from 'node:worker_threads';
4
+ import { compiledSnapshotExe } from '../cli/paths.js';
5
+ import { getEnvPaths } from '../config/env.js';
6
+ import { renameWithRetry } from '../utils/atomic-write.js';
7
+ import { sessionFileName } from '../utils/session-file.js';
8
+ import { EXT_TO_MIME, MEDIA_FILE_RE, MEDIA_HASH_RE } from '../ir/media.js';
9
+ import { offloadInputMedia, offloadOutputMedia, rehydrateInputMedia, rehydrateOutputMedia } from './media.js';
10
+ import { ensureDirSync, storeMediaPayload } from './media-fs.js';
11
+ import { SNAPSHOT_SCHEMA, } from './types.js';
12
+ const DATE_MS = 24 * 60 * 60 * 1000;
13
+ /**
14
+ * Media younger than this is never collected: a payload is written BEFORE its
15
+ * transcript line is appended (asynchronously), so during the write window the
16
+ * digest is referenced by a line that is not on disk yet. An orphan simply
17
+ * waits for a later sweep — the hourly cadence keeps the bound.
18
+ *
19
+ * Grace ALONE cannot close the window: a wall-clock jump (system sleep/resume,
20
+ * a paused process) ages a payload past any fixed grace while its append is
21
+ * still queued, and the resume-time sweep would collect a payload the pending
22
+ * line is about to reference. `pendingMedia` (the in-memory guard) closes it
23
+ * deterministically; the grace remains as the second line of defence for
24
+ * writes whose queue state this process no longer remembers.
25
+ */
26
+ const MEDIA_GC_GRACE_MS = 10 * 60 * 1000;
27
+ /**
28
+ * Strip everything the handoff plane must not carry, returning a deep clone of
29
+ * the items so the caller's live request object stays untouched.
30
+ *
31
+ * - `cache` breakpoints are dropped at every level (message, part, tool,
32
+ * tool-result) — a KV prefix cache is keyed by bytes AND provider account and
33
+ * can never hit on another instance.
34
+ * - `vendor` bags are dropped: they are carrier-private echoes that only mean
35
+ * something to the exact carrier that produced them.
36
+ * Everything else — text, signatures, tool call ids, reasoning `encrypted` —
37
+ * is preserved verbatim, because it is load-bearing for replay.
38
+ */
39
+ function sanitizeItems(items) {
40
+ const clone = structuredClone(items);
41
+ for (const item of clone) {
42
+ const rec = item;
43
+ delete rec.cache;
44
+ delete rec.vendor;
45
+ if (Array.isArray(rec.content)) {
46
+ for (const part of rec.content) {
47
+ delete part.cache;
48
+ }
49
+ }
50
+ }
51
+ return clone;
52
+ }
53
+ /** Read every line of a session file, tolerating a torn trailing line. */
54
+ function parseLines(raw) {
55
+ const turns = [];
56
+ for (const line of raw.split(/\r?\n/)) {
57
+ const trimmed = line.trim();
58
+ if (!trimmed)
59
+ continue;
60
+ try {
61
+ const parsed = JSON.parse(trimmed);
62
+ if (parsed?.kind === 'turn')
63
+ turns.push(parsed);
64
+ }
65
+ catch {
66
+ // A torn trailing line (crash mid-append) — skip it; the turn is simply
67
+ // absent. Earlier turns are intact because append never rewrites.
68
+ }
69
+ }
70
+ return turns;
71
+ }
72
+ /**
73
+ * Compiled sidecar: a plain path resolved against the compiled ENTRY ROOT — a
74
+ * snapshot cannot resolve a worker through `import.meta.url` (Bun issue
75
+ * #16869), so the worker ships as a SECOND entrypoint (`build-sidecar.ts`),
76
+ * and the root is the entries' common directory (`backend/src`). Dev /
77
+ * `node dist`: the URL form, which Bun maps `.js` → `.ts`.
78
+ */
79
+ function createSnapshotWorker() {
80
+ if (compiledSnapshotExe())
81
+ return new Worker('./snapshot/write-worker.ts');
82
+ return new Worker(new URL('./write-worker.js', import.meta.url));
83
+ }
84
+ export class SessionSnapshotStore {
85
+ enabled;
86
+ rootDir;
87
+ retentionDays;
88
+ maxTotalBytes;
89
+ maxTurnBytes;
90
+ sweepTimer;
91
+ /** Serialized append chain so concurrent turns never interleave and flush can await. */
92
+ writeChain = Promise.resolve();
93
+ /** Sessions that hit a cap and must not append further this process. */
94
+ halted = new Set();
95
+ /**
96
+ * Digest (`sha.ext`) → number of queued appends that still reference it.
97
+ * A payload leaves only when its last queued line lands on disk (or its
98
+ * append fails — the line will never exist, so the payload becomes a REAL
99
+ * orphan). collectMedia consults this so a clock jump cannot collect media
100
+ * out from under a queued turn.
101
+ */
102
+ pendingMedia = new Map();
103
+ /**
104
+ * Off-thread writer. Spawned lazily on the first recorded turn; a worker
105
+ * error or exit is permanent — the inline chain takes over again (fail-open,
106
+ * never a retry of the dropped turn: a duplicate line is worse than a
107
+ * missing one).
108
+ */
109
+ worker;
110
+ workerDead = false;
111
+ workerSeq = 0;
112
+ /** Digest keys pinned for a turn the worker is assembling right now. */
113
+ workerKeys = new Map();
114
+ workerWaiters = new Map();
115
+ constructor(config) {
116
+ // Mirror DEFAULT_CONFIG exactly (single source): a bare `new
117
+ // SessionSnapshotStore()` must not default to off when the shipped default
118
+ // is on — that divergence is how a feature silently disappears.
119
+ this.enabled = config?.enabled ?? true;
120
+ this.retentionDays = config?.retentionDays ?? 30;
121
+ this.maxTotalBytes = (config?.maxTotalMB ?? 1024) * 1024 * 1024;
122
+ this.maxTurnBytes = (config?.maxTurnMB ?? 8) * 1024 * 1024;
123
+ this.rootDir = path.resolve(config?.dir || getEnvPaths().snapshotsDir);
124
+ if (this.enabled) {
125
+ // Boot cost is one readdir + stat per session file; the sweep is what
126
+ // keeps a 30-day store from quietly outgrowing its budget across runs.
127
+ this.ensureDir(this.rootDir);
128
+ this.sweep();
129
+ this.startSweepTimer();
130
+ }
131
+ }
132
+ isEnabled() {
133
+ return this.enabled;
134
+ }
135
+ getDir() {
136
+ return this.rootDir;
137
+ }
138
+ /** Hot-apply a new config at runtime (console toggle). */
139
+ applyConfig(cfg) {
140
+ this.enabled = cfg?.enabled ?? this.enabled;
141
+ this.retentionDays = cfg?.retentionDays ?? this.retentionDays;
142
+ this.maxTotalBytes = cfg?.maxTotalMB !== undefined ? cfg.maxTotalMB * 1024 * 1024 : this.maxTotalBytes;
143
+ this.maxTurnBytes = cfg?.maxTurnMB !== undefined ? cfg.maxTurnMB * 1024 * 1024 : this.maxTurnBytes;
144
+ const newDir = path.resolve(cfg?.dir || this.rootDir);
145
+ if (newDir !== this.rootDir) {
146
+ this.rootDir = newDir;
147
+ this.halted.clear();
148
+ // Queued appends reference the OLD directory's payloads; the guard must
149
+ // not pin same-named digests in the new one.
150
+ this.pendingMedia.clear();
151
+ }
152
+ if (this.enabled) {
153
+ this.ensureDir(this.rootDir);
154
+ this.startSweepTimer();
155
+ }
156
+ else {
157
+ this.stopSweepTimer();
158
+ }
159
+ this.postConfigToWorker();
160
+ }
161
+ /**
162
+ * Record one completed model request. Writes nothing when disabled.
163
+ *
164
+ * The record is assembled and appended OFF the calling stack — in the write
165
+ * worker when it is available, in the serialized inline chain otherwise — so
166
+ * no base64 decode, sha256, media `writeFileSync`/rename or `JSON.stringify`
167
+ * of the turn runs before the caller returns. This runs on the response path
168
+ * of a streaming gateway: that work used to stall every OTHER in-flight
169
+ * stream for up to tens of milliseconds per completed turn (ADR-0038 §3).
170
+ * The response output is cloned here, synchronously, because the caller
171
+ * keeps mutating the live `ExecResult`.
172
+ */
173
+ recordTurn(input) {
174
+ if (!this.enabled)
175
+ return false;
176
+ if (this.halted.has(input.sessionId))
177
+ return false;
178
+ // The caller already handed us a private pre-compression clone with cache /
179
+ // vendor stripped (`snapshotRequestViewOf`), so it is safe to mutate in
180
+ // place for media offload. Re-clone the response's output because that one
181
+ // is the live ExecResult's array.
182
+ const request = input.request;
183
+ const response = {
184
+ status: input.response.status,
185
+ ...(input.response.reason ? { reason: input.response.reason } : {}),
186
+ output: sanitizeItems(input.response.output),
187
+ usage: structuredClone(input.response.usage),
188
+ };
189
+ const turn = {
190
+ schema: SNAPSHOT_SCHEMA,
191
+ kind: 'turn',
192
+ sessionId: input.sessionId,
193
+ turnIndex: input.turnIndex,
194
+ // `completed` unless the caller says otherwise: an aborted turn keeps its
195
+ // partial output but is never presented as a finished answer (ADR-0040).
196
+ outcome: input.outcome ?? 'completed',
197
+ ...(input.abortReason ? { abortReason: input.abortReason } : {}),
198
+ requestId: input.requestId,
199
+ ts: input.ts,
200
+ servedModel: input.servedModel,
201
+ request,
202
+ response,
203
+ };
204
+ const file = this.fileFor(input.sessionId);
205
+ const worker = this.ensureWorker();
206
+ if (worker) {
207
+ try {
208
+ const id = ++this.workerSeq;
209
+ // Structured-cloning the turn into the worker is a memcpy; the decode,
210
+ // hash, stringify and fs work all happen on the other thread.
211
+ worker.postMessage({ type: 'turn', id, sessionId: input.sessionId, file, turn });
212
+ return true;
213
+ }
214
+ catch (err) {
215
+ console.warn(`[snapshot] write worker post failed: ${err.message}`);
216
+ this.abandonWorker();
217
+ }
218
+ }
219
+ return this.appendInline(input, turn, file);
220
+ }
221
+ /** Legacy main-thread path, used when the worker is unavailable. */
222
+ appendInline(input, turn, file) {
223
+ try {
224
+ // Offload media AFTER sanitizing so the walk sees the clone's parts, and
225
+ // merge the entries the request and response halves contributed.
226
+ const reqMedia = offloadInputMedia(turn.request.input, (raw, sha, ext) => this.storeMediaFile(raw, sha, ext));
227
+ const resMedia = offloadOutputMedia(turn.response.output, (raw, sha, ext) => this.storeMediaFile(raw, sha, ext));
228
+ const media = { ...reqMedia.entries, ...resMedia.entries };
229
+ if (Object.keys(media).length)
230
+ turn.media = media;
231
+ const line = JSON.stringify(turn) + '\n';
232
+ const bytes = Buffer.byteLength(line, 'utf8');
233
+ if (bytes > this.maxTurnBytes) {
234
+ // Too big to be a turn we could ever hand over faithfully. Halt the
235
+ // session rather than store a giant line: export must refuse, not ship
236
+ // a conversation that will not fit through any downstream body limit.
237
+ this.writeIncomplete(file, input, 'turn-cap', bytes);
238
+ return false;
239
+ }
240
+ this.ensureDir(path.dirname(file));
241
+ // Register the digests BEFORE the line is durable: collectMedia skips a
242
+ // payload a queued append still references, so a wall-clock jump
243
+ // (sleep/resume) or a stalled disk can never let the hourly sweep
244
+ // collect media whose transcript line has not landed yet.
245
+ const mediaKeys = Object.keys(media);
246
+ this.pinMedia(mediaKeys);
247
+ // Serialize the appends through one chain so two turns of the same
248
+ // session can never interleave mid-line, and `flush()` can await them.
249
+ // `appendFile` itself still fails open — an unhandled rejection would kill
250
+ // the gateway, so the catch is on the chain, never on the caller. A
251
+ // failed append releases its digests too: without the line the payload
252
+ // is a real orphan for the next sweep.
253
+ this.writeChain = this.writeChain
254
+ .then(() => fs.promises.appendFile(file, line, 'utf8'))
255
+ .then(() => this.releaseMedia(mediaKeys), (err) => {
256
+ this.releaseMedia(mediaKeys);
257
+ console.warn(`[snapshot] failed to append turn for ${input.sessionId}: ${err.message}`);
258
+ });
259
+ return true;
260
+ }
261
+ catch (err) {
262
+ // Fail-open: a snapshot problem must never break the inference path.
263
+ console.warn(`[snapshot] failed to append turn for ${input.sessionId}: ${err.message}`);
264
+ return false;
265
+ }
266
+ }
267
+ ensureWorker() {
268
+ if (this.worker)
269
+ return this.worker;
270
+ if (this.workerDead || !this.enabled)
271
+ return undefined;
272
+ try {
273
+ const worker = createSnapshotWorker();
274
+ // Never hold the process open for an observability writer.
275
+ worker.unref?.();
276
+ worker.on('message', (message) => this.onWorkerMessage(message));
277
+ worker.on('error', (err) => {
278
+ console.warn(`[snapshot] write worker error: ${err.message}`);
279
+ this.abandonWorker();
280
+ });
281
+ worker.on('exit', (code) => {
282
+ if (!this.workerDead)
283
+ console.warn(`[snapshot] write worker exited (${code}); inline writes take over`);
284
+ this.abandonWorker();
285
+ });
286
+ this.worker = worker;
287
+ this.postConfigToWorker();
288
+ return worker;
289
+ }
290
+ catch (err) {
291
+ console.warn(`[snapshot] write worker unavailable: ${err.message}`);
292
+ this.workerDead = true;
293
+ return undefined;
294
+ }
295
+ }
296
+ postConfigToWorker() {
297
+ try {
298
+ this.worker?.postMessage({ type: 'config', rootDir: this.rootDir, maxTurnBytes: this.maxTurnBytes });
299
+ }
300
+ catch {
301
+ this.abandonWorker();
302
+ }
303
+ }
304
+ /**
305
+ * Drop the worker and everything only IT could finish. A turn already posted
306
+ * is lost (observability fails open) but never retried — the worker may have
307
+ * appended the line before dying, and a duplicate transcript line is worse
308
+ * than a missing one.
309
+ */
310
+ abandonWorker() {
311
+ this.worker = undefined;
312
+ this.workerDead = true;
313
+ for (const keys of this.workerKeys.values())
314
+ this.releaseMedia(keys);
315
+ this.workerKeys.clear();
316
+ for (const resolve of this.workerWaiters.values())
317
+ resolve();
318
+ this.workerWaiters.clear();
319
+ }
320
+ onWorkerMessage(message) {
321
+ // A late message from an abandoned worker must not re-pin digests that
322
+ // `abandonWorker` already released.
323
+ if (!this.worker)
324
+ return;
325
+ if (message.type === 'media') {
326
+ // Pin BEFORE acknowledging: the worker does not write a payload or a
327
+ // referencing line until it sees the ack.
328
+ this.pinMedia(message.keys);
329
+ this.workerKeys.set(message.id, message.keys);
330
+ try {
331
+ this.worker?.postMessage({ type: 'media-ack', id: message.id });
332
+ }
333
+ catch {
334
+ this.abandonWorker();
335
+ }
336
+ }
337
+ else if (message.type === 'written') {
338
+ this.releaseMedia(this.workerKeys.get(message.id) ?? []);
339
+ this.workerKeys.delete(message.id);
340
+ }
341
+ else if (message.type === 'halt') {
342
+ this.halted.add(message.sessionId);
343
+ this.releaseMedia(this.workerKeys.get(message.id) ?? []);
344
+ this.workerKeys.delete(message.id);
345
+ }
346
+ else if (message.type === 'failed') {
347
+ this.releaseMedia(this.workerKeys.get(message.id) ?? []);
348
+ this.workerKeys.delete(message.id);
349
+ console.warn(`[snapshot] failed to append turn: ${message.message}`);
350
+ }
351
+ else if (message.type === 'flushed') {
352
+ const resolve = this.workerWaiters.get(message.id);
353
+ this.workerWaiters.delete(message.id);
354
+ resolve?.();
355
+ }
356
+ }
357
+ pinMedia(keys) {
358
+ for (const key of keys)
359
+ this.pendingMedia.set(key, (this.pendingMedia.get(key) ?? 0) + 1);
360
+ }
361
+ releaseMedia(keys) {
362
+ for (const key of keys) {
363
+ const n = (this.pendingMedia.get(key) ?? 0) - 1;
364
+ if (n <= 0)
365
+ this.pendingMedia.delete(key);
366
+ else
367
+ this.pendingMedia.set(key, n);
368
+ }
369
+ }
370
+ /** Write an `incomplete` trailer ONCE and stop appending for that session. */
371
+ writeIncomplete(file, input, reason, refusedBytes) {
372
+ if (this.halted.has(input.sessionId))
373
+ return;
374
+ this.halted.add(input.sessionId);
375
+ const marker = {
376
+ schema: SNAPSHOT_SCHEMA,
377
+ kind: 'incomplete',
378
+ reason,
379
+ turnIndex: input.turnIndex,
380
+ requestId: input.requestId,
381
+ ts: input.ts,
382
+ refusedBytes,
383
+ limitBytes: reason === 'turn-cap' ? this.maxTurnBytes : this.maxTotalBytes,
384
+ };
385
+ try {
386
+ this.ensureDir(path.dirname(file));
387
+ fs.appendFileSync(file, JSON.stringify(marker) + '\n', 'utf8');
388
+ }
389
+ catch {
390
+ // Already halted in memory; the marker is best-effort.
391
+ }
392
+ console.warn(`[snapshot] session ${input.sessionId} halted (${reason}): ` +
393
+ `turn ${input.turnIndex ?? 'none'} needs ${refusedBytes} bytes, limit ${marker.limitBytes} — export will refuse`);
394
+ }
395
+ /** Read one session's full transcript (turns + any incomplete marker). */
396
+ read(sessionId) {
397
+ const file = this.fileFor(sessionId);
398
+ let raw;
399
+ try {
400
+ raw = fs.readFileSync(file, 'utf8');
401
+ }
402
+ catch {
403
+ return null;
404
+ }
405
+ const turns = [];
406
+ let incomplete;
407
+ for (const line of raw.split(/\r?\n/)) {
408
+ const trimmed = line.trim();
409
+ if (!trimmed)
410
+ continue;
411
+ try {
412
+ const parsed = JSON.parse(trimmed);
413
+ if (parsed?.kind === 'turn')
414
+ turns.push(parsed);
415
+ else if (parsed?.kind === 'incomplete') {
416
+ const m = parsed;
417
+ incomplete = {
418
+ reason: m.reason,
419
+ turnIndex: m.turnIndex,
420
+ requestId: m.requestId,
421
+ ts: m.ts,
422
+ refusedBytes: m.refusedBytes,
423
+ limitBytes: m.limitBytes,
424
+ };
425
+ }
426
+ }
427
+ catch {
428
+ // torn line — skip
429
+ }
430
+ }
431
+ if (!turns.length && !incomplete)
432
+ return null;
433
+ const createdAt = turns[0]?.ts ?? incomplete?.ts ?? 0;
434
+ const updatedAt = Math.max(turns[turns.length - 1]?.ts ?? 0, incomplete?.ts ?? 0);
435
+ return {
436
+ sessionId,
437
+ schema: SNAPSHOT_SCHEMA,
438
+ createdAt,
439
+ updatedAt,
440
+ turns,
441
+ ...(incomplete ? { incomplete } : {}),
442
+ };
443
+ }
444
+ /**
445
+ * Accumulate the session's history into a transport-neutral resume payload.
446
+ *
447
+ * Each stored record already carries the FULL input as it was sent, so the
448
+ * accumulated history is the LAST COMPLETED record's `input` plus its own
449
+ * output — not a fold of every record's delta. That is what makes the resume
450
+ * faithful: the last request is exactly what a client would resend on its
451
+ * next turn, so appending the last response reproduces the next request's
452
+ * history without re-deriving any boundary.
453
+ *
454
+ * ABORTED / FAILED records are skipped as the resume anchor (ADR-0040): their
455
+ * output is a fragment the model never finished, and resuming from it would
456
+ * tell the next client that fragment was a completed answer. If the session's
457
+ * latest records are all aborted, the resume falls back to the last completed
458
+ * one; a session with NO completed record has nothing resumable. Refuses
459
+ * (returns null) when the session is incomplete, so a caller never resumes a
460
+ * broken conversation.
461
+ */
462
+ resumeView(sessionId) {
463
+ const snap = this.read(sessionId);
464
+ if (!snap || !snap.turns.length || snap.incomplete)
465
+ return null;
466
+ const last = [...snap.turns].reverse().find((t) => t.outcome === 'completed');
467
+ if (!last)
468
+ return null;
469
+ // Rehydrate media on a clone so the read view is complete on its own.
470
+ const input = structuredClone(last.request.input);
471
+ const output = structuredClone(last.response.output);
472
+ const read = (sha) => this.readMedia(sha);
473
+ rehydrateInputMedia(input, read);
474
+ rehydrateOutputMedia(output, read);
475
+ // The output items ARE assistant history; append them after the input.
476
+ const fullInput = [...input, ...output];
477
+ const media = { ...(last.media ?? {}) };
478
+ return {
479
+ sessionId,
480
+ model: last.servedModel || last.request.model,
481
+ ...(last.request.instructions !== undefined ? { instructions: last.request.instructions } : {}),
482
+ input: fullInput,
483
+ ...(last.request.tools ? { tools: last.request.tools } : {}),
484
+ ...(last.request.toolChoice ? { toolChoice: last.request.toolChoice } : {}),
485
+ ...(last.request.parallelToolCalls !== undefined ? { parallelToolCalls: last.request.parallelToolCalls } : {}),
486
+ turns: snap.turns.filter((t) => t.outcome === 'completed').length,
487
+ ...(Object.keys(media).length ? { media } : {}),
488
+ };
489
+ }
490
+ /** Session ids with a snapshot file, newest-active first (by file mtime). */
491
+ listSessions() {
492
+ let names;
493
+ try {
494
+ names = fs.readdirSync(this.rootDir);
495
+ }
496
+ catch {
497
+ return [];
498
+ }
499
+ const rows = [];
500
+ for (const name of names) {
501
+ if (!name.endsWith('.jsonl'))
502
+ continue;
503
+ const fp = path.join(this.rootDir, name);
504
+ try {
505
+ const stat = fs.statSync(fp);
506
+ if (!stat.isFile())
507
+ continue;
508
+ const turns = parseLines(fs.readFileSync(fp, 'utf8'));
509
+ if (!turns.length)
510
+ continue;
511
+ rows.push({ sessionId: turns[0].sessionId, turns: turns.length, updatedAt: stat.mtimeMs });
512
+ }
513
+ catch {
514
+ // skip unreadable
515
+ }
516
+ }
517
+ return rows.sort((a, b) => b.updatedAt - a.updatedAt);
518
+ }
519
+ /**
520
+ * Delete a session's transcript. Shared `media/` is NOT touched: a digest may
521
+ * be referenced by another session, so payload cleanup belongs to the hourly
522
+ * sweep, which derives liveness from the surviving transcripts (ADR-0038).
523
+ */
524
+ deleteSession(sessionId) {
525
+ const file = this.fileFor(sessionId);
526
+ let existed = false;
527
+ try {
528
+ fs.rmSync(file, { force: true });
529
+ existed = true;
530
+ }
531
+ catch {
532
+ existed = false;
533
+ }
534
+ this.halted.delete(sessionId);
535
+ return existed;
536
+ }
537
+ /** True when this session stopped being completable (export must refuse). */
538
+ isIncomplete(sessionId) {
539
+ return this.read(sessionId)?.incomplete !== undefined;
540
+ }
541
+ /**
542
+ * Read one offloaded media payload by its 16–64 hex hash prefix. Media lives
543
+ * in ONE content-addressed `media/` dir shared by every session (a payload is
544
+ * session-independent by construction — several sessions resending the same
545
+ * screenshot land the bytes once).
546
+ */
547
+ readMedia(hash) {
548
+ if (!MEDIA_HASH_RE.test(hash))
549
+ return null;
550
+ const dir = path.join(this.rootDir, 'media');
551
+ let names;
552
+ try {
553
+ names = fs.readdirSync(dir);
554
+ }
555
+ catch {
556
+ return null;
557
+ }
558
+ const name = names
559
+ .sort()
560
+ .find((n) => {
561
+ const stem = n.slice(0, n.lastIndexOf('.'));
562
+ return stem === hash || (stem.length === 64 && stem.startsWith(hash));
563
+ });
564
+ if (!name || !MEDIA_FILE_RE.test(name))
565
+ return null;
566
+ try {
567
+ return fs.readFileSync(path.join(dir, name));
568
+ }
569
+ catch {
570
+ return null;
571
+ }
572
+ }
573
+ /**
574
+ * Land a verified bundle (ADR-0038 import). The caller has already parsed and
575
+ * checksum-verified it; this writes the media first (so a transcript can
576
+ * never reference a file that is not yet on disk) and then the transcript
577
+ * atomically. `sessionId` may differ from the bundle's own — an operator
578
+ * re-homing a conversation onto a fresh id — and is written into every line.
579
+ * Returns the count of turns and media files written.
580
+ */
581
+ importBundle(turns, media, sessionId) {
582
+ const mediaDir = path.join(this.rootDir, 'media');
583
+ let mediaWritten = 0;
584
+ for (const [key, body] of media) {
585
+ const m = /^([0-9a-f]{64})\.([a-z0-9]{1,8})$/.exec(key);
586
+ if (!m)
587
+ continue;
588
+ const fp = path.join(mediaDir, key);
589
+ try {
590
+ if (!fs.existsSync(fp)) {
591
+ this.ensureDir(mediaDir);
592
+ const tmp = `${fp}.${process.pid}.${crypto.randomUUID().slice(0, 8)}.tmp`;
593
+ fs.writeFileSync(tmp, body);
594
+ renameWithRetry(tmp, fp);
595
+ }
596
+ mediaWritten++;
597
+ }
598
+ catch (err) {
599
+ console.warn(`[snapshot] import media write failed for ${key}: ${err.message}`);
600
+ }
601
+ }
602
+ const file = this.fileFor(sessionId);
603
+ this.ensureDir(path.dirname(file));
604
+ const lines = turns.map((t) => JSON.stringify({ ...t, sessionId }) + '\n').join('');
605
+ const tmp = `${file}.${process.pid}.${crypto.randomUUID().slice(0, 8)}.tmp`;
606
+ fs.writeFileSync(tmp, lines, 'utf8');
607
+ renameWithRetry(tmp, file);
608
+ this.halted.delete(sessionId);
609
+ return { turns: turns.length, media: mediaWritten };
610
+ }
611
+ /** Resolve a media file's content type and name for a read route. */
612
+ mediaMeta(hash) {
613
+ if (!MEDIA_HASH_RE.test(hash))
614
+ return null;
615
+ const dir = path.join(this.rootDir, 'media');
616
+ let names;
617
+ try {
618
+ names = fs.readdirSync(dir);
619
+ }
620
+ catch {
621
+ return null;
622
+ }
623
+ const name = names.find((n) => {
624
+ const stem = n.slice(0, n.lastIndexOf('.'));
625
+ return stem === hash || (stem.length === 64 && stem.startsWith(hash));
626
+ });
627
+ if (!name || !MEDIA_FILE_RE.test(name))
628
+ return null;
629
+ const ext = name.slice(name.lastIndexOf('.') + 1);
630
+ return { contentType: EXT_TO_MIME[ext] ?? 'application/octet-stream', fileName: name };
631
+ }
632
+ /** Read a payload's raw bytes straight from the shared media dir (for bundles). */
633
+ readMediaByKey(key) {
634
+ const m = /^([0-9a-f]{64})\.([a-z0-9]{1,8})$/.exec(key);
635
+ if (!m)
636
+ return null;
637
+ try {
638
+ return fs.readFileSync(path.join(this.rootDir, 'media', key));
639
+ }
640
+ catch {
641
+ return null;
642
+ }
643
+ }
644
+ getStatus() {
645
+ const { totalBytes, sessionCount } = this.footprint();
646
+ return {
647
+ enabled: this.enabled,
648
+ dir: this.rootDir,
649
+ retentionDays: this.retentionDays,
650
+ maxTotalMB: Math.round(this.maxTotalBytes / (1024 * 1024)),
651
+ maxTurnMB: Math.round(this.maxTurnBytes / (1024 * 1024)),
652
+ totalBytes,
653
+ sessionCount,
654
+ };
655
+ }
656
+ stop() {
657
+ this.stopSweepTimer();
658
+ }
659
+ /**
660
+ * Await every queued turn append. Tests and shutdown call this so a
661
+ * just-recorded turn is on disk before the caller reads it back; production
662
+ * reads (`read`/`resumeView`/`export`) are reachable only through the admin
663
+ * API, which runs long after the write queue drains.
664
+ */
665
+ async flush() {
666
+ await this.writeChain;
667
+ const worker = this.worker;
668
+ if (!worker)
669
+ return;
670
+ const id = ++this.workerSeq;
671
+ await new Promise((resolve) => {
672
+ this.workerWaiters.set(id, resolve);
673
+ try {
674
+ // Worker messages are ordered: this reply lands only after every turn
675
+ // posted before it has been appended (or halted/failed).
676
+ worker.postMessage({ type: 'flush', id });
677
+ }
678
+ catch {
679
+ this.workerWaiters.delete(id);
680
+ resolve();
681
+ }
682
+ });
683
+ }
684
+ /**
685
+ * Retention sweep: delete session files older than retentionDays; collect
686
+ * media no surviving transcript references; then trim by size and collect
687
+ * again (a trimmed session's digests may have just become unreferenced).
688
+ *
689
+ * Media is content-addressed and SHARED across sessions, so it can never be
690
+ * deleted WITH a transcript — the digest may be referenced by another one.
691
+ * It is "left to the retention sweep" (ADR-0038) in exactly this sense: the
692
+ * sweep derives the live digest set from the surviving transcripts and drops
693
+ * every `media/` payload outside it, which is what keeps a media-heavy store
694
+ * inside `maxTotalMB` (counting media without ever releasing it would let
695
+ * `media/` grow unbounded once it alone exceeded the budget).
696
+ */
697
+ sweep() {
698
+ let entries;
699
+ try {
700
+ entries = fs.readdirSync(this.rootDir);
701
+ }
702
+ catch {
703
+ return;
704
+ }
705
+ const cutoff = Date.now() - this.retentionDays * DATE_MS;
706
+ const files = [];
707
+ for (const name of entries) {
708
+ if (!name.endsWith('.jsonl'))
709
+ continue;
710
+ const fp = path.join(this.rootDir, name);
711
+ try {
712
+ const st = fs.statSync(fp);
713
+ if (!st.isFile())
714
+ continue;
715
+ if (st.mtimeMs < cutoff) {
716
+ fs.rmSync(fp, { force: true });
717
+ continue;
718
+ }
719
+ files.push({ fp, mtime: st.mtimeMs, size: st.size });
720
+ }
721
+ catch {
722
+ // skip
723
+ }
724
+ }
725
+ // Collect BEFORE the size math: dropping unreferenced payloads can bring
726
+ // the store back under budget without sacrificing another session.
727
+ this.collectMedia();
728
+ let total = files.reduce((s, f) => s + f.size, 0);
729
+ total += this.mediaBytes();
730
+ if (total <= this.maxTotalBytes)
731
+ return;
732
+ // Oldest first.
733
+ files.sort((a, b) => a.mtime - b.mtime);
734
+ let trimmed = false;
735
+ for (const f of files) {
736
+ if (total <= this.maxTotalBytes)
737
+ break;
738
+ try {
739
+ fs.rmSync(f.fp, { force: true });
740
+ total -= f.size;
741
+ trimmed = true;
742
+ }
743
+ catch {
744
+ // skip
745
+ }
746
+ }
747
+ if (trimmed)
748
+ this.collectMedia();
749
+ }
750
+ /**
751
+ * Delete `media/` payloads no surviving transcript references.
752
+ *
753
+ * Three fail-safe rules, each a silent-corruption bug when broken:
754
+ * - an unreadable or unparseable transcript ABORTS the whole pass — a torn
755
+ * line may reference any digest, so deleting on a partial view would
756
+ * corrupt a bundle later;
757
+ * - a payload inside the grace window is kept (see `MEDIA_GC_GRACE_MS`);
758
+ * - a payload a QUEUED append still references is kept regardless of age
759
+ * (`pendingMedia`): a wall-clock jump can age a payload past the grace
760
+ * while its transcript line is still in the write queue.
761
+ */
762
+ collectMedia() {
763
+ const dir = path.join(this.rootDir, 'media');
764
+ let mediaNames;
765
+ try {
766
+ mediaNames = fs.readdirSync(dir);
767
+ }
768
+ catch {
769
+ return; // no media dir — nothing to collect
770
+ }
771
+ let transcripts;
772
+ try {
773
+ transcripts = fs.readdirSync(this.rootDir).filter((n) => n.endsWith('.jsonl'));
774
+ }
775
+ catch {
776
+ return;
777
+ }
778
+ const live = new Set();
779
+ for (const name of transcripts) {
780
+ let text;
781
+ try {
782
+ text = fs.readFileSync(path.join(this.rootDir, name), 'utf8');
783
+ }
784
+ catch {
785
+ return;
786
+ }
787
+ for (const line of text.split('\n')) {
788
+ if (!line.trim())
789
+ continue;
790
+ let parsed;
791
+ try {
792
+ parsed = JSON.parse(line);
793
+ }
794
+ catch {
795
+ return;
796
+ }
797
+ if (parsed && typeof parsed === 'object' && parsed.media && typeof parsed.media === 'object') {
798
+ for (const key of Object.keys(parsed.media))
799
+ live.add(key);
800
+ }
801
+ }
802
+ }
803
+ const cutoff = Date.now() - MEDIA_GC_GRACE_MS;
804
+ for (const name of mediaNames) {
805
+ if (live.has(name) || this.pendingMedia.has(name))
806
+ continue;
807
+ if (!MEDIA_FILE_RE.test(name))
808
+ continue; // tmp leftovers / foreign files: not ours to delete
809
+ const fp = path.join(dir, name);
810
+ try {
811
+ if (fs.statSync(fp).mtimeMs > cutoff)
812
+ continue;
813
+ fs.rmSync(fp, { force: true });
814
+ }
815
+ catch {
816
+ // skip
817
+ }
818
+ }
819
+ }
820
+ mediaBytes() {
821
+ const dir = path.join(this.rootDir, 'media');
822
+ let total = 0;
823
+ try {
824
+ for (const e of fs.readdirSync(dir, { withFileTypes: true })) {
825
+ if (!e.isFile())
826
+ continue;
827
+ try {
828
+ total += fs.statSync(path.join(dir, e.name)).size;
829
+ }
830
+ catch {
831
+ // skip
832
+ }
833
+ }
834
+ }
835
+ catch {
836
+ // no media dir
837
+ }
838
+ return total;
839
+ }
840
+ footprint() {
841
+ let totalBytes = 0;
842
+ let sessionCount = 0;
843
+ try {
844
+ for (const e of fs.readdirSync(this.rootDir, { withFileTypes: true })) {
845
+ if (!e.isFile() || !e.name.endsWith('.jsonl'))
846
+ continue;
847
+ sessionCount++;
848
+ try {
849
+ totalBytes += fs.statSync(path.join(this.rootDir, e.name)).size;
850
+ }
851
+ catch {
852
+ // skip
853
+ }
854
+ }
855
+ }
856
+ catch {
857
+ // no dir
858
+ }
859
+ totalBytes += this.mediaBytes();
860
+ return { totalBytes, sessionCount };
861
+ }
862
+ fileFor(sessionId) {
863
+ return path.join(this.rootDir, sessionFileName(sessionId));
864
+ }
865
+ /**
866
+ * Content-addressed media write (shared with the write worker so the two
867
+ * paths can never disagree about layout or dedup).
868
+ */
869
+ storeMediaFile(raw, sha256, ext) {
870
+ return storeMediaPayload(this.rootDir, raw, sha256, ext);
871
+ }
872
+ ensureDir(dir) {
873
+ ensureDirSync(dir);
874
+ }
875
+ startSweepTimer() {
876
+ if (this.sweepTimer)
877
+ return;
878
+ this.sweepTimer = setInterval(() => this.sweep(), 60 * 60 * 1000);
879
+ this.sweepTimer.unref?.();
880
+ }
881
+ stopSweepTimer() {
882
+ if (this.sweepTimer) {
883
+ clearInterval(this.sweepTimer);
884
+ this.sweepTimer = undefined;
885
+ }
886
+ }
887
+ }