omnicell-router 0.8.2 → 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 (400) hide show
  1. package/README.md +26 -7
  2. package/README.zh-CN.md +18 -5
  3. package/backend/dist/auth/api-keys.js +11 -0
  4. package/backend/dist/auth/key-models.d.ts +36 -0
  5. package/backend/dist/auth/key-models.js +99 -0
  6. package/backend/dist/capture/recorder.d.ts +4 -10
  7. package/backend/dist/capture/recorder.js +6 -58
  8. package/backend/dist/cli/clients/activity.js +2 -0
  9. package/backend/dist/cli/clients/base.d.ts +36 -11
  10. package/backend/dist/cli/clients/base.js +31 -15
  11. package/backend/dist/cli/clients/claude.d.ts +9 -0
  12. package/backend/dist/cli/clients/claude.js +6 -0
  13. package/backend/dist/cli/clients/codex.d.ts +78 -0
  14. package/backend/dist/cli/clients/codex.js +475 -57
  15. package/backend/dist/cli/clients/core-adapters.d.ts +1 -1
  16. package/backend/dist/cli/clients/core-adapters.js +1 -1
  17. package/backend/dist/cli/clients/dsh.d.ts +8 -0
  18. package/backend/dist/cli/clients/dsh.js +5 -0
  19. package/backend/dist/cli/clients/follow-catalog-sync.d.ts +62 -0
  20. package/backend/dist/cli/clients/follow-catalog-sync.js +435 -0
  21. package/backend/dist/cli/clients/grok.d.ts +15 -1
  22. package/backend/dist/cli/clients/grok.js +16 -2
  23. package/backend/dist/cli/clients/index.d.ts +13 -1
  24. package/backend/dist/cli/clients/index.js +97 -19
  25. package/backend/dist/cli/clients/kimi.d.ts +6 -0
  26. package/backend/dist/cli/clients/kimi.js +3 -0
  27. package/backend/dist/cli/clients/launcher.d.ts +1 -1
  28. package/backend/dist/cli/clients/model-meta.js +6 -3
  29. package/backend/dist/cli/clients/omp.d.ts +6 -0
  30. package/backend/dist/cli/clients/omp.js +3 -0
  31. package/backend/dist/cli/clients/openclaw.d.ts +6 -0
  32. package/backend/dist/cli/clients/openclaw.js +3 -0
  33. package/backend/dist/cli/clients/opencode.d.ts +8 -0
  34. package/backend/dist/cli/clients/opencode.js +8 -2
  35. package/backend/dist/cli/clients/pi.d.ts +6 -0
  36. package/backend/dist/cli/clients/pi.js +3 -0
  37. package/backend/dist/cli/clients/reserved.js +2 -0
  38. package/backend/dist/cli/clients/update-check.d.ts +37 -0
  39. package/backend/dist/cli/clients/update-check.js +309 -0
  40. package/backend/dist/cli/clients/workbuddy.d.ts +19 -0
  41. package/backend/dist/cli/clients/workbuddy.js +66 -0
  42. package/backend/dist/cli/index.js +5 -4
  43. package/backend/dist/cli/paths.js +8 -0
  44. package/backend/dist/cli/types.d.ts +101 -16
  45. package/backend/dist/config/comments-en.js +34 -25
  46. package/backend/dist/config/comments-zh.js +33 -24
  47. package/backend/dist/config/defaults.d.ts +280 -22
  48. package/backend/dist/config/defaults.js +279 -21
  49. package/backend/dist/config/env.d.ts +10 -0
  50. package/backend/dist/config/env.js +3 -2
  51. package/backend/dist/config/index.d.ts +22 -1
  52. package/backend/dist/config/index.js +218 -43
  53. package/backend/dist/config/migrations/v0-to-v1.d.ts +2 -2
  54. package/backend/dist/config/migrations/v10-to-v11.d.ts +38 -0
  55. package/backend/dist/config/migrations/v10-to-v11.js +43 -0
  56. package/backend/dist/config/migrations/v4-to-v5.d.ts +36 -0
  57. package/backend/dist/config/migrations/v4-to-v5.js +42 -0
  58. package/backend/dist/config/migrations/v5-to-v6.d.ts +27 -0
  59. package/backend/dist/config/migrations/v5-to-v6.js +29 -0
  60. package/backend/dist/config/migrations/v6-to-v7.d.ts +45 -0
  61. package/backend/dist/config/migrations/v6-to-v7.js +97 -0
  62. package/backend/dist/config/migrations/v7-to-v8.d.ts +36 -0
  63. package/backend/dist/config/migrations/v7-to-v8.js +43 -0
  64. package/backend/dist/config/migrations/v8-to-v9.d.ts +38 -0
  65. package/backend/dist/config/migrations/v8-to-v9.js +43 -0
  66. package/backend/dist/config/migrations/v9-to-v10.d.ts +51 -0
  67. package/backend/dist/config/migrations/v9-to-v10.js +71 -0
  68. package/backend/dist/config/runtime.js +1 -1
  69. package/backend/dist/config/schema.d.ts +3 -3
  70. package/backend/dist/config/schema.js +18 -4
  71. package/backend/dist/config/types.d.ts +221 -41
  72. package/backend/dist/egress-proxy/asset-download.d.ts +54 -0
  73. package/backend/dist/egress-proxy/asset-download.js +420 -0
  74. package/backend/dist/egress-proxy/manual-node-spec.d.ts +92 -0
  75. package/backend/dist/egress-proxy/manual-node-spec.js +408 -0
  76. package/backend/dist/egress-proxy/mihomo-binary.d.ts +54 -0
  77. package/backend/dist/egress-proxy/mihomo-binary.js +278 -0
  78. package/backend/dist/egress-proxy/mihomo-client.d.ts +94 -0
  79. package/backend/dist/egress-proxy/mihomo-client.js +308 -0
  80. package/backend/dist/egress-proxy/mihomo-config.d.ts +40 -0
  81. package/backend/dist/egress-proxy/mihomo-config.js +161 -0
  82. package/backend/dist/egress-proxy/mihomo-geo.d.ts +87 -0
  83. package/backend/dist/egress-proxy/mihomo-geo.js +213 -0
  84. package/backend/dist/egress-proxy/mihomo-logs.d.ts +43 -0
  85. package/backend/dist/egress-proxy/mihomo-logs.js +84 -0
  86. package/backend/dist/egress-proxy/mihomo-pac.d.ts +37 -0
  87. package/backend/dist/egress-proxy/mihomo-pac.js +75 -0
  88. package/backend/dist/egress-proxy/mihomo-rules-import.d.ts +43 -0
  89. package/backend/dist/egress-proxy/mihomo-rules-import.js +193 -0
  90. package/backend/dist/egress-proxy/mihomo-sidecar.d.ts +81 -0
  91. package/backend/dist/egress-proxy/mihomo-sidecar.js +637 -0
  92. package/backend/dist/forward-proxy/egress.d.ts +50 -11
  93. package/backend/dist/forward-proxy/egress.js +63 -17
  94. package/backend/dist/forward-proxy/h2-forward.js +42 -15
  95. package/backend/dist/forward-proxy/index.d.ts +11 -8
  96. package/backend/dist/forward-proxy/index.js +27 -60
  97. package/backend/dist/forward-proxy/interceptor.d.ts +3 -2
  98. package/backend/dist/forward-proxy/interceptor.js +4 -4
  99. package/backend/dist/forward-proxy/relay.js +3 -3
  100. package/backend/dist/forward-proxy/rules.d.ts +4 -4
  101. package/backend/dist/forward-proxy/rules.js +25 -4
  102. package/backend/dist/forward-proxy/server.d.ts +12 -16
  103. package/backend/dist/forward-proxy/server.js +237 -171
  104. package/backend/dist/harness/host/hosts.js +3 -2
  105. package/backend/dist/index.js +59 -19
  106. package/backend/dist/ingress-proxy/access-log.d.ts +176 -0
  107. package/backend/dist/ingress-proxy/access-log.js +774 -0
  108. package/backend/dist/ingress-proxy/ca-inventory.d.ts +106 -0
  109. package/backend/dist/ingress-proxy/ca-inventory.js +525 -0
  110. package/backend/dist/ingress-proxy/ca-trust.d.ts +96 -0
  111. package/backend/dist/ingress-proxy/ca-trust.js +315 -0
  112. package/backend/dist/ingress-proxy/ca.d.ts +104 -0
  113. package/backend/dist/ingress-proxy/ca.js +273 -0
  114. package/backend/dist/ingress-proxy/data-dir.d.ts +28 -0
  115. package/backend/dist/ingress-proxy/data-dir.js +45 -0
  116. package/backend/dist/ingress-proxy/egress.d.ts +151 -0
  117. package/backend/dist/ingress-proxy/egress.js +364 -0
  118. package/backend/dist/ingress-proxy/h2-forward.d.ts +66 -0
  119. package/backend/dist/ingress-proxy/h2-forward.js +561 -0
  120. package/backend/dist/ingress-proxy/index.d.ts +24 -0
  121. package/backend/dist/ingress-proxy/index.js +144 -0
  122. package/backend/dist/ingress-proxy/interceptor.d.ts +25 -0
  123. package/backend/dist/ingress-proxy/interceptor.js +52 -0
  124. package/backend/dist/ingress-proxy/ordered-relay.d.ts +29 -0
  125. package/backend/dist/ingress-proxy/ordered-relay.js +46 -0
  126. package/backend/dist/ingress-proxy/relay.d.ts +54 -0
  127. package/backend/dist/ingress-proxy/relay.js +188 -0
  128. package/backend/dist/ingress-proxy/rules.d.ts +195 -0
  129. package/backend/dist/ingress-proxy/rules.js +348 -0
  130. package/backend/dist/ingress-proxy/server.d.ts +153 -0
  131. package/backend/dist/ingress-proxy/server.js +2065 -0
  132. package/backend/dist/ingress-proxy/sni.d.ts +35 -0
  133. package/backend/dist/ingress-proxy/sni.js +124 -0
  134. package/backend/dist/ingress-proxy/status.d.ts +32 -0
  135. package/backend/dist/ingress-proxy/status.js +15 -0
  136. package/backend/dist/ingress-proxy/system-proxy.d.ts +112 -0
  137. package/backend/dist/ingress-proxy/system-proxy.js +481 -0
  138. package/backend/dist/ingress-proxy/traffic-delete.d.ts +21 -0
  139. package/backend/dist/ingress-proxy/traffic-delete.js +64 -0
  140. package/backend/dist/ingress-proxy/traffic-delete.worker.d.ts +44 -0
  141. package/backend/dist/ingress-proxy/traffic-delete.worker.js +228 -0
  142. package/backend/dist/ingress-proxy/traffic-files.d.ts +10 -0
  143. package/backend/dist/ingress-proxy/traffic-files.js +10 -0
  144. package/backend/dist/ingress-proxy/upstream-tls.d.ts +46 -0
  145. package/backend/dist/ingress-proxy/upstream-tls.js +105 -0
  146. package/backend/dist/ingress-proxy/ws-frames.d.ts +45 -0
  147. package/backend/dist/ingress-proxy/ws-frames.js +153 -0
  148. package/backend/dist/ir/adapters/anthropic-messages-stream.js +6 -1
  149. package/backend/dist/ir/adapters/anthropic-messages.js +12 -5
  150. package/backend/dist/ir/adapters/google-gemini-stream.js +7 -2
  151. package/backend/dist/ir/adapters/google-gemini.js +5 -2
  152. package/backend/dist/ir/adapters/openai-chat-stream.js +5 -1
  153. package/backend/dist/ir/adapters/openai-chat.d.ts +25 -0
  154. package/backend/dist/ir/adapters/openai-chat.js +50 -6
  155. package/backend/dist/ir/adapters/openai-responses-output.d.ts +1 -0
  156. package/backend/dist/ir/adapters/openai-responses-output.js +67 -21
  157. package/backend/dist/ir/adapters/openai-responses-stream.d.ts +13 -0
  158. package/backend/dist/ir/adapters/openai-responses-stream.js +34 -1
  159. package/backend/dist/ir/adapters/openai-responses.d.ts +92 -1
  160. package/backend/dist/ir/adapters/openai-responses.js +163 -12
  161. package/backend/dist/ir/capabilities.js +4 -0
  162. package/backend/dist/ir/media.d.ts +20 -0
  163. package/backend/dist/ir/media.js +41 -0
  164. package/backend/dist/ir/tool-identity.d.ts +35 -0
  165. package/backend/dist/ir/tool-identity.js +40 -0
  166. package/backend/dist/ir/types.d.ts +9 -1
  167. package/backend/dist/ir/validate.d.ts +24 -0
  168. package/backend/dist/ir/validate.js +113 -63
  169. package/backend/dist/local/build-jobs.d.ts +66 -0
  170. package/backend/dist/local/build-jobs.js +243 -0
  171. package/backend/dist/local/detect.d.ts +32 -0
  172. package/backend/dist/local/detect.js +145 -0
  173. package/backend/dist/local/draft-match.d.ts +58 -0
  174. package/backend/dist/local/draft-match.js +124 -0
  175. package/backend/dist/local/engine-runtime.d.ts +522 -0
  176. package/backend/dist/local/engine-runtime.js +1 -0
  177. package/backend/dist/local/engines.d.ts +241 -0
  178. package/backend/dist/local/engines.js +651 -0
  179. package/backend/dist/local/gguf.d.ts +35 -0
  180. package/backend/dist/local/gguf.js +314 -0
  181. package/backend/dist/local/hf.d.ts +120 -0
  182. package/backend/dist/local/hf.js +304 -0
  183. package/backend/dist/local/install.d.ts +90 -0
  184. package/backend/dist/local/install.js +421 -0
  185. package/backend/dist/local/llamacpp.d.ts +55 -0
  186. package/backend/dist/local/llamacpp.js +177 -0
  187. package/backend/dist/local/local-provider.d.ts +81 -0
  188. package/backend/dist/local/local-provider.js +301 -0
  189. package/backend/dist/local/machine-stats.d.ts +87 -0
  190. package/backend/dist/local/machine-stats.js +332 -0
  191. package/backend/dist/local/model-store.d.ts +347 -0
  192. package/backend/dist/local/model-store.js +1215 -0
  193. package/backend/dist/local/part-sweep.d.ts +32 -0
  194. package/backend/dist/local/part-sweep.js +156 -0
  195. package/backend/dist/local/plan.d.ts +65 -0
  196. package/backend/dist/local/plan.js +146 -0
  197. package/backend/dist/local/resources.d.ts +49 -0
  198. package/backend/dist/local/resources.js +64 -0
  199. package/backend/dist/local/run-stats.d.ts +95 -0
  200. package/backend/dist/local/run-stats.js +195 -0
  201. package/backend/dist/local/runner.d.ts +235 -0
  202. package/backend/dist/local/runner.js +1392 -0
  203. package/backend/dist/local/settings.d.ts +79 -0
  204. package/backend/dist/local/settings.js +180 -0
  205. package/backend/dist/local/strata-catalog.d.ts +30 -0
  206. package/backend/dist/local/strata-catalog.js +511 -0
  207. package/backend/dist/local/strata-drafting.d.ts +46 -0
  208. package/backend/dist/local/strata-drafting.js +265 -0
  209. package/backend/dist/local/strata.d.ts +278 -0
  210. package/backend/dist/local/strata.js +1392 -0
  211. package/backend/dist/local/tar.d.ts +20 -0
  212. package/backend/dist/local/tar.js +367 -0
  213. package/backend/dist/local/transport.d.ts +35 -0
  214. package/backend/dist/local/transport.js +89 -0
  215. package/backend/dist/local/tune.d.ts +58 -0
  216. package/backend/dist/local/tune.js +324 -0
  217. package/backend/dist/observability/http-exchange.d.ts +2 -2
  218. package/backend/dist/opencode/catalog/auto-pull.d.ts +14 -3
  219. package/backend/dist/opencode/catalog/auto-pull.js +284 -77
  220. package/backend/dist/opencode/catalog/ocr-store.d.ts +7 -6
  221. package/backend/dist/opencode/catalog/ocr-store.js +4 -2
  222. package/backend/dist/opencode/catalog/overrides-store.d.ts +15 -4
  223. package/backend/dist/opencode/catalog/overrides-store.js +28 -19
  224. package/backend/dist/opencode/catalog/reasoning-declaration.d.ts +35 -0
  225. package/backend/dist/opencode/catalog/reasoning-declaration.js +66 -0
  226. package/backend/dist/opencode/catalog/repository.js +28 -5
  227. package/backend/dist/opencode/catalog/sources/models-dev.d.ts +3 -3
  228. package/backend/dist/opencode/catalog/sources/models-dev.js +42 -14
  229. package/backend/dist/opencode/catalog/types.d.ts +42 -12
  230. package/backend/dist/opencode/catalog/types.js +38 -1
  231. package/backend/dist/opencode/credentials/def-materialize.js +27 -21
  232. package/backend/dist/opencode/credentials/ocr-store.js +11 -2
  233. package/backend/dist/opencode/credentials/sync.js +12 -3
  234. package/backend/dist/opencode/credentials/types.d.ts +31 -4
  235. package/backend/dist/opencode/credentials/types.js +25 -0
  236. package/backend/dist/opencode/migrate/engine.d.ts +20 -0
  237. package/backend/dist/opencode/migrate/engine.js +71 -0
  238. package/backend/dist/opencode/migrate/migrator.d.ts +11 -0
  239. package/backend/dist/opencode/migrate/migrator.js +6 -0
  240. package/backend/dist/opencode/migrate/steps/overrides-v1-to-v2.d.ts +6 -0
  241. package/backend/dist/opencode/migrate/steps/overrides-v1-to-v2.js +31 -0
  242. package/backend/dist/opencode/migrate/steps/providers-v1-to-v2.d.ts +6 -0
  243. package/backend/dist/opencode/migrate/steps/providers-v1-to-v2.js +62 -0
  244. package/backend/dist/opencode/probe.d.ts +21 -4
  245. package/backend/dist/opencode/probe.js +34 -10
  246. package/backend/dist/opencode/provider-def-adapters.d.ts +12 -11
  247. package/backend/dist/opencode/provider-def-adapters.js +43 -27
  248. package/backend/dist/opencode/provider-defs.d.ts +10 -16
  249. package/backend/dist/opencode/provider-defs.js +45 -45
  250. package/backend/dist/opencode/user-config.d.ts +23 -26
  251. package/backend/dist/opencode/user-config.js +95 -77
  252. package/backend/dist/pipeline/directives.d.ts +9 -4
  253. package/backend/dist/pipeline/directives.js +14 -10
  254. package/backend/dist/pipeline/orchestrator.d.ts +42 -13
  255. package/backend/dist/pipeline/orchestrator.js +514 -172
  256. package/backend/dist/plugins/builtin/model-gateway.js +38 -12
  257. package/backend/dist/plugins/environment-ack.d.ts +51 -0
  258. package/backend/dist/plugins/environment-ack.js +81 -0
  259. package/backend/dist/plugins/gateways.d.ts +6 -6
  260. package/backend/dist/plugins/gateways.js +2 -2
  261. package/backend/dist/plugins/host.d.ts +100 -16
  262. package/backend/dist/plugins/host.js +637 -99
  263. package/backend/dist/plugins/install-run.d.ts +27 -0
  264. package/backend/dist/plugins/install-run.js +99 -0
  265. package/backend/dist/plugins/manifest.d.ts +84 -32
  266. package/backend/dist/plugins/manifest.js +149 -45
  267. package/backend/dist/plugins/market-install.d.ts +18 -0
  268. package/backend/dist/plugins/market-install.js +111 -0
  269. package/backend/dist/plugins/market-source.d.ts +100 -0
  270. package/backend/dist/plugins/market-source.js +449 -0
  271. package/backend/dist/plugins/market-updates.d.ts +70 -0
  272. package/backend/dist/plugins/market-updates.js +97 -0
  273. package/backend/dist/plugins/market.d.ts +677 -0
  274. package/backend/dist/plugins/market.js +2113 -0
  275. package/backend/dist/plugins/source-index.d.ts +155 -0
  276. package/backend/dist/plugins/source-index.js +217 -0
  277. package/backend/dist/plugins/types.d.ts +402 -37
  278. package/backend/dist/projects/worktrees.d.ts +88 -0
  279. package/backend/dist/projects/worktrees.js +220 -0
  280. package/backend/dist/providers/boot-direct.d.ts +41 -7
  281. package/backend/dist/providers/boot-direct.js +284 -44
  282. package/backend/dist/providers/compat/tool-markup-recovery.js +31 -6
  283. package/backend/dist/providers/dial-wire.d.ts +17 -0
  284. package/backend/dist/providers/dial-wire.js +49 -0
  285. package/backend/dist/providers/executors/dispatch.d.ts +17 -7
  286. package/backend/dist/providers/executors/dispatch.js +28 -9
  287. package/backend/dist/providers/executors/openai-chat.js +14 -2
  288. package/backend/dist/providers/executors/plugin-adapter.d.ts +23 -1
  289. package/backend/dist/providers/executors/plugin-adapter.js +59 -3
  290. package/backend/dist/providers/member-match.d.ts +32 -9
  291. package/backend/dist/providers/member-match.js +65 -21
  292. package/backend/dist/providers/model-resolution.d.ts +62 -0
  293. package/backend/dist/providers/model-resolution.js +62 -0
  294. package/backend/dist/providers/price-order.d.ts +51 -0
  295. package/backend/dist/providers/price-order.js +54 -0
  296. package/backend/dist/providers/protocols-field.d.ts +24 -0
  297. package/backend/dist/providers/protocols-field.js +66 -0
  298. package/backend/dist/providers/provider-takedown.d.ts +5 -2
  299. package/backend/dist/providers/registry.d.ts +87 -26
  300. package/backend/dist/providers/registry.js +232 -121
  301. package/backend/dist/providers/selection.d.ts +91 -0
  302. package/backend/dist/providers/selection.js +158 -0
  303. package/backend/dist/providers/virtual-meta.d.ts +33 -2
  304. package/backend/dist/providers/virtual-meta.js +74 -18
  305. package/backend/dist/quota/cli-login.d.ts +25 -4
  306. package/backend/dist/quota/cli-login.js +38 -6
  307. package/backend/dist/quota/coverage-generation.d.ts +24 -0
  308. package/backend/dist/quota/coverage-generation.js +29 -0
  309. package/backend/dist/quota/declarations.js +8 -4
  310. package/backend/dist/quota/engine.js +2 -2
  311. package/backend/dist/quota/prober.d.ts +43 -2
  312. package/backend/dist/quota/prober.js +97 -22
  313. package/backend/dist/ratelimit/rate-limiter.d.ts +1 -1
  314. package/backend/dist/resilience/error-classifier.js +29 -0
  315. package/backend/dist/router/index.d.ts +1 -1
  316. package/backend/dist/router/index.js +17 -1
  317. package/backend/dist/router/layer2-decision.d.ts +1 -1
  318. package/backend/dist/router/layer2-decision.js +2 -2
  319. package/backend/dist/routes/console.js +1043 -405
  320. package/backend/dist/routes/environments.js +1 -1
  321. package/backend/dist/routes/local-models.d.ts +2 -0
  322. package/backend/dist/routes/local-models.js +1414 -0
  323. package/backend/dist/routes/mihomo.d.ts +2 -2
  324. package/backend/dist/routes/mihomo.js +20 -11
  325. package/backend/dist/routes/projects.js +121 -0
  326. package/backend/dist/server.js +409 -15
  327. package/backend/dist/session/session-manager.d.ts +42 -5
  328. package/backend/dist/session/session-manager.js +64 -11
  329. package/backend/dist/session/session-row.d.ts +29 -8
  330. package/backend/dist/session/session-row.js +18 -13
  331. package/backend/dist/snapshot/bundle.d.ts +40 -0
  332. package/backend/dist/snapshot/bundle.js +177 -0
  333. package/backend/dist/snapshot/handoff/compress.d.ts +46 -0
  334. package/backend/dist/snapshot/handoff/compress.js +77 -0
  335. package/backend/dist/snapshot/handoff/index.d.ts +119 -0
  336. package/backend/dist/snapshot/handoff/index.js +160 -0
  337. package/backend/dist/snapshot/handoff/jsonl-writer.d.ts +78 -0
  338. package/backend/dist/snapshot/handoff/jsonl-writer.js +175 -0
  339. package/backend/dist/snapshot/handoff/opencode-writer.d.ts +51 -0
  340. package/backend/dist/snapshot/handoff/opencode-writer.js +214 -0
  341. package/backend/dist/snapshot/handoff/summarize.d.ts +39 -0
  342. package/backend/dist/snapshot/handoff/summarize.js +118 -0
  343. package/backend/dist/snapshot/handoff/transcript.d.ts +71 -0
  344. package/backend/dist/snapshot/handoff/transcript.js +167 -0
  345. package/backend/dist/snapshot/media-fs.d.ts +10 -0
  346. package/backend/dist/snapshot/media-fs.js +50 -0
  347. package/backend/dist/snapshot/media.d.ts +32 -0
  348. package/backend/dist/snapshot/media.js +87 -0
  349. package/backend/dist/snapshot/store.d.ts +226 -0
  350. package/backend/dist/snapshot/store.js +887 -0
  351. package/backend/dist/snapshot/tree.d.ts +112 -0
  352. package/backend/dist/snapshot/tree.js +207 -0
  353. package/backend/dist/snapshot/types.d.ts +212 -0
  354. package/backend/dist/snapshot/types.js +14 -0
  355. package/backend/dist/snapshot/view.d.ts +19 -0
  356. package/backend/dist/snapshot/view.js +57 -0
  357. package/backend/dist/snapshot/write-worker.d.ts +67 -0
  358. package/backend/dist/snapshot/write-worker.js +129 -0
  359. package/backend/dist/surfaces/anthropic.js +4 -1
  360. package/backend/dist/surfaces/body-admission.d.ts +344 -0
  361. package/backend/dist/surfaces/body-admission.js +818 -0
  362. package/backend/dist/surfaces/chat-pipeline.js +8 -0
  363. package/backend/dist/surfaces/decision-pipeline.js +10 -7
  364. package/backend/dist/surfaces/gateway-catalog.d.ts +26 -0
  365. package/backend/dist/surfaces/gateway-catalog.js +202 -0
  366. package/backend/dist/surfaces/gateway-chat.d.ts +7 -11
  367. package/backend/dist/surfaces/gateway-chat.js +50 -12
  368. package/backend/dist/surfaces/ocr-headers.d.ts +6 -4
  369. package/backend/dist/surfaces/ocr-headers.js +11 -7
  370. package/backend/dist/surfaces/systemone.js +1 -1
  371. package/backend/dist/surfaces/transport-fastify.js +32 -5
  372. package/backend/dist/surfaces/transport-node-http.d.ts +51 -6
  373. package/backend/dist/surfaces/transport-node-http.js +76 -16
  374. package/backend/dist/surfaces/types.d.ts +11 -3
  375. package/backend/dist/trace/persist.js +21 -1
  376. package/backend/dist/trace/tracker.d.ts +35 -3
  377. package/backend/dist/trace/tracker.js +23 -0
  378. package/backend/dist/types/openai.d.ts +8 -0
  379. package/backend/dist/types/router.d.ts +17 -6
  380. package/backend/dist/types/router.js +14 -2
  381. package/backend/dist/utils/client-families.d.ts +66 -0
  382. package/backend/dist/utils/client-families.js +127 -0
  383. package/backend/dist/utils/event-ring.d.ts +1 -1
  384. package/backend/dist/utils/event-ring.js +1 -1
  385. package/backend/dist/utils/proxy-node.js +1 -1
  386. package/backend/dist/utils/proxy.d.ts +135 -11
  387. package/backend/dist/utils/proxy.js +144 -29
  388. package/backend/dist/utils/run-command.d.ts +21 -1
  389. package/backend/dist/utils/run-command.js +64 -4
  390. package/backend/dist/utils/server-liveness.d.ts +28 -0
  391. package/backend/dist/utils/server-liveness.js +32 -0
  392. package/backend/dist/utils/session-file.d.ts +28 -0
  393. package/backend/dist/utils/session-file.js +34 -0
  394. package/frontend/dist/assets/antigravity.color-DXFfVr6X.svg +39 -0
  395. package/frontend/dist/assets/gemini-cli.color-BfquLd1p.svg +1 -0
  396. package/frontend/dist/assets/index-CTZNvn1d.js +1707 -0
  397. package/frontend/dist/assets/{index-DxZ9MHKB.css → index-CqDSOPQ0.css} +1 -1
  398. package/frontend/dist/index.html +2 -2
  399. package/package.json +3 -1
  400. package/frontend/dist/assets/index-55VVwfFQ.js +0 -1521
