omnicell-router 0.8.4 → 0.10.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (363) hide show
  1. package/README.md +26 -7
  2. package/README.zh-CN.md +18 -5
  3. package/backend/dist/capture/recorder.d.ts +4 -10
  4. package/backend/dist/capture/recorder.js +6 -58
  5. package/backend/dist/cli/clients/base.d.ts +36 -11
  6. package/backend/dist/cli/clients/base.js +31 -15
  7. package/backend/dist/cli/clients/claude.d.ts +9 -0
  8. package/backend/dist/cli/clients/claude.js +6 -0
  9. package/backend/dist/cli/clients/codex.d.ts +8 -0
  10. package/backend/dist/cli/clients/codex.js +5 -0
  11. package/backend/dist/cli/clients/core-adapters.d.ts +1 -1
  12. package/backend/dist/cli/clients/core-adapters.js +1 -1
  13. package/backend/dist/cli/clients/dsh.d.ts +8 -0
  14. package/backend/dist/cli/clients/dsh.js +5 -0
  15. package/backend/dist/cli/clients/grok.d.ts +15 -1
  16. package/backend/dist/cli/clients/grok.js +16 -2
  17. package/backend/dist/cli/clients/index.d.ts +13 -1
  18. package/backend/dist/cli/clients/index.js +97 -19
  19. package/backend/dist/cli/clients/kimi.d.ts +6 -0
  20. package/backend/dist/cli/clients/kimi.js +3 -0
  21. package/backend/dist/cli/clients/launcher.d.ts +1 -1
  22. package/backend/dist/cli/clients/model-meta.js +6 -3
  23. package/backend/dist/cli/clients/omp.d.ts +6 -0
  24. package/backend/dist/cli/clients/omp.js +3 -0
  25. package/backend/dist/cli/clients/openclaw.d.ts +6 -0
  26. package/backend/dist/cli/clients/openclaw.js +3 -0
  27. package/backend/dist/cli/clients/opencode.d.ts +8 -0
  28. package/backend/dist/cli/clients/opencode.js +5 -0
  29. package/backend/dist/cli/clients/pi.d.ts +6 -0
  30. package/backend/dist/cli/clients/pi.js +3 -0
  31. package/backend/dist/cli/clients/update-check.d.ts +37 -0
  32. package/backend/dist/cli/clients/update-check.js +309 -0
  33. package/backend/dist/cli/clients/workbuddy.d.ts +19 -0
  34. package/backend/dist/cli/clients/workbuddy.js +66 -0
  35. package/backend/dist/cli/index.js +5 -4
  36. package/backend/dist/cli/paths.js +8 -0
  37. package/backend/dist/cli/types.d.ts +92 -16
  38. package/backend/dist/config/comments-en.js +31 -26
  39. package/backend/dist/config/comments-zh.js +29 -24
  40. package/backend/dist/config/defaults.d.ts +194 -33
  41. package/backend/dist/config/defaults.js +193 -32
  42. package/backend/dist/config/env.d.ts +10 -0
  43. package/backend/dist/config/env.js +3 -2
  44. package/backend/dist/config/index.d.ts +7 -0
  45. package/backend/dist/config/index.js +184 -43
  46. package/backend/dist/config/migrations/v0-to-v1.d.ts +2 -2
  47. package/backend/dist/config/migrations/v10-to-v11.d.ts +38 -0
  48. package/backend/dist/config/migrations/v10-to-v11.js +43 -0
  49. package/backend/dist/config/migrations/v6-to-v7.d.ts +45 -0
  50. package/backend/dist/config/migrations/v6-to-v7.js +97 -0
  51. package/backend/dist/config/migrations/v7-to-v8.d.ts +36 -0
  52. package/backend/dist/config/migrations/v7-to-v8.js +43 -0
  53. package/backend/dist/config/migrations/v8-to-v9.d.ts +38 -0
  54. package/backend/dist/config/migrations/v8-to-v9.js +43 -0
  55. package/backend/dist/config/migrations/v9-to-v10.d.ts +51 -0
  56. package/backend/dist/config/migrations/v9-to-v10.js +71 -0
  57. package/backend/dist/config/runtime.js +1 -1
  58. package/backend/dist/config/schema.d.ts +3 -3
  59. package/backend/dist/config/schema.js +14 -4
  60. package/backend/dist/config/types.d.ts +167 -38
  61. package/backend/dist/egress-proxy/asset-download.d.ts +54 -0
  62. package/backend/dist/egress-proxy/asset-download.js +420 -0
  63. package/backend/dist/egress-proxy/manual-node-spec.d.ts +92 -0
  64. package/backend/dist/egress-proxy/manual-node-spec.js +408 -0
  65. package/backend/dist/egress-proxy/mihomo-binary.d.ts +54 -0
  66. package/backend/dist/egress-proxy/mihomo-binary.js +278 -0
  67. package/backend/dist/egress-proxy/mihomo-client.d.ts +94 -0
  68. package/backend/dist/egress-proxy/mihomo-client.js +308 -0
  69. package/backend/dist/egress-proxy/mihomo-config.d.ts +40 -0
  70. package/backend/dist/egress-proxy/mihomo-config.js +161 -0
  71. package/backend/dist/egress-proxy/mihomo-geo.d.ts +87 -0
  72. package/backend/dist/egress-proxy/mihomo-geo.js +213 -0
  73. package/backend/dist/egress-proxy/mihomo-logs.d.ts +43 -0
  74. package/backend/dist/egress-proxy/mihomo-logs.js +84 -0
  75. package/backend/dist/egress-proxy/mihomo-pac.d.ts +37 -0
  76. package/backend/dist/egress-proxy/mihomo-pac.js +75 -0
  77. package/backend/dist/egress-proxy/mihomo-rules-import.d.ts +43 -0
  78. package/backend/dist/egress-proxy/mihomo-rules-import.js +193 -0
  79. package/backend/dist/egress-proxy/mihomo-sidecar.d.ts +81 -0
  80. package/backend/dist/egress-proxy/mihomo-sidecar.js +637 -0
  81. package/backend/dist/forward-proxy/egress.d.ts +50 -11
  82. package/backend/dist/forward-proxy/egress.js +50 -17
  83. package/backend/dist/forward-proxy/h2-forward.js +36 -10
  84. package/backend/dist/forward-proxy/index.d.ts +11 -8
  85. package/backend/dist/forward-proxy/index.js +22 -60
  86. package/backend/dist/forward-proxy/interceptor.d.ts +3 -2
  87. package/backend/dist/forward-proxy/interceptor.js +4 -4
  88. package/backend/dist/forward-proxy/relay.js +3 -3
  89. package/backend/dist/forward-proxy/rules.d.ts +4 -4
  90. package/backend/dist/forward-proxy/rules.js +25 -4
  91. package/backend/dist/forward-proxy/server.d.ts +0 -16
  92. package/backend/dist/forward-proxy/server.js +124 -156
  93. package/backend/dist/harness/host/hosts.js +3 -2
  94. package/backend/dist/index.js +53 -18
  95. package/backend/dist/ingress-proxy/access-log.d.ts +176 -0
  96. package/backend/dist/ingress-proxy/access-log.js +774 -0
  97. package/backend/dist/ingress-proxy/ca-inventory.d.ts +106 -0
  98. package/backend/dist/ingress-proxy/ca-inventory.js +525 -0
  99. package/backend/dist/ingress-proxy/ca-trust.d.ts +96 -0
  100. package/backend/dist/ingress-proxy/ca-trust.js +315 -0
  101. package/backend/dist/ingress-proxy/ca.d.ts +104 -0
  102. package/backend/dist/ingress-proxy/ca.js +273 -0
  103. package/backend/dist/ingress-proxy/data-dir.d.ts +28 -0
  104. package/backend/dist/ingress-proxy/data-dir.js +45 -0
  105. package/backend/dist/ingress-proxy/egress.d.ts +151 -0
  106. package/backend/dist/ingress-proxy/egress.js +364 -0
  107. package/backend/dist/ingress-proxy/h2-forward.d.ts +66 -0
  108. package/backend/dist/ingress-proxy/h2-forward.js +561 -0
  109. package/backend/dist/ingress-proxy/index.d.ts +24 -0
  110. package/backend/dist/ingress-proxy/index.js +144 -0
  111. package/backend/dist/ingress-proxy/interceptor.d.ts +25 -0
  112. package/backend/dist/ingress-proxy/interceptor.js +52 -0
  113. package/backend/dist/ingress-proxy/ordered-relay.d.ts +29 -0
  114. package/backend/dist/ingress-proxy/ordered-relay.js +46 -0
  115. package/backend/dist/ingress-proxy/relay.d.ts +54 -0
  116. package/backend/dist/ingress-proxy/relay.js +188 -0
  117. package/backend/dist/ingress-proxy/rules.d.ts +195 -0
  118. package/backend/dist/ingress-proxy/rules.js +348 -0
  119. package/backend/dist/ingress-proxy/server.d.ts +153 -0
  120. package/backend/dist/ingress-proxy/server.js +2065 -0
  121. package/backend/dist/ingress-proxy/sni.d.ts +35 -0
  122. package/backend/dist/ingress-proxy/sni.js +124 -0
  123. package/backend/dist/ingress-proxy/status.d.ts +32 -0
  124. package/backend/dist/ingress-proxy/status.js +15 -0
  125. package/backend/dist/ingress-proxy/system-proxy.d.ts +112 -0
  126. package/backend/dist/ingress-proxy/system-proxy.js +481 -0
  127. package/backend/dist/ingress-proxy/traffic-delete.d.ts +21 -0
  128. package/backend/dist/ingress-proxy/traffic-delete.js +64 -0
  129. package/backend/dist/ingress-proxy/traffic-delete.worker.d.ts +44 -0
  130. package/backend/dist/ingress-proxy/traffic-delete.worker.js +228 -0
  131. package/backend/dist/ingress-proxy/traffic-files.d.ts +10 -0
  132. package/backend/dist/ingress-proxy/traffic-files.js +10 -0
  133. package/backend/dist/ingress-proxy/upstream-tls.d.ts +46 -0
  134. package/backend/dist/ingress-proxy/upstream-tls.js +105 -0
  135. package/backend/dist/ingress-proxy/ws-frames.d.ts +45 -0
  136. package/backend/dist/ingress-proxy/ws-frames.js +153 -0
  137. package/backend/dist/ir/adapters/anthropic-messages-stream.js +6 -1
  138. package/backend/dist/ir/adapters/anthropic-messages.js +12 -5
  139. package/backend/dist/ir/adapters/google-gemini-stream.js +7 -2
  140. package/backend/dist/ir/adapters/google-gemini.js +5 -2
  141. package/backend/dist/ir/adapters/openai-chat-stream.js +5 -1
  142. package/backend/dist/ir/adapters/openai-chat.d.ts +25 -0
  143. package/backend/dist/ir/adapters/openai-chat.js +45 -3
  144. package/backend/dist/ir/adapters/openai-responses-output.d.ts +1 -0
  145. package/backend/dist/ir/adapters/openai-responses-output.js +67 -21
  146. package/backend/dist/ir/adapters/openai-responses-stream.d.ts +13 -0
  147. package/backend/dist/ir/adapters/openai-responses-stream.js +34 -1
  148. package/backend/dist/ir/adapters/openai-responses.d.ts +82 -24
  149. package/backend/dist/ir/adapters/openai-responses.js +146 -37
  150. package/backend/dist/ir/media.d.ts +20 -0
  151. package/backend/dist/ir/media.js +41 -0
  152. package/backend/dist/ir/tool-identity.d.ts +35 -0
  153. package/backend/dist/ir/tool-identity.js +40 -0
  154. package/backend/dist/ir/types.d.ts +9 -1
  155. package/backend/dist/local/build-jobs.d.ts +66 -0
  156. package/backend/dist/local/build-jobs.js +243 -0
  157. package/backend/dist/local/detect.d.ts +32 -0
  158. package/backend/dist/local/detect.js +145 -0
  159. package/backend/dist/local/draft-match.d.ts +58 -0
  160. package/backend/dist/local/draft-match.js +124 -0
  161. package/backend/dist/local/engine-runtime.d.ts +522 -0
  162. package/backend/dist/local/engine-runtime.js +1 -0
  163. package/backend/dist/local/engines.d.ts +241 -0
  164. package/backend/dist/local/engines.js +651 -0
  165. package/backend/dist/local/gguf.d.ts +35 -0
  166. package/backend/dist/local/gguf.js +314 -0
  167. package/backend/dist/local/hf.d.ts +120 -0
  168. package/backend/dist/local/hf.js +304 -0
  169. package/backend/dist/local/install.d.ts +90 -0
  170. package/backend/dist/local/install.js +421 -0
  171. package/backend/dist/local/llamacpp.d.ts +55 -0
  172. package/backend/dist/local/llamacpp.js +177 -0
  173. package/backend/dist/local/local-provider.d.ts +81 -0
  174. package/backend/dist/local/local-provider.js +301 -0
  175. package/backend/dist/local/machine-stats.d.ts +87 -0
  176. package/backend/dist/local/machine-stats.js +332 -0
  177. package/backend/dist/local/model-store.d.ts +347 -0
  178. package/backend/dist/local/model-store.js +1215 -0
  179. package/backend/dist/local/part-sweep.d.ts +32 -0
  180. package/backend/dist/local/part-sweep.js +156 -0
  181. package/backend/dist/local/plan.d.ts +65 -0
  182. package/backend/dist/local/plan.js +146 -0
  183. package/backend/dist/local/resources.d.ts +49 -0
  184. package/backend/dist/local/resources.js +64 -0
  185. package/backend/dist/local/run-stats.d.ts +95 -0
  186. package/backend/dist/local/run-stats.js +195 -0
  187. package/backend/dist/local/runner.d.ts +235 -0
  188. package/backend/dist/local/runner.js +1392 -0
  189. package/backend/dist/local/settings.d.ts +79 -0
  190. package/backend/dist/local/settings.js +180 -0
  191. package/backend/dist/local/strata-catalog.d.ts +30 -0
  192. package/backend/dist/local/strata-catalog.js +511 -0
  193. package/backend/dist/local/strata-drafting.d.ts +46 -0
  194. package/backend/dist/local/strata-drafting.js +265 -0
  195. package/backend/dist/local/strata.d.ts +278 -0
  196. package/backend/dist/local/strata.js +1392 -0
  197. package/backend/dist/local/tar.d.ts +20 -0
  198. package/backend/dist/local/tar.js +367 -0
  199. package/backend/dist/local/transport.d.ts +35 -0
  200. package/backend/dist/local/transport.js +89 -0
  201. package/backend/dist/local/tune.d.ts +58 -0
  202. package/backend/dist/local/tune.js +324 -0
  203. package/backend/dist/observability/http-exchange.d.ts +2 -2
  204. package/backend/dist/opencode/catalog/auto-pull.d.ts +14 -3
  205. package/backend/dist/opencode/catalog/auto-pull.js +276 -70
  206. package/backend/dist/opencode/catalog/ocr-store.js +3 -1
  207. package/backend/dist/opencode/catalog/overrides-store.d.ts +10 -1
  208. package/backend/dist/opencode/catalog/overrides-store.js +6 -0
  209. package/backend/dist/opencode/catalog/reasoning-declaration.d.ts +35 -0
  210. package/backend/dist/opencode/catalog/reasoning-declaration.js +66 -0
  211. package/backend/dist/opencode/catalog/repository.js +25 -2
  212. package/backend/dist/opencode/catalog/sources/models-dev.js +13 -3
  213. package/backend/dist/opencode/catalog/types.d.ts +35 -3
  214. package/backend/dist/opencode/catalog/types.js +38 -1
  215. package/backend/dist/opencode/credentials/ocr-store.js +11 -2
  216. package/backend/dist/opencode/credentials/sync.js +12 -3
  217. package/backend/dist/opencode/credentials/types.d.ts +31 -4
  218. package/backend/dist/opencode/credentials/types.js +25 -0
  219. package/backend/dist/opencode/probe.d.ts +21 -4
  220. package/backend/dist/opencode/probe.js +34 -10
  221. package/backend/dist/pipeline/directives.d.ts +9 -4
  222. package/backend/dist/pipeline/directives.js +14 -10
  223. package/backend/dist/pipeline/orchestrator.d.ts +42 -13
  224. package/backend/dist/pipeline/orchestrator.js +497 -165
  225. package/backend/dist/plugins/environment-ack.d.ts +51 -0
  226. package/backend/dist/plugins/environment-ack.js +81 -0
  227. package/backend/dist/plugins/gateways.d.ts +6 -6
  228. package/backend/dist/plugins/gateways.js +2 -2
  229. package/backend/dist/plugins/host.d.ts +98 -14
  230. package/backend/dist/plugins/host.js +622 -87
  231. package/backend/dist/plugins/install-run.d.ts +27 -0
  232. package/backend/dist/plugins/install-run.js +99 -0
  233. package/backend/dist/plugins/manifest.d.ts +84 -32
  234. package/backend/dist/plugins/manifest.js +149 -45
  235. package/backend/dist/plugins/market-install.d.ts +18 -0
  236. package/backend/dist/plugins/market-install.js +111 -0
  237. package/backend/dist/plugins/market-source.d.ts +100 -0
  238. package/backend/dist/plugins/market-source.js +449 -0
  239. package/backend/dist/plugins/market-updates.d.ts +70 -0
  240. package/backend/dist/plugins/market-updates.js +97 -0
  241. package/backend/dist/plugins/market.d.ts +677 -0
  242. package/backend/dist/plugins/market.js +2113 -0
  243. package/backend/dist/plugins/source-index.d.ts +155 -0
  244. package/backend/dist/plugins/source-index.js +217 -0
  245. package/backend/dist/plugins/types.d.ts +402 -37
  246. package/backend/dist/projects/worktrees.d.ts +88 -0
  247. package/backend/dist/projects/worktrees.js +220 -0
  248. package/backend/dist/providers/boot-direct.d.ts +41 -7
  249. package/backend/dist/providers/boot-direct.js +252 -36
  250. package/backend/dist/providers/compat/tool-markup-recovery.js +31 -6
  251. package/backend/dist/providers/executors/dispatch.d.ts +17 -7
  252. package/backend/dist/providers/executors/dispatch.js +28 -9
  253. package/backend/dist/providers/executors/openai-chat.js +14 -2
  254. package/backend/dist/providers/executors/plugin-adapter.d.ts +23 -1
  255. package/backend/dist/providers/executors/plugin-adapter.js +59 -3
  256. package/backend/dist/providers/member-match.d.ts +32 -9
  257. package/backend/dist/providers/member-match.js +65 -21
  258. package/backend/dist/providers/model-resolution.d.ts +62 -0
  259. package/backend/dist/providers/model-resolution.js +62 -0
  260. package/backend/dist/providers/price-order.d.ts +51 -0
  261. package/backend/dist/providers/price-order.js +54 -0
  262. package/backend/dist/providers/provider-takedown.d.ts +5 -2
  263. package/backend/dist/providers/registry.d.ts +84 -25
  264. package/backend/dist/providers/registry.js +209 -114
  265. package/backend/dist/providers/selection.d.ts +91 -0
  266. package/backend/dist/providers/selection.js +158 -0
  267. package/backend/dist/providers/virtual-meta.d.ts +33 -2
  268. package/backend/dist/providers/virtual-meta.js +74 -18
  269. package/backend/dist/quota/cli-login.d.ts +25 -4
  270. package/backend/dist/quota/cli-login.js +35 -5
  271. package/backend/dist/quota/coverage-generation.d.ts +24 -0
  272. package/backend/dist/quota/coverage-generation.js +29 -0
  273. package/backend/dist/quota/declarations.js +8 -4
  274. package/backend/dist/quota/engine.js +2 -2
  275. package/backend/dist/quota/prober.d.ts +43 -2
  276. package/backend/dist/quota/prober.js +97 -22
  277. package/backend/dist/ratelimit/rate-limiter.d.ts +1 -1
  278. package/backend/dist/resilience/error-classifier.js +29 -0
  279. package/backend/dist/router/index.d.ts +1 -1
  280. package/backend/dist/router/index.js +17 -1
  281. package/backend/dist/router/layer2-decision.d.ts +1 -1
  282. package/backend/dist/router/layer2-decision.js +2 -2
  283. package/backend/dist/routes/console.js +928 -310
  284. package/backend/dist/routes/environments.js +1 -1
  285. package/backend/dist/routes/local-models.d.ts +2 -0
  286. package/backend/dist/routes/local-models.js +1414 -0
  287. package/backend/dist/routes/mihomo.d.ts +2 -2
  288. package/backend/dist/routes/mihomo.js +20 -11
  289. package/backend/dist/routes/projects.js +121 -0
  290. package/backend/dist/server.js +318 -13
  291. package/backend/dist/session/session-manager.d.ts +42 -5
  292. package/backend/dist/session/session-manager.js +64 -11
  293. package/backend/dist/session/session-row.d.ts +29 -8
  294. package/backend/dist/session/session-row.js +18 -13
  295. package/backend/dist/snapshot/bundle.d.ts +40 -0
  296. package/backend/dist/snapshot/bundle.js +177 -0
  297. package/backend/dist/snapshot/handoff/compress.d.ts +46 -0
  298. package/backend/dist/snapshot/handoff/compress.js +77 -0
  299. package/backend/dist/snapshot/handoff/index.d.ts +119 -0
  300. package/backend/dist/snapshot/handoff/index.js +160 -0
  301. package/backend/dist/snapshot/handoff/jsonl-writer.d.ts +78 -0
  302. package/backend/dist/snapshot/handoff/jsonl-writer.js +175 -0
  303. package/backend/dist/snapshot/handoff/opencode-writer.d.ts +51 -0
  304. package/backend/dist/snapshot/handoff/opencode-writer.js +214 -0
  305. package/backend/dist/snapshot/handoff/summarize.d.ts +39 -0
  306. package/backend/dist/snapshot/handoff/summarize.js +118 -0
  307. package/backend/dist/snapshot/handoff/transcript.d.ts +71 -0
  308. package/backend/dist/snapshot/handoff/transcript.js +167 -0
  309. package/backend/dist/snapshot/media-fs.d.ts +10 -0
  310. package/backend/dist/snapshot/media-fs.js +50 -0
  311. package/backend/dist/snapshot/media.d.ts +32 -0
  312. package/backend/dist/snapshot/media.js +87 -0
  313. package/backend/dist/snapshot/store.d.ts +226 -0
  314. package/backend/dist/snapshot/store.js +887 -0
  315. package/backend/dist/snapshot/tree.d.ts +112 -0
  316. package/backend/dist/snapshot/tree.js +207 -0
  317. package/backend/dist/snapshot/types.d.ts +212 -0
  318. package/backend/dist/snapshot/types.js +14 -0
  319. package/backend/dist/snapshot/view.d.ts +19 -0
  320. package/backend/dist/snapshot/view.js +57 -0
  321. package/backend/dist/snapshot/write-worker.d.ts +67 -0
  322. package/backend/dist/snapshot/write-worker.js +129 -0
  323. package/backend/dist/surfaces/body-admission.d.ts +67 -2
  324. package/backend/dist/surfaces/body-admission.js +218 -13
  325. package/backend/dist/surfaces/chat-pipeline.js +8 -0
  326. package/backend/dist/surfaces/decision-pipeline.js +10 -7
  327. package/backend/dist/surfaces/gateway-catalog.d.ts +26 -0
  328. package/backend/dist/surfaces/gateway-catalog.js +202 -0
  329. package/backend/dist/surfaces/gateway-chat.d.ts +7 -11
  330. package/backend/dist/surfaces/gateway-chat.js +50 -12
  331. package/backend/dist/surfaces/ocr-headers.d.ts +6 -4
  332. package/backend/dist/surfaces/ocr-headers.js +11 -7
  333. package/backend/dist/surfaces/systemone.js +1 -1
  334. package/backend/dist/surfaces/transport-fastify.js +32 -5
  335. package/backend/dist/surfaces/transport-node-http.d.ts +9 -3
  336. package/backend/dist/surfaces/transport-node-http.js +6 -19
  337. package/backend/dist/surfaces/types.d.ts +11 -3
  338. package/backend/dist/trace/persist.js +21 -1
  339. package/backend/dist/trace/tracker.d.ts +35 -3
  340. package/backend/dist/trace/tracker.js +23 -0
  341. package/backend/dist/types/openai.d.ts +8 -0
  342. package/backend/dist/types/router.d.ts +17 -6
  343. package/backend/dist/types/router.js +14 -2
  344. package/backend/dist/utils/client-families.d.ts +66 -0
  345. package/backend/dist/utils/client-families.js +127 -0
  346. package/backend/dist/utils/event-ring.d.ts +1 -1
  347. package/backend/dist/utils/event-ring.js +1 -1
  348. package/backend/dist/utils/proxy-node.js +1 -1
  349. package/backend/dist/utils/proxy.d.ts +135 -11
  350. package/backend/dist/utils/proxy.js +144 -29
  351. package/backend/dist/utils/run-command.d.ts +21 -1
  352. package/backend/dist/utils/run-command.js +64 -4
  353. package/backend/dist/utils/server-liveness.d.ts +3 -2
  354. package/backend/dist/utils/server-liveness.js +3 -2
  355. package/backend/dist/utils/session-file.d.ts +28 -0
  356. package/backend/dist/utils/session-file.js +34 -0
  357. package/frontend/dist/assets/antigravity.color-DXFfVr6X.svg +39 -0
  358. package/frontend/dist/assets/gemini-cli.color-BfquLd1p.svg +1 -0
  359. package/frontend/dist/assets/index-CTZNvn1d.js +1707 -0
  360. package/frontend/dist/assets/{index-KI1OW5x6.css → index-CqDSOPQ0.css} +1 -1
  361. package/frontend/dist/index.html +2 -2
  362. package/package.json +3 -1
  363. package/frontend/dist/assets/index-Dk76uc7e.js +0 -1522
