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
@@ -0,0 +1,818 @@
1
+ /**
2
+ * Body admission — the ONE place that decides what the gateway accepts as a
3
+ * request body, and what it says when it refuses.
4
+ *
5
+ * WHY THIS MODULE EXISTS: before it, "what is the body limit" was written in
6
+ * four places (the Fastify route option, the node-http read loop, the h2 preface
7
+ * buffer, and a local `MiB` literal used to format the message) and "what does a
8
+ * rejection look like" in two (the surface envelope on the native leg, a bare
9
+ * string on the MITM leg). That is exactly how the original bug happened: the
10
+ * native leg silently inherited Fastify's 1 MiB framework default while the MITM
11
+ * leg admitted 32 MB, so the SAME request from the SAME client was 413 on one
12
+ * path and 200 on the other. Numbers, messages and envelopes now come from here.
13
+ *
14
+ * THE TIERS (values declared in config/defaults.ts, never re-declared here):
15
+ * - inference GATEWAY_MAX_BODY_BYTES — both inference legs;
16
+ * - admin ADMIN_MAX_BODY_BYTES — the Fastify instance default, so no
17
+ * console/API route can silently inherit 1 MiB;
18
+ * - upload IMPORT_BODY_LIMIT_BYTES / PLUGIN_PACKAGE_MAX_BYTES — declared
19
+ * per route, because those bodies are archives, not prompts.
20
+ *
21
+ * COMPRESSION: a client may send the body gzipped/deflate/br. Two things follow,
22
+ * both handled here so both legs behave identically:
23
+ * 1. the cap bounds the DECOMPRESSED body (Fastify measures the stream a
24
+ * `preParsing` hook returns; the MITM leg passes `maxOutputLength` to zlib),
25
+ * so a compressed bomb cannot inflate past the limit;
26
+ * 2. an encoding we cannot decode is an explicit 415, never a silent
27
+ * pass-through that surfaces as a misleading "Invalid JSON body" 400.
28
+ */
29
+ import { brotliDecompressSync, createBrotliDecompress, createGunzip, createInflate, gunzipSync, inflateRawSync, inflateSync, } from 'node:zlib';
30
+ import { ADMIN_MAX_BODY_BYTES, GATEWAY_MAX_BODY_BYTES, REQUEST_BODY_IDLE_TIMEOUT_MS } from '../config/defaults.js';
31
+ /** Bytes per MiB — declared once so no consumer writes `1024 * 1024` inline. */
32
+ export const BYTES_PER_MIB = 1024 * 1024;
33
+ /**
34
+ * A body that will not be admitted. It carries its own HTTP status and surface
35
+ * `code` so BOTH legs answer identically: the Fastify route `errorHandler` reads
36
+ * `statusCode`/`code` off the error, the node-http adapter passes the same pair
37
+ * to `sendPreDispatchError`. Neither leg keeps a private message template.
38
+ *
39
+ * `headers` carries the negotiation headers RFC 9110 tells a rejecting server it
40
+ * MAY/CAN send (see ACCEPT_ENCODING_ADVERTISEMENT / ACCEPT_MEDIA_ADVERTISEMENT):
41
+ * they ride on the error, not on the senders, so an admission refusal answers them
42
+ * on both legs and no other 4xx accidentally grows them.
43
+ */
44
+ export class BodyAdmissionError extends Error {
45
+ statusCode;
46
+ code;
47
+ headers;
48
+ constructor(statusCode, code, message, headers) {
49
+ super(message);
50
+ this.name = 'BodyAdmissionError';
51
+ this.statusCode = statusCode;
52
+ this.code = code;
53
+ this.headers = headers ?? admissionNegotiationHeaders(code);
54
+ }
55
+ }
56
+ /** 33554432 -> "32 MiB"; 512000 -> "500 KiB". Whole units only: a limit stated
57
+ * as "33554432 bytes" is never actionable for a human reading a 413. */
58
+ export function formatByteLimit(bytes) {
59
+ if (bytes >= BYTES_PER_MIB && bytes % BYTES_PER_MIB === 0)
60
+ return `${bytes / BYTES_PER_MIB} MiB`;
61
+ if (bytes >= 1024 && bytes % 1024 === 0)
62
+ return `${bytes / 1024} KiB`;
63
+ return `${bytes} bytes`;
64
+ }
65
+ /** The 413 sentence, shared by the native leg, the MITM leg and the h2 preface
66
+ * guard. Names the author (the gateway), the number, and the fix.
67
+ *
68
+ * No `Retry-After` is sent on purpose: RFC 9110 15.5.14 defines that header for
69
+ * when "the request condition is likely to be temporary" (rate limits, maintenance
70
+ * windows). An oversized body is not temporary — it stays oversized until the
71
+ * client changes the request — so a delay would only invite pointless retries of
72
+ * the same refusal. */
73
+ export function bodyTooLargeMessage(capBytes) {
74
+ return (`OmniCellRouter: request body exceeds the gateway limit of ${formatByteLimit(capBytes)}. ` +
75
+ 'Shorten the conversation history, or reference large media by URL/file id instead of inlining base64.');
76
+ }
77
+ /**
78
+ * The admission caps THIS process enforces. They start at the shipped constants and
79
+ * are replaced once at boot by `configureBodyLimits` from `client.bodyLimits`, so a
80
+ * build with no config (standalone CLI, a test that boots a bare server) behaves
81
+ * exactly as it did before the knobs existed.
82
+ *
83
+ * Boot-frozen on purpose, not by omission: Fastify reads a route's `bodyLimit` at
84
+ * REGISTRATION time, and a request already being parsed cannot be policed against a
85
+ * number that changed mid-flight. A new value therefore applies on the next
86
+ * controlled restart (ADR-0007), which is also the only moment the h2 preface and
87
+ * MITM drain guards are re-sized. Reading the caps through these two accessors —
88
+ * instead of importing the constants at each site — is what keeps the six admission
89
+ * legs on ONE number, which is the whole point of this module.
90
+ */
91
+ let effectiveGatewayCap = GATEWAY_MAX_BODY_BYTES;
92
+ let effectiveAdminCap = ADMIN_MAX_BODY_BYTES;
93
+ /** Install the configured caps (called once from `createServer`) and return what
94
+ * will actually be enforced, so the caller can log the effective number. Junk
95
+ * (non-finite, <= 0) falls back to the shipped constant: the cleaner in
96
+ * `resolveBodyLimits` already clamps a loaded file, so this is the guard for a
97
+ * hand-built config object, not a second policy. */
98
+ export function configureBodyLimits(limits) {
99
+ const sane = (value, fallback) => typeof value === 'number' && Number.isFinite(value) && value > 0 ? Math.floor(value) : fallback;
100
+ effectiveGatewayCap = sane(limits?.maxBytes, GATEWAY_MAX_BODY_BYTES);
101
+ effectiveAdminCap = sane(limits?.adminMaxBytes, ADMIN_MAX_BODY_BYTES);
102
+ return { maxBytes: effectiveGatewayCap, adminMaxBytes: effectiveAdminCap };
103
+ }
104
+ /** The enforced cap of one plane. Read at call time, never captured at module load. */
105
+ export function bodyLimitFor(plane) {
106
+ return plane === 'admin' ? effectiveAdminCap : effectiveGatewayCap;
107
+ }
108
+ export function payloadTooLarge(capBytes = bodyLimitFor('gateway')) {
109
+ return new BodyAdmissionError(413, 'payload_too_large', bodyTooLargeMessage(capBytes));
110
+ }
111
+ /**
112
+ * A body that stopped arriving. 408 (RFC 9110 15.5.9), NOT another 413: nothing is
113
+ * oversized on this path, and the two verdicts ask the client for opposite fixes —
114
+ * shrink the payload versus send the same one again. `connection: close` rides with
115
+ * it because a stalled connection is exactly the thing we are reaping.
116
+ */
117
+ export function requestBodyTimeout(idleMs = REQUEST_BODY_IDLE_TIMEOUT_MS) {
118
+ return new BodyAdmissionError(408, 'request_body_timeout', `OmniCellRouter: the request body stalled — no bytes arrived for ${Math.round(idleMs / 1000)}s. Retry the request, or raise the client's write timeout.`, { connection: 'close' });
119
+ }
120
+ /** A body that arrived as text but is not JSON. Lives here so both legs use the
121
+ * same words as Fastify's own parser-failure path. */
122
+ export function invalidJsonBody() {
123
+ return new BodyAdmissionError(400, 'invalid_json_body', 'Invalid JSON body');
124
+ }
125
+ /**
126
+ * Content encodings this gateway decodes on the way IN. gzip/deflate/br are what
127
+ * agent SDKs actually send (the Anthropic SDK gzips system-prompt-heavy requests;
128
+ * opencode does it for large bodies). `zstd` is deliberately absent — Node ships
129
+ * no zstd binding — and an undecodable body must be refused by name rather than
130
+ * parsed as garbage.
131
+ */
132
+ const DECODABLE_ENCODINGS = new Set(['gzip', 'x-gzip', 'deflate', 'br']);
133
+ /**
134
+ * What we advertise as acceptable request codings, derived from the decode table
135
+ * so the advertisement and the decoder cannot drift. `x-gzip` is the same coding
136
+ * under a legacy name, so it is not advertised; `identity` needs no mention
137
+ * (RFC 9110 8.4.1: a coding token of `identity` is always acceptable).
138
+ *
139
+ * RFC 9110 15.5.16: a 415 response "CAN" list what the server accepts. The coding
140
+ * refusal is the 415 where that list is Content-Encoding, and 8.4.1 is explicit
141
+ * that the media-type 415 MUST NOT carry it — "an incorrectly generated
142
+ * Accept-Encoding header field would be interpreted by the client as an
143
+ * indication that the server supports the listed content codings" — which is why
144
+ * this header rides on the error object instead of on the shared send path.
145
+ */
146
+ export const ACCEPT_ENCODING_ADVERTISEMENT = [...DECODABLE_ENCODINGS]
147
+ .filter((coding) => coding !== 'x-gzip')
148
+ .join(', ');
149
+ /** The media-type 415 gets the other half of the same sentence: the media type
150
+ * whose body we will actually parse. `text/plain` is tolerated in the parser but
151
+ * not advertised, because it is a mis-declaration allowance, not a contract. */
152
+ export const ACCEPT_MEDIA_ADVERTISEMENT = 'application/json';
153
+ /** The codings a client may declare on the way in — the same table the decoders
154
+ * use, so the 415 message and the Accept-Encoding advertisement cannot drift. */
155
+ export const SUPPORTED_REQUEST_CODINGS = [...DECODABLE_ENCODINGS].filter((coding) => coding !== 'x-gzip');
156
+ /**
157
+ * The two headers a rejecting gateway is allowed to advertise, keyed by the code
158
+ * that fired. RFC 9110 15.5.16: a 415 "MUST NOT include a Content-Encoding"-family
159
+ * negotiation field for the rejected payload — it may include `Accept`; 12.5.3
160
+ * gives `Accept-Encoding` to the coding refusal. Attaching the wrong one is not
161
+ * cosmetic: `Accept-Encoding` on a 415 tells the client the media type was fine.
162
+ *
163
+ * Returns undefined for the codes that negotiate nothing (413, 400), so the send
164
+ * sites never have to know which code means what.
165
+ */
166
+ export function admissionNegotiationHeaders(code) {
167
+ if (code === 'unsupported_content_encoding')
168
+ return { 'accept-encoding': ACCEPT_ENCODING_ADVERTISEMENT };
169
+ if (code === 'unsupported_media_type')
170
+ return { accept: ACCEPT_MEDIA_ADVERTISEMENT };
171
+ return undefined;
172
+ }
173
+ /** True when the client declared `Expect: 100-continue` (token match, so an
174
+ * extension expectation alongside it does not confuse the guard). */
175
+ export function expects100Continue(headers) {
176
+ const raw = headers.expect;
177
+ const values = Array.isArray(raw) ? raw : raw === undefined ? [] : [raw];
178
+ return values.some((v) => /(^|[,\s])100-continue([,\s]|$)/i.test(v));
179
+ }
180
+ /** The body size a client declared, or undefined when it declared none (chunked
181
+ * transfer, or a junk `Content-Length` — both are settled while reading). */
182
+ export function declaredBodyBytes(headers) {
183
+ const raw = headers['content-length'];
184
+ const first = Array.isArray(raw) ? raw[0] : raw;
185
+ if (typeof first !== 'string')
186
+ return undefined;
187
+ const n = Number(first.trim());
188
+ return Number.isSafeInteger(n) && n >= 0 ? n : undefined;
189
+ }
190
+ export function settleContinuationExpectation(req, res, resolveRoute) {
191
+ // A response already in flight (or a request that never set the expectation) is
192
+ // not ours to settle; write the continue only if the reply is still open.
193
+ if (!expects100Continue(req.headers) || res.writableEnded || res.headersSent) {
194
+ if (!res.writableEnded && !res.headersSent)
195
+ res.writeContinue();
196
+ return false;
197
+ }
198
+ const target = req.url || '';
199
+ const route = resolveRoute(target);
200
+ if (!route) {
201
+ res.writeContinue();
202
+ return false;
203
+ }
204
+ // Format first, then size: both are settled by the headers, and the order matches
205
+ // the post-body gate, so a client gets the same code whether or not it used the
206
+ // expectation.
207
+ const declared = declaredBodyBytes(req.headers);
208
+ const err = preflightBodyAdmission(req.headers, route.capBytes) ??
209
+ (declared !== undefined && declared > route.capBytes ? payloadTooLarge(route.capBytes) : undefined);
210
+ if (!err) {
211
+ res.writeContinue();
212
+ return false;
213
+ }
214
+ logBodyRejection({
215
+ leg: route.leg ?? 'native',
216
+ path: target,
217
+ err,
218
+ capBytes: route.capBytes,
219
+ receivedBytes: 0,
220
+ encoding: requestContentEncoding(req.headers),
221
+ }, route.log);
222
+ try {
223
+ const body = JSON.stringify(route.errorBody(err));
224
+ res.writeHead(err.statusCode, {
225
+ 'content-type': 'application/json; charset=utf-8',
226
+ 'content-length': String(Buffer.byteLength(body)),
227
+ connection: 'close',
228
+ ...(err.headers ?? {}),
229
+ });
230
+ res.end(body);
231
+ }
232
+ catch {
233
+ // Dead peer: the client saved the upload either way. Never let a continuation
234
+ // guard throw into the server's event loop (R-3: log, do not swallow silently).
235
+ logWriteFailure(err);
236
+ try {
237
+ res.destroy();
238
+ }
239
+ catch { }
240
+ }
241
+ try {
242
+ route.refuse?.();
243
+ }
244
+ catch { }
245
+ return true;
246
+ }
247
+ function logWriteFailure(err) {
248
+ console.error('[body-admission] continuation rejection write failed', err);
249
+ }
250
+ /** The encoding token of a request, normalised (`GZIP ` -> `gzip`). Missing,
251
+ * empty or `identity` all mean "no transformation" and return undefined. */
252
+ export function requestContentEncoding(headers) {
253
+ const raw = headers['content-encoding'];
254
+ const first = Array.isArray(raw) ? raw[0] : raw;
255
+ if (typeof first !== 'string')
256
+ return undefined;
257
+ const token = first.trim().toLowerCase();
258
+ return token.length > 0 && token !== 'identity' ? token : undefined;
259
+ }
260
+ function unsupportedEncoding(encoding) {
261
+ return new BodyAdmissionError(415, 'unsupported_content_encoding', `Unsupported Content-Encoding '${encoding}'. The gateway decodes: ${[...DECODABLE_ENCODINGS].join(', ')}.`, { 'accept-encoding': ACCEPT_ENCODING_ADVERTISEMENT });
262
+ }
263
+ /**
264
+ * Media types whose body this gateway reads as JSON. `application/json` (and any
265
+ * `+json` structured type) is the rule and `text/plain` is tolerated, because real
266
+ * agents do mis-declare and the body is unambiguous once you look at it.
267
+ *
268
+ * Anything else — form-urlencoded (what bare `curl -d` sends), multipart, XML, a
269
+ * binary type — and a MISSING header are refused with 415 on BOTH legs, before the
270
+ * body is buffered. Two reasons: an inference gateway has no business accepting a
271
+ * 30 MB upload it will never parse, and the native leg cannot be lenient here (that
272
+ * is Fastify's own content-type gate, which answers 415 for an undeclared type), so
273
+ * the stricter rule is the one that keeps the legs identical — the asymmetry is the
274
+ * bug family this whole pass is about. The refusal names the fix, so a hand-rolled
275
+ * request learns `Content-Type: application/json` instead of a mystery 400.
276
+ */
277
+ const JSON_MEDIA_TYPE = /^application\/([\w.+-]+\+)?json\b/i;
278
+ const TOLERATED_MEDIA_TYPE = /^text\/plain\b/i;
279
+ export function requestMediaType(headers) {
280
+ const raw = headers['content-type'];
281
+ const first = Array.isArray(raw) ? raw[0] : raw;
282
+ if (typeof first !== 'string')
283
+ return undefined;
284
+ const token = first.trim();
285
+ return token.length > 0 ? token : undefined;
286
+ }
287
+ function unsupportedMediaType(received) {
288
+ return new BodyAdmissionError(415, 'unsupported_media_type', received
289
+ ? `Unsupported Media Type '${received}'. The gateway reads a JSON request body (Content-Type: ${ACCEPT_MEDIA_ADVERTISEMENT}).`
290
+ : `Missing Content-Type. The gateway reads a JSON request body (Content-Type: ${ACCEPT_MEDIA_ADVERTISEMENT}).`, { accept: ACCEPT_MEDIA_ADVERTISEMENT });
291
+ }
292
+ /** True when this request's declared media type is one whose body we will parse.
293
+ * An absent header is NOT acceptable — it is the one case where leniency on one
294
+ * leg and a framework gate on the other would disagree silently. */
295
+ export function mediaTypeAcceptable(headers) {
296
+ const ct = requestMediaType(headers);
297
+ if (ct === undefined)
298
+ return false;
299
+ return JSON_MEDIA_TYPE.test(ct) || TOLERATED_MEDIA_TYPE.test(ct);
300
+ }
301
+ /**
302
+ * The MITM leg's media-type gate, thrown (not replied) so answering and logging
303
+ * stay on the single admission path in `model-gateway.ts`. Called BEFORE the body
304
+ * is read, which is the point: reject the type, not the size.
305
+ */
306
+ export function assertJsonMediaType(headers) {
307
+ if (!mediaTypeAcceptable(headers))
308
+ throw unsupportedMediaType(requestMediaType(headers));
309
+ }
310
+ /**
311
+ * Decide from the HEADERS alone whether this request could ever be admitted:
312
+ * framing first (an ambiguous `Content-Length` is not a message we may forward,
313
+ * RFC 9112 6.3), then media type (cheap, and independent of size), then the
314
+ * content coding, by asking the same decoder table `decompressBody` uses against
315
+ * an empty buffer -- an undecodable coding throws there and here, with the same
316
+ * 415, so the two checks cannot disagree about which codings exist. Also the
317
+ * header-only half of `settleContinuationExpectation`, which is why it returns
318
+ * the error instead of throwing it.
319
+ *
320
+ * Returns the rejection, or undefined when the request may proceed. The MITM legs
321
+ * call it BEFORE the body is drained, so a request we intend to refuse never pays
322
+ * for its own upload (the counterpart of the `Expect: 100-continue` guard, which
323
+ * cannot help a chunked body or a client that ignores the expectation).
324
+ */
325
+ export function preflightBodyAdmission(headers, capBytes = bodyLimitFor('gateway')) {
326
+ // FRAMING FIRST (RFC 9112 6.3): when `Content-Length` cannot be determined
327
+ // unambiguously the message must be rejected, never processed and never
328
+ // forwarded. Node's parser refuses a duplicated CL on its own, but BUN ACCEPTS
329
+ // two identical values and hands the application an ARRAY -- so without this
330
+ // check the gateway would relay the duplicate framing upstream and become the
331
+ // smuggle carrier. A non-numeric value is the same defect (no route to the
332
+ // framework's length error on either runtime).
333
+ const declaredLength = headers['content-length'];
334
+ if (declaredLength !== undefined && (Array.isArray(declaredLength) || !/^\d+$/.test(declaredLength))) {
335
+ return invalidContentLength();
336
+ }
337
+ try {
338
+ assertJsonMediaType(headers);
339
+ if (requestContentEncoding(headers))
340
+ decompressBody(Buffer.alloc(0), headers, capBytes);
341
+ return undefined;
342
+ }
343
+ catch (err) {
344
+ return isBodyAdmissionError(err) ? err : undefined;
345
+ }
346
+ }
347
+ /** A `Content-Length` the server could not frame: duplicated values, a non-numeric
348
+ * value, or bytes that do not match the declaration. 400 because the framing, not
349
+ * the payload, is broken (RFC 9110 8.6 makes a message with conflicting
350
+ * Content-Length values an error, not something to guess at). The declared numbers
351
+ * are deliberately NOT echoed: a mismatch gives the client nothing to fix beyond
352
+ * "reframe the request", and repeating a caller-chosen length into a response and a
353
+ * log line is free noise. */
354
+ export function invalidContentLength() {
355
+ return new BodyAdmissionError(400, 'invalid_content_length', 'The request declares an invalid or duplicated Content-Length. Send exactly one Content-Length, or use a chunked body.');
356
+ }
357
+ /**
358
+ * Normalize what Fastify handed the handler.
359
+ *
360
+ * A `text/plain` (or any tolerated-but-not-json) declaration makes Fastify's own
361
+ * parser deliver a raw STRING, and passing that to the pipeline produced the
362
+ * misleading `"messages" array is required` 400 for a perfectly valid body. Parse
363
+ * it here so the native leg agrees with the MITM leg, and reject a top-level
364
+ * non-object the same way the MITM leg does.
365
+ */
366
+ export function normalizeNativeBody(body) {
367
+ const parsed = typeof body === 'string' ? parseJsonBody(body) : body;
368
+ if (!parsed || typeof parsed !== 'object')
369
+ throw invalidJsonBody();
370
+ return parsed;
371
+ }
372
+ /**
373
+ * Streaming decoder for the native leg, returned from a Fastify `preParsing`
374
+ * hook. Returning a stream (instead of buffering) keeps the request on Fastify's
375
+ * normal parse path.
376
+ *
377
+ * The limit is deliberately NOT passed here: Fastify measures the stream this
378
+ * hook returns and enforces `bodyLimit` against its OUTPUT length, so an
379
+ * inflated bomb is refused at the same ceiling as a plain body.
380
+ *
381
+ * `receivedEncodedLength` is defined as a live getter over the COMPRESSED bytes:
382
+ * Fastify compares it against the `Content-Length` header and reads it after each
383
+ * chunk, so a static 0 makes the request fail as a length mismatch.
384
+ */
385
+ export function createBodyDecompressor(headers, payload) {
386
+ const encoding = requestContentEncoding(headers);
387
+ if (!encoding)
388
+ return payload;
389
+ if (!DECODABLE_ENCODINGS.has(encoding))
390
+ throw unsupportedEncoding(encoding);
391
+ const decoder = encoding === 'br'
392
+ ? createBrotliDecompress()
393
+ : encoding === 'gzip' || encoding === 'x-gzip'
394
+ ? createGunzip()
395
+ : createInflate();
396
+ let compressed = 0;
397
+ payload.on('data', (chunk) => {
398
+ compressed += typeof chunk === 'string' ? Buffer.byteLength(chunk) : chunk.length;
399
+ });
400
+ Object.defineProperty(decoder, 'receivedEncodedLength', {
401
+ configurable: true,
402
+ get: () => compressed,
403
+ });
404
+ // `.pipe` alone would swallow a source error (a truncated or corrupt gzip
405
+ // stream) and leave Fastify waiting on a decoder that never ends, so the
406
+ // source error is forwarded as a destroy: the request then fails as a 400
407
+ // instead of hanging until socket timeout.
408
+ payload.pipe(decoder);
409
+ payload.on('error', (err) => {
410
+ if (!decoder.destroyed)
411
+ decoder.destroy(err);
412
+ });
413
+ return decoder;
414
+ }
415
+ /** Buffer decoder for the MITM leg, which already holds the whole body.
416
+ * `maxOutputLength` is the bomb guard: zlib aborts with ERR_BUFFER_TOO_LARGE
417
+ * rather than inflating past the cap, and that is reported as the SAME 413 the
418
+ * native leg produces. */
419
+ export function decompressBody(raw, headers, capBytes = bodyLimitFor('gateway')) {
420
+ const encoding = requestContentEncoding(headers);
421
+ if (!encoding)
422
+ return raw;
423
+ if (!DECODABLE_ENCODINGS.has(encoding))
424
+ throw unsupportedEncoding(encoding);
425
+ const opts = { maxOutputLength: capBytes };
426
+ try {
427
+ switch (encoding) {
428
+ case 'br':
429
+ return brotliDecompressSync(raw, opts);
430
+ case 'gzip':
431
+ case 'x-gzip':
432
+ return gunzipSync(raw, opts);
433
+ default:
434
+ // HTTP `deflate` is the zlib format (RFC 1950). Raw deflate (RFC 1951)
435
+ // has no valid zlib header but is sent in the wild, so sniff instead of
436
+ // rejecting: a 400 for a body we can actually read would be a lie.
437
+ return looksLikeZlibStream(raw) ? inflateSync(raw, opts) : inflateRawSync(raw, opts);
438
+ }
439
+ }
440
+ catch (err) {
441
+ const code = err.code;
442
+ if (code === 'ERR_BUFFER_TOO_LARGE')
443
+ throw payloadTooLarge(capBytes);
444
+ throw invalidJsonBody(); // undecodable bytes: the body itself is broken
445
+ }
446
+ }
447
+ /** zlib stream header check (RFC 1950): CM must be 8 and (CMF<<8|FLG) % 31 === 0. */
448
+ function looksLikeZlibStream(buf) {
449
+ return buf.length >= 2 && buf[0] === 0x78 && (((buf[0] << 8) | buf[1]) % 31 === 0);
450
+ }
451
+ /** Parse an admitted JSON body, rejecting with the shared 400 rather than a raw
452
+ * SyntaxError whose message leaks byte offsets to the client. */
453
+ export function parseJsonBody(body) {
454
+ const text = typeof body === 'string' ? body : body.toString('utf8');
455
+ try {
456
+ return JSON.parse(text);
457
+ }
458
+ catch {
459
+ throw invalidJsonBody();
460
+ }
461
+ }
462
+ /**
463
+ * One operator-facing line per admission rejection. Without it a 413/415 is
464
+ * invisible: capture records nothing on this path (ADR-0008 — 400/413 precede
465
+ * processing) and Fastify request logging is disabled, so an operator debugging
466
+ * "my agent fails on long sessions" has no server-side evidence at all.
467
+ * `log` is the request logger when available; the fallback keeps the line in the
468
+ * process log for the legs that have no pino child.
469
+ */
470
+ export function logBodyRejection(info, log) {
471
+ const record = {
472
+ type: 'body_rejected',
473
+ leg: info.leg,
474
+ path: info.path,
475
+ status: info.err.statusCode,
476
+ code: info.err.code,
477
+ capBytes: info.capBytes,
478
+ receivedBytes: info.receivedBytes,
479
+ contentEncoding: info.encoding ?? 'identity',
480
+ };
481
+ if (log)
482
+ log.warn(record, `body rejected (${info.err.code}) on ${info.leg} leg ${info.path}`);
483
+ else
484
+ console.warn(`[body-admission] body rejected (${info.err.code}) on ${info.leg} leg ${info.path}`, record);
485
+ }
486
+ /** Narrowing helper for the answering layers on both legs. */
487
+ export function isBodyAdmissionError(err) {
488
+ return err instanceof BodyAdmissionError;
489
+ }
490
+ /** How long a refusal may wait for the sender to finish before it is delivered
491
+ * anyway. Generous on purpose: this is bandwidth on ONE refused request, and the
492
+ * alternative is an answer the client never sees. */
493
+ const REFUSAL_DRAIN_BEFORE_ANSWER_MS = 2000;
494
+ /** The idle window a refusal waits for the NEXT chunk before it gives up on the
495
+ * sender. Re-armed per chunk, so a continuous upload is read to its end while a
496
+ * client that stopped (or never started) is answered promptly — a client with
497
+ * `Expect: 100-continue` declares a length and then waits for US. */
498
+ const REFUSAL_DRAIN_IDLE_MS = 250;
499
+ /** How long a refusal already on the wire keeps reading (the raw leg, where the
500
+ * answer is flushed first and only the close is deferred). */
501
+ const REFUSAL_DRAIN_AFTER_ANSWER_MS = 2000;
502
+ /**
503
+ * A refusal is an ANSWER, not a reset — the module's own rule (RFC 9110
504
+ * 15.5.14), and sending only half of it is worse than a bare reset, because the
505
+ * client cannot tell which one it got.
506
+ *
507
+ * The failure this exists for: a client is still uploading when the cap is
508
+ * crossed. The 413 is written, the socket is closed while unread inbound bytes
509
+ * remain, and the OS turns that `close()` into RST — the client's pending write
510
+ * fails, so it never reads the status, the code, or the limit that was named.
511
+ * (Reproduced on the admin plane: the same 8 MiB upload answered 413 four times
512
+ * running and then threw `ECONNRESET` three times, with no code change.)
513
+ *
514
+ * So the body we just refused is read and discarded first, bounded in BYTES and
515
+ * TIME: past either bound the drain STOPS READING but never destroys the request
516
+ * — destroying it before the answer is written makes Bun answer a bare `200 OK`
517
+ * (see `writeRefusalAnswer`), and a refusal that says "OK" is worse than a reset.
518
+ * Nothing here admits the request — the refusal is already decided; this only
519
+ * decides whether the client can hear it.
520
+ */
521
+ function startRefusalDrain(req, opts) {
522
+ const { maxBytes, maxMs } = opts;
523
+ if (!req || req.destroyed || req.readableEnded || req.complete) {
524
+ return { started: false, done: Promise.resolve() };
525
+ }
526
+ let read = 0;
527
+ const done = new Promise((resolve) => {
528
+ const stop = () => {
529
+ clearTimeout(timer);
530
+ clearTimeout(idle);
531
+ req.removeListener('data', onData);
532
+ req.removeListener('end', onEnd);
533
+ req.removeListener('close', onClose);
534
+ req.removeListener('error', onClose);
535
+ // Never destroy: the caller still has an answer to write on this socket.
536
+ resolve();
537
+ };
538
+ const onData = (chunk) => {
539
+ // Bytes are flowing: this client really is mid-upload, so finish reading
540
+ // its body (bounded) — that is what keeps the refusal readable. The idle
541
+ // timer is re-armed on every chunk, so a client that STOPS is answered
542
+ // within one idle window instead of waiting out the whole budget.
543
+ clearTimeout(idle);
544
+ idle = setTimeout(() => stop(), REFUSAL_DRAIN_IDLE_MS);
545
+ idle.unref?.();
546
+ read += typeof chunk === 'string' ? Buffer.byteLength(chunk) : chunk.length;
547
+ if (read >= maxBytes)
548
+ stop();
549
+ };
550
+ const onEnd = () => stop();
551
+ const onClose = () => stop();
552
+ const timer = setTimeout(() => stop(), maxMs);
553
+ let idle = setTimeout(() => stop(), REFUSAL_DRAIN_IDLE_MS);
554
+ // Never hold the process open for a client that stopped talking.
555
+ timer.unref?.();
556
+ idle.unref?.();
557
+ req.on('data', onData);
558
+ req.once('end', onEnd);
559
+ req.once('close', onClose);
560
+ req.once('error', onClose);
561
+ req.resume();
562
+ });
563
+ return { started: true, done };
564
+ }
565
+ /**
566
+ * Read what the client still has in flight BEFORE writing the answer, so the
567
+ * refusal lands in a readable state on a socket the framework will close as soon
568
+ * as the reply finishes. Used by the Fastify (native) legs and the pre-dispatch
569
+ * gate — every place that still has to WRITE an answer.
570
+ *
571
+ * The budget is TWICE the plane's cap: a body just over the limit (the common
572
+ * case, and the one a client can actually fix by reading the answer) is consumed
573
+ * in full, so the sender finishes its write and the answer is read cleanly. A
574
+ * sender far over the limit is cut there — a server is not obliged to download an
575
+ * upload it already refused (RFC 9110 15.5.14), and `Expect: 100-continue`, which
576
+ * this gateway honours, is how a client learns the limit before sending.
577
+ *
578
+ * The drain NEVER destroys the request: expiry only stops reading, so the caller
579
+ * can still write its 413. (Destruction-before-answer is what produced a bare
580
+ * `200 OK` on Bun.)
581
+ */
582
+ export async function settleRefusedBody(req, capBytes = bodyLimitFor('gateway')) {
583
+ const { done } = startRefusalDrain(req, {
584
+ maxBytes: Math.max(capBytes * 2, 1024 * 1024),
585
+ maxMs: REFUSAL_DRAIN_BEFORE_ANSWER_MS,
586
+ });
587
+ await done;
588
+ }
589
+ /**
590
+ * Same idea AFTER the answer was already flushed (every refusal path). Returns
591
+ * whether the drain took over the request; when it did not, the caller closes the
592
+ * transport itself. `whenDone` runs once the client finished (or the budget
593
+ * expired), so the close still happens exactly once.
594
+ *
595
+ * The byte budget is the PLANE'S cap doubled, not a fixed number: a body just
596
+ * over the limit is the normal case, and cutting the drain short mid-write makes
597
+ * the client see a reset instead of the answer we already wrote. Measured on the
598
+ * admin plane: an 8 MiB upload reset ~20% of the time while the budget was a flat
599
+ * 4 MiB, and stopped resetting once the drain covered the whole body.
600
+ */
601
+ export function drainRefusedBody(req, whenDone, capBytes = bodyLimitFor('gateway')) {
602
+ const { started, done } = startRefusalDrain(req, {
603
+ maxBytes: Math.max(capBytes * 2, 1024 * 1024),
604
+ maxMs: REFUSAL_DRAIN_AFTER_ANSWER_MS,
605
+ });
606
+ if (!started)
607
+ return false;
608
+ void done.then(() => whenDone?.());
609
+ return true;
610
+ }
611
+ /**
612
+ * Write ONE refusal, then deal with the socket. WHICH order is used depends on
613
+ * the leg, and both orders exist for the same reason — the answer must reach a
614
+ * client that is still uploading:
615
+ *
616
+ * - the RAW leg calls this writer only (answer first, then drain). Answering
617
+ * before reading is what lets a client that ignores the limit still see the
618
+ * 413; the bounded drain only prevents the OS from turning the close into a
619
+ * reset the client never reads past.
620
+ * - the FASTIFY legs drain first (`settleRefusedBody`) and then call this with
621
+ * `drainBody: false`: the framework closes the socket with the reply, so an
622
+ * answer written while the sender is still writing is the reset, and a drain
623
+ * that ran AFTER the answer would only add a second budget on a socket that
624
+ * is already being torn down.
625
+ *
626
+ * Neither path may `destroy()` the request: destroying it before the answer
627
+ * makes Bun reply with a bare `200 OK` and an empty body — a refusal that tells
628
+ * the client the request SUCCEEDED (measured: `+3006 ms`, `HTTP/1.1 200 OK`).
629
+ *
630
+ * `content-length` is declared because Bun 1.4.x otherwise frames the answer as
631
+ * chunked, so a raw-socket client reads hex chunk-size lines instead of JSON.
632
+ * `connection: close` rides only on h1: HTTP/2 forbids connection-specific
633
+ * fields, and on h2 the response completes normally while flow control stops a
634
+ * client that keeps uploading (nothing is buffered).
635
+ */
636
+ export function writeRefusalAnswer(res, status, serialized, opts = {}) {
637
+ const isH2 = res.stream !== undefined;
638
+ res.writeHead(status, {
639
+ 'content-type': 'application/json; charset=utf-8',
640
+ 'content-length': String(Buffer.byteLength(serialized)),
641
+ ...(isH2 ? {} : { connection: 'close' }),
642
+ ...(opts.headers ?? {}),
643
+ });
644
+ res.end(serialized);
645
+ if (isH2) {
646
+ // A refused request body cannot be drained here without reading it, and
647
+ // resetting the stream AFTER the response was delivered risks the client
648
+ // discarding an answer we promised it. Neither is needed: HTTP/2 flow
649
+ // control bounds the damage — measured on Node 24 and Bun 1.4.5, a client
650
+ // that keeps uploading after the 413 manages exactly one window (64 KiB)
651
+ // and then stalls, with the response delivered and RSS flat. (The h2
652
+ // compatibility response has no `destroySoon`; an earlier revision called
653
+ // one through an optional chain, which silently did nothing on every
654
+ // runtime — hence this explicit note.)
655
+ return;
656
+ }
657
+ // h1: the connection is not reusable either way, so close it — after the body
658
+ // we just refused has been read (bounded), so the sender finishes its write
659
+ // and sees the answer. `destroySoon` lives on the SOCKET, not on the response
660
+ // (verified on Node 24 and Bun 1.4.5: `res.destroySoon` is undefined, so
661
+ // calling it through an optional chain was a no-op that left the close to the
662
+ // `connection: close` header alone).
663
+ const close = () => {
664
+ const socket = res.socket;
665
+ if (socket?.destroySoon) {
666
+ socket.destroySoon();
667
+ return;
668
+ }
669
+ try {
670
+ res.destroy?.();
671
+ }
672
+ catch {
673
+ // The header still closes it on the runtime's own schedule.
674
+ }
675
+ };
676
+ if (opts.drainBody === false) {
677
+ close();
678
+ return;
679
+ }
680
+ const draining = drainRefusedBody(res.req, close, opts.capBytes);
681
+ if (!draining)
682
+ close();
683
+ }
684
+ /**
685
+ * Fastify codes for the failures the content parser raises BEFORE a handler runs.
686
+ * They must be answered here because at that point no transport and no capture
687
+ * event exists (ADR-0008: 400/413 precede process), so the only thing left to
688
+ * shape the response with is the surface's error envelope.
689
+ */
690
+ const FRAMEWORK_BODY_CODES = new Set(['FST_ERR_CTP_BODY_TOO_LARGE']);
691
+ const FRAMEWORK_JSON_CODES = new Set(['FST_ERR_CTP_INVALID_JSON_BODY', 'FST_ERR_CTP_EMPTY_JSON_BODY']);
692
+ // Two producers, one meaning: Fastify's content-type gate on the native leg, and
693
+ // Node's own media-type abort on the raw/MITM leg (node/lib/_http_server.js).
694
+ const FRAMEWORK_MEDIA_CODES = new Set(['FST_ERR_CTP_INVALID_MEDIA_TYPE', 'ERR_HTTP_INVALID_MEDIA_TYPE']);
695
+ // Framing errors on the raw legs: the LLM client cannot act on "your lengths
696
+ // disagree", but it can reframe -- and silence (Node aborts with no response) is
697
+ // worse than a 400 that says so.
698
+ const FRAMEWORK_LENGTH_CODES = new Set([
699
+ 'ERR_REQUEST_CONTENT_LENGTH_COUNT',
700
+ 'ERR_REQUEST_CONTENT_LENGTH_INVALID',
701
+ 'ERR_REQUEST_CONTENT_LENGTH_INVALID_CHAR',
702
+ 'ERR_REQUEST_CONTENT_LENGTH_MISMATCH',
703
+ ]);
704
+ /**
705
+ * Route options that give the NATIVE leg the same admission policy the MITM leg
706
+ * applies by hand: decode `Content-Encoding` on the way in, cap the DECOMPRESSED
707
+ * body at the configured inference cap (`bodyLimitFor('gateway')`), and answer every
708
+ * rejection in the surface's own envelope with a machine-readable `code`.
709
+ *
710
+ * `preParsing` is registered per route rather than app-wide on purpose — an
711
+ * app-wide hook would also decompress admin/upload bodies it knows nothing about.
712
+ */
713
+ export function surfaceBodyAdmissionOptions(surface) {
714
+ const capBytes = bodyLimitFor('gateway');
715
+ return {
716
+ bodyLimit: capBytes,
717
+ preParsing(request, _reply, payload, done) {
718
+ try {
719
+ done(null, createBodyDecompressor(request.headers, payload));
720
+ }
721
+ catch (err) {
722
+ // A 415 for an encoding we cannot decode. Passing it to `done` (rather
723
+ // than replying from the hook) keeps ONE answering path for every
724
+ // rejection and leaves Fastify to drain/close the socket.
725
+ done(err);
726
+ }
727
+ },
728
+ async errorHandler(err, request, reply) {
729
+ // One translation call covers the framework's own refusals, including
730
+ // FST_ERR_CTP_INVALID_MEDIA_TYPE: Fastify answers that with its own
731
+ // string-`error` envelope, which Anthropic-style clients cannot parse, so it
732
+ // is re-answered here naming the type that was actually received.
733
+ const admission = isBodyAdmissionError(err)
734
+ ? err
735
+ : frameworkBodyError(err, capBytes, requestMediaType(request.headers));
736
+ if (!admission)
737
+ throw err; // not ours: delegate to the parent handler
738
+ logBodyRejection({
739
+ leg: 'native',
740
+ path: request.url,
741
+ err: admission,
742
+ capBytes,
743
+ encoding: requestContentEncoding(request.headers),
744
+ }, request.log);
745
+ // Read the refused body FIRST (bounded, never destroying the request),
746
+ // then answer: Fastify closes the socket with this reply, so an answer
747
+ // written while the sender is still uploading is the reset it never reads.
748
+ // The drain stops at 2× this plane's cap or the time budget — a server is
749
+ // not obliged to download an upload it already refused — and never
750
+ // destroys, which is what keeps the 413 below on the wire (destroying it
751
+ // first made Bun answer a bare `200 OK`).
752
+ await settleRefusedBody(request.raw, capBytes);
753
+ reply.hijack();
754
+ writeRefusalAnswer(reply.raw, admission.statusCode, JSON.stringify(surface.errorBody(admission.statusCode, admission.message, admission.code)),
755
+ // `drainBody: false` — the body was settled above; a second drain would
756
+ // spend another budget on a socket Fastify is already closing.
757
+ { headers: admission.headers, capBytes, drainBody: false });
758
+ return reply;
759
+ },
760
+ };
761
+ }
762
+ /**
763
+ * App-level `errorHandler` for the ADMIN plane (everything that is not a
764
+ * protocol surface). The console reads failures as `{ success: false, message }`;
765
+ * Fastify's default shape is `{ statusCode, code, error, message }` whose
766
+ * `error` is a reason phrase, which the UI renders as the bare
767
+ * `Error: 413 "Payload Too Large"` this whole module exists to kill.
768
+ *
769
+ * Non-admission errors are RE-THROWN, which hands them to Fastify's default
770
+ * handler (fastify/docs/Reference/Errors.md) — this handler must not become a
771
+ * second, worse error serializer for validation and 5xx paths it knows nothing
772
+ * about, and it never echoes a stack or an upstream body.
773
+ */
774
+ export async function adminBodyErrorHandler(err, request, reply) {
775
+ const capBytes = bodyLimitFor('admin');
776
+ const admission = isBodyAdmissionError(err)
777
+ ? err
778
+ : frameworkBodyError(err, capBytes, requestMediaType(request.headers));
779
+ if (!admission)
780
+ throw err;
781
+ logBodyRejection({
782
+ leg: 'native',
783
+ path: request.url,
784
+ err: admission,
785
+ capBytes,
786
+ encoding: requestContentEncoding(request.headers),
787
+ }, request.log);
788
+ // Same order as the inference planes, with THIS plane's cap: drain the
789
+ // refused body first (never destroying the request), then write the admin
790
+ // envelope. The cap matters — the post-answer drain used to default to the
791
+ // inference cap (32 MiB) on a plane whose own limit is 8 MiB.
792
+ await settleRefusedBody(request.raw, capBytes);
793
+ reply.hijack();
794
+ writeRefusalAnswer(reply.raw, admission.statusCode, JSON.stringify({ success: false, message: admission.message }), { headers: admission.headers, capBytes, drainBody: false });
795
+ return reply;
796
+ }
797
+ /** Translate a framework content-parser failure into this module's error type, so
798
+ * one message builder and one `code` cover both producers. Returns undefined for
799
+ * errors that belong to somebody else. */
800
+ function frameworkBodyError(err, capBytes, receivedMediaType) {
801
+ if (FRAMEWORK_BODY_CODES.has(err.code ?? ''))
802
+ return payloadTooLarge(capBytes);
803
+ if (FRAMEWORK_JSON_CODES.has(err.code ?? ''))
804
+ return invalidJsonBody();
805
+ // A refused media type from the framework does not name what was SENT (our own
806
+ // gate does, via unsupportedMediaType(received)), so this variant says what the
807
+ // server accepts instead; the `Accept` header carries the same answer.
808
+ if (FRAMEWORK_MEDIA_CODES.has(err.code ?? ''))
809
+ return unsupportedMediaType(receivedMediaType);
810
+ if (FRAMEWORK_LENGTH_CODES.has(err.code ?? ''))
811
+ return invalidContentLength();
812
+ // A body that ENDS SHORT of its declared length is deliberately NOT mapped: Node
813
+ // (and Bun) abort the request and no response is written at all -- there is
814
+ // nothing here to shape (verified on both runtimes). The reachable truncation case
815
+ // is the reverse, a declared length SHORTER than the bytes sent: the parser sees a
816
+ // truncated JSON document and answers `invalid_json_body` above.
817
+ return undefined;
818
+ }