@@ -12,13 +12,17 @@ import { registerTranslationRoutes } from './routes/translation.js';
12
12
  import { MarketplaceRescanScheduler } from './harness/common/marketplace-rescan-scheduler.js';
13
13
  import { allHostProbes, probeOptionsFor } from './harness/plugin/adapters/index.js';
14
14
  import { INFERENCE_ROUTE_PATHS, SURFACES } from './surfaces/table.js';
15
+ import { adminBodyErrorHandler, bodyLimitFor, configureBodyLimits, normalizeNativeBody, settleContinuationExpectation, surfaceBodyAdmissionOptions, } from './surfaces/body-admission.js';
15
16
  import { createFastifyTransport } from './surfaces/transport-fastify.js';
17
+ import { applyInboundLiveness } from './utils/server-liveness.js';
18
+ import { clientFamiliesOf } from './utils/client-families.js';
16
19
  import { dispatchSurface } from './surfaces/dispatch.js';
17
20
  import { purgeResponseChainForSession } from './surfaces/responses.js';
18
21
  import fastify, { LogController } from 'fastify';
19
22
  import cors from '@fastify/cors';
20
23
  import { PipelineOrchestrator } from './pipeline/orchestrator.js';
21
24
  import { ProviderRegistry } from './providers/registry.js';