@@ -0,0 +1,774 @@
1
+ import fs from 'node:fs';
2
+ import path from 'node:path';
3
+ import { EventRing, nextRingEventId, PROXY_ACCESS_RING_CAPACITY } from '../utils/event-ring.js';
4
+ import zlib from 'node:zlib';
5
+ import { promisify } from 'node:util';
6
+ import { DEFAULT_PROXY_ACCESS_LOG_BODY_BYTES, DEFAULT_PROXY_ACCESS_LOG_PERSIST_DAYS } from '../config/defaults.js';
7
+ import { sanitizePlainHeadersForCapture } from '../observability/http-exchange.js';
8
+ import { PROXY_BODY_REF_RE, PROXY_DAY_FILE_RE } from './traffic-files.js';
9
+ /** Image container sniffing from magic bytes; everything else is octet-stream. */
10
+ function sniffMime(b) {
11
+ if (b.length >= 4 && b[0] === 0x89 && b[1] === 0x50 && b[2] === 0x4e && b[3] === 0x47)
12
+ return 'image/png';
13
+ if (b.length >= 3 && b[0] === 0x47 && b[1] === 0x49 && b[2] === 0x46)
14
+ return 'image/gif';
15
+ if (b.length >= 3 && b[0] === 0xff && b[1] === 0xd8 && b[2] === 0xff)
16
+ return 'image/jpeg';
17
+ if (b.length >= 2 && b[0] === 0x42 && b[1] === 0x4d)
18
+ return 'image/bmp';
19
+ if (b.length >= 4 && b[0] === 0x00 && b[1] === 0x00 && b[2] === 0x01 && b[3] === 0x00)
20
+ return 'image/x-icon';
21
+ if (b.length >= 12 && b[8] === 0x57 && b[9] === 0x45 && b[10] === 0x42 && b[11] === 0x50)
22
+ return 'image/webp';
23
+ return 'application/octet-stream';
24
+ }
25
+ /**
26
+ * Decompression bomb guard: a captured body is already capped on the wire, but
27
+ * `gzip`/`br`/`deflate` inflate by an arbitrary factor — the inflate call needs
28
+ * its own ceiling or a tiny hostile body becomes a multi-GB allocation.
29
+ */
30
+ const MAX_INFLATE_BYTES = 32 * 1024 * 1024;
31
+ /**
32
+ * Persistence batching: day-file lines are queued and written in one append
33
+ * per batch instead of an open/write/close per exchange. The queue is bounded
34
+ * — a burst that outruns the timer forces an immediate flush rather than
35
+ * growing the heap, so the loss window stays at one timer tick.
36
+ */
37
+ const PERSIST_FLUSH_DELAY_MS = 100;
38
+ const PERSIST_MAX_QUEUED_LINES = 512;
39
+ /**
40
+ * Spill-stream queue bound. Node's WriteStream buffers whatever is written
41
+ * while the disk drains; ignoring that would turn a fast download into an
42
+ * unbounded heap again. Past this ceiling the capture stops and the row is
43
+ * flagged truncated instead.
44
+ */
45
+ const MAX_SPILL_PENDING_BYTES = 32 * 1024 * 1024;
46
+ /**
47
+ * Body-sidecar sweep trails the day-file cutoff by one day: a sidecar is
48
+ * stamped with the exchange's START day while its JSONL row carries the END
49
+ * day, so a cross-midnight exchange can reference a body one day older than
50
+ * any surviving line. One extra day on disk beats deleting bytes a live row
51
+ * still points at.
52
+ */
53
+ const BODY_SWEEP_GRACE_MS = 86_400_000;
54
+ const gunzipAsync = promisify(zlib.gunzip);
55
+ const brotliDecompressAsync = promisify(zlib.brotliDecompress);
56
+ const inflateAsync = promisify(zlib.inflate);
57
+ const inflateRawAsync = promisify(zlib.inflateRaw);
58
+ let settingsReader;
59
+ /** Wired once by ingress-proxy/index.ts; reads the live config ref per event. */
60
+ export function setProxyAccessLogSettingsReader(reader) {
61
+ settingsReader = reader;
62
+ }
63
+ function settings() {
64
+ const s = settingsReader?.();
65
+ return {
66
+ enabled: s?.enabled ?? false,
67
+ // Absent in config = the finite default cap (never unlimited: this ledger
68
+ // is fed by a full-capture proxy, so "no cap" means "whole downloads in
69
+ // the heap"). An explicit 0 still means headers-only.
70
+ bodyBytes: s?.bodyBytes ?? DEFAULT_PROXY_ACCESS_LOG_BODY_BYTES,
71
+ persist: s?.persist ?? true,
72
+ persistDays: s?.persistDays ?? DEFAULT_PROXY_ACCESS_LOG_PERSIST_DAYS,
73
+ };
74
+ }
75
+ const ring = new EventRing(undefined, PROXY_ACCESS_RING_CAPACITY);
76
+ export function proxyAccessLogSettings() {
77
+ return settings();
78
+ }
79
+ export function listProxyAccessEvents() {
80
+ return ring.rows().reverse();
81
+ }
82
+ export function clearProxyAccessLog() {
83
+ // Operator "clear" means wipe: drop the ring, day files AND body files.
84
+ const stale = listProxyAccessEvents();
85
+ ring.clear();
86
+ // Unflushed rows belong to the files being wiped — never resurrect them.
87
+ discardQueuedPersistLines();
88
+ try {
89
+ for (const f of persistedFiles(persistDir))
90
+ fs.unlinkSync(f);
91
+ if (persistDir)
92
+ fs.rmSync(path.join(persistDir, 'bodies'), { recursive: true, force: true });
93
+ }
94
+ catch {
95
+ // Best effort — the ring is already clear.
96
+ }
97
+ removeBodyFiles(stale.flatMap((e) => [e.reqBodyFile, e.resBodyFile]));
98
+ }
99
+ /**
100
+ * Drop these rows from the LIVE ring only — the live view's "clear". Day
101
+ * files, body sidecars and the history scope stay intact; the caller records
102
+ * the matching tombstones (observability/traffic-live-hidden.ts) so the rows
103
+ * are not served again by the live read (including after a ring replay).
104
+ */
105
+ export function forgetProxyAccessRingEvents(ids) {
106
+ let removed = 0;
107
+ for (const id of ids)
108
+ if (ring.remove(id))
109
+ removed++;
110
+ return removed;
111
+ }
112
+ function append(ev) {
113
+ ring.append(ev);
114
+ persistEvent(ev);
115
+ }
116
+ // ── disk persistence ────────────────────────────────────────────────────────
117
+ let persistDir = null;
118
+ /** Wired once by ingress-proxy/index.ts with `<ocrHome>/ingress-proxy/access-log/`. */
119
+ export function setProxyAccessLogPersistDir(dir) {
120
+ persistDir = dir;
121
+ fs.mkdirSync(dir, { recursive: true });
122
+ }
123
+ /** The live persist root — the history-delete worker receives it via workerData. */
124
+ export function proxyAccessLogPersistDir() {
125
+ return persistDir;
126
+ }
127
+ // ── raw binary body files ───────────────────────────────────────────────────
128
+ // Binary bodies do NOT go inline as hex text: they are written as raw files
129
+ // under `<dir>/bodies/<day>/<event>-<side>.bin` and referenced from the
130
+ // JSONL / ring row. The console fetches them through readProxyAccessBodyFile.
131
+ const dayStamp = (ts) => new Date(ts).toISOString().slice(0, 10).replace(/-/g, '');
132
+ /** UTC midnight of a `YYYYMMDD` stamp; NaN when the stamp is not a real date. */
133
+ const dayStampTs = (stamp) => Date.parse(`${stamp.slice(0, 4)}-${stamp.slice(4, 6)}-${stamp.slice(6, 8)}T00:00:00Z`);
134
+ /** Absolute path + ring ref (`<day>/<name>.bin`) of one persisted body file. */
135
+ function bodyFileTarget(id, ts, side) {
136
+ const day = dayStamp(ts);
137
+ const name = `${id}-${side}.bin`;
138
+ return { path: path.join(persistDir, 'bodies', day, name), ref: `${day}/${name}` };
139
+ }
140
+ async function writeBodyFile(id, ts, side, buf) {
141
+ const target = bodyFileTarget(id, ts, side);
142
+ fs.mkdirSync(path.dirname(target.path), { recursive: true });
143
+ await fs.promises.writeFile(target.path, buf);
144
+ return target.ref;
145
+ }
146
+ /**
147
+ * Absolute path of a persisted body, validated against the ref grammar (a
148
+ * hand-crafted ref cannot walk out of the bodies tree). The console streams
149
+ * this path; nothing else may address the directory.
150
+ */
151
+ export function proxyAccessBodyPath(ref) {
152
+ if (!persistDir)
153
+ return null;
154
+ const m = PROXY_BODY_REF_RE.exec(ref);
155
+ if (!m)
156
+ return null;
157
+ return path.join(persistDir, 'bodies', m[1], `${m[2]}.bin`);
158
+ }
159
+ /** Console-side fetch of a persisted binary body; null when missing/invalid. */
160
+ export function readProxyAccessBodyFile(ref) {
161
+ const abs = proxyAccessBodyPath(ref);
162
+ if (!abs)
163
+ return null;
164
+ try {
165
+ return fs.readFileSync(abs);
166
+ }
167
+ catch {
168
+ return null;
169
+ }
170
+ }
171
+ function removeBodyFiles(refs) {
172
+ for (const ref of refs) {
173
+ if (!ref)
174
+ continue;
175
+ const m = PROXY_BODY_REF_RE.exec(ref);
176
+ if (!m)
177
+ continue;
178
+ try {
179
+ fs.unlinkSync(path.join(persistDir, 'bodies', m[1], `${m[2]}.bin`));
180
+ }
181
+ catch {
182
+ // Best effort.
183
+ }
184
+ }
185
+ }
186
+ const dayFile = (dir, ts) => path.join(dir, `access-log-${dayStamp(ts)}.jsonl`);
187
+ function persistedFiles(dir) {
188
+ if (!dir)
189
+ return [];
190
+ try {
191
+ return fs
192
+ .readdirSync(dir)
193
+ .filter((f) => PROXY_DAY_FILE_RE.test(f))
194
+ .map((f) => path.join(dir, f))
195
+ .sort();
196
+ }
197
+ catch {
198
+ return [];
199
+ }
200
+ }
201
+ const matchHistoryFilter = (ev, o) => {
202
+ if (o.kind && ev.kind !== o.kind)
203
+ return false;
204
+ if (o.method && ev.method !== o.method)
205
+ return false;
206
+ if (o.status && String(ev.status ?? '') !== o.status)
207
+ return false;
208
+ if (o.host && ev.host !== o.host)
209
+ return false;
210
+ return true;
211
+ };
212
+ /** Read one day file's lines newest-first; a torn last line is skipped. */
213
+ function readDayLines(file) {
214
+ let raw;
215
+ try {
216
+ raw = fs.readFileSync(file, 'utf8');
217
+ }
218
+ catch {
219
+ return [];
220
+ }
221
+ const out = [];
222
+ for (const line of raw.split('\n')) {
223
+ const s = line.trim();
224
+ if (!s)
225
+ continue;
226
+ try {
227
+ out.push(JSON.parse(s));
228
+ }
229
+ catch {
230
+ // Torn tail (crash mid-append) — skip.
231
+ }
232
+ }
233
+ return out.reverse();
234
+ }
235
+ /**
236
+ * The FULL filtered proxy-access history, newest-first — the input of the
237
+ * console's FEDERATED history query, which interleaves these rows with the
238
+ * plugin traffic feeds and pages the merge (exact total = all sources).
239
+ * Retention is thousands of rows at most, so a full materialization per
240
+ * request is cheap; bodies never leave the files here.
241
+ */
242
+ export async function readProxyAccessHistory(opts = {}) {
243
+ await flushPersistedLines();
244
+ const out = [];
245
+ for (const file of persistedFiles(persistDir).reverse()) { // newest day first
246
+ for (const ev of readDayLines(file)) {
247
+ if (matchHistoryFilter(ev, opts))
248
+ out.push(ev);
249
+ }
250
+ }
251
+ return out;
252
+ }
253
+ let persistQueue = [];
254
+ let persistTimer;
255
+ /** FIFO chain: batches complete in enqueue order (an append issued later must
256
+ * never land before one issued earlier — the day file is an audit trail). */
257
+ let persistChain = Promise.resolve();
258
+ function schedulePersistFlush() {
259
+ if (persistTimer !== undefined)
260
+ return;
261
+ persistTimer = setTimeout(() => {
262
+ persistTimer = undefined;
263
+ void flushPersistedLines();
264
+ }, PERSIST_FLUSH_DELAY_MS);
265
+ persistTimer.unref?.();
266
+ }
267
+ function groupByFile(batch) {
268
+ const groups = new Map();
269
+ for (const { file, line } of batch) {
270
+ const lines = groups.get(file);
271
+ if (lines)
272
+ lines.push(line);
273
+ else
274
+ groups.set(file, [line]);
275
+ }
276
+ return groups;
277
+ }
278
+ /**
279
+ * Write every queued row, grouped into ONE append per day file, in call
280
+ * order. Resolves once the batch reached disk; failures are swallowed —
281
+ * observability never breaks the proxy path.
282
+ */
283
+ function flushPersistedLines() {
284
+ if (persistTimer !== undefined) {
285
+ clearTimeout(persistTimer);
286
+ persistTimer = undefined;
287
+ }
288
+ if (persistQueue.length > 0) {
289
+ const batch = persistQueue;
290
+ persistQueue = [];
291
+ for (const [file, lines] of groupByFile(batch)) {
292
+ const data = lines.join('');
293
+ persistChain = persistChain
294
+ .then(() => fs.promises.appendFile(file, data, 'utf8'))
295
+ .catch(() => { });
296
+ }
297
+ }
298
+ return persistChain;
299
+ }
300
+ /** Test seam: resolves when every queued row has reached the disk. */
301
+ export function flushProxyAccessLogPersistence() {
302
+ return flushPersistedLines();
303
+ }
304
+ /**
305
+ * Last-chance flush for the process 'exit' handler (Node allows only sync
306
+ * code there). A batch already handed to the async chain cannot be awaited
307
+ * here — the honest loss bound at exit is one in-flight batch.
308
+ */
309
+ export function flushProxyAccessLogPersistenceSync() {
310
+ if (persistTimer !== undefined) {
311
+ clearTimeout(persistTimer);
312
+ persistTimer = undefined;
313
+ }
314
+ if (persistQueue.length === 0)
315
+ return;
316
+ const batch = persistQueue;
317
+ persistQueue = [];
318
+ for (const [file, lines] of groupByFile(batch)) {
319
+ try {
320
+ fs.appendFileSync(file, lines.join(''));
321
+ }
322
+ catch {
323
+ // Best effort at exit.
324
+ }
325
+ }
326
+ }
327
+ function discardQueuedPersistLines() {
328
+ if (persistTimer !== undefined) {
329
+ clearTimeout(persistTimer);
330
+ persistTimer = undefined;
331
+ }
332
+ persistQueue = [];
333
+ }
334
+ function persistEvent(ev) {
335
+ if (!persistDir || !settings().persist)
336
+ return;
337
+ let line;
338
+ try {
339
+ line = JSON.stringify(ev) + '\n';
340
+ }
341
+ catch {
342
+ return;
343
+ }
344
+ persistQueue.push({ file: dayFile(persistDir, ev.ts), line });
345
+ if (persistQueue.length >= PERSIST_MAX_QUEUED_LINES)
346
+ void flushPersistedLines();
347
+ else
348
+ schedulePersistFlush();
349
+ }
350
+ /**
351
+ * Reload persisted events into the ring and start the daily cleanup that
352
+ * deletes day files (and their body-sidecar directories) older than
353
+ * `persistDays`. Only the NEWEST
354
+ * PROXY_ACCESS_RING_CAPACITY rows are parsed: the ring cannot hold more, so
355
+ * scanning the whole retention window (7 days by default) at boot would pay
356
+ * for history it immediately evicts. Windows replay OLDEST-first in
357
+ * chronological line order (newer days are read backwards from the last
358
+ * line), since EventRing.append trims the EARLIEST-appended rows.
359
+ */
360
+ export function initProxyAccessLogPersistence() {
361
+ if (!persistDir)
362
+ return;
363
+ const windows = [];
364
+ let need = PROXY_ACCESS_RING_CAPACITY;
365
+ for (const f of persistedFiles(persistDir).reverse()) { // newest day first
366
+ if (need <= 0)
367
+ break;
368
+ const events = readDayLines(f); // newest first, torn tail skipped
369
+ const take = events.slice(0, need);
370
+ need -= take.length;
371
+ windows.unshift(take.reverse()); // back to chronological order
372
+ }
373
+ for (const ev of windows.flat())
374
+ ring.append(ev);
375
+ const cleanup = () => {
376
+ const dir = persistDir;
377
+ if (!dir)
378
+ return;
379
+ const cutoff = Date.now() - settings().persistDays * 86_400_000;
380
+ for (const f of persistedFiles(dir)) {
381
+ const m = /access-log-(\d{8})\.jsonl$/.exec(f);
382
+ if (!m)
383
+ continue;
384
+ const dayTs = dayStampTs(m[1]);
385
+ if (Number.isFinite(dayTs) && dayTs < cutoff) {
386
+ try {
387
+ fs.unlinkSync(f);
388
+ }
389
+ catch {
390
+ // Already gone or locked — next sweep retries.
391
+ }
392
+ }
393
+ }
394
+ // A body sidecar is reachable only through JSONL rows (its own day's, or
395
+ // the next day's for a cross-midnight exchange), so it must not outlive
396
+ // them — the grace above covers the one-day stamp skew.
397
+ const bodiesRoot = path.join(dir, 'bodies');
398
+ let entries;
399
+ try {
400
+ entries = fs.readdirSync(bodiesRoot, { withFileTypes: true });
401
+ }
402
+ catch {
403
+ return;
404
+ }
405
+ const bodyCutoff = cutoff - BODY_SWEEP_GRACE_MS;
406
+ for (const ent of entries) {
407
+ if (!ent.isDirectory() || !/^\d{8}$/.test(ent.name))
408
+ continue;
409
+ const dayTs = dayStampTs(ent.name);
410
+ if (!Number.isFinite(dayTs) || dayTs >= bodyCutoff)
411
+ continue;
412
+ try {
413
+ fs.rmSync(path.join(bodiesRoot, ent.name), { recursive: true, force: true });
414
+ }
415
+ catch {
416
+ // Best effort — next sweep retries.
417
+ }
418
+ }
419
+ };
420
+ cleanup();
421
+ setInterval(cleanup, 24 * 3600_000).unref();
422
+ }
423
+ /** Record one CONNECT tunnel decision (no decrypted content exists). */
424
+ export function recordProxyConnect(args) {
425
+ if (!settings().enabled)
426
+ return;
427
+ append({
428
+ id: nextRingEventId('pa-', Date.now()),
429
+ ts: Date.now(),
430
+ kind: 'connect',
431
+ host: args.host,
432
+ port: args.port,
433
+ reqBytes: 0,
434
+ respBytes: 0,
435
+ note: args.note,
436
+ });
437
+ }
438
+ /**
439
+ * Record one FINISHED blind tunnel — the byte totals a `connect` decision row
440
+ * cannot know yet.
441
+ *
442
+ * A tunnel is opaque on purpose (ADR-0020: TCP is passthrough-only), so the
443
+ * counts and the lifetime are the entire observation. Without them "the tunnel
444
+ * was opened" and "the tunnel carried nothing for six hours" look identical on
445
+ * the console.
446
+ */
447
+ export function recordProxyTunnel(args) {
448
+ if (!settings().enabled)
449
+ return;
450
+ const now = Date.now();
451
+ append({
452
+ id: nextRingEventId('pa-', now),
453
+ ts: now,
454
+ kind: 'connect',
455
+ host: args.host,
456
+ port: args.port,
457
+ reqBytes: args.reqBytes,
458
+ respBytes: args.respBytes,
459
+ durationMs: args.durationMs,
460
+ note: args.note,
461
+ });
462
+ }
463
+ /**
464
+ * A live tap on one non-intercepted HTTP exchange. The forwarders feed it
465
+ * request/response chunks; `finish` lands the ring row exactly once.
466
+ */
467
+ const BINARY_CT_RE = /^(?:image|audio|video|font)\//i;
468
+ /** Binary content types beyond the media families (framed / object formats). */
469
+ const BINARY_CT_EXTRA_RE = /octet-stream|protobuf|msgpack|cbor|grpc/i;
470
+ function isBinaryBody(buf, contentType) {
471
+ if (contentType && (BINARY_CT_RE.test(contentType) || BINARY_CT_EXTRA_RE.test(contentType)))
472
+ return true;
473
+ // NUL byte in the sampled window — text decoders never emit NUL for real text.
474
+ return buf.subarray(0, 4096).includes(0);
475
+ }
476
+ /** Canonical 16-bytes-per-row hex dump: offset, hex cells, ASCII gutter. */
477
+ function toHexDump(buf) {
478
+ const rows = [];
479
+ for (let off = 0; off < buf.length; off += 16) {
480
+ const slice = buf.subarray(off, off + 16);
481
+ const hex = [...slice].map((b) => b.toString(16).padStart(2, '0'));
482
+ const cells = [];
483
+ for (let i = 0; i < 16; i += 8)
484
+ cells.push(hex.slice(i, i + 8).join(' ').padEnd(23, ' '));
485
+ const ascii = [...slice].map((b) => (b >= 0x20 && b < 0x7f ? String.fromCharCode(b) : '.')).join('');
486
+ rows.push(`${off.toString(16).padStart(8, '0')} ${cells.join(' ')} |${ascii}|`);
487
+ }
488
+ return rows.join('\n');
489
+ }
490
+ /** First value of a header (case-insensitive), or undefined when absent. */
491
+ function headerValue(headers, name) {
492
+ const v = headers?.[name];
493
+ const first = Array.isArray(v) ? v[0] : v;
494
+ return typeof first === 'string' ? first.toLowerCase() : undefined;
495
+ }
496
+ /** Charset label from a Content-Type header, kept when it looks like a valid decoder label. */
497
+ function charsetOf(contentType) {
498
+ const m = /charset\s*=\s*"?([a-z0-9_-]+)"?/i.exec(contentType ?? '');
499
+ const label = m?.[1];
500
+ return label && /^[a-z0-9_-]+$/i.test(label) ? label : undefined;
501
+ }
502
+ /**
503
+ * Decode a captured body for display. Compressed bodies (gzip / deflate /
504
+ * br) are decompressed first — raw compressed bytes would land in the log
505
+ * as mojibake. Decompression only applies to a COMPLETE body: a body cut at
506
+ * the capture cap cannot be inflated, so it falls back to the raw bytes.
507
+ * Binary content (media types, framed formats, or anything containing NUL)
508
+ * becomes a hex dump capped only when a bodyBytes cap is configured; text is
509
+ * decoded with the declared charset when Node supports it (utf-8 fallback).
510
+ */
511
+ async function decodeCaptureBody(parts, cap, encoding, contentType, truncated) {
512
+ if (parts.length === 0)
513
+ return { text: undefined };
514
+ let buf = Buffer.concat(parts);
515
+ try {
516
+ if (!truncated && buf.length > 0) {
517
+ // Async zlib runs on the libuv threadpool: inflating a compressed body
518
+ // must never block the event loop that is also forwarding the proxy.
519
+ const inflate = { maxOutputLength: MAX_INFLATE_BYTES };
520
+ if (encoding === 'gzip' || encoding === 'x-gzip')
521
+ buf = await gunzipAsync(buf, inflate);
522
+ else if (encoding === 'br')
523
+ buf = await brotliDecompressAsync(buf, inflate);
524
+ else if (encoding === 'deflate') {
525
+ try {
526
+ buf = await inflateAsync(buf, inflate);
527
+ }
528
+ catch {
529
+ buf = await inflateRawAsync(buf, inflate);
530
+ }
531
+ }
532
+ }
533
+ }
534
+ catch {
535
+ // Truncated or corrupt stream — keep the raw bytes as-is.
536
+ }
537
+ if (isBinaryBody(buf, contentType)) {
538
+ return { hex: true, bytes: buf, mime: sniffMime(buf) };
539
+ }
540
+ if (buf.length > cap)
541
+ buf = buf.subarray(0, cap);
542
+ try {
543
+ return { text: new TextDecoder(charsetOf(contentType) ?? 'utf-8').decode(buf) };
544
+ }
545
+ catch {
546
+ return { text: buf.toString('utf8') };
547
+ }
548
+ }
549
+ /**
550
+ * Bounded body capture for ONE side of an exchange.
551
+ *
552
+ * `cap` is the INLINE budget (finite by default — DEFAULT_PROXY_ACCESS_LOG_BODY_BYTES):
553
+ * the bytes that fit are buffered for the decoded text/hex rendering the
554
+ * console shows. The moment a body outgrows the cap, the WHOLE body (buffered
555
+ * prefix + the rest) is spilled to a raw body file and every later chunk is
556
+ * appended straight to disk — full capture without an unbounded heap. With no
557
+ * disk sink (persistence off) the tail is dropped and the row is marked
558
+ * truncated.
559
+ */
560
+ class BodyCapture {
561
+ cap;
562
+ spill;
563
+ parts = [];
564
+ buffered = 0;
565
+ total = 0;
566
+ spilled = false;
567
+ spillStream;
568
+ spillRef;
569
+ spillMime;
570
+ spillClosed = Promise.resolve();
571
+ truncated = false;
572
+ constructor(cap, spill) {
573
+ this.cap = cap;
574
+ this.spill = spill;
575
+ }
576
+ get byteCount() {
577
+ return this.total;
578
+ }
579
+ push(chunk) {
580
+ this.total += chunk.length;
581
+ if (this.cap === 0)
582
+ return; // headers-only capture
583
+ if (this.spilled) {
584
+ const stream = this.spillStream;
585
+ if (!stream || stream.destroyed) {
586
+ this.truncated = true; // the spill died mid-body — the tail is gone
587
+ return;
588
+ }
589
+ if (stream.writableLength + chunk.length > MAX_SPILL_PENDING_BYTES) {
590
+ // Upstream outran the disk: stop capturing rather than queue the
591
+ // whole body in the heap (the same bound the inline cap promises).
592
+ this.truncated = true;
593
+ this.spillStream = undefined;
594
+ stream.destroy();
595
+ return;
596
+ }
597
+ stream.write(chunk);
598
+ return;
599
+ }
600
+ if (this.buffered + chunk.length <= this.cap) {
601
+ this.parts.push(chunk);
602
+ this.buffered += chunk.length;
603
+ return;
604
+ }
605
+ if (this.openSpill()) {
606
+ this.spillStream.write(chunk);
607
+ return;
608
+ }
609
+ // No disk sink: keep what fits the cap, drop the tail, flag the row.
610
+ const room = this.cap - this.buffered;
611
+ if (room > 0) {
612
+ this.parts.push(chunk.subarray(0, room));
613
+ this.buffered += room;
614
+ }
615
+ this.truncated = true;
616
+ }
617
+ /** Decode this side: inline text/hex, or a raw body-file ref. Resolves once
618
+ * a spilled/raw body file is fully on disk, so the JSONL row that
619
+ * references it can never point at a half-written file. */
620
+ async finish(encoding, contentType) {
621
+ if (this.spilled) {
622
+ await this.endSpill();
623
+ return { fileRef: this.spillRef, fileMime: this.spillMime, truncated: this.truncated };
624
+ }
625
+ const body = await decodeCaptureBody(this.parts, this.cap, encoding, contentType, this.truncated);
626
+ if (body.hex && body.bytes) {
627
+ // Binary content: a persisted body lands as a raw file, never inline.
628
+ if (this.spill && persistDir) {
629
+ try {
630
+ const ref = await writeBodyFile(this.spill.id, this.spill.ts, this.spill.side, body.bytes);
631
+ return { fileRef: ref, fileMime: body.mime, truncated: this.truncated };
632
+ }
633
+ catch {
634
+ // Fall through to the inline hex dump.
635
+ }
636
+ }
637
+ return { hex: true, bytes: body.bytes, mime: body.mime, truncated: this.truncated };
638
+ }
639
+ return { text: body.text, truncated: this.truncated };
640
+ }
641
+ /** Open the spill file and hand the buffered prefix to its stream. */
642
+ openSpill() {
643
+ if (!this.spill || !persistDir)
644
+ return false;
645
+ try {
646
+ const target = bodyFileTarget(this.spill.id, this.spill.ts, this.spill.side);
647
+ fs.mkdirSync(path.dirname(target.path), { recursive: true });
648
+ const stream = fs.createWriteStream(target.path);
649
+ stream.on('error', () => {
650
+ // Disk trouble must never break the proxy path — stop capturing.
651
+ this.truncated = true;
652
+ });
653
+ this.spillClosed = new Promise((resolve) => stream.once('close', resolve));
654
+ this.spillStream = stream;
655
+ this.spillRef = target.ref;
656
+ if (this.buffered > 0) {
657
+ const prefix = Buffer.concat(this.parts);
658
+ stream.write(prefix);
659
+ this.spillMime = sniffMime(prefix);
660
+ }
661
+ this.parts = [];
662
+ this.buffered = 0;
663
+ this.spilled = true;
664
+ return true;
665
+ }
666
+ catch {
667
+ this.spillStream = undefined;
668
+ return false;
669
+ }
670
+ }
671
+ /** End the spill stream and resolve once its fd is closed. */
672
+ endSpill() {
673
+ const stream = this.spillStream;
674
+ if (!stream)
675
+ return this.spillClosed;
676
+ this.spillStream = undefined;
677
+ try {
678
+ stream.end();
679
+ }
680
+ catch {
681
+ this.truncated = true;
682
+ stream.destroy();
683
+ }
684
+ return this.spillClosed;
685
+ }
686
+ }
687
+ /** Create a tap for one decrypted exchange. Returns undefined when disabled. */
688
+ export function createAccessTap(args) {
689
+ const s = settings();
690
+ if (!s.enabled)
691
+ return undefined;
692
+ const started = Date.now();
693
+ // Row id up front: a spilled body file is named after it.
694
+ const id = nextRingEventId('pa-', started);
695
+ const sink = (side) => s.persist && persistDir !== null ? { id, ts: started, side } : undefined;
696
+ const cap = s.bodyBytes ?? DEFAULT_PROXY_ACCESS_LOG_BODY_BYTES;
697
+ const reqCap = new BodyCapture(cap, sink('req'));
698
+ const resCap = new BodyCapture(cap, sink('res'));
699
+ return {
700
+ onReqChunk(chunk) {
701
+ reqCap.push(chunk);
702
+ },
703
+ onResChunk(chunk) {
704
+ resCap.push(chunk);
705
+ },
706
+ async finish(status, responseHeaders, note) {
707
+ try {
708
+ const [reqSide, resSide] = await Promise.all([
709
+ reqCap.finish(headerValue(args.requestHeaders, 'content-encoding'), headerValue(args.requestHeaders, 'content-type')),
710
+ resCap.finish(headerValue(responseHeaders, 'content-encoding'), headerValue(responseHeaders, 'content-type')),
711
+ ]);
712
+ const ev = {
713
+ id,
714
+ ts: started,
715
+ kind: 'http',
716
+ wire: args.wire,
717
+ host: args.host,
718
+ port: args.port,
719
+ method: args.method,
720
+ path: args.path,
721
+ status,
722
+ durationMs: Date.now() - started,
723
+ reqBytes: reqCap.byteCount,
724
+ respBytes: resCap.byteCount,
725
+ requestHeaders: sanitizePlainHeadersForCapture(args.requestHeaders),
726
+ responseHeaders: sanitizePlainHeadersForCapture(responseHeaders),
727
+ truncated: reqSide.truncated || resSide.truncated,
728
+ note,
729
+ };
730
+ for (const [side, fileKey, mimeKey, textKey, formatKey] of [
731
+ [reqSide, 'reqBodyFile', 'reqBodyMime', 'requestBody', 'reqBodyFormat'],
732
+ [resSide, 'resBodyFile', 'resBodyMime', 'responseBody', 'resBodyFormat'],
733
+ ]) {
734
+ if (side.fileRef !== undefined) {
735
+ ev[fileKey] = side.fileRef;
736
+ if (side.fileMime !== undefined)
737
+ ev[mimeKey] = side.fileMime;
738
+ }
739
+ else if (side.hex && side.bytes) {
740
+ // Not persisting — keep the hex dump inline in the ring.
741
+ ev[textKey] = toHexDump(side.bytes);
742
+ ev[formatKey] = 'hex';
743
+ }
744
+ else if (side.text !== undefined) {
745
+ ev[textKey] = side.text;
746
+ }
747
+ }
748
+ append(ev);
749
+ }
750
+ catch {
751
+ // A broken body pipeline must still leave the exchange observable:
752
+ // the row lands without bodies rather than vanishing.
753
+ append({
754
+ id,
755
+ ts: started,
756
+ kind: 'http',
757
+ wire: args.wire,
758
+ host: args.host,
759
+ port: args.port,
760
+ method: args.method,
761
+ path: args.path,
762
+ status,
763
+ durationMs: Date.now() - started,
764
+ reqBytes: reqCap.byteCount,
765
+ respBytes: resCap.byteCount,
766
+ requestHeaders: sanitizePlainHeadersForCapture(args.requestHeaders),
767
+ responseHeaders: sanitizePlainHeadersForCapture(responseHeaders),
768
+ truncated: true,
769
+ note,
770
+ });
771
+ }
772
+ },
773
+ };
774
+ }