25
+ import { normalizeSelectionStrategy } from './providers/selection.js';
22
26
  import { FinOpsTracker } from './metrics/finops-tracker.js';
23
27
  import { APP_VERSION } from './version.js';
24
28
  import { setGatewayMetaDeps } from './cli/clients/model-meta.js';
@@ -26,8 +30,13 @@ import { noteClientActivityFromUserAgent } from './cli/clients/activity.js';
26
30
  import { comboEnvelope, findMemberCatalogRecords, modelsDevBlock, tierAliasEnvelope, virtualModelsDevBlock, } from './providers/virtual-meta.js';
27
31
  import { modelSupportsEfforts } from './types/router.js';
28
32
  import { isInternalSessionId } from './session/session-manager.js';
29
- import { currentModelOf, deriveSessionEntryMode, projectSessionEntity, promptTurnsOf, sessionIdSourceOf, sessionTitleOf, boundCredentialLabelOf, } from './session/session-row.js';
30
- const TIER_RANK = { lite: 1, plus: 2, pro: 3, ultra: 4 };
33
+ import { currentModelOf, deriveSessionEntryMode, projectSessionEntity, promptTurnsOf, sessionIdSourceOf, sessionTitleOf, boundCredentialOf, } from './session/session-row.js';
34
+ import { buildSessionBundle, parseSessionBundle, sessionBundleName, SessionBundleError } from './snapshot/bundle.js';
35
+ import { buildMessageTree } from './snapshot/tree.js';
36
+ import { HANDOFF_MODES, HANDOFF_TARGETS, HandoffError, exportJsonlSession, migrateSession } from './snapshot/handoff/index.js';
37
+ import { summarizeHandoff } from './snapshot/handoff/summarize.js';
38
+ import { IMPORT_BODY_LIMIT_BYTES } from './config/env-archive.js';
39
+ import { TIER_RANK } from './types/router.js';
31
40
  /**
32
41
  * Live inbound grace-wait sleepers (see MAX_GRACE_SLEEPERS). Bun is
33
42
  * single-threaded and the increment/decrement happen in one synchronous
@@ -48,6 +57,7 @@ function reconstructSessionFromTraces(traceTracker, id) {
48
57
  const maxTier = traces.reduce((acc, t) => ((TIER_RANK[t.routing.targetTier] ?? 0) > (TIER_RANK[acc] ?? 0) ? t.routing.targetTier : acc), 'lite');
49
58
  const keyList = distinctTraceKeys(traces);
50
59
  const uaList = distinctTraceUserAgents(traces);
60
+ const famList = clientFamiliesOf(distinctTraceClientFingerprints(traces));
51
61
  const refList = distinctTraceClientRefs(traces);
52
62
  return {
53
63
  id,
@@ -75,6 +85,9 @@ function reconstructSessionFromTraces(traceTracker, id) {
75
85
  apiKeys: keyList.length ? keyList : undefined,
76
86
  // DISTINCT client User-Agent strings (write order) — console display only.
77
87
  clients: uaList.length ? uaList : undefined,
88
+ // DISTINCT client families derived from those UAs (write order) — the
89
+ // console filter axis (display only, never identity).
90
+ ...(famList.length ? { clientFamilies: famList } : {}),
78
91
  // DISTINCT client-minted conversation ids (write order) — the alias half
79
92
  // of the gateway-id ↔ client-id mapping (ADR-0002 §1).
80
93
  clientRefs: refList.length ? refList : undefined,
@@ -129,6 +142,29 @@ function distinctTraceUserAgents(traces) {
129
142
  }
130
143
  return list;
131
144
  }
145
+ /**
146
+ * Distinct client fingerprints across a session's traces (write order, first
147
+ * element = display anchor), pairing each request's self-declared
148
+ * `x-ocr-client` hint with the UA that request carried so family
149
+ * classification can prefer the hint PER REQUEST (a browser strips a
150
+ * script-set UA, but another caller on the same session may not declare one).
151
+ */
152
+ function distinctTraceClientFingerprints(traces) {
153
+ const seen = new Set();
154
+ const list = [];
155
+ for (const t of traces) {
156
+ const hint = t.request.clientHeaders?.clientHint;
157
+ const userAgent = t.request.clientHeaders?.userAgent;
158
+ if (!hint && !userAgent)
159
+ continue;
160
+ const key = `${hint ?? ''}\u0000${userAgent ?? ''}`;
161
+ if (seen.has(key))
162
+ continue;
163
+ seen.add(key);
164
+ list.push({ ...(hint ? { hint } : {}), ...(userAgent ? { userAgent } : {}) });
165
+ }
166
+ return list;
167
+ }
132
168
  /**
133
169
  * Security P2-3 — drive-by CSRF verdict for state-changing /api/admin/* calls
134
170
  * while webAuth is INACTIVE (no session gate means any local web page could
@@ -215,6 +251,11 @@ export function createServer(config, mockMode = false, customRegistry, customOrc
215
251
  /** Extra provider configs for the bootstrapped registry (test seam only —
216
252
  * production chat providers enter via `registerProvider` post-boot). */
217
253
  providerConfigs = []) {
254
+ // Install the operator-tunable admission caps (`client.bodyLimits`) BEFORE
255
+ // Fastify reads any `bodyLimit` — a route's cap is captured at registration
256
+ // time, which is exactly why the knob is restart-only (ADR-0007). With no
257
+ // configured value this returns the shipped constants unchanged.
258
+ configureBodyLimits(config.bodyLimits);
218
259
  // disableRequestLogging: Fastify's built-in per-request lifecycle logs
219
260
  // ("incoming request" / "request completed" at info) are pure noise here —
220
261
  // every UI poll of /health + /api/* produced a pair, drowning ocr.log.
@@ -228,6 +269,66 @@ providerConfigs = []) {
228
269
  level: process.env.LOG_LEVEL || 'info',
229
270
  },
230
271
  logController: new LogController({ disableRequestLogging: true }),
272
+ // Instance-wide body cap = the ADMIN tier. Fastify's own default is 1 MiB,
273
+ // which every console/API route inherited: a multi-MB `config.yaml` save
274
+ // failed as `413 "Payload Too Large"` in a shape the UI cannot render.
275
+ // Inference routes override this per route with the gateway tier cap, and
276
+ // the two upload routes declare their own bigger caps.
277
+ bodyLimit: bodyLimitFor('admin'),
278
+ });
279
+ // Inbound liveness, spelled from ONE source (utils/server-liveness + the
280
+ // SERVER_* constants): relying on runtime defaults is the same class of bug as
281
+ // the original 413 — Node arms 300s/60s/5s, Bun arms nothing, so which clients
282
+ // got served depended on which runtime started the process. Applied to the
283
+ // instance rather than passed as options because these keys are ambiguous across
284
+ // Fastify's http2 overloads and switch its inferred server type.
285
+ applyInboundLiveness(app.server);
286
+ // Admin-plane admission errors (413 oversized / 400 malformed body / 415
287
+ // undecodable) must answer `{ success: false, message }` — the shape the
288
+ // console already reads. Everything else is re-thrown to Fastify's default
289
+ // handler, so this never becomes a second error serializer.
290
+ app.setErrorHandler(adminBodyErrorHandler);
291
+ // `Expect: 100-continue` guard (RFC 9110 10.1.1): a client that declared a body
292
+ // over the cap of the route that would serve it is refused from the HEADERS
293
+ // alone, so it never pays for an upload we will throw away. Registering the
294
+ // listener switches off Node's automatic continue, so every continuation flows
295
+ // through `settleContinuationExpectation`, which always settles the request —
296
+ // either 413 or `100 Continue`.
297
+ //
298
+ // The cap comes from the route's OWN registration (recorded by `onRoute` below),
299
+ // never from a constant guessed here: the two upload routes accept more than the
300
+ // admin default, and refusing one of them early would reject a body the route
301
+ // would have taken. An unknown path or a route with no explicit cap gets no
302
+ // early answer — that costs one wasted upload, the other direction costs data.
303
+ const explicitRouteCaps = new Map();
304
+ app.addHook('onRoute', (routeOptions) => {
305
+ if (typeof routeOptions.bodyLimit === 'number') {
306
+ explicitRouteCaps.set(routeOptions.url, routeOptions.bodyLimit);
307
+ }
308
+ });
309
+ app.server.on('checkContinue', (req, res) => {
310
+ const answered = settleContinuationExpectation(req, res, (url) => {
311
+ const path = url.split('?')[0];
312
+ const capBytes = explicitRouteCaps.get(path);
313
+ if (capBytes === undefined)
314
+ return undefined;
315
+ const surface = SURFACES.find((s) => s.routePath === path);
316
+ return {
317
+ capBytes,
318
+ errorBody: surface
319
+ ? (err) => surface.errorBody(err.statusCode, err.message, err.code)
320
+ : (err) => ({ success: false, message: err.message }),
321
+ log: app.log,
322
+ };
323
+ });
324
+ if (answered)
325
+ return;
326
+ // Installing the listener above suppressed the server's own delivery: verified
327
+ // on Bun 1.3.14 and Node 24, a `checkContinue` listener that only writes the
328
+ // continue leaves the request UNDISPATCHED (the client hangs until timeout).
329
+ // So the continue is written by the guard and the exchange is handed to the
330
+ // router here -- the same re-emit Node's own documentation prescribes.
331
+ app.server.emit('request', req, res);
231
332
  });
232
333
  app.addHook('onError', async (req, _reply, err) => {
233
334
  req.log.error(err, 'request errored');
@@ -908,8 +1009,9 @@ providerConfigs = []) {
908
1009
  // members/parent/variant) live under each model's `ocr` key:
909
1010
  // - concrete models: verbatim passthrough of the catalog record's
910
1011
  // capability fields;
911
- // - virtual refs (auto*/combos): the member envelope — safe-min limits,
912
- // intersection capability flags, leader cost, full effort ladder (the
1012
+ // - virtual refs (auto*/combos): the member envelope — tier aliases and
1013
+ // `auto` publish their DECLARED rung window (ADR-0041), combos the safe-min
1014
+ // limits; intersection capability flags, leader cost, full effort ladder (the
913
1015
  // gateway clamps per request and reports truth via X-OCR-Thinking-*).
914
1016
  app.get('/v1/models', async (req) => {
915
1017
  const policy = getModelAccessPolicy(req.authInfo?.keyConfig);
@@ -974,10 +1076,10 @@ providerConfigs = []) {
974
1076
  continue;
975
1077
  virtualModels[c.id] = {
976
1078
  id: c.id,
977
- description: `Custom model combo (${c.models.length} members, ${c.selection || 'priority'} selection)`,
1079
+ description: `Custom model combo (${c.models.length} members, ${normalizeSelectionStrategy(c.selection)} selection)`,
978
1080
  ...(await virtualModel(comboEnvelope(registry, listCatalogOnce, c), {
979
1081
  kind: 'combo',
980
- selection: c.selection || 'priority',
1082
+ selection: normalizeSelectionStrategy(c.selection),
981
1083
  members: c.models.map((raw) => (typeof raw === 'string' ? raw : raw?.id)).filter(Boolean),
982
1084
  })),
983
1085
  };
@@ -1174,6 +1276,14 @@ providerConfigs = []) {
1174
1276
  // Per-application selector (same semantics as the capture sessions route):
1175
1277
  // exact client API-key id OR case-insensitive name substring.
1176
1278
  const ak = firstStr(query.apiKey).trim();
1279
+ // Client-family selector: membership in the session's distinct family set
1280
+ // (machine ids from utils/client-families.ts). The UA that produced the
1281
+ // family is forgeable and display-only, so filtering happens on the derived
1282
+ // family, never on a raw UA string.
1283
+ const client = firstStr(query.client).trim().toLowerCase();
1284
+ // Tier selector: exact `maxTier` (lite|plus|pro|ultra) — the session's
1285
+ // ratchet ceiling, identical on live and reconstructed rows.
1286
+ const tier = firstStr(query.tier).trim().toLowerCase();
1177
1287
  // Internal (gateway-loopback) rows: hidden unless the caller asks for
1178
1288
  // them. Filtered BEFORE pagination so `total` stays truthful.
1179
1289
  const hideInternal = firstStr(query.hideInternal) !== '0';
@@ -1198,6 +1308,7 @@ providerConfigs = []) {
1198
1308
  const sessTraces = traceTracker.getTracesBySession(s.id);
1199
1309
  const keyList = distinctTraceKeys(sessTraces);
1200
1310
  const uaList = distinctTraceUserAgents(sessTraces);
1311
+ const famList = clientFamiliesOf(distinctTraceClientFingerprints(sessTraces));
1201
1312
  const refList = distinctTraceClientRefs(sessTraces);
1202
1313
  const row = {
1203
1314
  // Whitelisted entity projection (session-row.ts): the entity's
@@ -1220,6 +1331,9 @@ providerConfigs = []) {
1220
1331
  apiKeys: keyList.length ? keyList : undefined,
1221
1332
  // Client User-Agents (write order) — console display only (forgeable).
1222
1333
  clients: uaList.length ? uaList : undefined,
1334
+ // Client families derived from those UAs (write order) — console
1335
+ // filter axis; same derivation as reconstructed rows.
1336
+ ...(famList.length ? { clientFamilies: famList } : {}),
1223
1337
  // Client-minted conversation ids (write order) — the alias half of the
1224
1338
  // gateway-id ↔ client-id mapping, derived from traces exactly like the
1225
1339
  // reconstructed rows so both shapes show the same pair.
@@ -1233,8 +1347,8 @@ providerConfigs = []) {
1233
1347
  idSource: sessionIdSourceOf(sessTraces, s.origin?.lookupType) ?? null,
1234
1348
  ...traceTracker.getSessionAggregates(s.id),
1235
1349
  };
1236
- const boundCredentialLabel = boundCredentialLabelOf(registry.getCredentialChain(row.currentProvider ?? ''), row.boundKeyHashPrefix);
1237
- return boundCredentialLabel ? { ...row, boundCredentialLabel } : row;
1350
+ const bound = boundCredentialOf(registry.getCredentialChain(row.currentProvider ?? ''), row.boundKeyHashPrefix);
1351
+ return { ...row, ...(bound.label ? { boundCredentialLabel: bound.label } : {}), ...(bound.machineLogin ? { boundCredentialMachineLogin: true } : {}) };
1238
1352
  });
1239
1353
  const liveIds = new Set(live.map(s => s.id));
1240
1354
  const reconstructed = traceTracker
@@ -1244,9 +1358,12 @@ providerConfigs = []) {
1244
1358
  // Most recently active first — stable ordering for pagination. `q`
1245
1359
  // filters (case-insensitive substring) across session id, current model AND
1246
1360
  // its provider (both are rendered in that column), first user message,
1247
- // every app name and every client-minted conversation id (the alias half
1248
- // of the ADR-0002 §1 pair), applied BEFORE pagination.
1249
- // `apiKey` (ak) selects by membership in the session's distinct key set.
1361
+ // every app name, every client FAMILY (id and label — never the raw UA,
1362
+ // which is forgeable) and every client-minted conversation id (the alias
1363
+ // half of the ADR-0002 §1 pair), applied BEFORE pagination.
1364
+ // `apiKey` (ak) selects by membership in the session's distinct key set;
1365
+ // `client` selects by membership in its distinct client-family set;
1366
+ // `tier` selects the exact maxTier value.
1250
1367
  const all = [...live, ...reconstructed]
1251
1368
  .filter(s => {
1252
1369
  if (hideInternal && s.internal)
@@ -1259,6 +1376,13 @@ providerConfigs = []) {
1259
1376
  const keys = s.apiKeys ?? [];
1260
1377
  if (ak && !keys.some(k => k.id === ak || k.name.toLowerCase().includes(ak.toLowerCase())))
1261
1378
  return false;
1379
+ // Client-family membership, applied BEFORE pagination so `total` stays
1380
+ // truthful. An empty selector means "every client".
1381
+ if (client && !(s.clientFamilies ?? []).some(f => f.id.toLowerCase() === client))
1382
+ return false;
1383
+ // Exact tier selector, also applied BEFORE pagination.
1384
+ if (tier && String(s.maxTier ?? '').toLowerCase() !== tier)
1385
+ return false;
1262
1386
  return (!q ||
1263
1387
  s.id.toLowerCase().includes(q) ||
1264
1388
  String(s.currentModel || '')
@@ -1271,6 +1395,7 @@ providerConfigs = []) {
1271
1395
  .toLowerCase()
1272
1396
  .includes(q) ||
1273
1397
  keys.some(k => k.name.toLowerCase().includes(q)) ||
1398
+ (s.clientFamilies ?? []).some(f => f.id.toLowerCase().includes(q) || f.label.toLowerCase().includes(q)) ||
1274
1399
  (s.clientRefs ?? []).some(r => r.id.toLowerCase().includes(q) || r.kind.toLowerCase().includes(q)));
1275
1400
  })
1276
1401
  .sort((a, b) => b.lastActiveAt - a.lastActiveAt);
@@ -1299,7 +1424,7 @@ providerConfigs = []) {
1299
1424
  const execution = currentModelOf(traces);
1300
1425
  // Same display identity join as the list rows: match the bound prefix
1301
1426
  // against the serving provider's live chain.
1302
- const boundCredentialLabel = boundCredentialLabelOf(orchestrator.getRegistry().getCredentialChain(execution.currentProvider ?? ''), session.boundKeyHashPrefix);
1427
+ const bound = boundCredentialOf(orchestrator.getRegistry().getCredentialChain(execution.currentProvider ?? ''), session.boundKeyHashPrefix);
1303
1428
  return {
1304
1429
  object: 'session',
1305
1430
  // Same two projections as the list rows (ADR-0002 §3): the routing pin
@@ -1313,7 +1438,8 @@ providerConfigs = []) {
1313
1438
  // the fallback) so list and detail cannot disagree.
1314
1439
  firstUserMessage: session.firstUserMessage ?? sessionTitleOf(traces),
1315
1440
  ...execution,
1316
- ...(boundCredentialLabel ? { boundCredentialLabel } : {}),
1441
+ ...(bound.label ? { boundCredentialLabel: bound.label } : {}),
1442
+ ...(bound.machineLogin ? { boundCredentialMachineLogin: true } : {}),
1317
1443
  traceCount: traces.length,
1318
1444
  recentTraces: traces.slice(-5),
1319
1445
  };
@@ -1374,11 +1500,25 @@ providerConfigs = []) {
1374
1500
  catch (err) {
1375
1501
  req.log.warn(err, 'capture cascade delete errored — left to retention sweep');
1376
1502
  }
1503
+ // Cascade: drop this session's snapshot transcript (ADR-0038). The store
1504
+ // keys by session id, so one file covers the whole conversation; its
1505
+ // content-addressed media is SHARED by digest across sessions, so it is
1506
+ // left to the retention sweep rather than deleted here (another live
1507
+ // session may reference the same payload). Fails soft — a locked file must
1508
+ // not turn a successful delete into a 500.
1509
+ let snapshotDeleted = false;
1510
+ try {
1511
+ snapshotDeleted = orchestrator.getSnapshotStore().deleteSession(id);
1512
+ }
1513
+ catch (err) {
1514
+ req.log.warn(err, 'snapshot cascade delete errored — left to retention sweep');
1515
+ }
1377
1516
  return {
1378
1517
  status: 'ok',
1379
1518
  message: `Session '${id}' and its traces have been successfully cleared`,
1380
1519
  capturesDeleted,
1381
1520
  chainNodesDeleted,
1521
+ snapshotDeleted,
1382
1522
  };
1383
1523
  });
1384
1524
  // 3F. Query Trajectory / Traces by Session ID
@@ -1395,6 +1535,238 @@ providerConfigs = []) {
1395
1535
  data: traces,
1396
1536
  };
1397
1537
  });
1538
+ // 3F-bis. Session snapshot handoff (ADR-0038): read the semantic transcript,
1539
+ // build a transport-neutral resume payload, or download a portable bundle.
1540
+ // The transcript only exists when `sessionSnapshots.enabled` is on; every
1541
+ // route fails soft to a plain "not found" when the plane never recorded it.
1542
+ app.get('/api/admin/sessions/:id/snapshot', async (req, reply) => {
1543
+ const { id } = req.params;
1544
+ const snap = orchestrator.getSnapshotStore().read(id);
1545
+ if (!snap) {
1546
+ return reply.status(404).send({
1547
+ error: { message: `No snapshot transcript for session '${id}'`, type: 'invalid_request_error' },
1548
+ });
1549
+ }
1550
+ return { object: 'session_snapshot', ...snap };
1551
+ });
1552
+ app.get('/api/admin/sessions/:id/resume', async (req, reply) => {
1553
+ const { id } = req.params;
1554
+ const resume = orchestrator.getSnapshotStore().resumeView(id);
1555
+ if (!resume) {
1556
+ // Either no transcript, or one that halted mid-session — both mean "you
1557
+ // cannot faithfully continue this conversation from here".
1558
+ const snap = orchestrator.getSnapshotStore().read(id);
1559
+ return reply.status(409).send({
1560
+ error: {
1561
+ message: snap?.incomplete
1562
+ ? `Session '${id}' is incomplete (${snap.incomplete.reason}) — resuming would drop history`
1563
+ : `No complete snapshot transcript for session '${id}'`,
1564
+ type: 'invalid_request_error',
1565
+ },
1566
+ });
1567
+ }
1568
+ return { object: 'session_resume', ...resume };
1569
+ });
1570
+ /**
1571
+ * Message TREE of a stored session (ADR-0038 §8 / ADR-0039). The console's
1572
+ * message-level list/tree view reads this: `nodes` is the deduped message map,
1573
+ * `commits` the per-request chain, `branched` flags a non-linear conversation.
1574
+ * The tree is DERIVED from the stored prefixes (the wire names no parent), so
1575
+ * this is the one place that derivation runs.
1576
+ */
1577
+ app.get('/api/admin/sessions/:id/snapshot/tree', async (req, reply) => {
1578
+ const { id } = req.params;
1579
+ const snap = orchestrator.getSnapshotStore().read(id);
1580
+ if (!snap) {
1581
+ return reply.status(404).send({
1582
+ error: { message: `No snapshot transcript for session '${id}'`, type: 'invalid_request_error' },
1583
+ });
1584
+ }
1585
+ const tree = buildMessageTree(id, snap.turns);
1586
+ return {
1587
+ object: 'session_message_tree',
1588
+ sessionId: id,
1589
+ incomplete: snap.incomplete ?? null,
1590
+ branched: tree.branched,
1591
+ roots: tree.roots,
1592
+ commits: tree.commits,
1593
+ nodes: tree.nodes,
1594
+ media: tree.media,
1595
+ };
1596
+ });
1597
+ /**
1598
+ * Migration preview (ADR-0039): what a handoff to `target` would produce —
1599
+ * message counts, the title, the resolved paths — WITHOUT writing anything.
1600
+ * The operator confirms against this before the real migration runs, because
1601
+ * a wrong working directory files the session under the wrong project.
1602
+ */
1603
+ app.get('/api/admin/sessions/:id/handoff/preview', async (req, reply) => {
1604
+ const { id } = req.params;
1605
+ const query = req.query;
1606
+ const target = (query.target ?? 'pi');
1607
+ if (!HANDOFF_TARGETS.includes(target)) {
1608
+ return reply.status(400).send({ error: { message: `Unknown handoff target '${String(target)}'`, type: 'invalid_request_error' } });
1609
+ }
1610
+ const snap = orchestrator.getSnapshotStore().read(id);
1611
+ if (!snap) {
1612
+ return reply.status(404).send({ error: { message: `No snapshot transcript for session '${id}'`, type: 'invalid_request_error' } });
1613
+ }
1614
+ // Default the suggested directory to the gateway's own cwd so the field is
1615
+ // never empty; the operator can (and usually should) change it.
1616
+ const workingDir = typeof query.workingDir === 'string' && query.workingDir.trim() ? query.workingDir.trim() : process.cwd();
1617
+ const tree = buildMessageTree(id, snap.turns);
1618
+ const preview = { target, workingDir, incomplete: snap.incomplete ?? null, messages: tree.commits.reduce((n, c) => n + c.outputNodes.length, 0), branches: tree.commits.filter((c) => !c.extendsPrevious).length };
1619
+ return { object: 'session_handoff_preview', sessionId: id, ...preview };
1620
+ });
1621
+ /**
1622
+ * JSONL export (ADR-0039): the SAME session file a pi/omp migration would
1623
+ * write, returned as a download instead of filed under the client's home.
1624
+ * The working directory only rides in the session header's `cwd` (the file
1625
+ * lands wherever the operator saves it), so it defaults to the gateway's own
1626
+ * cwd. opencode has no JSONL session format — its export is the migration's
1627
+ * `session import` path.
1628
+ */
1629
+ app.get('/api/admin/sessions/:id/handoff/export', async (req, reply) => {
1630
+ const { id } = req.params;
1631
+ const query = req.query;
1632
+ const target = query.target ?? 'pi';
1633
+ if (target !== 'pi' && target !== 'omp') {
1634
+ return reply.status(400).send({
1635
+ error: { message: `JSONL export targets are pi and omp — '${target}' has no JSONL session format`, type: 'invalid_request_error' },
1636
+ });
1637
+ }
1638
+ const mode = (query.mode ?? 'fork');
1639
+ if (!HANDOFF_MODES.includes(mode)) {
1640
+ return reply.status(400).send({ error: { message: `mode must be one of ${HANDOFF_MODES.join(', ')}`, type: 'invalid_request_error' } });
1641
+ }
1642
+ try {
1643
+ const out = await exportJsonlSession(orchestrator.getSnapshotStore(), {
1644
+ sessionId: id,
1645
+ target,
1646
+ mode,
1647
+ model: typeof query.model === 'string' ? query.model : undefined,
1648
+ summarize: summarizeHandoff,
1649
+ ...(typeof query.workingDir === 'string' && query.workingDir.trim() ? { workingDir: query.workingDir.trim() } : {}),
1650
+ });
1651
+ return reply
1652
+ .header('Content-Disposition', `attachment; filename="${out.fileName}"`)
1653
+ .type('application/x-ndjson')
1654
+ .send(out.body);
1655
+ }
1656
+ catch (err) {
1657
+ const code = err instanceof HandoffError ? err.code : 500;
1658
+ return reply.status(code).send({ error: { message: err.message, type: 'invalid_request_error' } });
1659
+ }
1660
+ });
1661
+ /**
1662
+ * Migrate a session into another client as a NEW session (ADR-0039). pi/omp
1663
+ * get a JSONL session file under `<agentDir>/sessions/<slug>/`; opencode goes
1664
+ * through its own `session import`. Never mutates the gateway's state, and a
1665
+ * failure leaves nothing half-written.
1666
+ */
1667
+ app.post('/api/admin/sessions/:id/handoff', async (req, reply) => {
1668
+ const { id } = req.params;
1669
+ const body = (req.body ?? {});
1670
+ const target = (body.target ?? '');
1671
+ if (!HANDOFF_TARGETS.includes(target)) {
1672
+ return reply.status(400).send({
1673
+ error: { message: `target must be one of ${HANDOFF_TARGETS.join(', ')}`, type: 'invalid_request_error' },
1674
+ });
1675
+ }
1676
+ const mode = (body.mode ?? 'fork');
1677
+ if (!HANDOFF_MODES.includes(mode)) {
1678
+ return reply.status(400).send({ error: { message: `mode must be one of ${HANDOFF_MODES.join(', ')}`, type: 'invalid_request_error' } });
1679
+ }
1680
+ try {
1681
+ const result = await migrateSession(orchestrator.getSnapshotStore(), {
1682
+ sessionId: id,
1683
+ target,
1684
+ mode,
1685
+ model: typeof body.model === 'string' ? body.model : undefined,
1686
+ summarize: summarizeHandoff,
1687
+ workingDir: String(body.workingDir ?? ''),
1688
+ ...(body.agentDir ? { agentDir: body.agentDir } : {}),
1689
+ });
1690
+ return { status: 'ok', ...result };
1691
+ }
1692
+ catch (err) {
1693
+ const code = err instanceof HandoffError ? err.code : 500;
1694
+ return reply.status(code).send({ error: { message: err.message, type: 'invalid_request_error' } });
1695
+ }
1696
+ });
1697
+ app.get('/api/admin/sessions/:id/snapshot/export', async (req, reply) => {
1698
+ const { id } = req.params;
1699
+ try {
1700
+ const bytes = buildSessionBundle(orchestrator.getSnapshotStore(), id);
1701
+ const filename = sessionBundleName(id);
1702
+ return reply
1703
+ .header('Content-Disposition', `attachment; filename="${filename}"`)
1704
+ .type('application/zip')
1705
+ .send(Buffer.from(bytes));
1706
+ }
1707
+ catch (err) {
1708
+ const code = err instanceof SessionBundleError ? err.code : 500;
1709
+ return reply.status(code).send({
1710
+ error: { message: err.message, type: 'invalid_request_error' },
1711
+ });
1712
+ }
1713
+ });
1714
+ // Media referenced by a snapshot transcript, served for the replay view and
1715
+ // for a consumer that fetched a resume payload but not the whole bundle.
1716
+ app.get('/api/admin/sessions/:id/snapshot/media/:hash', async (req, reply) => {
1717
+ const { hash } = req.params;
1718
+ const store = orchestrator.getSnapshotStore();
1719
+ const data = store.readMedia(hash);
1720
+ const meta = store.mediaMeta(hash);
1721
+ if (!data || !meta)
1722
+ return reply.status(404).send({ error: { message: 'media not found', type: 'invalid_request_error' } });
1723
+ return reply.type(meta.contentType).send(data);
1724
+ });
1725
+ // 3F-ter. Import a portable session bundle (ADR-0038). The body is the raw
1726
+ // zip (Content-Type untrusted, same posture as the env-archive import). The
1727
+ // whole bundle is verified before anything is written — a tampered or
1728
+ // truncated archive is refused whole, never half-imported. `?sessionId=`
1729
+ // re-homes the conversation onto a caller-chosen id (deduping into an
1730
+ // existing one would silently append to another conversation, so a collision
1731
+ // is a 409, never an overwrite).
1732
+ app.post('/api/admin/sessions/import', { bodyLimit: IMPORT_BODY_LIMIT_BYTES }, async (req, reply) => {
1733
+ const body = req.body;
1734
+ if (!Buffer.isBuffer(body)) {
1735
+ return reply.status(400).send({
1736
+ error: { message: 'Import body must be a session bundle zip (.ocr_session.zip)', type: 'invalid_request_error' },
1737
+ });
1738
+ }
1739
+ let parsed;
1740
+ try {
1741
+ parsed = parseSessionBundle(new Uint8Array(body));
1742
+ }
1743
+ catch (err) {
1744
+ const code = err instanceof SessionBundleError ? err.code : 400;
1745
+ return reply.status(code).send({ error: { message: err.message, type: 'invalid_request_error' } });
1746
+ }
1747
+ const store = orchestrator.getSnapshotStore();
1748
+ const targetId = (req.query.sessionId ?? '').trim() || parsed.manifest.sessionId;
1749
+ if (!targetId || targetId.length > 200) {
1750
+ return reply.status(400).send({ error: { message: 'Invalid target session id', type: 'invalid_request_error' } });
1751
+ }
1752
+ if (store.read(targetId) || orchestrator.getSessionManager()?.getSession(targetId)) {
1753
+ return reply.status(409).send({
1754
+ error: {
1755
+ message: `Session '${targetId}' already exists — refusing to merge a bundle into a live conversation`,
1756
+ type: 'invalid_request_error',
1757
+ },
1758
+ });
1759
+ }
1760
+ try {
1761
+ const result = store.importBundle(parsed.turns, parsed.media, targetId);
1762
+ return { status: 'ok', sessionId: targetId, ...result };
1763
+ }
1764
+ catch (err) {
1765
+ return reply.status(500).send({
1766
+ error: { message: `Import failed: ${err.message}`, type: 'invalid_request_error' },
1767
+ });
1768
+ }
1769
+ });
1398
1770
  // 3G. Global Request Trajectory Queries (with optional session_id / model
1399
1771
  // filter, time-window & pagination). `model` is an exact match on the
1400
1772
  // resolved physical model id recorded in each trace.
@@ -1453,10 +1825,32 @@ providerConfigs = []) {
1453
1825
  // former server-level capture hooks are deleted). `return reply` mirrors
1454
1826
  // the old handler's terminal pattern — the Fastify transport has already
1455
1827
  // sent via reply / reply.raw.
1828
+ //
1829
+ // bodyLimit is NOT decoration: Fastify's instance default is 1 MiB, so an
1830
+ // unset value makes the native leg answer 413 "Payload Too Large" on any
1831
+ // ordinary agent context (Claude Code / opencode routinely post several
1832
+ // MB) while the MITM leg of the SAME request admits 32 MB. One constant,
1833
+ // both legs — see config/defaults.ts and surfaces/body-admission.ts.
1834
+ //
1835
+ // surfaceBodyAdmissionOptions carries the whole admission policy for this
1836
+ // leg: Content-Encoding decode (gzip/deflate/br, 415 for anything else),
1837
+ // the cap on the DECOMPRESSED body, and rejection answers shaped with the
1838
+ // surface's own error envelope (ADR-0008: 400/413 precede process, so no
1839
+ // transport and no capture event exists to shape them later). Left to
1840
+ // Fastify's default it answers {statusCode, code, error, message}, which
1841
+ // client SDKs surface as an opaque `413 "Payload Too Large"` naming neither
1842
+ // the cap nor the gateway as its author. Non-admission errors are re-thrown
1843
+ // to the parent handler per fastify/docs/Reference/Errors.md.
1456
1844
  for (const surface of SURFACES) {
1457
- app.post(surface.routePath, async (req, reply) => {
1845
+ app.post(surface.routePath, surfaceBodyAdmissionOptions(surface), async (req, reply) => {
1458
1846
  const t = createFastifyTransport(req, reply, orchestrator);
1459
- await dispatchSurface(t, surface, orchestrator, req.body);
1847
+ // `normalizeNativeBody` closes the parser-shape gap: a tolerated but
1848
+ // non-json declaration (text/plain) hands Fastify's parser a raw STRING,
1849
+ // which would otherwise reach the pipeline and fail as a misleading
1850
+ // "messages array is required" 400 for a perfectly valid body. A wrong
1851
+ // shape throws BodyAdmissionError, which the route handler above answers
1852
+ // in the surface envelope.
1853
+ await dispatchSurface(t, surface, orchestrator, normalizeNativeBody(req.body));
1460
1854
  return reply;
1461
1855
  });
1462
1856
  }
@@ -223,7 +223,13 @@ export declare class SessionManager {
223
223
  * arguments on resend, so raw JSON.stringify of the whole object would
224
224
  * miss every tool-call boundary on the next turn.
225
225
  */
226
- private static serializeMessage;
226
+ /**
227
+ * PUBLIC on purpose: the snapshot message tree (ADR-0038 §8) derives node
228
+ * identity from THIS canonical form, so two branches that share an ancestry
229
+ * must collapse onto the same node ids it would produce. Exposing it keeps ONE
230
+ * canonicalization instead of a second copy that could drift from the anchors.
231
+ */
232
+ static serializeMessage(item: InputItem | OutputItem): string;
227
233
  private static contentText;
228
234
  private static canonicalToolArgs;
229
235
  /** One canonical string per item: no content-tree clone on the request path. */
@@ -268,9 +274,10 @@ export declare class SessionManager {
268
274
  * is no second namespace to map, while the body channel below covers wires
269
275
  * that have no HTTP headers at all). Returns the alphabetically first
270
276
  * matching header's value (array header → first entry), or null. The bare
271
- * `x-session-id` / `x-conversation-id` / `session-id` / `conversation-id`
272
- * forms never match (the app segment must be non-empty) — they are step 1's
273
- * explicit_header territory. Two namespace guards bind each value: a value
277
+ * explicit forms (`x-session-id`, `x-conversation-id`, `x-session-affinity`,
278
+ * `session_id`, `session-id`, `conversation-id`) never match (the app
279
+ * segment must be non-empty) — they are step 1's explicit_header territory.
280
+ * Two namespace guards bind each value: a value
274
281
  * claiming the reserved `ocr-internal:` prefix (a gateway-internal row
275
282
  * marker — a client must not be able to hide its row from the console) or
276
283
  * exceeding `VENDOR_SESSION_ID_MAX` is skipped, falling through to the next
@@ -294,9 +301,32 @@ export declare class SessionManager {
294
301
  * and the session it names can never disagree.
295
302
  */
296
303
  /**
297
- * Caller-supplied conversation id. Reads the four explicit header names and
304
+ * Header names that carry a client conversation id, in precedence order.
305
+ * Every entry is conversation-scoped on the clients that emit it, and none
306
+ * is reachable by the vendor probe: `x-session-id` (explicit contract,
307
+ * console, billion-context proxy — proven 1:1 in the capture archive),
308
+ * `x-conversation-id` (same explicit namespace, backward compatibility),
309
+ * `x-session-affinity` (pi chat on a non-OpenRouter endpoint and the
310
+ * Anthropic leg — an affinity key only works per-conversation; the probe
311
+ * regex needs a trailing `-id`, so this spelling is never claimed twice),
312
+ * `session_id` (pi's openai-format id on the chat and Responses HTTP legs;
313
+ * underscore, so the hyphen-only probe can never match it), then the legacy
314
+ * `session-id` / `conversation-id`.
315
+ */
316
+ private static readonly EXPLICIT_SESSION_HEADERS;
317
+ /** Trimmed first entry of a possibly-array header value, else ''. */
318
+ private static headerValue;
319
+ /**
320
+ * Caller-supplied conversation id. Reads the explicit header list and
298
321
  * nothing else: no mint, no anchor, no session-manager write. Archive code
299
322
  * uses this when it needs a file name and the request is not a conversation.
323
+ *
324
+ * A blank value falls through to the next name — a truthy-but-empty header
325
+ * must never mask a real id later in the list. `session-id` is skipped when
326
+ * it equals the request's `x-client-request-id`: pi's Codex Responses
327
+ * websocket leg stamps both with the PER-REQUEST id, so that pair is a
328
+ * correlation id, not a conversation id (a legitimate client never names a
329
+ * conversation after its own per-request id).
300
330
  */
301
331
  static explicitSessionId(headers?: Record<string, string | string[] | undefined>): string | undefined;
302
332
  static clientRefOf(request: CanonicalRequest): ClientConversationRef | null;
@@ -356,6 +386,13 @@ export declare class SessionManager {
356
386
  private bindClientRef;
357
387
  /** FIFO-bounded map set (Map preserves insertion order). */
358
388
  private setBounded;
389
+ /**
390
+ * True when a ratchet call actually persists a per-session model pin.
391
+ * `applyRatchet` still resolves a representative model in the stateless /
392
+ * disabled branch, but that representative is thrown away with the dummy
393
+ * session — callers must not let it consume a rotation pick.
394
+ */
395
+ pinsModels(): boolean;
359
396
  /**
360
397
  * Applies the Monotonic Session Ratchet policy.
361
398
  *