omnicell-router 0.3.1 → 0.7.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 (1002) hide show
  1. package/README.md +70 -10
  2. package/README.zh-CN.md +57 -8
  3. package/RELEASING.md +6 -0
  4. package/RELEASING.zh-CN.md +5 -0
  5. package/backend/dist/auth/api-keys.d.ts +14 -2
  6. package/backend/dist/auth/api-keys.js +26 -14
  7. package/backend/dist/auth/model-access.d.ts +27 -10
  8. package/backend/dist/auth/model-access.js +34 -17
  9. package/backend/dist/capture/migrate/engine.d.ts +38 -0
  10. package/backend/dist/capture/migrate/engine.js +307 -0
  11. package/backend/dist/capture/migrate/index.d.ts +18 -0
  12. package/backend/dist/capture/migrate/index.js +18 -0
  13. package/backend/dist/capture/migrate/migrator.d.ts +113 -0
  14. package/backend/dist/capture/migrate/migrator.js +16 -0
  15. package/backend/dist/capture/migrate/registry.d.ts +16 -0
  16. package/backend/dist/capture/migrate/registry.js +19 -0
  17. package/backend/dist/capture/migrate/steps/v1-to-v2.d.ts +86 -0
  18. package/backend/dist/capture/migrate/steps/v1-to-v2.js +396 -0
  19. package/backend/dist/capture/recorder.d.ts +422 -272
  20. package/backend/dist/capture/recorder.js +873 -417
  21. package/backend/dist/capture/turn-boundary.d.ts +17 -0
  22. package/backend/dist/capture/turn-boundary.js +31 -0
  23. package/backend/dist/cli/clients/base.d.ts +158 -23
  24. package/backend/dist/cli/clients/base.js +150 -4
  25. package/backend/dist/cli/clients/claude.d.ts +3 -2
  26. package/backend/dist/cli/clients/claude.js +4 -3
  27. package/backend/dist/cli/clients/codex.d.ts +3 -2
  28. package/backend/dist/cli/clients/codex.js +4 -3
  29. package/backend/dist/cli/clients/core-adapters.d.ts +25 -0
  30. package/backend/dist/cli/clients/core-adapters.js +44 -0
  31. package/backend/dist/cli/clients/dsh.d.ts +5 -3
  32. package/backend/dist/cli/clients/dsh.js +29 -18
  33. package/backend/dist/cli/clients/grok.d.ts +53 -0
  34. package/backend/dist/cli/clients/grok.js +249 -0
  35. package/backend/dist/cli/clients/index.d.ts +28 -19
  36. package/backend/dist/cli/clients/index.js +156 -60
  37. package/backend/dist/cli/clients/kimi.d.ts +75 -0
  38. package/backend/dist/cli/clients/kimi.js +316 -0
  39. package/backend/dist/cli/clients/launcher.d.ts +48 -0
  40. package/backend/dist/cli/clients/launcher.js +41 -0
  41. package/backend/dist/cli/clients/omp.d.ts +10 -20
  42. package/backend/dist/cli/clients/omp.js +28 -155
  43. package/backend/dist/cli/clients/openclaw.d.ts +55 -0
  44. package/backend/dist/cli/clients/openclaw.js +525 -0
  45. package/backend/dist/cli/clients/opencode.d.ts +7 -20
  46. package/backend/dist/cli/clients/opencode.js +32 -159
  47. package/backend/dist/cli/clients/pi.d.ts +7 -21
  48. package/backend/dist/cli/clients/pi.js +32 -221
  49. package/backend/dist/cli/clients/plugin-adapters.d.ts +20 -0
  50. package/backend/dist/cli/clients/plugin-adapters.js +88 -0
  51. package/backend/dist/cli/clients/reserved.d.ts +51 -0
  52. package/backend/dist/cli/clients/reserved.js +53 -0
  53. package/backend/dist/cli/clients/workbuddy.d.ts +31 -0
  54. package/backend/dist/cli/clients/workbuddy.js +259 -0
  55. package/backend/dist/cli/daemon.d.ts +105 -27
  56. package/backend/dist/cli/daemon.js +509 -151
  57. package/backend/dist/cli/index.d.ts +6 -1
  58. package/backend/dist/cli/index.js +238 -22
  59. package/backend/dist/cli/paths.d.ts +86 -0
  60. package/backend/dist/cli/paths.js +269 -0
  61. package/backend/dist/cli/shim.d.ts +47 -1
  62. package/backend/dist/cli/shim.js +180 -13
  63. package/backend/dist/cli/types.d.ts +102 -16
  64. package/backend/dist/cli/types.js +5 -4
  65. package/backend/dist/compression/caveman-prompts.d.ts +1 -1
  66. package/backend/dist/compression/caveman.d.ts +2 -16
  67. package/backend/dist/compression/caveman.js +25 -37
  68. package/backend/dist/compression/headroom.d.ts +4 -3
  69. package/backend/dist/compression/headroom.js +2 -2
  70. package/backend/dist/compression/index.d.ts +5 -26
  71. package/backend/dist/compression/index.js +79 -17
  72. package/backend/dist/compression/tool-output.d.ts +2 -20
  73. package/backend/dist/compression/tool-output.js +40 -47
  74. package/backend/dist/config/comments-en.d.ts +17 -0
  75. package/backend/dist/config/comments-en.js +232 -0
  76. package/backend/dist/config/comments-zh.d.ts +10 -0
  77. package/backend/dist/config/comments-zh.js +217 -0
  78. package/backend/dist/config/defaults.d.ts +190 -2
  79. package/backend/dist/config/defaults.js +191 -2
  80. package/backend/dist/config/env-archive.js +77 -38
  81. package/backend/dist/config/env.d.ts +4 -0
  82. package/backend/dist/config/env.js +16 -0
  83. package/backend/dist/config/index.d.ts +48 -12
  84. package/backend/dist/config/index.js +794 -368
  85. package/backend/dist/config/layout.d.ts +29 -0
  86. package/backend/dist/config/layout.js +86 -0
  87. package/backend/dist/config/migrations/v0-to-v1.d.ts +105 -0
  88. package/backend/dist/config/migrations/v0-to-v1.js +78 -0
  89. package/backend/dist/config/migrations/v1-to-v2.d.ts +14 -0
  90. package/backend/dist/config/migrations/v1-to-v2.js +41 -0
  91. package/backend/dist/config/migrations/v2-to-v3.d.ts +34 -0
  92. package/backend/dist/config/migrations/v2-to-v3.js +66 -0
  93. package/backend/dist/config/migrations/v3-to-v4.d.ts +34 -0
  94. package/backend/dist/config/migrations/v3-to-v4.js +61 -0
  95. package/backend/dist/config/runtime.d.ts +13 -0
  96. package/backend/dist/config/runtime.js +26 -0
  97. package/backend/dist/config/schema.d.ts +28 -0
  98. package/backend/dist/config/schema.js +98 -0
  99. package/backend/dist/config/types.d.ts +491 -84
  100. package/backend/dist/forward-proxy/access-log.d.ts +173 -0
  101. package/backend/dist/forward-proxy/access-log.js +657 -0
  102. package/backend/dist/forward-proxy/ca-trust.d.ts +42 -0
  103. package/backend/dist/forward-proxy/ca-trust.js +242 -0
  104. package/backend/dist/forward-proxy/ca.d.ts +66 -2
  105. package/backend/dist/forward-proxy/ca.js +146 -11
  106. package/backend/dist/forward-proxy/caller-context.d.ts +18 -0
  107. package/backend/dist/forward-proxy/caller-context.js +20 -0
  108. package/backend/dist/forward-proxy/egress.d.ts +104 -0
  109. package/backend/dist/forward-proxy/egress.js +280 -0
  110. package/backend/dist/forward-proxy/h2-forward.d.ts +66 -0
  111. package/backend/dist/forward-proxy/h2-forward.js +526 -0
  112. package/backend/dist/forward-proxy/index.d.ts +13 -1
  113. package/backend/dist/forward-proxy/index.js +148 -7
  114. package/backend/dist/forward-proxy/interceptor.d.ts +16 -13
  115. package/backend/dist/forward-proxy/interceptor.js +35 -57
  116. package/backend/dist/forward-proxy/relay.d.ts +21 -1
  117. package/backend/dist/forward-proxy/relay.js +48 -1
  118. package/backend/dist/forward-proxy/rules.d.ts +148 -0
  119. package/backend/dist/forward-proxy/rules.js +280 -0
  120. package/backend/dist/forward-proxy/server.d.ts +102 -9
  121. package/backend/dist/forward-proxy/server.js +1310 -305
  122. package/backend/dist/forward-proxy/sni.d.ts +29 -7
  123. package/backend/dist/forward-proxy/sni.js +109 -47
  124. package/backend/dist/forward-proxy/system-proxy.d.ts +72 -0
  125. package/backend/dist/forward-proxy/system-proxy.js +303 -0
  126. package/backend/dist/forward-proxy/upstream-tls.d.ts +46 -0
  127. package/backend/dist/forward-proxy/upstream-tls.js +105 -0
  128. package/backend/dist/forward-proxy/ws-frames.d.ts +45 -0
  129. package/backend/dist/forward-proxy/ws-frames.js +153 -0
  130. package/backend/dist/harness/common/catalog-registry.d.ts +63 -0
  131. package/backend/dist/harness/common/catalog-registry.js +77 -0
  132. package/backend/dist/harness/common/github.d.ts +6 -0
  133. package/backend/dist/harness/common/github.js +13 -0
  134. package/backend/dist/harness/common/market.d.ts +590 -0
  135. package/backend/dist/harness/common/market.js +1079 -0
  136. package/backend/dist/harness/common/marketplace-rescan-scheduler.d.ts +24 -0
  137. package/backend/dist/harness/common/marketplace-rescan-scheduler.js +62 -0
  138. package/backend/dist/harness/{catalog-npm.d.ts → common/npm-catalog.d.ts} +5 -5
  139. package/backend/dist/harness/{catalog-npm.js → common/npm-catalog.js} +7 -7
  140. package/backend/dist/harness/common/npm-source.d.ts +29 -0
  141. package/backend/dist/harness/common/npm-source.js +121 -0
  142. package/backend/dist/harness/common/pypi-source.d.ts +28 -0
  143. package/backend/dist/harness/common/pypi-source.js +71 -0
  144. package/backend/dist/harness/common/source-views.d.ts +22 -0
  145. package/backend/dist/harness/common/source-views.js +25 -0
  146. package/backend/dist/harness/{stars.d.ts → common/stars.d.ts} +1 -1
  147. package/backend/dist/harness/{stars.js → common/stars.js} +2 -2
  148. package/backend/dist/harness/common/text.d.ts +11 -0
  149. package/backend/dist/harness/common/text.js +18 -0
  150. package/backend/dist/harness/config-file.d.ts +14 -1
  151. package/backend/dist/harness/config-file.js +38 -0
  152. package/backend/dist/harness/db-probe.d.ts +29 -0
  153. package/backend/dist/harness/db-probe.js +270 -0
  154. package/backend/dist/harness/detail.d.ts +10 -1
  155. package/backend/dist/harness/detail.js +144 -7
  156. package/backend/dist/harness/host/adapters/amp.d.ts +19 -0
  157. package/backend/dist/harness/host/adapters/amp.js +21 -0
  158. package/backend/dist/harness/host/adapters/antigravity.d.ts +18 -0
  159. package/backend/dist/harness/host/adapters/antigravity.js +21 -0
  160. package/backend/dist/harness/host/adapters/base.d.ts +225 -0
  161. package/backend/dist/harness/host/adapters/base.js +521 -0
  162. package/backend/dist/harness/host/adapters/claude.d.ts +54 -0
  163. package/backend/dist/harness/host/adapters/claude.js +145 -0
  164. package/backend/dist/harness/host/adapters/cline.d.ts +18 -0
  165. package/backend/dist/harness/host/adapters/cline.js +20 -0
  166. package/backend/dist/harness/host/adapters/codex.d.ts +54 -0
  167. package/backend/dist/harness/host/adapters/codex.js +133 -0
  168. package/backend/dist/harness/host/adapters/cursor.d.ts +18 -0
  169. package/backend/dist/harness/host/adapters/cursor.js +24 -0
  170. package/backend/dist/harness/host/adapters/declarative.d.ts +22 -0
  171. package/backend/dist/harness/host/adapters/declarative.js +38 -0
  172. package/backend/dist/harness/host/adapters/dsh.d.ts +76 -0
  173. package/backend/dist/harness/host/adapters/dsh.js +253 -0
  174. package/backend/dist/harness/host/adapters/factory.d.ts +36 -0
  175. package/backend/dist/harness/host/adapters/factory.js +34 -0
  176. package/backend/dist/harness/host/adapters/gemini-cli.d.ts +17 -0
  177. package/backend/dist/harness/host/adapters/gemini-cli.js +19 -0
  178. package/backend/dist/harness/host/adapters/grok.d.ts +66 -0
  179. package/backend/dist/harness/host/adapters/grok.js +136 -0
  180. package/backend/dist/harness/{adapters → host/adapters}/index.d.ts +9 -4
  181. package/backend/dist/harness/{adapters → host/adapters}/index.js +31 -10
  182. package/backend/dist/harness/host/adapters/kimi.d.ts +30 -0
  183. package/backend/dist/harness/host/adapters/kimi.js +59 -0
  184. package/backend/dist/harness/host/adapters/omp.d.ts +55 -0
  185. package/backend/dist/harness/host/adapters/omp.js +90 -0
  186. package/backend/dist/harness/host/adapters/openclaw.d.ts +54 -0
  187. package/backend/dist/harness/host/adapters/openclaw.js +141 -0
  188. package/backend/dist/harness/host/adapters/opencode.d.ts +24 -0
  189. package/backend/dist/harness/host/adapters/opencode.js +48 -0
  190. package/backend/dist/harness/host/adapters/pi.d.ts +27 -0
  191. package/backend/dist/harness/host/adapters/pi.js +58 -0
  192. package/backend/dist/harness/host/adapters/types.d.ts +395 -0
  193. package/backend/dist/harness/host/adapters/types.js +17 -0
  194. package/backend/dist/harness/host/adapters/universal.d.ts +14 -0
  195. package/backend/dist/harness/host/adapters/universal.js +18 -0
  196. package/backend/dist/harness/host/adapters/windsurf.d.ts +20 -0
  197. package/backend/dist/harness/host/adapters/windsurf.js +22 -0
  198. package/backend/dist/harness/host/adapters/zed.d.ts +12 -0
  199. package/backend/dist/harness/host/adapters/zed.js +14 -0
  200. package/backend/dist/harness/host/claude-mcp-runtime.d.ts +6 -0
  201. package/backend/dist/harness/host/claude-mcp-runtime.js +56 -0
  202. package/backend/dist/harness/{discover.d.ts → host/discover.d.ts} +54 -18
  203. package/backend/dist/harness/{discover.js → host/discover.js} +314 -53
  204. package/backend/dist/harness/{drift.d.ts → host/drift.d.ts} +1 -1
  205. package/backend/dist/harness/{drift.js → host/drift.js} +1 -1
  206. package/backend/dist/harness/host/grok-mcp-runtime.d.ts +6 -0
  207. package/backend/dist/harness/host/grok-mcp-runtime.js +56 -0
  208. package/backend/dist/harness/{hosts.d.ts → host/hosts.d.ts} +3 -3
  209. package/backend/dist/harness/{hosts.js → host/hosts.js} +7 -3
  210. package/backend/dist/harness/host/index.d.ts +10 -0
  211. package/backend/dist/harness/host/index.js +12 -0
  212. package/backend/dist/harness/host/install-log.d.ts +22 -0
  213. package/backend/dist/harness/host/install-log.js +106 -0
  214. package/backend/dist/harness/{install.d.ts → host/install.d.ts} +32 -13
  215. package/backend/dist/harness/{install.js → host/install.js} +133 -50
  216. package/backend/dist/harness/host/inventory.d.ts +30 -0
  217. package/backend/dist/harness/{inventory.js → host/inventory.js} +107 -16
  218. package/backend/dist/harness/host/kimi-mcp-runtime.d.ts +6 -0
  219. package/backend/dist/harness/host/kimi-mcp-runtime.js +84 -0
  220. package/backend/dist/harness/{ledger.d.ts → host/ledger.d.ts} +1 -1
  221. package/backend/dist/harness/{ledger.js → host/ledger.js} +3 -3
  222. package/backend/dist/harness/{maintenance.d.ts → host/maintenance.d.ts} +23 -6
  223. package/backend/dist/harness/{maintenance.js → host/maintenance.js} +355 -63
  224. package/backend/dist/harness/{manifest.d.ts → host/manifest.d.ts} +11 -2
  225. package/backend/dist/harness/{manifest.js → host/manifest.js} +76 -15
  226. package/backend/dist/harness/host/marketplace-sync.d.ts +64 -0
  227. package/backend/dist/harness/host/marketplace-sync.js +231 -0
  228. package/backend/dist/harness/host/mcp-cli.d.ts +44 -0
  229. package/backend/dist/harness/host/mcp-cli.js +545 -0
  230. package/backend/dist/harness/host/mcp-edit.d.ts +89 -0
  231. package/backend/dist/harness/host/mcp-edit.js +342 -0
  232. package/backend/dist/harness/host/mcp-entry.d.ts +100 -0
  233. package/backend/dist/harness/host/mcp-entry.js +435 -0
  234. package/backend/dist/harness/host/mcp-inspector.d.ts +125 -0
  235. package/backend/dist/harness/host/mcp-inspector.js +634 -0
  236. package/backend/dist/harness/host/mcp-registry.d.ts +66 -0
  237. package/backend/dist/harness/host/mcp-registry.js +331 -0
  238. package/backend/dist/harness/host/mcp-runtime.d.ts +19 -0
  239. package/backend/dist/harness/host/mcp-runtime.js +22 -0
  240. package/backend/dist/harness/host/opencode-mcp-runtime.d.ts +7 -0
  241. package/backend/dist/harness/host/opencode-mcp-runtime.js +73 -0
  242. package/backend/dist/harness/{probe.d.ts → host/probe.d.ts} +4 -4
  243. package/backend/dist/harness/{probe.js → host/probe.js} +8 -8
  244. package/backend/dist/harness/{registry.d.ts → host/registry.d.ts} +1 -1
  245. package/backend/dist/harness/host/registry.js +28 -0
  246. package/backend/dist/harness/host/request.d.ts +56 -0
  247. package/backend/dist/harness/host/request.js +1 -0
  248. package/backend/dist/harness/{sources → host/resolvers}/clawhub.d.ts +1 -1
  249. package/backend/dist/harness/{sources → host/resolvers}/clawhub.js +1 -1
  250. package/backend/dist/harness/host/resolvers/git-marketplace.d.ts +16 -0
  251. package/backend/dist/harness/host/resolvers/git-marketplace.js +53 -0
  252. package/backend/dist/harness/{sources → host/resolvers}/github.d.ts +1 -1
  253. package/backend/dist/harness/{sources → host/resolvers}/github.js +2 -2
  254. package/backend/dist/harness/host/resolvers/npm.d.ts +2 -0
  255. package/backend/dist/harness/{sources → host/resolvers}/npm.js +16 -10
  256. package/backend/dist/harness/host/resolvers/pypi.d.ts +2 -0
  257. package/backend/dist/harness/host/resolvers/pypi.js +100 -0
  258. package/backend/dist/harness/host/scopes.d.ts +11 -0
  259. package/backend/dist/harness/host/scopes.js +12 -0
  260. package/backend/dist/harness/host/timeouts.d.ts +8 -0
  261. package/backend/dist/harness/host/timeouts.js +8 -0
  262. package/backend/dist/harness/host/writers/kimi-web.d.ts +70 -0
  263. package/backend/dist/harness/host/writers/kimi-web.js +222 -0
  264. package/backend/dist/harness/host/writers/mcp.d.ts +119 -0
  265. package/backend/dist/harness/host/writers/mcp.js +359 -0
  266. package/backend/dist/harness/host/writers/plugin.d.ts +176 -0
  267. package/backend/dist/harness/host/writers/plugin.js +528 -0
  268. package/backend/dist/harness/{writers → host/writers}/skill.d.ts +3 -3
  269. package/backend/dist/harness/{writers → host/writers}/skill.js +6 -3
  270. package/backend/dist/harness/lang.d.ts +14 -0
  271. package/backend/dist/harness/lang.js +33 -0
  272. package/backend/dist/harness/net.d.ts +33 -0
  273. package/backend/dist/harness/net.js +63 -0
  274. package/backend/dist/harness/plugin/adapters/antigravity.d.ts +11 -0
  275. package/backend/dist/harness/plugin/adapters/antigravity.js +14 -0
  276. package/backend/dist/harness/plugin/adapters/base.d.ts +107 -0
  277. package/backend/dist/harness/plugin/adapters/base.js +454 -0
  278. package/backend/dist/harness/plugin/adapters/claude.d.ts +28 -0
  279. package/backend/dist/harness/plugin/adapters/claude.js +63 -0
  280. package/backend/dist/harness/plugin/adapters/codex.d.ts +13 -0
  281. package/backend/dist/harness/plugin/adapters/codex.js +16 -0
  282. package/backend/dist/harness/plugin/adapters/cursor.d.ts +13 -0
  283. package/backend/dist/harness/plugin/adapters/cursor.js +16 -0
  284. package/backend/dist/harness/plugin/adapters/dsh-plugin-net.d.ts +20 -0
  285. package/backend/dist/harness/plugin/adapters/dsh-plugin-net.js +371 -0
  286. package/backend/dist/harness/plugin/adapters/dsh.d.ts +22 -0
  287. package/backend/dist/harness/plugin/adapters/dsh.js +50 -0
  288. package/backend/dist/harness/plugin/adapters/factory.d.ts +11 -0
  289. package/backend/dist/harness/plugin/adapters/factory.js +19 -0
  290. package/backend/dist/harness/plugin/adapters/gemini.d.ts +12 -0
  291. package/backend/dist/harness/plugin/adapters/gemini.js +22 -0
  292. package/backend/dist/harness/plugin/adapters/grok.d.ts +15 -0
  293. package/backend/dist/harness/plugin/adapters/grok.js +23 -0
  294. package/backend/dist/harness/plugin/adapters/index.d.ts +41 -0
  295. package/backend/dist/harness/plugin/adapters/index.js +143 -0
  296. package/backend/dist/harness/plugin/adapters/kimi.d.ts +6 -0
  297. package/backend/dist/harness/plugin/adapters/kimi.js +35 -0
  298. package/backend/dist/harness/plugin/adapters/omp.d.ts +19 -0
  299. package/backend/dist/harness/plugin/adapters/omp.js +26 -0
  300. package/backend/dist/harness/plugin/adapters/openclaw.d.ts +20 -0
  301. package/backend/dist/harness/plugin/adapters/openclaw.js +36 -0
  302. package/backend/dist/harness/plugin/adapters/pi-dev.d.ts +124 -0
  303. package/backend/dist/harness/plugin/adapters/pi-dev.js +420 -0
  304. package/backend/dist/harness/plugin/adapters/pi-github.d.ts +18 -0
  305. package/backend/dist/harness/plugin/adapters/pi-github.js +27 -0
  306. package/backend/dist/harness/plugin/adapters/universal.d.ts +11 -0
  307. package/backend/dist/harness/plugin/adapters/universal.js +18 -0
  308. package/backend/dist/harness/plugin/builtin.d.ts +13 -0
  309. package/backend/dist/harness/plugin/builtin.js +34 -0
  310. package/backend/dist/harness/plugin/catalog.d.ts +30 -0
  311. package/backend/dist/harness/plugin/catalog.js +200 -0
  312. package/backend/dist/harness/plugin/index.d.ts +9 -0
  313. package/backend/dist/harness/plugin/index.js +9 -0
  314. package/backend/dist/harness/plugin/types.d.ts +164 -0
  315. package/backend/dist/harness/plugin/types.js +1 -0
  316. package/backend/dist/harness/{clawhub.d.ts → skill/clawhub.d.ts} +28 -5
  317. package/backend/dist/harness/{clawhub.js → skill/clawhub.js} +170 -5
  318. package/backend/dist/harness/skill/skills-sh.d.ts +47 -0
  319. package/backend/dist/harness/skill/skills-sh.js +270 -0
  320. package/backend/dist/harness/skill/sources.d.ts +41 -0
  321. package/backend/dist/harness/skill/sources.js +131 -0
  322. package/backend/dist/harness/spi.d.ts +11 -7
  323. package/backend/dist/harness/tcp-reach.d.ts +30 -0
  324. package/backend/dist/harness/tcp-reach.js +61 -0
  325. package/backend/dist/harness/translation.d.ts +31 -13
  326. package/backend/dist/harness/translation.js +202 -60
  327. package/backend/dist/harness/types.d.ts +61 -16
  328. package/backend/dist/index.js +170 -16
  329. package/backend/dist/ir/adapters/anthropic-messages-stream.d.ts +18 -0
  330. package/backend/dist/ir/adapters/anthropic-messages-stream.js +266 -0
  331. package/backend/dist/ir/adapters/anthropic-messages.d.ts +30 -0
  332. package/backend/dist/ir/adapters/anthropic-messages.js +870 -0
  333. package/backend/dist/ir/adapters/google-gemini-stream.d.ts +22 -0
  334. package/backend/dist/ir/adapters/google-gemini-stream.js +246 -0
  335. package/backend/dist/ir/adapters/google-gemini.d.ts +9 -0
  336. package/backend/dist/ir/adapters/google-gemini.js +450 -0
  337. package/backend/dist/ir/adapters/openai-chat-stream.d.ts +41 -0
  338. package/backend/dist/ir/adapters/openai-chat-stream.js +369 -0
  339. package/backend/dist/ir/adapters/openai-chat.d.ts +17 -0
  340. package/backend/dist/ir/adapters/openai-chat.js +670 -0
  341. package/backend/dist/ir/adapters/openai-responses-output.d.ts +50 -0
  342. package/backend/dist/ir/adapters/openai-responses-output.js +353 -0
  343. package/backend/dist/ir/adapters/openai-responses-stream.d.ts +12 -0
  344. package/backend/dist/ir/adapters/openai-responses-stream.js +193 -0
  345. package/backend/dist/ir/adapters/openai-responses.d.ts +14 -0
  346. package/backend/dist/ir/adapters/openai-responses.js +670 -0
  347. package/backend/dist/ir/capabilities.d.ts +41 -0
  348. package/backend/dist/ir/capabilities.js +147 -0
  349. package/backend/dist/ir/errors.d.ts +23 -0
  350. package/backend/dist/ir/errors.js +31 -0
  351. package/backend/dist/ir/index.d.ts +5 -0
  352. package/backend/dist/ir/index.js +5 -0
  353. package/backend/dist/ir/media.d.ts +2 -0
  354. package/backend/dist/ir/media.js +2 -0
  355. package/backend/dist/ir/stream.d.ts +17 -0
  356. package/backend/dist/ir/stream.js +250 -0
  357. package/backend/dist/ir/types.d.ts +523 -0
  358. package/backend/dist/ir/types.js +19 -0
  359. package/backend/dist/ir/validate.d.ts +18 -0
  360. package/backend/dist/ir/validate.js +272 -0
  361. package/backend/dist/metrics/request-cost.d.ts +3 -11
  362. package/backend/dist/metrics/request-cost.js +9 -27
  363. package/backend/dist/observability/failure-events.d.ts +20 -4
  364. package/backend/dist/observability/failure-events.js +9 -1
  365. package/backend/dist/observability/http-exchange.d.ts +75 -27
  366. package/backend/dist/observability/http-exchange.js +136 -39
  367. package/backend/dist/observability/request-identity.d.ts +40 -0
  368. package/backend/dist/observability/request-identity.js +102 -0
  369. package/backend/dist/observability/traffic-live-hidden.d.ts +24 -0
  370. package/backend/dist/observability/traffic-live-hidden.js +82 -0
  371. package/backend/dist/observability/upstream-body-redaction.d.ts +23 -0
  372. package/backend/dist/observability/upstream-body-redaction.js +72 -0
  373. package/backend/dist/observability/upstream-events.d.ts +16 -10
  374. package/backend/dist/observability/upstream-events.js +17 -11
  375. package/backend/dist/opencode/agents.d.ts +3 -2
  376. package/backend/dist/opencode/catalog/auto-pull.d.ts +35 -1
  377. package/backend/dist/opencode/catalog/auto-pull.js +169 -33
  378. package/backend/dist/opencode/catalog/ocr-store.d.ts +6 -6
  379. package/backend/dist/opencode/catalog/ocr-store.js +2 -2
  380. package/backend/dist/opencode/catalog/overrides-store.d.ts +6 -5
  381. package/backend/dist/opencode/catalog/overrides-store.js +28 -3
  382. package/backend/dist/opencode/catalog/repository.d.ts +4 -0
  383. package/backend/dist/opencode/catalog/repository.js +19 -0
  384. package/backend/dist/opencode/catalog/sources/models-dev.d.ts +4 -0
  385. package/backend/dist/opencode/catalog/sources/models-dev.js +15 -4
  386. package/backend/dist/opencode/catalog/types.d.ts +10 -7
  387. package/backend/dist/opencode/connector.d.ts +2 -2
  388. package/backend/dist/opencode/connector.js +2 -2
  389. package/backend/dist/opencode/credentials/def-materialize.d.ts +0 -5
  390. package/backend/dist/opencode/credentials/def-materialize.js +149 -11
  391. package/backend/dist/opencode/credentials/ocr-store.d.ts +18 -0
  392. package/backend/dist/opencode/credentials/ocr-store.js +88 -7
  393. package/backend/dist/opencode/credentials/opencode-v2-store.d.ts +24 -13
  394. package/backend/dist/opencode/credentials/opencode-v2-store.js +70 -29
  395. package/backend/dist/opencode/credentials/paths.d.ts +8 -0
  396. package/backend/dist/opencode/credentials/paths.js +10 -0
  397. package/backend/dist/opencode/credentials/sync.d.ts +1 -1
  398. package/backend/dist/opencode/credentials/sync.js +4 -4
  399. package/backend/dist/opencode/credentials/types.d.ts +40 -4
  400. package/backend/dist/opencode/probe.d.ts +9 -5
  401. package/backend/dist/opencode/probe.js +68 -15
  402. package/backend/dist/opencode/provider-defs.js +59 -2
  403. package/backend/dist/opencode/provider-package.d.ts +31 -0
  404. package/backend/dist/opencode/provider-package.js +70 -0
  405. package/backend/dist/opencode/user-config.d.ts +11 -17
  406. package/backend/dist/opencode/user-config.js +42 -66
  407. package/backend/dist/pipeline/credential-selection.d.ts +13 -0
  408. package/backend/dist/pipeline/credential-selection.js +29 -1
  409. package/backend/dist/pipeline/directives.d.ts +14 -22
  410. package/backend/dist/pipeline/directives.js +122 -68
  411. package/backend/dist/pipeline/orchestrator.d.ts +42 -7
  412. package/backend/dist/pipeline/orchestrator.js +736 -266
  413. package/backend/dist/pipeline/prompt-optimizer.d.ts +6 -13
  414. package/backend/dist/pipeline/prompt-optimizer.js +9 -52
  415. package/backend/dist/pipeline/streaming-posture.d.ts +29 -0
  416. package/backend/dist/pipeline/streaming-posture.js +27 -0
  417. package/backend/dist/pipeline/tool-pairing.d.ts +10 -0
  418. package/backend/dist/pipeline/tool-pairing.js +90 -0
  419. package/backend/dist/plugins/builtin/model-gateway.d.ts +30 -0
  420. package/backend/dist/plugins/builtin/model-gateway.js +98 -0
  421. package/backend/dist/plugins/config.d.ts +41 -0
  422. package/backend/dist/plugins/config.js +113 -0
  423. package/backend/dist/plugins/gateways.d.ts +98 -0
  424. package/backend/dist/plugins/gateways.js +151 -0
  425. package/backend/dist/plugins/host.d.ts +203 -0
  426. package/backend/dist/plugins/host.js +1310 -0
  427. package/backend/dist/plugins/manifest.d.ts +43 -0
  428. package/backend/dist/plugins/manifest.js +462 -0
  429. package/backend/dist/plugins/pack.d.ts +32 -0
  430. package/backend/dist/plugins/pack.js +222 -0
  431. package/backend/dist/plugins/seed.d.ts +53 -0
  432. package/backend/dist/plugins/seed.js +136 -0
  433. package/backend/dist/plugins/types.d.ts +721 -0
  434. package/backend/dist/plugins/types.js +1 -0
  435. package/backend/dist/projects/store.d.ts +56 -0
  436. package/backend/dist/projects/store.js +194 -0
  437. package/backend/dist/projects/types.d.ts +12 -0
  438. package/backend/dist/projects/types.js +1 -0
  439. package/backend/dist/protocols/chat-compat.d.ts +2 -0
  440. package/backend/dist/protocols/chat-compat.js +137 -0
  441. package/backend/dist/protocols/systemone/convert.d.ts +5 -4
  442. package/backend/dist/protocols/systemone/convert.js +72 -26
  443. package/backend/dist/protocols/systemone/decide.js +128 -51
  444. package/backend/dist/protocols/systemone/native.d.ts +1 -1
  445. package/backend/dist/protocols/systemone/native.js +6 -6
  446. package/backend/dist/providers/anthropic.js +6 -6
  447. package/backend/dist/providers/base.d.ts +8 -47
  448. package/backend/dist/providers/boot-direct.d.ts +20 -2
  449. package/backend/dist/providers/boot-direct.js +72 -23
  450. package/backend/dist/providers/compat/tool-markup-leak.d.ts +41 -0
  451. package/backend/dist/providers/compat/tool-markup-leak.js +57 -0
  452. package/backend/dist/providers/compat/tool-markup-recovery.d.ts +27 -0
  453. package/backend/dist/providers/compat/tool-markup-recovery.js +831 -0
  454. package/backend/dist/providers/dispatch.d.ts +5 -8
  455. package/backend/dist/providers/dispatch.js +18 -12
  456. package/backend/dist/providers/executors/anthropic-messages.d.ts +12 -0
  457. package/backend/dist/providers/executors/anthropic-messages.js +56 -0
  458. package/backend/dist/providers/executors/dispatch.d.ts +14 -0
  459. package/backend/dist/providers/executors/dispatch.js +71 -0
  460. package/backend/dist/providers/executors/google-gemini.d.ts +12 -0
  461. package/backend/dist/providers/executors/google-gemini.js +53 -0
  462. package/backend/dist/providers/executors/http-json.d.ts +19 -0
  463. package/backend/dist/providers/executors/http-json.js +125 -0
  464. package/backend/dist/providers/executors/http-stream.d.ts +53 -0
  465. package/backend/dist/providers/executors/http-stream.js +472 -0
  466. package/backend/dist/providers/executors/openai-chat.d.ts +13 -0
  467. package/backend/dist/providers/executors/openai-chat.js +89 -0
  468. package/backend/dist/providers/executors/openai-responses.d.ts +12 -0
  469. package/backend/dist/providers/executors/openai-responses.js +71 -0
  470. package/backend/dist/providers/executors/plugin-adapter.d.ts +9 -0
  471. package/backend/dist/providers/executors/plugin-adapter.js +31 -0
  472. package/backend/dist/providers/google.js +6 -6
  473. package/backend/dist/providers/openai-compatible.js +13 -13
  474. package/backend/dist/providers/opencode-proxy.js +6 -6
  475. package/backend/dist/providers/plugin-wires.d.ts +34 -0
  476. package/backend/dist/providers/plugin-wires.js +82 -0
  477. package/backend/dist/providers/pool-refresh.d.ts +14 -0
  478. package/backend/dist/providers/pool-refresh.js +13 -0
  479. package/backend/dist/providers/protocol.d.ts +4 -0
  480. package/backend/dist/providers/protocol.js +61 -0
  481. package/backend/dist/providers/provider-takedown.d.ts +59 -0
  482. package/backend/dist/providers/provider-takedown.js +135 -0
  483. package/backend/dist/providers/registry.d.ts +37 -21
  484. package/backend/dist/providers/registry.js +204 -109
  485. package/backend/dist/providers/responses.d.ts +4 -2
  486. package/backend/dist/providers/responses.js +12 -9
  487. package/backend/dist/providers/vocabulary.d.ts +24 -6
  488. package/backend/dist/providers/vocabulary.js +75 -33
  489. package/backend/dist/providers/wire.d.ts +12 -17
  490. package/backend/dist/providers/wire.js +43 -91
  491. package/backend/dist/proxy/manual-node-spec.d.ts +92 -0
  492. package/backend/dist/proxy/manual-node-spec.js +408 -0
  493. package/backend/dist/proxy/mihomo-binary.d.ts +39 -0
  494. package/backend/dist/proxy/mihomo-binary.js +267 -0
  495. package/backend/dist/proxy/mihomo-client.d.ts +94 -0
  496. package/backend/dist/proxy/mihomo-client.js +294 -0
  497. package/backend/dist/proxy/mihomo-config.d.ts +40 -0
  498. package/backend/dist/proxy/mihomo-config.js +152 -0
  499. package/backend/dist/proxy/mihomo-pac.d.ts +26 -0
  500. package/backend/dist/proxy/mihomo-pac.js +60 -0
  501. package/backend/dist/proxy/mihomo-rules-import.d.ts +43 -0
  502. package/backend/dist/proxy/mihomo-rules-import.js +193 -0
  503. package/backend/dist/proxy/mihomo-sidecar.d.ts +65 -0
  504. package/backend/dist/proxy/mihomo-sidecar.js +515 -0
  505. package/backend/dist/quota/engine.d.ts +9 -2
  506. package/backend/dist/quota/engine.js +19 -1
  507. package/backend/dist/quota/prober.d.ts +8 -4
  508. package/backend/dist/quota/prober.js +9 -10
  509. package/backend/dist/ratelimit/rate-limiter.d.ts +119 -6
  510. package/backend/dist/ratelimit/rate-limiter.js +358 -20
  511. package/backend/dist/ratelimit/window-store.d.ts +34 -0
  512. package/backend/dist/ratelimit/window-store.js +70 -0
  513. package/backend/dist/resilience/breaker-state.js +8 -1
  514. package/backend/dist/resilience/circuit-breaker-manager.d.ts +229 -132
  515. package/backend/dist/resilience/circuit-breaker-manager.js +566 -297
  516. package/backend/dist/resilience/circuit-breaker.d.ts +11 -0
  517. package/backend/dist/resilience/circuit-breaker.js +39 -7
  518. package/backend/dist/resilience/error-classifier.d.ts +31 -3
  519. package/backend/dist/resilience/error-classifier.js +159 -31
  520. package/backend/dist/resilience/health-prober.d.ts +21 -4
  521. package/backend/dist/resilience/health-prober.js +100 -18
  522. package/backend/dist/resilience/types.d.ts +56 -9
  523. package/backend/dist/resilience/types.js +1 -1
  524. package/backend/dist/router/index.d.ts +6 -29
  525. package/backend/dist/router/index.js +15 -61
  526. package/backend/dist/router/layer2-decision.d.ts +2 -2
  527. package/backend/dist/router/layer2-decision.js +22 -19
  528. package/backend/dist/router/request-traits.d.ts +4 -11
  529. package/backend/dist/router/request-traits.js +5 -13
  530. package/backend/dist/routes/console.js +1948 -253
  531. package/backend/dist/routes/environments.d.ts +3 -2
  532. package/backend/dist/routes/environments.js +8 -4
  533. package/backend/dist/routes/harness.d.ts +3 -1
  534. package/backend/dist/routes/harness.js +1162 -356
  535. package/backend/dist/routes/mihomo.d.ts +5 -0
  536. package/backend/dist/routes/mihomo.js +882 -0
  537. package/backend/dist/routes/projects.d.ts +2 -0
  538. package/backend/dist/routes/projects.js +90 -0
  539. package/backend/dist/routes/responses.d.ts +20 -1
  540. package/backend/dist/routes/responses.js +65 -3
  541. package/backend/dist/routes/translation.d.ts +9 -0
  542. package/backend/dist/routes/translation.js +155 -0
  543. package/backend/dist/server.js +353 -67
  544. package/backend/dist/session/resp-store.d.ts +18 -49
  545. package/backend/dist/session/resp-store.js +114 -122
  546. package/backend/dist/session/session-manager.d.ts +222 -81
  547. package/backend/dist/session/session-manager.js +428 -180
  548. package/backend/dist/session/session-row.d.ts +81 -2
  549. package/backend/dist/session/session-row.js +69 -1
  550. package/backend/dist/surfaces/anthropic.d.ts +1 -15
  551. package/backend/dist/surfaces/anthropic.js +63 -44
  552. package/backend/dist/surfaces/chat-pipeline.d.ts +8 -4
  553. package/backend/dist/surfaces/chat-pipeline.js +102 -35
  554. package/backend/dist/surfaces/chat.d.ts +1 -9
  555. package/backend/dist/surfaces/chat.js +52 -29
  556. package/backend/dist/surfaces/decision-pipeline.js +26 -18
  557. package/backend/dist/surfaces/gateway-chat.d.ts +53 -0
  558. package/backend/dist/surfaces/gateway-chat.js +204 -0
  559. package/backend/dist/surfaces/ocr-headers.d.ts +25 -4
  560. package/backend/dist/surfaces/ocr-headers.js +52 -6
  561. package/backend/dist/surfaces/responses.d.ts +9 -1
  562. package/backend/dist/surfaces/responses.js +141 -141
  563. package/backend/dist/surfaces/systemone-probe.js +1 -1
  564. package/backend/dist/surfaces/systemone.d.ts +1 -1
  565. package/backend/dist/surfaces/systemone.js +1 -1
  566. package/backend/dist/surfaces/table.d.ts +15 -0
  567. package/backend/dist/surfaces/table.js +15 -0
  568. package/backend/dist/surfaces/transport-backpressure.d.ts +46 -0
  569. package/backend/dist/surfaces/transport-backpressure.js +122 -0
  570. package/backend/dist/surfaces/transport-fastify.js +92 -21
  571. package/backend/dist/surfaces/transport-node-http.js +92 -18
  572. package/backend/dist/surfaces/types.d.ts +74 -12
  573. package/backend/dist/trace/persist.d.ts +5 -0
  574. package/backend/dist/trace/persist.js +185 -24
  575. package/backend/dist/trace/tracker.d.ts +153 -16
  576. package/backend/dist/trace/tracker.js +77 -27
  577. package/backend/dist/translation/index.d.ts +151 -0
  578. package/backend/dist/translation/index.js +735 -0
  579. package/backend/dist/types/openai.d.ts +82 -1
  580. package/backend/dist/types/router.d.ts +71 -6
  581. package/backend/dist/types/router.js +33 -1
  582. package/backend/dist/update/check.d.ts +43 -0
  583. package/backend/dist/update/check.js +126 -0
  584. package/backend/dist/utils/chat-sse.d.ts +2 -22
  585. package/backend/dist/utils/chat-sse.js +1 -69
  586. package/backend/dist/utils/chat-stream.d.ts +2 -1
  587. package/backend/dist/utils/client-envelope.d.ts +108 -0
  588. package/backend/dist/utils/client-envelope.js +305 -0
  589. package/backend/dist/utils/event-ring.d.ts +8 -1
  590. package/backend/dist/utils/event-ring.js +13 -5
  591. package/backend/dist/utils/harness-profiles.d.ts +51 -0
  592. package/backend/dist/utils/harness-profiles.js +70 -0
  593. package/backend/dist/utils/percentile.d.ts +16 -0
  594. package/backend/dist/utils/percentile.js +29 -0
  595. package/backend/dist/utils/popularity.d.ts +4 -0
  596. package/backend/dist/utils/popularity.js +33 -0
  597. package/backend/dist/utils/probe-interval.d.ts +12 -0
  598. package/backend/dist/utils/probe-interval.js +16 -0
  599. package/backend/dist/utils/proxy-node.d.ts +13 -0
  600. package/backend/dist/utils/proxy-node.js +471 -0
  601. package/backend/dist/utils/proxy.d.ts +12 -0
  602. package/backend/dist/utils/proxy.js +44 -4
  603. package/backend/dist/utils/run-command.d.ts +42 -0
  604. package/backend/dist/utils/run-command.js +93 -0
  605. package/backend/dist/utils/self-url.d.ts +13 -0
  606. package/backend/dist/utils/self-url.js +90 -2
  607. package/backend/dist/utils/semver.d.ts +22 -0
  608. package/backend/dist/utils/semver.js +75 -0
  609. package/backend/dist/utils/stream-relay.d.ts +35 -0
  610. package/backend/dist/utils/stream-relay.js +1 -0
  611. package/backend/dist/utils/upstream-url-guard.d.ts +15 -0
  612. package/backend/dist/utils/upstream-url-guard.js +107 -0
  613. package/backend/dist/validator/parser.d.ts +2 -5
  614. package/backend/dist/validator/parser.js +12 -16
  615. package/backend/dist/validator/schema-assertion.d.ts +3 -2
  616. package/backend/dist/validator/schema-assertion.js +53 -8
  617. package/frontend/dist/assets/index-CLvxJjp_.js +1476 -0
  618. package/frontend/dist/assets/index-CQSLGFTV.css +1 -0
  619. package/frontend/dist/assets/qoder.color-tVX5GCcD.svg +5 -0
  620. package/frontend/dist/index.html +2 -2
  621. package/frontend/dist/provider-logos/302ai.svg +7 -0
  622. package/frontend/dist/provider-logos/NOTICE.txt +39 -0
  623. package/frontend/dist/provider-logos/abacus.svg +14 -0
  624. package/frontend/dist/provider-logos/abliteration-ai.svg +6 -0
  625. package/frontend/dist/provider-logos/above.svg +3 -0
  626. package/frontend/dist/provider-logos/agentrouter.svg +4 -0
  627. package/frontend/dist/provider-logos/agnes.svg +1 -0
  628. package/frontend/dist/provider-logos/ai-router.svg +5 -0
  629. package/frontend/dist/provider-logos/ai21.svg +3 -0
  630. package/frontend/dist/provider-logos/aiand.svg +4 -0
  631. package/frontend/dist/provider-logos/aihubmix.svg +3 -0
  632. package/frontend/dist/provider-logos/aimlapi.svg +3 -0
  633. package/frontend/dist/provider-logos/ainetcafe.svg +1 -0
  634. package/frontend/dist/provider-logos/aixy.svg +4 -0
  635. package/frontend/dist/provider-logos/aki-io.svg +8 -0
  636. package/frontend/dist/provider-logos/alibaba-cn.svg +3 -0
  637. package/frontend/dist/provider-logos/alibaba-coding-plan-cn.svg +3 -0
  638. package/frontend/dist/provider-logos/alibaba-coding-plan.svg +3 -0
  639. package/frontend/dist/provider-logos/alibaba-token-plan-cn.svg +1 -0
  640. package/frontend/dist/provider-logos/alibaba-token-plan.svg +1 -0
  641. package/frontend/dist/provider-logos/alibaba.svg +3 -0
  642. package/frontend/dist/provider-logos/amazon-bedrock.svg +3 -0
  643. package/frontend/dist/provider-logos/ambient.svg +3 -0
  644. package/frontend/dist/provider-logos/amd.svg +3 -0
  645. package/frontend/dist/provider-logos/anthropic.svg +3 -0
  646. package/frontend/dist/provider-logos/anyapi.svg +3 -0
  647. package/frontend/dist/provider-logos/arcee.svg +3 -0
  648. package/frontend/dist/provider-logos/atomic-chat.svg +1 -0
  649. package/frontend/dist/provider-logos/auriko.svg +6 -0
  650. package/frontend/dist/provider-logos/azure-cognitive-services.svg +3 -0
  651. package/frontend/dist/provider-logos/azure.svg +3 -0
  652. package/frontend/dist/provider-logos/bailing.svg +3 -0
  653. package/frontend/dist/provider-logos/baseten.svg +3 -0
  654. package/frontend/dist/provider-logos/bee.svg +1 -0
  655. package/frontend/dist/provider-logos/berget.svg +3 -0
  656. package/frontend/dist/provider-logos/blueclaw.svg +3 -0
  657. package/frontend/dist/provider-logos/bothub.svg +33 -0
  658. package/frontend/dist/provider-logos/boundless.svg +12 -0
  659. package/frontend/dist/provider-logos/cerebras.svg +4 -0
  660. package/frontend/dist/provider-logos/chutes.svg +24 -0
  661. package/frontend/dist/provider-logos/clarifai.svg +3 -0
  662. package/frontend/dist/provider-logos/claudinio.svg +19 -0
  663. package/frontend/dist/provider-logos/cline-pass.svg +24 -0
  664. package/frontend/dist/provider-logos/cloudferro-sherlock.svg +5 -0
  665. package/frontend/dist/provider-logos/cloudflare-ai-gateway.svg +4 -0
  666. package/frontend/dist/provider-logos/cloudflare-workers-ai.svg +4 -0
  667. package/frontend/dist/provider-logos/cohere.svg +5 -0
  668. package/frontend/dist/provider-logos/commandcode.svg +11 -0
  669. package/frontend/dist/provider-logos/coralbricks.svg +6 -0
  670. package/frontend/dist/provider-logos/cortecs.svg +24 -0
  671. package/frontend/dist/provider-logos/crossmodel.svg +5 -0
  672. package/frontend/dist/provider-logos/crusoe.svg +23 -0
  673. package/frontend/dist/provider-logos/daoxe.svg +3 -0
  674. package/frontend/dist/provider-logos/databricks.svg +3 -0
  675. package/frontend/dist/provider-logos/deepinfra.svg +4 -0
  676. package/frontend/dist/provider-logos/deepseek.svg +3 -0
  677. package/frontend/dist/provider-logos/digitalocean.svg +6 -0
  678. package/frontend/dist/provider-logos/dinference.svg +1 -0
  679. package/frontend/dist/provider-logos/drun.svg +8 -0
  680. package/frontend/dist/provider-logos/ebcloud.svg +8 -0
  681. package/frontend/dist/provider-logos/echo.svg +7 -0
  682. package/frontend/dist/provider-logos/edenai.svg +8 -0
  683. package/frontend/dist/provider-logos/empiriolabs.svg +1 -0
  684. package/frontend/dist/provider-logos/engy.svg +1 -0
  685. package/frontend/dist/provider-logos/evroc.svg +3 -0
  686. package/frontend/dist/provider-logos/fastrouter.svg +3 -0
  687. package/frontend/dist/provider-logos/fireworks-ai.svg +3 -0
  688. package/frontend/dist/provider-logos/freemodel.svg +3 -0
  689. package/frontend/dist/provider-logos/friendli.svg +3 -0
  690. package/frontend/dist/provider-logos/frogbot.svg +36 -0
  691. package/frontend/dist/provider-logos/github-copilot.svg +3 -0
  692. package/frontend/dist/provider-logos/gitlab.svg +3 -0
  693. package/frontend/dist/provider-logos/gmicloud.svg +24 -0
  694. package/frontend/dist/provider-logos/google-vertex-anthropic.svg +10 -0
  695. package/frontend/dist/provider-logos/google-vertex.svg +10 -0
  696. package/frontend/dist/provider-logos/google.svg +3 -0
  697. package/frontend/dist/provider-logos/greenpt.svg +6 -0
  698. package/frontend/dist/provider-logos/groq.svg +3 -0
  699. package/frontend/dist/provider-logos/helicone.svg +6 -0
  700. package/frontend/dist/provider-logos/hetzner.svg +3 -0
  701. package/frontend/dist/provider-logos/hopper.svg +4 -0
  702. package/frontend/dist/provider-logos/hpc-ai.svg +446 -0
  703. package/frontend/dist/provider-logos/huggingface.svg +3 -0
  704. package/frontend/dist/provider-logos/hyper.svg +20 -0
  705. package/frontend/dist/provider-logos/impossibl.svg +3 -0
  706. package/frontend/dist/provider-logos/inception.svg +14 -0
  707. package/frontend/dist/provider-logos/inceptron.svg +14 -0
  708. package/frontend/dist/provider-logos/inco.svg +3 -0
  709. package/frontend/dist/provider-logos/infer.svg +4 -0
  710. package/frontend/dist/provider-logos/inference.svg +3 -0
  711. package/frontend/dist/provider-logos/inferx.svg +5 -0
  712. package/frontend/dist/provider-logos/infomaniak.svg +3 -0
  713. package/frontend/dist/provider-logos/io-net.svg +5 -0
  714. package/frontend/dist/provider-logos/iteracompute.svg +7 -0
  715. package/frontend/dist/provider-logos/jalapeno.svg +8 -0
  716. package/frontend/dist/provider-logos/jiekou.svg +4 -0
  717. package/frontend/dist/provider-logos/kenari.svg +4 -0
  718. package/frontend/dist/provider-logos/kilo.svg +4 -0
  719. package/frontend/dist/provider-logos/kimi-code-plan-cn.svg +3 -0
  720. package/frontend/dist/provider-logos/kimi-code-plan-global.svg +3 -0
  721. package/frontend/dist/provider-logos/klokintegration.svg +11 -0
  722. package/frontend/dist/provider-logos/kosmik.svg +28 -0
  723. package/frontend/dist/provider-logos/kuae-cloud-coding-plan.svg +3 -0
  724. package/frontend/dist/provider-logos/lilac.svg +6 -0
  725. package/frontend/dist/provider-logos/liquid.svg +1 -0
  726. package/frontend/dist/provider-logos/llmgateway-providers.svg +6 -0
  727. package/frontend/dist/provider-logos/llmgateway.svg +6 -0
  728. package/frontend/dist/provider-logos/llmtech.svg +6 -0
  729. package/frontend/dist/provider-logos/llmtr.svg +12 -0
  730. package/frontend/dist/provider-logos/lmstudio.svg +3 -0
  731. package/frontend/dist/provider-logos/longcat.svg +6 -0
  732. package/frontend/dist/provider-logos/lowrouter.svg +8 -0
  733. package/frontend/dist/provider-logos/lucidquery.svg +3 -0
  734. package/frontend/dist/provider-logos/lynkr.svg +1 -0
  735. package/frontend/dist/provider-logos/meganova.svg +3 -0
  736. package/frontend/dist/provider-logos/melious.svg +3 -0
  737. package/frontend/dist/provider-logos/merge-gateway.svg +4 -0
  738. package/frontend/dist/provider-logos/meta.svg +3 -0
  739. package/frontend/dist/provider-logos/minimax-cn-coding-plan.svg +3 -0
  740. package/frontend/dist/provider-logos/minimax-cn.svg +3 -0
  741. package/frontend/dist/provider-logos/minimax-coding-plan.svg +3 -0
  742. package/frontend/dist/provider-logos/minimax.svg +3 -0
  743. package/frontend/dist/provider-logos/mistral.svg +3 -0
  744. package/frontend/dist/provider-logos/mixlayer.svg +9 -0
  745. package/frontend/dist/provider-logos/moark.svg +3 -0
  746. package/frontend/dist/provider-logos/modal.svg +3 -0
  747. package/frontend/dist/provider-logos/model-oracle-ai.svg +11 -0
  748. package/frontend/dist/provider-logos/modelis.svg +1 -0
  749. package/frontend/dist/provider-logos/modelscope.svg +5 -0
  750. package/frontend/dist/provider-logos/modular.svg +3 -0
  751. package/frontend/dist/provider-logos/moonshotai-cn.svg +3 -0
  752. package/frontend/dist/provider-logos/moonshotai.svg +3 -0
  753. package/frontend/dist/provider-logos/morph.svg +24 -0
  754. package/frontend/dist/provider-logos/munito-eu.svg +1 -0
  755. package/frontend/dist/provider-logos/munito.svg +1 -0
  756. package/frontend/dist/provider-logos/nan.svg +1 -0
  757. package/frontend/dist/provider-logos/nano-gpt.svg +3 -0
  758. package/frontend/dist/provider-logos/nearai.svg +1 -0
  759. package/frontend/dist/provider-logos/nebius.svg +4 -0
  760. package/frontend/dist/provider-logos/neon.svg +3 -0
  761. package/frontend/dist/provider-logos/neosmith.svg +6 -0
  762. package/frontend/dist/provider-logos/neuralwatt.svg +27 -0
  763. package/frontend/dist/provider-logos/nova.svg +3 -0
  764. package/frontend/dist/provider-logos/novita-ai.svg +10 -0
  765. package/frontend/dist/provider-logos/nvidia.svg +3 -0
  766. package/frontend/dist/provider-logos/oci.svg +3 -0
  767. package/frontend/dist/provider-logos/ofox.svg +5 -0
  768. package/frontend/dist/provider-logos/ollama-cloud.svg +7 -0
  769. package/frontend/dist/provider-logos/openai.svg +3 -0
  770. package/frontend/dist/provider-logos/opencode-go.svg +4 -0
  771. package/frontend/dist/provider-logos/opencode.svg +4 -0
  772. package/frontend/dist/provider-logos/openreason.svg +8 -0
  773. package/frontend/dist/provider-logos/openrouter.svg +5 -0
  774. package/frontend/dist/provider-logos/opper.svg +3 -0
  775. package/frontend/dist/provider-logos/orcarouter.svg +2 -0
  776. package/frontend/dist/provider-logos/ovhcloud.svg +3 -0
  777. package/frontend/dist/provider-logos/pareto.svg +5 -0
  778. package/frontend/dist/provider-logos/pendra.svg +10 -0
  779. package/frontend/dist/provider-logos/perplexity-agent.svg +3 -0
  780. package/frontend/dist/provider-logos/perplexity.svg +3 -0
  781. package/frontend/dist/provider-logos/pioneer.svg +3 -0
  782. package/frontend/dist/provider-logos/poe.svg +7 -0
  783. package/frontend/dist/provider-logos/poolside.svg +3 -0
  784. package/frontend/dist/provider-logos/prime.svg +7 -0
  785. package/frontend/dist/provider-logos/privatemode-ai.svg +5 -0
  786. package/frontend/dist/provider-logos/qihang-ai.svg +9 -0
  787. package/frontend/dist/provider-logos/qiniu-ai.svg +7 -0
  788. package/frontend/dist/provider-logos/qvac.svg +6 -0
  789. package/frontend/dist/provider-logos/reflection.svg +3 -0
  790. package/frontend/dist/provider-logos/regolo-ai.svg +46 -0
  791. package/frontend/dist/provider-logos/requesty.svg +24 -0
  792. package/frontend/dist/provider-logos/routing-run.svg +4 -0
  793. package/frontend/dist/provider-logos/runinfra.svg +10 -0
  794. package/frontend/dist/provider-logos/sakana.svg +24 -0
  795. package/frontend/dist/provider-logos/salad-cloud.svg +15 -0
  796. package/frontend/dist/provider-logos/sambanova.svg +26 -0
  797. package/frontend/dist/provider-logos/sap-ai-core.svg +24 -0
  798. package/frontend/dist/provider-logos/sarvam.svg +24 -0
  799. package/frontend/dist/provider-logos/scaleway.svg +5 -0
  800. package/frontend/dist/provider-logos/scnet-token-plan.svg +8 -0
  801. package/frontend/dist/provider-logos/scx-ai.svg +1 -0
  802. package/frontend/dist/provider-logos/sensenova.svg +18 -0
  803. package/frontend/dist/provider-logos/siliconflow-cn.svg +3 -0
  804. package/frontend/dist/provider-logos/siliconflow.svg +3 -0
  805. package/frontend/dist/provider-logos/snowflake-cortex.svg +3 -0
  806. package/frontend/dist/provider-logos/stackit.svg +4 -0
  807. package/frontend/dist/provider-logos/standardcompute.svg +5 -0
  808. package/frontend/dist/provider-logos/stepfun-ai-step-plan.svg +16 -0
  809. package/frontend/dist/provider-logos/stepfun-ai.svg +16 -0
  810. package/frontend/dist/provider-logos/stepfun-step-plan.svg +16 -0
  811. package/frontend/dist/provider-logos/stepfun.svg +16 -0
  812. package/frontend/dist/provider-logos/subconscious.svg +3 -0
  813. package/frontend/dist/provider-logos/submodel.svg +3 -0
  814. package/frontend/dist/provider-logos/synthetic.svg +24 -0
  815. package/frontend/dist/provider-logos/tempr.svg +4 -0
  816. package/frontend/dist/provider-logos/tencent-coding-plan.svg +5 -0
  817. package/frontend/dist/provider-logos/tencent-token-plan.svg +3 -0
  818. package/frontend/dist/provider-logos/tencent-tokenhub.svg +3 -0
  819. package/frontend/dist/provider-logos/tensorx.svg +6 -0
  820. package/frontend/dist/provider-logos/the-grid-ai.svg +14 -0
  821. package/frontend/dist/provider-logos/thinkingmachines.svg +3 -0
  822. package/frontend/dist/provider-logos/tinfoil.svg +3 -0
  823. package/frontend/dist/provider-logos/togetherai.svg +4 -0
  824. package/frontend/dist/provider-logos/tokengo.svg +3 -0
  825. package/frontend/dist/provider-logos/tokenrouter.svg +4 -0
  826. package/frontend/dist/provider-logos/trustedrouter.svg +4 -0
  827. package/frontend/dist/provider-logos/umans-ai-coding-plan.svg +29 -0
  828. package/frontend/dist/provider-logos/umans-ai.svg +29 -0
  829. package/frontend/dist/provider-logos/unorouter.svg +7 -0
  830. package/frontend/dist/provider-logos/upstage.svg +24 -0
  831. package/frontend/dist/provider-logos/vancine.svg +6 -0
  832. package/frontend/dist/provider-logos/venice.svg +4 -0
  833. package/frontend/dist/provider-logos/vercel.svg +3 -0
  834. package/frontend/dist/provider-logos/vispark.svg +3 -0
  835. package/frontend/dist/provider-logos/vivgrid.svg +4 -0
  836. package/frontend/dist/provider-logos/volcengine-coding-plan.svg +1 -0
  837. package/frontend/dist/provider-logos/volcengine.svg +1 -0
  838. package/frontend/dist/provider-logos/vultr.svg +6 -0
  839. package/frontend/dist/provider-logos/wafer.ai.svg +3 -0
  840. package/frontend/dist/provider-logos/wallaby.svg +4 -0
  841. package/frontend/dist/provider-logos/wally.svg +1 -0
  842. package/frontend/dist/provider-logos/wandb.svg +6 -0
  843. package/frontend/dist/provider-logos/watsonx.svg +5 -0
  844. package/frontend/dist/provider-logos/xai.svg +3 -0
  845. package/frontend/dist/provider-logos/xiaomi-token-plan-ams.svg +3 -0
  846. package/frontend/dist/provider-logos/xiaomi-token-plan-cn.svg +3 -0
  847. package/frontend/dist/provider-logos/xiaomi-token-plan-sgp.svg +3 -0
  848. package/frontend/dist/provider-logos/xiaomi.svg +3 -0
  849. package/frontend/dist/provider-logos/xpersona.svg +8 -0
  850. package/frontend/dist/provider-logos/zai-coding-plan.svg +3 -0
  851. package/frontend/dist/provider-logos/zai.svg +3 -0
  852. package/frontend/dist/provider-logos/zeldoc.svg +3 -0
  853. package/frontend/dist/provider-logos/zenifra.svg +4 -0
  854. package/frontend/dist/provider-logos/zenmux.svg +4 -0
  855. package/frontend/dist/provider-logos/zhipuai-coding-plan.svg +3 -0
  856. package/frontend/dist/provider-logos/zhipuai.svg +3 -0
  857. package/package.json +13 -5
  858. package/backend/dist/budget/budget-manager.d.ts +0 -25
  859. package/backend/dist/budget/budget-manager.js +0 -54
  860. package/backend/dist/cli/clients/opencode-proxy.d.ts +0 -16
  861. package/backend/dist/cli/clients/opencode-proxy.js +0 -372
  862. package/backend/dist/config/governance-limits.d.ts +0 -68
  863. package/backend/dist/config/governance-limits.js +0 -261
  864. package/backend/dist/flywheel/collector.d.ts +0 -74
  865. package/backend/dist/flywheel/collector.js +0 -235
  866. package/backend/dist/flywheel/dataset.d.ts +0 -130
  867. package/backend/dist/flywheel/dataset.js +0 -638
  868. package/backend/dist/flywheel/decision-capture.d.ts +0 -68
  869. package/backend/dist/flywheel/decision-capture.js +0 -85
  870. package/backend/dist/flywheel/prune.d.ts +0 -133
  871. package/backend/dist/flywheel/prune.js +0 -495
  872. package/backend/dist/flywheel/schema.d.ts +0 -108
  873. package/backend/dist/flywheel/schema.js +0 -117
  874. package/backend/dist/flywheel/trainer.d.ts +0 -84
  875. package/backend/dist/flywheel/trainer.js +0 -198
  876. package/backend/dist/forward-proxy/bypass.d.ts +0 -20
  877. package/backend/dist/forward-proxy/bypass.js +0 -28
  878. package/backend/dist/harness/adapters/amp.d.ts +0 -2
  879. package/backend/dist/harness/adapters/amp.js +0 -8
  880. package/backend/dist/harness/adapters/claude.d.ts +0 -2
  881. package/backend/dist/harness/adapters/claude.js +0 -8
  882. package/backend/dist/harness/adapters/cline.d.ts +0 -2
  883. package/backend/dist/harness/adapters/cline.js +0 -8
  884. package/backend/dist/harness/adapters/codex.d.ts +0 -2
  885. package/backend/dist/harness/adapters/codex.js +0 -8
  886. package/backend/dist/harness/adapters/cursor.d.ts +0 -5
  887. package/backend/dist/harness/adapters/cursor.js +0 -11
  888. package/backend/dist/harness/adapters/declarative.d.ts +0 -64
  889. package/backend/dist/harness/adapters/declarative.js +0 -216
  890. package/backend/dist/harness/adapters/dsh.d.ts +0 -5
  891. package/backend/dist/harness/adapters/dsh.js +0 -6
  892. package/backend/dist/harness/adapters/gemini-cli.d.ts +0 -2
  893. package/backend/dist/harness/adapters/gemini-cli.js +0 -8
  894. package/backend/dist/harness/adapters/github-copilot.d.ts +0 -5
  895. package/backend/dist/harness/adapters/github-copilot.js +0 -11
  896. package/backend/dist/harness/adapters/omp.d.ts +0 -11
  897. package/backend/dist/harness/adapters/omp.js +0 -22
  898. package/backend/dist/harness/adapters/opencode.d.ts +0 -2
  899. package/backend/dist/harness/adapters/opencode.js +0 -56
  900. package/backend/dist/harness/adapters/pi.d.ts +0 -1
  901. package/backend/dist/harness/adapters/pi.js +0 -23
  902. package/backend/dist/harness/adapters/types.d.ts +0 -189
  903. package/backend/dist/harness/adapters/types.js +0 -12
  904. package/backend/dist/harness/adapters/universal.d.ts +0 -6
  905. package/backend/dist/harness/adapters/universal.js +0 -10
  906. package/backend/dist/harness/adapters/windsurf.d.ts +0 -2
  907. package/backend/dist/harness/adapters/windsurf.js +0 -11
  908. package/backend/dist/harness/adapters/zed.d.ts +0 -2
  909. package/backend/dist/harness/adapters/zed.js +0 -8
  910. package/backend/dist/harness/awesome-opencode.d.ts +0 -40
  911. package/backend/dist/harness/awesome-opencode.js +0 -75
  912. package/backend/dist/harness/browse.d.ts +0 -202
  913. package/backend/dist/harness/browse.js +0 -1214
  914. package/backend/dist/harness/inventory.d.ts +0 -10
  915. package/backend/dist/harness/opencode-cafe.d.ts +0 -40
  916. package/backend/dist/harness/opencode-cafe.js +0 -85
  917. package/backend/dist/harness/opencode-ecosystem.d.ts +0 -34
  918. package/backend/dist/harness/opencode-ecosystem.js +0 -246
  919. package/backend/dist/harness/pi-dev.d.ts +0 -81
  920. package/backend/dist/harness/pi-dev.js +0 -187
  921. package/backend/dist/harness/registry.js +0 -26
  922. package/backend/dist/harness/scopes.d.ts +0 -21
  923. package/backend/dist/harness/scopes.js +0 -22
  924. package/backend/dist/harness/skills-sh.d.ts +0 -109
  925. package/backend/dist/harness/skills-sh.js +0 -178
  926. package/backend/dist/harness/smithery.d.ts +0 -64
  927. package/backend/dist/harness/smithery.js +0 -146
  928. package/backend/dist/harness/sources/awesome-opencode.d.ts +0 -11
  929. package/backend/dist/harness/sources/awesome-opencode.js +0 -39
  930. package/backend/dist/harness/sources/mcp-official.d.ts +0 -2
  931. package/backend/dist/harness/sources/mcp-official.js +0 -110
  932. package/backend/dist/harness/sources/npm.d.ts +0 -2
  933. package/backend/dist/harness/sources/opencode-cafe.d.ts +0 -11
  934. package/backend/dist/harness/sources/opencode-cafe.js +0 -41
  935. package/backend/dist/harness/sources/smithery.d.ts +0 -2
  936. package/backend/dist/harness/sources/smithery.js +0 -81
  937. package/backend/dist/harness/writers/extension.d.ts +0 -116
  938. package/backend/dist/harness/writers/extension.js +0 -219
  939. package/backend/dist/harness/writers/mcp.d.ts +0 -72
  940. package/backend/dist/harness/writers/mcp.js +0 -195
  941. package/backend/dist/observability/trace-id.d.ts +0 -40
  942. package/backend/dist/observability/trace-id.js +0 -134
  943. package/backend/dist/opencode/catalog/custom-store.d.ts +0 -50
  944. package/backend/dist/opencode/catalog/custom-store.js +0 -144
  945. package/backend/dist/opencode/credentials/push.d.ts +0 -38
  946. package/backend/dist/opencode/credentials/push.js +0 -116
  947. package/backend/dist/opencode/credentials/reconcile.d.ts +0 -49
  948. package/backend/dist/opencode/credentials/reconcile.js +0 -216
  949. package/backend/dist/opencode/sync.d.ts +0 -29
  950. package/backend/dist/opencode/sync.js +0 -186
  951. package/backend/dist/pipeline/account-selection.d.ts +0 -101
  952. package/backend/dist/pipeline/account-selection.js +0 -112
  953. package/backend/dist/providers/systemone.d.ts +0 -29
  954. package/backend/dist/providers/systemone.js +0 -170
  955. package/backend/dist/ratelimit/duration.d.ts +0 -24
  956. package/backend/dist/ratelimit/duration.js +0 -43
  957. package/backend/dist/ratelimit/governance-runtime.d.ts +0 -121
  958. package/backend/dist/ratelimit/governance-runtime.js +0 -183
  959. package/backend/dist/ratelimit/index.d.ts +0 -4
  960. package/backend/dist/ratelimit/index.js +0 -4
  961. package/backend/dist/ratelimit/limiter.d.ts +0 -157
  962. package/backend/dist/ratelimit/limiter.js +0 -244
  963. package/backend/dist/ratelimit/sliding-window-counter.d.ts +0 -63
  964. package/backend/dist/ratelimit/sliding-window-counter.js +0 -103
  965. package/backend/dist/ratelimit/subject.d.ts +0 -26
  966. package/backend/dist/ratelimit/subject.js +0 -28
  967. package/backend/dist/resilience/account-state.d.ts +0 -84
  968. package/backend/dist/resilience/account-state.js +0 -228
  969. package/backend/dist/router/layer1-classifier.d.ts +0 -111
  970. package/backend/dist/router/layer1-classifier.js +0 -467
  971. package/backend/dist/router/layer2-judge.d.ts +0 -111
  972. package/backend/dist/router/layer2-judge.js +0 -373
  973. package/backend/dist/router/retry-escalation.d.ts +0 -89
  974. package/backend/dist/router/retry-escalation.js +0 -99
  975. package/backend/dist/routes/flywheel.d.ts +0 -3
  976. package/backend/dist/routes/flywheel.js +0 -268
  977. package/backend/dist/routes/systemone.d.ts +0 -3
  978. package/backend/dist/routes/systemone.js +0 -90
  979. package/backend/dist/surfaces/governance-envelope.d.ts +0 -34
  980. package/backend/dist/surfaces/governance-envelope.js +0 -47
  981. package/backend/dist/utils/token-estimator.d.ts +0 -7
  982. package/backend/dist/utils/token-estimator.js +0 -20
  983. package/frontend/dist/assets/index-B7GKsUyU.js +0 -982
  984. package/frontend/dist/assets/index-DLKLOkQJ.css +0 -1
  985. package/frontend/dist/assets/inter-cyrillic-800-normal-C7MGvYyJ.woff2 +0 -0
  986. package/frontend/dist/assets/inter-cyrillic-800-normal-CCHyn08d.woff +0 -0
  987. package/frontend/dist/assets/inter-cyrillic-ext-800-normal-BZOjs1Xv.woff2 +0 -0
  988. package/frontend/dist/assets/inter-cyrillic-ext-800-normal-Ca-gJeZY.woff +0 -0
  989. package/frontend/dist/assets/inter-greek-800-normal-BU00tryP.woff +0 -0
  990. package/frontend/dist/assets/inter-greek-800-normal-CLIouy3y.woff2 +0 -0
  991. package/frontend/dist/assets/inter-greek-ext-800-normal-B--PVpEC.woff2 +0 -0
  992. package/frontend/dist/assets/inter-greek-ext-800-normal-DUe57HfS.woff +0 -0
  993. package/frontend/dist/assets/inter-latin-800-normal-BYj_oED-.woff2 +0 -0
  994. package/frontend/dist/assets/inter-latin-800-normal-D1mf63XC.woff +0 -0
  995. package/frontend/dist/assets/inter-latin-ext-800-normal-BOMpwxm3.woff +0 -0
  996. package/frontend/dist/assets/inter-latin-ext-800-normal-DZJjya6U.woff2 +0 -0
  997. package/frontend/dist/assets/inter-vietnamese-800-normal-Cm7tD1pz.woff2 +0 -0
  998. package/frontend/dist/assets/inter-vietnamese-800-normal-DDlpr_Ee.woff +0 -0
  999. /package/backend/dist/harness/{adapters → host/adapters}/skills-paths.d.ts +0 -0
  1000. /package/backend/dist/harness/{adapters → host/adapters}/skills-paths.js +0 -0
  1001. /package/backend/dist/harness/{skill-md.d.ts → skill/skill-md.d.ts} +0 -0
  1002. /package/backend/dist/harness/{skill-md.js → skill/skill-md.js} +0 -0
@@ -3,23 +3,34 @@ import https from 'node:https';
3
3
  import net from 'node:net';
4
4
  import tls from 'node:tls';
5
5
  import { CertMinter, ensureCa } from './ca.js';
6
- import { parseClientHelloSNI } from './sni.js';
6
+ import { peekClientHello } from './sni.js';
7
7
  import { splice } from './relay.js';
8
- import { matchBypass } from './bypass.js';
9
- import { resolveProxyUrl } from '../utils/proxy.js';
10
- import { FORWARD_PROXY_HANG_TIMEOUT_MS } from '../config/defaults.js';
8
+ import { DEFAULT_FORWARD_PROXY_MAX_CONNECTIONS, FORWARD_PROXY_HANG_TIMEOUT_MS, FORWARD_PROXY_KEEPALIVE_MS, } from '../config/defaults.js';
9
+ import { describeUpstreamFailure, filterHeaders, isRuleRejected, openViaProxy, parseProxy, ruleTunnels, setBootRules, setLiveForwardProxy, transitEgressFor, transitProxyFor, UPSTREAM_TIMEOUT_CODE, upstreamServernameOption, } from './egress.js';
10
+ import { resolveUpstreamTls } from './upstream-tls.js';
11
+ import { createAccessTap, recordProxyConnect, recordProxyTunnel } from './access-log.js';
12
+ import { closeH2Pool, forwardH2 } from './h2-forward.js';
13
+ import { createWsObserver } from './ws-frames.js';
14
+ import { findGateway, listGatewayHosts } from '../plugins/gateways.js';
15
+ import { markProxyCaller } from './caller-context.js';
16
+ import http2 from 'node:http2';
11
17
  /**
12
18
  * Inbound forward proxy (the HTTP_PROXY / HTTPS_PROXY server).
13
19
  *
14
20
  * Design (settled & validated on Bun 1.3.14):
15
- * - FULL CAPTURE by default: every HTTPS CONNECT is MITM'd. The decrypted
16
- * request is inspected — LLM-protocol traffic (via `intercept`) enters the
17
- * routing pipeline; everything else is forwarded transparently.
18
- * - Transit egress optionally via the outbound proxy policy
19
- * (`viaOutboundProxy` — CONNECT through config.proxy, e.g. clash), so
20
- * network-blocked targets stay reachable for tunnels and forwards.
21
- * - Exceptions are blind-tunneled, never decrypted: loopback targets and
22
- * `bypassHosts` matches.
21
+ * - INTERCEPTION IS DECIDED (ADR-0018 Revision 4): a CONNECT is MITM'd only
22
+ * when a rule row says so, when a live client-gateway plugin CLAIMS the host,
23
+ * or when the operator turned on the audit posture (`intercept: 'all'`).
24
+ * Everything else is a blind tunnel. The decrypted request is inspected —
25
+ * LLM-protocol traffic (via `intercept`) enters the routing pipeline;
26
+ * everything else is forwarded transparently.
27
+ * - ONE ordered rule table decides both halves per host (ADR-0018,
28
+ * `forwardProxy.rules`): two fields per row — `ingress` = intercept (MITM) /
29
+ * passthrough (blind tunnel) / reject, `egress` = direct / proxy. First match
30
+ * wins; loopback is always passthrough (cycle safety + local dev); an
31
+ * unmatched host takes the catch-all's `egress` and is blind-tunneled unless
32
+ * claimed or the audit posture is on. `reject` is answered 403 on admission —
33
+ * before any tunnel is opened or certificate minted.
23
34
  * - Bun node:tls gaps worked around (all verified experimentally):
24
35
  * * no SNICallback → per-host tls.Server with an explicit cert, cached;
25
36
  * the servername is read by peeking the raw ClientHello (sni.ts);
@@ -27,136 +38,276 @@ import { FORWARD_PROXY_HANG_TIMEOUT_MS } from '../config/defaults.js';
27
38
  * explicit relay (relay.ts);
28
39
  * * tlsServer/httpServer.emit('connection', socket) is not honored →
29
40
  * the decrypted stream is spliced over a loopback socket into an
30
- * inner http.Server that does native Bun HTTP parsing.
31
- * - ALPN is pinned to http/1.1 so clients never negotiate h2 into the
32
- * HTTP/1.1 inner parser.
41
+ * inner http.Server that does native Bun HTTP parsing;
42
+ * * the node:http 'upgrade' event is unusable (the handler's socket
43
+ * swallows every write and the parser then answers 505) → an
44
+ * `Upgrade:` handshake is caught on the decrypted stream before the
45
+ * inner server and relayed byte-verbatim (relayUpgrade).
46
+ * - Per-host terminators and minted certs are LRU-bounded
47
+ * (MAX_HOST_TERMINATORS / MAX_CACHED_CERTS): full capture sees every host
48
+ * a client visits, so an unbounded cache is an fd leak per host.
49
+ * - Transport-complete MITM: the decrypted stream is parsed by an h1 inner
50
+ * OR an h2 inner (prior-knowledge h2c loopback), picked by sniffing the
51
+ * first decrypted bytes for the h2 connection preface. Both inners run the
52
+ * SAME intercept chain and the SAME transparent forward — an h2 request is
53
+ * re-originated upstream over h2 (h2-forward.ts) so gRPC/Connect framing,
54
+ * trailers and bidi streams survive the hop, with an h1 fallback when the
55
+ * upstream refuses h2.
56
+ * - ALPN: every host offers both protocols, ordered by who is talking. Bun
57
+ * honours the SERVER's preference, so an unclaimed host offers
58
+ * ['http/1.1','h2'] (dual-offer clients keep the h1 path — zero regression;
59
+ * h2-only clients get h2) while a gateway-claimed host offers
60
+ * ['h2','http/1.1']. The negotiated protocol is only a hint: the preface is
61
+ * the authority (Bun does not reliably surface alpnProtocol at callback
62
+ * time).
33
63
  *
34
64
  * No-request-loss rule: the client's decoded stream may emit data the moment
35
65
  * the handshake completes — the 'data' listener is attached SYNCHRONOUSLY in
36
66
  * the secureConnection callback; pre-connect chunks are buffered.
37
67
  */
38
68
  const MAX_HELLO_BYTES = 32 * 1024;
69
+ /** Bound on the buffered HTTP/1 request head examined for an `Upgrade:`
70
+ * handshake; a head that outgrows it goes to the inner server unexamined. */
71
+ const MAX_HEAD_BYTES = 32 * 1024;
72
+ /** LRU bound on per-host TLS terminators (each = one listening loopback socket
73
+ * + one minted leaf cert). Full capture sees EVERY host a client visits, so an
74
+ * unbounded map leaks one file descriptor per host for the life of the process. */
75
+ const MAX_HOST_TERMINATORS = 256;
76
+ /**
77
+ * Grace window for an evicted terminator: long enough for a CONNECT that
78
+ * already resolved its port to finish dialing, short enough to keep the fd
79
+ * budget bounded. `server.close()` never touches established connections, so
80
+ * this is the ONLY cost of eviction.
81
+ */
82
+ const TERMINATOR_DRAIN_MS = 30_000;
83
+ /** Hard cap on the draining set — eviction must not become a second cache. */
84
+ const MAX_DRAINING_TERMINATORS = 64;
85
+ /**
86
+ * One ledger row per this window, per terminator. A client that rejects the
87
+ * intercepted leaf (pinning, missing CA) reconnects in a tight loop; without
88
+ * the dedupe it would flush every real row out of the access ring.
89
+ */
90
+ const CLIENT_TLS_ERROR_DEDUPE_MS = 5_000;
91
+ /**
92
+ * Upper bound on "the error envelope is on its way" — the abort normally fires
93
+ * the moment the envelope chunk reaches the client transport; this only covers
94
+ * the case where no chunk ever arrives.
95
+ */
96
+ const MITM_ABORT_FLUSH_MS = 1_000;
97
+ /**
98
+ * How long a blind tunnel waits for client bytes before recording its decision
99
+ * row without an identity. Never a relay delay — the tunnel is already flowing;
100
+ * this only bounds the observation window for a server-speaks-first protocol.
101
+ */
39
102
  const CLIENT_ERROR_RESPONSE = 'HTTP/1.1 400 Bad Request\r\nConnection: close\r\n\r\n';
40
- const HOP_BY_HOP = new Set([
41
- 'connection',
42
- 'proxy-connection',
43
- 'keep-alive',
44
- 'proxy-authenticate',
45
- 'proxy-authorization',
46
- 'te',
47
- 'trailer',
48
- 'transfer-encoding',
49
- 'upgrade',
50
- ]);
51
- function filterHeaders(headers) {
52
- const out = {};
53
- for (const [k, v] of Object.entries(headers)) {
54
- if (v === undefined)
55
- continue;
56
- if (HOP_BY_HOP.has(k.toLowerCase()))
57
- continue;
58
- out[k] = v;
103
+ /** Raw-socket 403 for a CONNECT whose host a rule rejects (ADR-0018).
104
+ * Answered on the raw socket BEFORE the 200, so no tunnel and no minted
105
+ * certificate ever exist for a rejected host. */
106
+ const RULE_REJECT_RESPONSE = 'HTTP/1.1 403 Forbidden\r\nContent-Length: 0\r\nConnection: close\r\n\r\n';
107
+ /** Realm for the proxy-auth challenge (407). */
108
+ const PROXY_AUTH_REALM = 'OmniCellRouter';
109
+ /** Raw-socket 407: a CONNECT may arrive before any TLS material, so the only
110
+ * thing we can write is a plain HTTP/1.1 status line. */
111
+ const PROXY_AUTH_REQUIRED_RESPONSE = 'HTTP/1.1 407 Proxy Authentication Required\r\n' +
112
+ `Proxy-Authenticate: Basic realm="${PROXY_AUTH_REALM}"\r\n` +
113
+ 'Content-Length: 0\r\nConnection: close\r\n\r\n';
114
+ /**
115
+ * Dedupe window for pre-admission ledger rows (407 / cap / bad request line).
116
+ * A client failing auth or hammering the cap reconnects in a tight loop; the
117
+ * row is the audit signal, not a per-attempt count — one row per window per
118
+ * host keeps a hostile client from flushing real rows out of the access ring.
119
+ */
120
+ const PRE_ADMISSION_ROW_DEDUPE_MS = CLIENT_TLS_ERROR_DEDUPE_MS;
121
+ const preAdmissionRowAt = new Map();
122
+ /** true = this pre-admission row should be recorded; false = deduped. */
123
+ function shouldRecordPreAdmission(key) {
124
+ const now = Date.now();
125
+ const last = preAdmissionRowAt.get(key) ?? 0;
126
+ if (now - last < PRE_ADMISSION_ROW_DEDUPE_MS)
127
+ return false;
128
+ preAdmissionRowAt.set(key, now);
129
+ if (preAdmissionRowAt.size > 512) {
130
+ // Bounded: drop expired entries instead of growing per hostile host.
131
+ for (const [k, t] of preAdmissionRowAt)
132
+ if (now - t >= PRE_ADMISSION_ROW_DEDUPE_MS)
133
+ preAdmissionRowAt.delete(k);
134
+ if (preAdmissionRowAt.size > 512)
135
+ preAdmissionRowAt.clear();
59
136
  }
60
- return out;
137
+ return true;
61
138
  }
62
- // ── outbound-proxy transit (config.proxy policy) ──────────────────────────
63
- // When enabled, bypass tunnels and non-intercepted forwards egress through
64
- // the configured outbound proxy (e.g. clash/v2ray) via CONNECT, so
65
- // network-blocked targets become reachable without touching interception.
66
- // Module-level because only one forward proxy instance exists per process;
67
- // createForwardProxyServer sets it (last created wins).
68
- let transitViaOutboundProxy = false;
69
- function transitProxyFor(host, port, force) {
70
- // force: per-host egress choice (bypass entries carry it); undefined = the
71
- // global `viaOutboundProxy` flag (non-intercepted forwards).
72
- const enabled = force === undefined ? transitViaOutboundProxy : force;
73
- if (!enabled)
74
- return undefined;
75
- return resolveProxyUrl(`https://${host}:${port}/`, { model: host });
76
- }
77
- function parseProxy(proxyUrl) {
78
- try {
79
- const u = new URL(proxyUrl);
80
- const port = parseInt(u.port || (u.protocol === 'https:' ? '443' : '80'), 10);
81
- const auth = u.username
82
- ? 'Basic ' + Buffer.from(`${decodeURIComponent(u.username)}:${decodeURIComponent(u.password)}`).toString('base64')
83
- : undefined;
84
- return { host: u.hostname, port, auth };
139
+ /** Split a `host[:port]` header value (bracketed IPv6 supported). */
140
+ function splitHostPort(value, defaultPort) {
141
+ const raw = (value || '').trim();
142
+ if (raw.startsWith('[')) {
143
+ const end = raw.indexOf(']');
144
+ const host = raw.slice(1, end);
145
+ const rest = raw.slice(end + 1);
146
+ return { host, port: rest.startsWith(':') ? parseInt(rest.slice(1), 10) || defaultPort : defaultPort };
85
147
  }
86
- catch {
87
- return null;
148
+ const colon = raw.lastIndexOf(':');
149
+ // Exactly one colon ⇒ host:port; a bare IPv6 literal (several colons) has none.
150
+ if (colon > 0 && raw.indexOf(':') === colon) {
151
+ return { host: raw.slice(0, colon), port: parseInt(raw.slice(colon + 1), 10) || defaultPort };
88
152
  }
153
+ return { host: raw, port: defaultPort };
89
154
  }
155
+ /** Per-response slot carrying the connection's abort hook to `proxyFail`. */
156
+ const MITM_ABORT = Symbol('ocr.forwardProxy.mitmAbort');
90
157
  /**
91
- * Open a raw byte pipe to `host:port` through an HTTP CONNECT proxy.
92
- * Resolves with the tunneled socket (paused — consumers must splice/pipe,
93
- * which resumes it; Bun drops listener-less early data, hence the pause).
158
+ * Parse a request head that carries an `Upgrade:` handshake, else null.
159
+ *
160
+ * The head is read off the DECRYPTED stream (see `relayUpgrade` for why the
161
+ * runtime's own upgrade event cannot be used). Only the target and the method
162
+ * are extracted — the head itself is relayed byte-verbatim, so nothing about
163
+ * the handshake (subprotocols, extensions, cookies) is ever re-serialized.
94
164
  */
95
- function openViaProxy(proxyUrl, host, port) {
96
- return new Promise((resolve, reject) => {
97
- const p = parseProxy(proxyUrl);
98
- if (!p)
99
- return reject(new Error('invalid outbound proxy url'));
100
- const sock = net.connect(p.port, p.host);
101
- let settled = false;
102
- const timer = setTimeout(() => {
103
- if (!settled) {
104
- settled = true;
105
- sock.destroy();
106
- reject(new Error('outbound proxy connect timeout'));
107
- }
108
- }, 15000);
109
- let buf = '';
110
- const onData = (d) => {
111
- buf += d.toString('latin1');
112
- const idx = buf.indexOf('\r\n\r\n');
113
- if (idx === -1)
114
- return;
115
- settled = true;
116
- clearTimeout(timer);
117
- sock.removeListener('data', onData);
118
- const head = buf.slice(0, idx);
119
- const rest = buf.slice(idx + 4);
120
- if (!/^HTTP\/1\.[01] 200/.test(head)) {
121
- sock.destroy();
122
- reject(new Error(`outbound proxy rejected CONNECT: ${head.split('\r\n')[0] || 'no status'}`));
123
- return;
124
- }
125
- if (rest.length)
126
- sock.unshift(Buffer.from(rest, 'latin1'));
127
- sock.pause();
128
- resolve(sock);
129
- };
130
- sock.on('data', onData);
131
- sock.on('error', (err) => {
132
- if (!settled) {
133
- settled = true;
134
- clearTimeout(timer);
135
- reject(err);
165
+ function parseUpgradeHead(head, defaultPort) {
166
+ const lines = head.split('\r\n');
167
+ const requestLine = /^([A-Z]+) (\S+) HTTP\/1\.[01]$/.exec(lines[0] ?? '');
168
+ if (!requestLine)
169
+ return null;
170
+ const headers = {};
171
+ for (const line of lines.slice(1)) {
172
+ const colon = line.indexOf(':');
173
+ if (colon <= 0)
174
+ continue;
175
+ headers[line.slice(0, colon).trim().toLowerCase()] = line.slice(colon + 1).trim();
176
+ }
177
+ const upgrade = headers.upgrade;
178
+ const connection = headers.connection;
179
+ const hostHeader = headers.host;
180
+ if (!upgrade || !connection || !hostHeader)
181
+ return null;
182
+ const tokens = String(connection).toLowerCase().split(',').map((v) => v.trim());
183
+ if (!tokens.includes('upgrade'))
184
+ return null;
185
+ // Same port precedence as the request leg (ADR-0018 §3a): an explicit Host
186
+ // port > the CONNECT authority's port > 443. A WebSocket client sends the
187
+ // plain host name, so defaulting to 443 sent an upgrade for a non-443 target
188
+ // to the wrong port.
189
+ const { host, port } = splitHostPort(String(hostHeader), defaultPort);
190
+ if (!host)
191
+ return null;
192
+ return { method: requestLine[1], path: requestLine[2], host, port, headers };
193
+ }
194
+ /** Send the request body upstream: the h2 relay's captured preface first (if
195
+ * any), then the live stream. With a tap, chunks tee into the access log
196
+ * alongside the upstream writes (both consumers see every chunk).
197
+ *
198
+ * A preface can be up to 16 MB (`DEFAULT_MAX_BODY_BYTES`), so it is written
199
+ * under backpressure: the old loop queued every chunk regardless of
200
+ * `write()` returning false, spiking the outgoing buffer by the whole body. */
201
+ function pumpRequestBody(req, upstream, tap, preface) {
202
+ if (!preface) {
203
+ if (tap)
204
+ req.on('data', (d) => tap.onReqChunk(d));
205
+ req.pipe(upstream);
206
+ req.on('error', () => {
207
+ try {
208
+ upstream.destroy();
136
209
  }
210
+ catch { }
137
211
  });
138
- sock.on('connect', () => {
139
- const lines = [
140
- `CONNECT ${host}:${port} HTTP/1.1`,
141
- `Host: ${host}:${port}`,
142
- ...(p.auth ? [`Proxy-Authorization: ${p.auth}`] : []),
143
- '',
144
- '',
145
- ];
146
- sock.write(lines.join('\r\n'));
147
- });
212
+ return;
213
+ }
214
+ // Keep the live listener attached even while the preface drains: a paused
215
+ // stream does not restart itself, and Bun's h1 body may emit before the
216
+ // preface has been flushed. Chunks queue behind the preface to keep order.
217
+ const queue = [...preface.chunks];
218
+ let head = 0;
219
+ let ended = preface.ended;
220
+ let blocked = false;
221
+ let upstreamEnded = false;
222
+ const flush = () => {
223
+ if (blocked)
224
+ return;
225
+ while (head < queue.length) {
226
+ const chunk = queue[head];
227
+ tap?.onReqChunk(chunk);
228
+ const ok = upstream.write(chunk);
229
+ head += 1;
230
+ if (!ok) {
231
+ blocked = true;
232
+ req.pause();
233
+ upstream.once('drain', () => {
234
+ blocked = false;
235
+ req.resume();
236
+ flush();
237
+ });
238
+ return;
239
+ }
240
+ }
241
+ queue.length = 0;
242
+ head = 0;
243
+ if (ended && !upstreamEnded) {
244
+ upstreamEnded = true;
245
+ upstream.end();
246
+ }
247
+ };
248
+ req.on('data', (chunk) => {
249
+ queue.push(chunk);
250
+ flush();
251
+ });
252
+ req.on('end', () => {
253
+ ended = true;
254
+ flush();
148
255
  });
256
+ req.on('error', () => {
257
+ try {
258
+ upstream.destroy();
259
+ }
260
+ catch { }
261
+ });
262
+ flush();
263
+ }
264
+ /** Pipe the upstream response to the client, teeing chunks into the tap. */
265
+ function pipeUpResponse(up, res, tap) {
266
+ if (tap)
267
+ up.on('data', (d) => tap.onResChunk(d));
268
+ up.pipe(res);
149
269
  }
150
- /** Stream one http request to its real target and pipe the response back. */
151
- function forwardTo(req, res, t) {
152
- const proxyUrl = transitProxyFor(t.host, t.port, t.viaProxy);
270
+ /**
271
+ * Relay one decrypted exchange upstream on the h1 leg (direct or through the
272
+ * outbound proxy), tapping both directions when a tap is given. Gateway
273
+ * plugins call this through the host SDK so transport policy lives in core.
274
+ */
275
+ export function forwardTo(req, res, t, upstreamTls) {
276
+ const egress = transitEgressFor(t.host);
277
+ const proxyUrl = transitProxyFor(egress.proxy);
153
278
  if (proxyUrl) {
154
- return t.secure ? forwardSecureViaProxy(req, res, t, proxyUrl) : forwardPlainViaProxy(req, res, t, proxyUrl);
279
+ return t.secure
280
+ ? forwardSecureViaProxy(req, res, t, proxyUrl, upstreamTls)
281
+ : forwardPlainViaProxy(req, res, t, proxyUrl, upstreamTls);
155
282
  }
156
- return forwardDirect(req, res, t);
283
+ return forwardDirect(req, res, t, upstreamTls);
284
+ }
285
+ /**
286
+ * Arm the kernel probe on an upstream socket (see `FORWARD_PROXY_KEEPALIVE_MS`).
287
+ * A relayed leg has no application-level idle timeout — an SSE stream that has
288
+ * gone quiet is indistinguishable from one between tokens — so the peer that
289
+ * disappeared without FIN/RST is reaped by TCP keepalive instead. Failure is
290
+ * non-fatal: some injected test sockets are not real handles.
291
+ */
292
+ /**
293
+ * The synthetic error our hang guard destroys a request with. It carries a CODE
294
+ * so `describeUpstreamFailure` classifies it as a timeout (504) without string
295
+ * matching a message that any future edit could reword.
296
+ */
297
+ function hangGuardError() {
298
+ const err = new Error('upstream timeout');
299
+ err.code = UPSTREAM_TIMEOUT_CODE;
300
+ return err;
301
+ }
302
+ function armUpstreamKeepalive(req) {
303
+ req.on('socket', (s) => {
304
+ try {
305
+ s.setKeepAlive(true, FORWARD_PROXY_KEEPALIVE_MS);
306
+ }
307
+ catch { }
308
+ });
157
309
  }
158
- /** Direct upstream request (no outbound proxy involved). */
159
- function forwardDirect(req, res, t) {
310
+ function forwardDirect(req, res, t, upstreamTls) {
160
311
  return new Promise((resolve) => {
161
312
  const transport = t.secure ? https : http;
162
313
  const upstream = transport.request({
@@ -165,52 +316,92 @@ function forwardDirect(req, res, t) {
165
316
  method: req.method,
166
317
  path: t.path,
167
318
  headers: filterHeaders(req.headers),
168
- ...(t.secure ? { servername: t.host.replace(/^\[|\]$/g, '') } : {}),
319
+ ...(t.secure ? { ...upstreamServernameOption(t.host), ...(upstreamTls.opts || {}) } : {}),
169
320
  }, (up) => {
170
321
  // Headers arrived — the request is alive; clear the hang-protection
171
- // timer so long-lived streams (SSE passthrough) are never killed.
322
+ // timer so long-lived streams (SSE direct forwards) are never killed.
323
+ // Keepalive is what still reaps a half-dead peer (see relay.ts).
172
324
  upstream.setTimeout(0);
173
325
  res.writeHead(up.statusCode || 502, filterHeaders(up.headers));
174
- up.pipe(res);
175
- up.on('end', resolve);
326
+ pipeUpResponse(up, res, t.tap);
327
+ up.on('end', () => {
328
+ t.tap?.finish(up.statusCode, up.headers);
329
+ resolve();
330
+ });
176
331
  up.on('error', () => {
177
332
  try {
178
333
  res.destroy();
179
334
  }
180
335
  catch { }
336
+ t.tap?.finish(up.statusCode, up.headers, 'upstream error mid-response');
181
337
  resolve();
182
338
  });
183
339
  });
340
+ armUpstreamKeepalive(upstream);
184
341
  // Hang protection: a blackholed upstream (packets dropped, no RST — e.g. a
185
342
  // blocked host) would otherwise stall the client forever. Applies only
186
343
  // until response headers arrive.
187
344
  upstream.setTimeout(FORWARD_PROXY_HANG_TIMEOUT_MS, () => {
188
- upstream.destroy(new Error('upstream timeout'));
345
+ upstream.destroy(hangGuardError());
189
346
  });
190
347
  upstream.on('error', (err) => {
191
- const timedOut = err?.message === 'upstream timeout';
192
- try {
193
- if (!res.headersSent)
194
- res.writeHead(timedOut ? 504 : 502, { 'content-type': 'text/plain; charset=utf-8' });
195
- res.end(timedOut ? 'Forward proxy: upstream timed out (target unreachable from this machine?)' : 'Forward proxy: upstream connection failed');
196
- }
197
- catch { }
348
+ const failure = describeUpstreamFailure(err);
349
+ t.tap?.finish(undefined, undefined, failure.note);
350
+ proxyFail(res, failure.status, failure.message);
198
351
  resolve();
199
352
  });
200
- req.pipe(upstream);
201
- req.on('error', () => {
202
- try {
203
- upstream.destroy();
204
- }
205
- catch { }
206
- });
353
+ pumpRequestBody(req, upstream, t.tap, t.preface);
207
354
  });
208
355
  }
209
- function proxyFail(res, code, msg) {
356
+ /**
357
+ * The admission gate's refusal body, spelled ONCE (ADR-0018 §3): every leg
358
+ * that answers 403 for a `reject` row — plain proxy, intercepted inner server,
359
+ * client-gateway relay — says exactly this.
360
+ */
361
+ export const RULE_REJECTED_MESSAGE = 'Forward proxy: host rejected by rule';
362
+ /**
363
+ * Answer with an error envelope and CLOSE the connection.
364
+ *
365
+ * `Connection: close` is not decoration: on Bun an error answer written through
366
+ * the MITM inner server left the client's TLS session open (verified 1.3.14), so
367
+ * a client that waits for the stream to end — every non-streaming HTTP client —
368
+ * hung on a response it had already received in full. An error envelope is
369
+ * terminal; the connection must say so.
370
+ */
371
+ export function proxyFail(res, code, msg) {
210
372
  try {
211
- if (!res.headersSent)
212
- res.writeHead(code, { 'content-type': 'text/plain; charset=utf-8' });
373
+ if (!res.headersSent) {
374
+ res.writeHead(code, { 'content-type': 'text/plain; charset=utf-8', connection: 'close' });
375
+ }
213
376
  res.end(msg);
377
+ // An error envelope is terminal: close the client transport. On the MITM
378
+ // leg the only working handle is the terminator's abort hook (the inner
379
+ // server's `res.socket.end()` is inert on Bun); on the plain-proxy leg the
380
+ // socket is ours to end. Never touch the h2 session socket — it is
381
+ // multiplexed, and the stream's own end is the answer; the h2 guard must
382
+ // run BEFORE the abort hook, which end()s the whole session.
383
+ // Runtime-attached fields the declared `res` type cannot express.
384
+ const resExt = res;
385
+ if (Boolean(resExt.stream))
386
+ return;
387
+ const abort = resExt[MITM_ABORT];
388
+ if (abort) {
389
+ abort();
390
+ return;
391
+ }
392
+ const endSocket = () => {
393
+ try {
394
+ if (res.socket && !res.socket.destroyed)
395
+ res.socket.end();
396
+ }
397
+ catch { }
398
+ };
399
+ // After 'finish', not right after `end()`: the envelope must be on the wire
400
+ // before the socket closes, or the client sees a truncated body.
401
+ if (res.writableFinished)
402
+ endSocket();
403
+ else
404
+ res.once('finish', endSocket);
214
405
  }
215
406
  catch { }
216
407
  }
@@ -219,7 +410,7 @@ function proxyFail(res, code, msg) {
219
410
  * relay → https.request over the relay (TLS runs end-to-end through the
220
411
  * tunnel, so the real target certificate is what gets validated).
221
412
  */
222
- function forwardSecureViaProxy(req, res, t, proxyUrl) {
413
+ function forwardSecureViaProxy(req, res, t, proxyUrl, upstreamTls) {
223
414
  return new Promise((resolve) => {
224
415
  openViaProxy(proxyUrl, t.host, t.port)
225
416
  .then((pipeSock) => {
@@ -246,12 +437,14 @@ function forwardSecureViaProxy(req, res, t, proxyUrl) {
246
437
  method: req.method,
247
438
  path: t.path,
248
439
  headers: filterHeaders(req.headers),
249
- servername: t.host.replace(/^\[|\]$/g, ''),
440
+ ...upstreamServernameOption(t.host),
441
+ ...(upstreamTls.opts || {}),
250
442
  }, (up) => {
251
443
  upstream.setTimeout(0);
252
444
  res.writeHead(up.statusCode || 502, filterHeaders(up.headers));
253
- up.pipe(res);
445
+ pipeUpResponse(up, res, t.tap);
254
446
  up.on('end', () => {
447
+ t.tap?.finish(up.statusCode, up.headers);
255
448
  cleanup();
256
449
  resolve();
257
450
  });
@@ -260,40 +453,40 @@ function forwardSecureViaProxy(req, res, t, proxyUrl) {
260
453
  res.destroy();
261
454
  }
262
455
  catch { }
456
+ t.tap?.finish(up.statusCode, up.headers, 'upstream error mid-response');
263
457
  cleanup();
264
458
  resolve();
265
459
  });
266
460
  });
461
+ armUpstreamKeepalive(upstream);
267
462
  upstream.setTimeout(FORWARD_PROXY_HANG_TIMEOUT_MS, () => {
268
- upstream.destroy(new Error('upstream timeout'));
463
+ upstream.destroy(hangGuardError());
269
464
  });
270
465
  upstream.on('error', (err) => {
271
- const timedOut = err?.message === 'upstream timeout';
272
- proxyFail(res, timedOut ? 504 : 502, timedOut ? 'Forward proxy: upstream timed out (via outbound proxy)' : 'Forward proxy: upstream connection failed (via outbound proxy)');
466
+ const failure = describeUpstreamFailure(err, { proxied: true });
467
+ t.tap?.finish(undefined, undefined, failure.note);
468
+ proxyFail(res, failure.status, failure.message);
273
469
  cleanup();
274
470
  resolve();
275
471
  });
276
- req.pipe(upstream);
277
- req.on('error', () => {
278
- try {
279
- upstream.destroy();
280
- }
281
- catch { }
282
- });
472
+ pumpRequestBody(req, upstream, t.tap, t.preface);
283
473
  });
284
474
  })
285
475
  .catch((err) => {
476
+ // The CONNECT to the outbound proxy itself failed — a different class
477
+ // from an origin failure, and the note must say so.
478
+ t.tap?.finish(undefined, undefined, `outbound proxy connect failed: ${err?.code || err?.message || err}`);
286
479
  proxyFail(res, 502, `Forward proxy: outbound proxy connection failed (${err?.message || err})`);
287
480
  resolve();
288
481
  });
289
482
  });
290
483
  }
291
484
  /** Plain-HTTP target via an outbound HTTP proxy (absolute-URI request form). */
292
- function forwardPlainViaProxy(req, res, t, proxyUrl) {
485
+ function forwardPlainViaProxy(req, res, t, proxyUrl, upstreamTls) {
293
486
  return new Promise((resolve) => {
294
487
  const p = parseProxy(proxyUrl);
295
488
  if (!p) {
296
- void forwardDirect(req, res, t).then(resolve);
489
+ void forwardDirect(req, res, t, upstreamTls).then(resolve);
297
490
  return;
298
491
  }
299
492
  const headers = filterHeaders(req.headers);
@@ -308,41 +501,42 @@ function forwardPlainViaProxy(req, res, t, proxyUrl) {
308
501
  }, (up) => {
309
502
  upstream.setTimeout(0);
310
503
  res.writeHead(up.statusCode || 502, filterHeaders(up.headers));
311
- up.pipe(res);
312
- up.on('end', resolve);
504
+ pipeUpResponse(up, res, t.tap);
505
+ up.on('end', () => {
506
+ t.tap?.finish(up.statusCode, up.headers);
507
+ resolve();
508
+ });
313
509
  up.on('error', () => {
314
510
  try {
315
511
  res.destroy();
316
512
  }
317
513
  catch { }
514
+ t.tap?.finish(up.statusCode, up.headers, 'upstream error mid-response');
318
515
  resolve();
319
516
  });
320
517
  });
518
+ armUpstreamKeepalive(upstream);
321
519
  upstream.setTimeout(FORWARD_PROXY_HANG_TIMEOUT_MS, () => {
322
- upstream.destroy(new Error('upstream timeout'));
520
+ upstream.destroy(hangGuardError());
323
521
  });
324
522
  upstream.on('error', (err) => {
325
- const timedOut = err?.message === 'upstream timeout';
326
- proxyFail(res, timedOut ? 504 : 502, timedOut ? 'Forward proxy: upstream timed out (via outbound proxy)' : 'Forward proxy: upstream connection failed (via outbound proxy)');
523
+ const failure = describeUpstreamFailure(err, { proxied: true });
524
+ t.tap?.finish(undefined, undefined, failure.note);
525
+ proxyFail(res, failure.status, failure.message);
327
526
  resolve();
328
527
  });
329
- req.pipe(upstream);
330
- req.on('error', () => {
331
- try {
332
- upstream.destroy();
333
- }
334
- catch { }
335
- });
528
+ pumpRequestBody(req, upstream, t.tap, t.preface);
336
529
  });
337
530
  }
338
531
  export async function createForwardProxyServer(deps) {
339
532
  const log = deps.log ?? (() => { });
340
- transitViaOutboundProxy = deps.viaOutboundProxy === true;
533
+ setLiveForwardProxy(deps.liveForwardProxy);
534
+ setBootRules(deps.rules, deps.interceptPosture);
341
535
  const ca = ensureCa(deps.caDir);
342
536
  const minter = new CertMinter(ca);
343
537
  // ── inner HTTP server: parses decrypted MITM traffic, intercept-or-forward ──
344
538
  const inner = http.createServer((req, res) => {
345
- void handleInnerRequest(req, res);
539
+ void handleInnerRequest(req, res, false);
346
540
  });
347
541
  inner.on('clientError', (_err, socket) => {
348
542
  try {
@@ -350,101 +544,356 @@ export async function createForwardProxyServer(deps) {
350
544
  }
351
545
  catch { }
352
546
  });
353
- async function handleInnerRequest(req, res) {
547
+ // ── h2 loopback inner (prior-knowledge h2c): the transport-complete half of
548
+ // the MITM leg. EVERY host may reach it (see the ALPN offer below) — h2 is
549
+ // not a vendor feature but the base transport of gRPC/Connect clients, and
550
+ // a proxy that terminates TLS must re-originate the protocol it accepted.
551
+ // Both legs dispatch through the same intercept chain, and the http2
552
+ // compatibility API mirrors the node-http req/res shape the gateway
553
+ // contract consumes.
554
+ const h2Inner = http2.createServer();
555
+ h2Inner.on('request', (req, res) => {
556
+ void handleInnerRequest(req, res, true);
557
+ });
558
+ h2Inner.on('sessionError', (err) => {
559
+ log(`h2 inner session error: ${err?.message || err}`);
560
+ });
561
+ async function handleInnerRequest(req, res, h2Leg) {
354
562
  try {
563
+ // The CONNECT authority's per-connection entry also carries the
564
+ // authenticated caller; the gateway leg reads it via ALS (ADR-0017).
565
+ const mitmTarget = mitmTargets.get(req.socket?.remotePort ?? -1);
566
+ markProxyCaller(req, mitmTarget?.caller);
355
567
  if (await deps.intercept(req, res))
356
568
  return;
357
- const hostHeader = String(req.headers.host || '');
358
- let host = hostHeader;
359
- let port = 443;
360
- if (hostHeader.startsWith('[')) {
361
- const i = hostHeader.indexOf(']');
362
- host = hostHeader.slice(1, i);
363
- const rest = hostHeader.slice(i + 1);
364
- if (rest.startsWith(':'))
365
- port = parseInt(rest.slice(1), 10) || 443;
366
- }
367
- else if (hostHeader.includes(':')) {
368
- const [h, p] = hostHeader.split(':');
369
- host = h;
370
- port = parseInt(p, 10) || 443;
569
+ // h2 compatibility requests carry the target in `:authority` (there is
570
+ // no `host` header) — accept either so gateway-declined h2 traffic can
571
+ // still fall through to transparent forward.
572
+ const hostHeader = String(req.headers[':authority'] || req.headers.host || '');
573
+ // Port precedence: an explicit Host/`:authority` port > the CONNECT
574
+ // authority's port > 443. HTTPS clients routinely omit the port from the
575
+ // request head (they assume 443), so `CONNECT host:8443` + `Host: host`
576
+ // used to be forwarded to 443 — a silent wrong-port forward. The CONNECT
577
+ // port rides in on the per-connection `mitmTargets` entry (see
578
+ // onDecryptedConnection), keyed by the loopback source port.
579
+ const connectPort = mitmTarget?.port;
580
+ if (mitmTarget) {
581
+ res[MITM_ABORT] = mitmTarget.abort;
371
582
  }
583
+ const { host, port } = splitHostPort(hostHeader, connectPort ?? 443);
372
584
  if (!host) {
373
- res.writeHead(400, { 'content-type': 'text/plain; charset=utf-8' });
374
- res.end('Forward proxy: missing Host header');
585
+ proxyFail(res, 400, 'Forward proxy: missing Host header');
586
+ return;
587
+ }
588
+ const tap = createAccessTap({
589
+ host,
590
+ port,
591
+ method: req.method,
592
+ path: req.url || '/',
593
+ wire: h2Leg ? 'h2' : String(req.headers.upgrade ?? '').toLowerCase().includes('websocket') ? 'ws' : 'h1',
594
+ // h2 pseudo-headers are transport framing, not wire headers — the row
595
+ // already carries host/method/path from them.
596
+ requestHeaders: h2Leg
597
+ ? Object.fromEntries(Object.entries(req.headers).filter(([k]) => !k.startsWith(':')))
598
+ : req.headers,
599
+ });
600
+ const target = { host, port, path: req.url || '/', secure: true, tap };
601
+ // Rule admission on the MITM leg: the inner Host can differ from the
602
+ // CONNECT target, so the same gate runs here (403 lands in the ledger).
603
+ if (isRuleRejected(host)) {
604
+ tap?.finish(403, undefined, 'rejected by rule');
605
+ proxyFail(res, 403, RULE_REJECTED_MESSAGE);
375
606
  return;
376
607
  }
377
- await forwardTo(req, res, { host, port, path: req.url || '/', secure: true });
608
+ // Protocol fidelity: an h2 client is answered upstream over h2 (gRPC and
609
+ // Connect cannot survive an h1 hop). `forwardH2` reports false when the
610
+ // upstream is not h2 — nothing has reached the client at that point, so
611
+ // the h1 forwarder takes over (ADR-0017 §3).
612
+ const upstreamTls = resolveUpstreamTls(deps.upstreamTls);
613
+ if (h2Leg) {
614
+ const relay = await forwardH2(req, res, target, upstreamTls);
615
+ if (relay.owned)
616
+ return;
617
+ target.preface = relay.preface;
618
+ }
619
+ await forwardTo(req, res, target, upstreamTls);
378
620
  }
379
621
  catch {
380
- try {
381
- if (!res.headersSent)
382
- res.writeHead(502, { 'content-type': 'text/plain; charset=utf-8' });
383
- res.end('Forward proxy error');
384
- }
385
- catch { }
622
+ proxyFail(res, 502, 'Forward proxy error');
386
623
  }
387
624
  }
388
625
  // ── per-host TLS terminators (explicit certs; SNICallback unsupported on Bun) ──
389
- const hostServers = new Map();
390
- const hostPorts = new Map();
391
- function hostTlsPort(host) {
392
- const existing = hostPorts.get(host);
393
- if (existing)
394
- return existing;
395
- const p = new Promise((resolve, reject) => {
626
+ // EVERY host advertises h2; the ORDER is what differs. Bun honours the
627
+ // SERVER's preference (verified: server ['http/1.1','h2'] + client
628
+ // ['h2','http/1.1'] negotiates http/1.1), so:
629
+ // * unclaimed host → ['http/1.1','h2']: dual-offer clients (curl, browsers,
630
+ // most SDKs) keep the h1 path untouched, while h2-only clients
631
+ // (gRPC/Connect — Cursor included) get h2 instead of a broken h1
632
+ // downgrade. h1 interception therefore has ZERO regression surface.
633
+ // * gateway-claimed host → ['h2','http/1.1']: the plugin wants h2 even
634
+ // from dual-offer clients (it speaks the vendor's h2 wire).
635
+ // The negotiated protocol is only a hint — the preface sniff below is the
636
+ // authority. Ports are assigned at the bottom (before any CONNECT arrives).
637
+ let innerH1Port = 0;
638
+ let innerH2Port = 0;
639
+ // Per-host terminators, LRU-bounded (see MAX_HOST_TERMINATORS): insertion
640
+ // order IS the LRU order — a hit re-inserts. Eviction closes the listener
641
+ // only, never an established connection (server.close stops accepting).
642
+ const terminators = new Map();
643
+ const pendingTerminators = new Map();
644
+ /**
645
+ * Evicted terminators still finishing their grace window (see
646
+ * evictTerminators). Bounded: the whole point of the LRU is a finite fd
647
+ * budget, so draining may not become a second unbounded cache.
648
+ */
649
+ const drainingTerminators = new Map();
650
+ /**
651
+ * Per-connection CONNECT authority, keyed by the loopback source port of the
652
+ * connection this proxy dials into the inner server (= the inner server's
653
+ * `remotePort`). Entries live exactly as long as their connection.
654
+ */
655
+ const mitmTargets = new Map();
656
+ function hostTlsPort(host, targetPort, caller) {
657
+ const h2First = listGatewayHosts().has(host);
658
+ // Cache by host + CONNECT port + ALPN mode + authenticated key: a runtime
659
+ // gateway install flips a host's ALPN order, a second CONNECT to another
660
+ // port of the same host needs its own authority context, and two keys must
661
+ // never share a terminator — the decrypted connection inherits the key of
662
+ // the CONNECT that created it (ADR-0017 attribution).
663
+ const cacheKey = `${host}:${targetPort}|${h2First ? 'gateway' : 'plain'}|${caller?.keyId ?? ''}`;
664
+ const live = terminators.get(cacheKey);
665
+ if (live) {
666
+ terminators.delete(cacheKey);
667
+ terminators.set(cacheKey, live);
668
+ return Promise.resolve(live.port);
669
+ }
670
+ const inflight = pendingTerminators.get(cacheKey);
671
+ if (inflight)
672
+ return inflight.then((t) => t.port);
673
+ const created = createTerminator(host, targetPort, h2First, cacheKey, caller).then((t) => {
674
+ pendingTerminators.delete(cacheKey);
675
+ return t;
676
+ }, (err) => {
677
+ // Never cache a FAILED creation — a transient listen error (e.g. an
678
+ // ephemeral-port collision) must not permanently degrade this host to
679
+ // the blind-tunnel fallback; the next connection retries from scratch.
680
+ pendingTerminators.delete(cacheKey);
681
+ throw err;
682
+ });
683
+ pendingTerminators.set(cacheKey, created);
684
+ return created.then((t) => t.port);
685
+ }
686
+ function createTerminator(host, targetPort, h2First, cacheKey, caller) {
687
+ return new Promise((resolve, reject) => {
396
688
  const { key, cert } = minter.get(host);
397
- const srv = tls.createServer({ key, cert, ALPNProtocols: ['http/1.1'] }, (tlsSock) => {
398
- // Attach SYNCHRONOUSLY — a Bun TLSSocket may drop data that arrives
399
- // with no listener; buffer until the loopback conn is ready.
400
- const pending = [];
401
- let conn = null;
402
- tlsSock.on('data', (d) => {
403
- if (conn) {
404
- if (!conn.write(d)) {
405
- tlsSock.pause();
406
- conn.once('drain', () => tlsSock.resume());
407
- }
408
- }
409
- else {
410
- pending.push(d);
689
+ const target = { host, port: targetPort, ...(caller ? { caller } : {}) };
690
+ let clientErrorLoggedAt = 0;
691
+ /** One ledger row per dedupe window for a client that never got a request through. */
692
+ const reportClientFailure = (reason) => {
693
+ const now = Date.now();
694
+ if (now - clientErrorLoggedAt < CLIENT_TLS_ERROR_DEDUPE_MS)
695
+ return;
696
+ clientErrorLoggedAt = now;
697
+ recordProxyConnect({ host, port: targetPort, note: `connect (${reason})` });
698
+ };
699
+ const srv = tls.createServer({ key, cert, ALPNProtocols: h2First ? ['h2', 'http/1.1'] : ['http/1.1', 'h2'] }, (tlsSock) => onDecryptedConnection(tlsSock, target, reportClientFailure));
700
+ // A client that REJECTS our leaf (certificate pinning, a missing CA in its
701
+ // trust store) fails inside the handshake and never sends a request, so
702
+ // this is the only place that failure is visible. The operator's question
703
+ // is always "why does this app not work through the proxy" — a console
704
+ // log line nobody tails is not an answer, so it lands in the ledger.
705
+ //
706
+ // Bun 1.3.14 does NOT emit `tlsClientError` when the client rejects the
707
+ // certificate (verified: the server sees `secureConnection` and then a
708
+ // bare socket close), so the abort is also caught on the decrypted stream
709
+ // (see onDecryptedConnection). Both paths share this dedupe: a pinned
710
+ // client retries in a tight loop and would otherwise evict every real row
711
+ // from the ring.
712
+ srv.on('tlsClientError', (e) => {
713
+ const message = String(e?.message || e);
714
+ log(`tlsClientError ${host}:${targetPort}: ${message}`);
715
+ reportClientFailure(`client TLS handshake failed: ${message}`);
716
+ });
717
+ srv.on('error', reject);
718
+ srv.listen(0, '127.0.0.1', () => {
719
+ const terminator = {
720
+ srv,
721
+ port: srv.address().port,
722
+ state: 'live',
723
+ };
724
+ terminators.set(cacheKey, terminator);
725
+ evictTerminators();
726
+ resolve(terminator);
727
+ });
728
+ });
729
+ }
730
+ /**
731
+ * Retire the LRU tail into a DRAINING set instead of closing it outright.
732
+ *
733
+ * `srv.close()` stops accepting but leaves established connections alone —
734
+ * however a CONNECT that already resolved this terminator's port and has not
735
+ * dialed yet would hit ECONNREFUSED and degrade to a blind tunnel, silently
736
+ * losing interception for that exchange. The grace window covers exactly that
737
+ * window; a drained terminator is never reused for a NEW CONNECT (it is out
738
+ * of `terminators`, so `hostTlsPort` misses and mints a fresh one).
739
+ */
740
+ function evictTerminators() {
741
+ const bound = deps.maxHostTerminators ?? MAX_HOST_TERMINATORS;
742
+ while (terminators.size > bound) {
743
+ const oldest = terminators.keys().next();
744
+ if (oldest.done)
745
+ return;
746
+ const victim = terminators.get(oldest.value);
747
+ terminators.delete(oldest.value);
748
+ if (!victim)
749
+ continue;
750
+ victim.state = 'draining';
751
+ drainingTerminators.set(oldest.value, victim);
752
+ const timer = setTimeout(() => {
753
+ drainingTerminators.delete(oldest.value);
754
+ try {
755
+ victim.srv.close();
756
+ }
757
+ catch { }
758
+ }, TERMINATOR_DRAIN_MS);
759
+ // Never hold the process open for a drained listener.
760
+ timer.unref?.();
761
+ while (drainingTerminators.size > MAX_DRAINING_TERMINATORS) {
762
+ const stale = drainingTerminators.keys().next();
763
+ if (stale.done)
764
+ break;
765
+ const forced = drainingTerminators.get(stale.value);
766
+ drainingTerminators.delete(stale.value);
767
+ try {
768
+ forced?.srv.close();
769
+ }
770
+ catch { }
771
+ }
772
+ log(`terminator evicted (LRU bound ${bound}), draining: ${oldest.value}`);
773
+ }
774
+ }
775
+ /**
776
+ * Decrypted-stream entry for one TLS session: decide h2 / h1 / Upgrade, then
777
+ * hand the bytes on.
778
+ *
779
+ * Attach SYNCHRONOUSLY — a Bun TLSSocket may drop data that arrives with no
780
+ * listener; buffer until the loopback conn is ready. Bun does not reliably
781
+ * expose alpnProtocol on the server side at callback time, so the negotiated
782
+ * ALPN is only a hint — the h2 connection preface ('PRI * HTTP/2.0') is the
783
+ * authority. On the h1 path the request head is buffered until it is
784
+ * complete so an `Upgrade:` handshake can be caught BEFORE the inner server
785
+ * (relayUpgrade); a head that outgrows MAX_HEAD_BYTES goes to the inner
786
+ * server unexamined.
787
+ */
788
+ function onDecryptedConnection(tlsSock, target, reportClientFailure) {
789
+ const pending = [];
790
+ let conn = null;
791
+ let decided = false;
792
+ /** Decrypted bytes seen so far — zero at close means the client never spoke. */
793
+ let decryptedBytes = 0;
794
+ /**
795
+ * Set when the inner request answered with a terminal error envelope: the
796
+ * client transport is closed as soon as that envelope has been handed over.
797
+ * The next chunk the inner server emits IS the envelope, so this is exact —
798
+ * no flush timing guesswork (an immediate `end()` truncated the response;
799
+ * the inner server's own socket `end()` is inert on Bun).
800
+ */
801
+ let abortRequested = false;
802
+ let abortTimer;
803
+ const finishAbort = () => {
804
+ if (abortTimer !== undefined) {
805
+ clearTimeout(abortTimer);
806
+ abortTimer = undefined;
807
+ }
808
+ if (!abortRequested)
809
+ return;
810
+ abortRequested = false;
811
+ try {
812
+ tlsSock.end();
813
+ }
814
+ catch { }
815
+ };
816
+ const onDecrypted = (d) => {
817
+ decryptedBytes += d.length;
818
+ if (conn) {
819
+ if (!conn.write(d)) {
820
+ tlsSock.pause();
821
+ conn.once('drain', () => tlsSock.resume());
822
+ }
823
+ return;
824
+ }
825
+ pending.push(d);
826
+ if (decided)
827
+ return;
828
+ const buf = Buffer.concat(pending);
829
+ const isH2 = tlsSock.alpnProtocol === 'h2' || buf.subarray(0, 14).toString('latin1') === 'PRI * HTTP/2.0';
830
+ if (!isH2) {
831
+ const headEnd = buf.indexOf('\r\n\r\n');
832
+ if (headEnd === -1) {
833
+ // No complete head yet: keep buffering ONLY while the bytes still
834
+ // look like an HTTP/1 request — a non-HTTP tunnel payload (or a head
835
+ // past MAX_HEAD_BYTES) must not wait for a head that never arrives.
836
+ const lineEnd = buf.indexOf('\r\n');
837
+ const firstLine = (lineEnd === -1 ? buf.subarray(0, 64) : buf.subarray(0, lineEnd)).toString('latin1');
838
+ const looksHttp = lineEnd === -1
839
+ ? /^[A-Z]{1,8}( [^\r\n]*)?$/.test(firstLine) // still mid request-line
840
+ : /^[A-Z]+ \S+ HTTP\/1\.[01]$/.test(firstLine);
841
+ if (buf.length <= MAX_HEAD_BYTES && looksHttp)
842
+ return;
843
+ }
844
+ else {
845
+ const parsed = parseUpgradeHead(buf.subarray(0, headEnd + 4).toString('latin1'), target.port);
846
+ if (parsed) {
847
+ decided = true;
848
+ tlsSock.removeListener('data', onDecrypted);
849
+ void relayUpgrade(tlsSock, buf, parsed);
850
+ return;
411
851
  }
412
- });
413
- tlsSock.on('end', () => {
414
- try {
415
- conn?.end();
852
+ }
853
+ }
854
+ decided = true;
855
+ conn = net.connect(isH2 ? innerH2Port : innerH1Port, '127.0.0.1', () => {
856
+ // Register the CONNECT target BEFORE the first byte reaches the inner
857
+ // server — the inner request must never run without its authority
858
+ // context. The key is this loopback connection's source port, which is
859
+ // exactly the inner server's `remotePort` for the same TCP connection.
860
+ const localPort = conn.localPort;
861
+ if (localPort) {
862
+ mitmTargets.set(localPort, {
863
+ host: target.host,
864
+ port: target.port,
865
+ ...(target.caller ? { caller: target.caller } : {}),
866
+ abort: () => {
867
+ if (abortRequested)
868
+ return;
869
+ abortRequested = true;
870
+ // Safety net: an envelope that never produces a chunk (or a
871
+ // response already mid-flight) still closes, just not instantly.
872
+ abortTimer = setTimeout(finishAbort, MITM_ABORT_FLUSH_MS);
873
+ abortTimer.unref?.();
874
+ },
875
+ });
876
+ }
877
+ for (const p of pending)
878
+ conn.write(p);
879
+ pending.length = 0;
880
+ conn.on('data', (d2) => {
881
+ if (!tlsSock.write(d2)) {
882
+ conn.pause();
883
+ tlsSock.once('drain', () => {
884
+ conn.resume();
885
+ finishAbort();
886
+ });
887
+ return;
416
888
  }
417
- catch { }
889
+ finishAbort();
418
890
  });
419
- tlsSock.on('error', () => {
891
+ conn.on('end', () => {
420
892
  try {
421
- conn?.destroy();
893
+ tlsSock.end();
422
894
  }
423
895
  catch { }
424
896
  });
425
- conn = net.connect(innerPort, '127.0.0.1', () => {
426
- for (const d of pending)
427
- conn.write(d);
428
- pending.length = 0;
429
- conn.on('data', (d) => {
430
- if (!tlsSock.write(d)) {
431
- conn.pause();
432
- tlsSock.once('drain', () => conn.resume());
433
- }
434
- });
435
- conn.on('end', () => {
436
- try {
437
- tlsSock.end();
438
- }
439
- catch { }
440
- });
441
- conn.on('error', () => {
442
- try {
443
- tlsSock.destroy();
444
- }
445
- catch { }
446
- });
447
- });
448
897
  conn.on('error', () => {
449
898
  try {
450
899
  tlsSock.destroy();
@@ -452,37 +901,113 @@ export async function createForwardProxyServer(deps) {
452
901
  catch { }
453
902
  });
454
903
  });
455
- srv.on('tlsClientError', (e) => log(`tlsClientError ${host}: ${e?.message || e}`));
456
- srv.on('error', reject);
457
- srv.listen(0, '127.0.0.1', () => {
458
- hostServers.set(host, srv);
459
- resolve(srv.address().port);
904
+ conn.on('close', () => {
905
+ const localPort = conn?.localPort;
906
+ if (localPort)
907
+ mitmTargets.delete(localPort);
908
+ });
909
+ conn.on('error', () => {
910
+ try {
911
+ tlsSock.destroy();
912
+ }
913
+ catch { }
460
914
  });
915
+ };
916
+ tlsSock.on('data', onDecrypted);
917
+ tlsSock.on('end', () => {
918
+ try {
919
+ conn?.end();
920
+ }
921
+ catch { }
461
922
  });
462
- const guarded = p.catch((err) => {
463
- // Never cache a FAILED creation — a transient listen error (e.g. an
464
- // ephemeral-port collision) must not permanently degrade this host to
465
- // the blind-tunnel fallback; the next connection retries from scratch.
466
- hostPorts.delete(host);
467
- throw err;
923
+ // The pinning signal Bun actually gives us: a TLS session that closes
924
+ // WITHOUT a single decrypted byte. A client that rejects our leaf aborts
925
+ // right after the handshake, so no request head ever arrives.
926
+ tlsSock.on('close', () => {
927
+ if (decryptedBytes === 0) {
928
+ reportClientFailure('client closed the intercepted TLS session before any request (certificate rejected or client abort)');
929
+ }
930
+ });
931
+ tlsSock.on('error', () => {
932
+ try {
933
+ conn?.destroy();
934
+ }
935
+ catch { }
468
936
  });
469
- hostPorts.set(host, guarded);
470
- return guarded;
471
937
  }
472
938
  // ── tunnel (no decryption) ──
473
- function tunnel(socket, host, port, replay, viaProxy) {
474
- // Per-host egress: bypass entries carry their own viaProxy flag (object
475
- // form); undefined (no-SNI/MITM-failure fallback) = global flag.
476
- const proxyUrl = transitProxyFor(host, port, viaProxy);
939
+ function tunnel(socket, host, port, replay) {
940
+ // Egress comes from the ordered rule table (ADR-0018).
941
+ const egress = transitEgressFor(host);
942
+ const proxyUrl = transitProxyFor(egress.proxy);
943
+ // Tunnel observation (ADR-0020): a blind tunnel is opaque BY DESIGN, so the
944
+ // identity we can see without decrypting (SNI, offered ALPN), the byte
945
+ // totals and the lifetime are the whole story. The peek rides the relay's
946
+ // own tap — it can never steal bytes from the splice.
947
+ const started = Date.now();
948
+ let reqBytes = replay?.length ?? 0;
949
+ let respBytes = 0;
950
+ let identity;
951
+ let identityDone = false;
952
+ const hello = [];
953
+ let helloTotal = 0;
954
+ const observe = (dir, chunk) => {
955
+ if (dir === 'b2a') {
956
+ respBytes += chunk.length;
957
+ return;
958
+ }
959
+ reqBytes += chunk.length;
960
+ if (identityDone)
961
+ return;
962
+ hello.push(chunk);
963
+ helloTotal += chunk.length;
964
+ const peek = peekClientHello(Buffer.concat(hello, helloTotal));
965
+ if (!peek.isTls) {
966
+ identityDone = true;
967
+ identity = 'not tls';
968
+ return;
969
+ }
970
+ if (peek.complete || helloTotal > MAX_HELLO_BYTES) {
971
+ identityDone = true;
972
+ // The peek buffer is only needed until the identity is known; a tunnel
973
+ // can outlive it by hours, so do not pin the hello bytes.
974
+ hello.length = 0;
975
+ if (!peek.complete)
976
+ return;
977
+ const bits = [peek.sni ? `sni ${peek.sni}` : 'no sni'];
978
+ // Space-separated: a protocol id may itself contain '/', so a slash
979
+ // separator would make "h2" + "http/1.1" unreadable.
980
+ if (peek.alpn?.length)
981
+ bits.push(`alpn ${peek.alpn.join(' ')}`);
982
+ identity = bits.join(', ');
983
+ }
984
+ };
985
+ let closed = false;
986
+ const closeRow = (note) => {
987
+ if (closed)
988
+ return;
989
+ closed = true;
990
+ recordProxyTunnel({
991
+ host,
992
+ port,
993
+ note: identity ? `${note}, ${identity}` : note,
994
+ reqBytes,
995
+ respBytes,
996
+ durationMs: Date.now() - started,
997
+ });
998
+ };
999
+ socket.on('close', () => closeRow('connect (tunnel closed)'));
477
1000
  if (proxyUrl) {
478
1001
  openViaProxy(proxyUrl, host, port)
479
1002
  .then((up) => {
1003
+ up.on('close', () => closeRow('connect (tunnel via outbound proxy closed)'));
480
1004
  if (replay && replay.length)
481
1005
  up.write(replay);
482
- splice(socket, up);
1006
+ splice(socket, up, observe);
483
1007
  })
484
1008
  .catch((err) => {
485
1009
  log(`tunnel via outbound proxy failed for ${host}:${port}: ${err?.message || err}`);
1010
+ closeRow(`connect (tunnel failed: outbound proxy ${err?.code || err?.message || err})`);
486
1011
  try {
487
1012
  socket.destroy();
488
1013
  }
@@ -493,8 +1018,10 @@ export async function createForwardProxyServer(deps) {
493
1018
  const up = net.connect(port, host, () => {
494
1019
  if (replay && replay.length)
495
1020
  up.write(replay);
496
- splice(socket, up);
1021
+ splice(socket, up, observe);
497
1022
  });
1023
+ up.on('close', () => closeRow('connect (tunnel closed)'));
1024
+ up.on('error', (err) => closeRow(`connect (tunnel failed: ${err?.code || err?.message || err})`));
498
1025
  up.on('error', () => {
499
1026
  try {
500
1027
  socket.destroy();
@@ -508,16 +1035,263 @@ export async function createForwardProxyServer(deps) {
508
1035
  catch { }
509
1036
  });
510
1037
  }
1038
+ /**
1039
+ * WebSocket / generic `Upgrade:` relay on the MITM leg.
1040
+ *
1041
+ * Bun's node:http 'upgrade' event is NOT usable (verified on 1.3.14: the
1042
+ * socket handed to the handler swallows every write and the parser keeps
1043
+ * running, answering 505 to whatever the client sends next), so the
1044
+ * handshake is caught on the DECRYPTED stream before it reaches the inner
1045
+ * server and relayed byte-verbatim: request head (+ any bytes the client
1046
+ * already pipelined after it) → origin socket, then a raw bidirectional
1047
+ * splice. Nothing is re-serialized — an upgrade is a single hop, so the
1048
+ * client's own handshake headers are exactly what the origin must see, and
1049
+ * any upgrade protocol rides this path, not just WebSocket.
1050
+ *
1051
+ * Non-TLS `ws://` through the plain proxy port is NOT covered: that leg
1052
+ * never decrypts, and the same runtime gap blocks its 'upgrade' event.
1053
+ */
1054
+ async function relayUpgrade(tlsSock, head, parsed) {
1055
+ const { host, port } = parsed;
1056
+ // A client gateway may OWN the handshake (a WS-native vendor wire). Without
1057
+ // this hook an upgrade on a claimed host is relayed verbatim and the plugin
1058
+ // never sees it — the same host would be handled for requests but not for
1059
+ // sockets. Returning false (or throwing) falls through to the relay.
1060
+ const gateway = findGateway({ method: parsed.method, url: parsed.path, headers: parsed.headers });
1061
+ if (gateway?.handleUpgrade) {
1062
+ try {
1063
+ const owned = await gateway.handleUpgrade({
1064
+ socket: tlsSock,
1065
+ head,
1066
+ host,
1067
+ port,
1068
+ method: parsed.method,
1069
+ path: parsed.path,
1070
+ headers: parsed.headers,
1071
+ });
1072
+ if (owned)
1073
+ return;
1074
+ }
1075
+ catch {
1076
+ // Ownership was ambiguous — never leave the client hanging on a socket
1077
+ // nobody drives; the gateway already had its chance to answer.
1078
+ try {
1079
+ tlsSock.destroy();
1080
+ }
1081
+ catch { }
1082
+ return;
1083
+ }
1084
+ }
1085
+ const tap = createAccessTap({
1086
+ host,
1087
+ port,
1088
+ method: parsed.method,
1089
+ path: parsed.path,
1090
+ requestHeaders: parsed.headers,
1091
+ });
1092
+ let status;
1093
+ let finished = false;
1094
+ const finish = (note) => {
1095
+ if (finished)
1096
+ return;
1097
+ finished = true;
1098
+ tap?.finish(status, undefined, note);
1099
+ };
1100
+ // Only answer with an error envelope while the origin has said nothing —
1101
+ // once its bytes are flowing, the client owns the stream.
1102
+ const fail = (note) => {
1103
+ finish(note);
1104
+ if (status !== undefined) {
1105
+ try {
1106
+ tlsSock.destroy();
1107
+ }
1108
+ catch { }
1109
+ return;
1110
+ }
1111
+ try {
1112
+ tlsSock.write(`HTTP/1.1 502 Bad Gateway\r\nContent-Type: text/plain; charset=utf-8\r\nConnection: close\r\n\r\nForward proxy: ${note}`);
1113
+ tlsSock.end();
1114
+ }
1115
+ catch { }
1116
+ };
1117
+ /**
1118
+ * The same answer, built from a classified origin failure (ADR-0019): status,
1119
+ * client-facing sentence and ledger note all come from
1120
+ * `describeUpstreamFailure`, so an upgrade leg reports a TLS trust failure
1121
+ * exactly like the h1 and h2 legs do.
1122
+ */
1123
+ const failWith = (failure) => {
1124
+ finish(failure.note);
1125
+ if (status !== undefined) {
1126
+ try {
1127
+ tlsSock.destroy();
1128
+ }
1129
+ catch { }
1130
+ return;
1131
+ }
1132
+ try {
1133
+ tlsSock.write(`HTTP/1.1 ${failure.status} ${failure.status === 504 ? 'Gateway Timeout' : 'Bad Gateway'}\r\n` +
1134
+ 'Content-Type: text/plain; charset=utf-8\r\nConnection: close\r\n\r\n' +
1135
+ failure.message);
1136
+ tlsSock.end();
1137
+ }
1138
+ catch { }
1139
+ };
1140
+ const onOrigin = (origin) => {
1141
+ // Hang guard until the origin answers: a blackholed upgrade must not
1142
+ // hold the client's socket open forever. Cleared on the first byte so a
1143
+ // long-lived WebSocket is never killed.
1144
+ const hang = setTimeout(() => {
1145
+ try {
1146
+ origin.destroy();
1147
+ }
1148
+ catch { }
1149
+ fail('upgrade upstream timed out');
1150
+ }, FORWARD_PROXY_HANG_TIMEOUT_MS);
1151
+ // Frame-level observation (ADR-0020): the relay stays byte-verbatim, the
1152
+ // observer only counts what crosses it. Frames begin after the origin
1153
+ // response head, so the first chunk is split at its CRLFCRLF marker.
1154
+ const ws = createWsObserver();
1155
+ let responseHeadSeen = false;
1156
+ // The response head is accumulated across chunks: an origin may split it,
1157
+ // and the frames start at its end — guessing from a single chunk either
1158
+ // lost the status or fed handshake bytes to the frame parser.
1159
+ let responseHead = '';
1160
+ const noteFor = () => (status === 101 ? ws.note() : '');
1161
+ origin.on('data', (d) => {
1162
+ clearTimeout(hang);
1163
+ tap?.onResChunk(d);
1164
+ if (!responseHeadSeen) {
1165
+ responseHead += d.toString('latin1');
1166
+ const end = responseHead.indexOf('\r\n\r\n');
1167
+ if (end === -1) {
1168
+ if (responseHead.length > MAX_HEAD_BYTES)
1169
+ responseHeadSeen = true;
1170
+ return;
1171
+ }
1172
+ responseHeadSeen = true;
1173
+ if (status === undefined) {
1174
+ const m = /^HTTP\/1\.[01] (\d{3})/.exec(responseHead.slice(0, 16));
1175
+ if (m)
1176
+ status = Number(m[1]);
1177
+ }
1178
+ const rest = responseHead.slice(end + 4);
1179
+ if (rest.length)
1180
+ ws.push('s2c', Buffer.from(rest, 'latin1'));
1181
+ return;
1182
+ }
1183
+ ws.push('s2c', d);
1184
+ });
1185
+ tlsSock.on('data', (d) => {
1186
+ tap?.onReqChunk(d);
1187
+ ws.push('c2s', d);
1188
+ });
1189
+ origin.on('close', () => {
1190
+ clearTimeout(hang);
1191
+ finish(noteFor());
1192
+ });
1193
+ tlsSock.on('close', () => {
1194
+ clearTimeout(hang);
1195
+ finish(noteFor());
1196
+ });
1197
+ origin.write(head);
1198
+ splice(tlsSock, origin);
1199
+ };
1200
+ const egress = transitEgressFor(host);
1201
+ const proxyUrl = transitProxyFor(egress.proxy);
1202
+ const upstreamTls = resolveUpstreamTls(deps.upstreamTls).opts;
1203
+ if (proxyUrl) {
1204
+ openViaProxy(proxyUrl, host, port)
1205
+ .then((tunnelSock) => {
1206
+ try {
1207
+ const origin = tls.connect({ socket: tunnelSock, ...upstreamServernameOption(host), ...(upstreamTls || {}) }, () => onOrigin(origin));
1208
+ origin.once('error', (err) => failWith(describeUpstreamFailure(err, { proxied: true })));
1209
+ }
1210
+ catch {
1211
+ // A synchronous TLS-option throw (bad servername, bad material) must
1212
+ // not escape a socket callback — answer the client instead.
1213
+ try {
1214
+ tunnelSock.destroy();
1215
+ }
1216
+ catch { }
1217
+ fail('upgrade upstream TLS setup failed');
1218
+ }
1219
+ })
1220
+ .catch((err) => fail(`upgrade outbound proxy connection failed${err?.code ? ` (${err.code})` : ''}`));
1221
+ return;
1222
+ }
1223
+ try {
1224
+ const origin = tls.connect({ host, port, ...upstreamServernameOption(host), ...(upstreamTls || {}) }, () => onOrigin(origin));
1225
+ origin.once('error', (err) => failWith(describeUpstreamFailure(err)));
1226
+ }
1227
+ catch {
1228
+ fail('upgrade upstream TLS setup failed');
1229
+ }
1230
+ }
511
1231
  // ── CONNECT: peek ClientHello → MITM, else blind tunnel ──
512
1232
  function handleConnect(req, socket, head) {
513
- const [rawHost, rawPort] = String(req.url || '').split(':');
514
- const port = parseInt(rawPort || '443', 10) || 443;
1233
+ // Bracket-aware: `[::1]:8443` is a valid authority, and `rawHost` becomes
1234
+ // the CERTIFICATE IDENTITY for a no-SNI client (see the MITM branch), so a
1235
+ // naive `split(':')` would mint a leaf for `[`.
1236
+ const { host: rawHost, port } = splitHostPort(String(req.url || ''), 443);
1237
+ if (!rawHost) {
1238
+ try {
1239
+ socket.end('HTTP/1.1 400 Bad Request\r\n\r\n');
1240
+ }
1241
+ catch { }
1242
+ return;
1243
+ }
1244
+ const auth = authorize(req.headers['proxy-authorization']);
1245
+ if (!auth.ok) {
1246
+ if (shouldRecordPreAdmission(`407:${rawHost}`)) {
1247
+ recordProxyConnect({ host: rawHost, port, note: 'connect (407, missing or bad proxy auth)' });
1248
+ }
1249
+ try {
1250
+ socket.end(PROXY_AUTH_REQUIRED_RESPONSE);
1251
+ }
1252
+ catch { }
1253
+ return;
1254
+ }
1255
+ const caller = auth.caller;
1256
+ if (!admit(socket)) {
1257
+ // A raw socket may not be TLS-ready yet, so there is no status line to
1258
+ // write — closing it is the only honest answer.
1259
+ if (shouldRecordPreAdmission(`cap:${rawHost}`)) {
1260
+ recordProxyConnect({ host: rawHost, port, note: 'connect (503-equivalent, connection cap reached)' });
1261
+ }
1262
+ try {
1263
+ socket.destroy();
1264
+ }
1265
+ catch { }
1266
+ return;
1267
+ }
1268
+ // Rule admission (ADR-0018): a rejected host is answered 403 on the raw
1269
+ // socket BEFORE the 200, so no tunnel is opened and no certificate is
1270
+ // minted for a host this machine refuses to reach.
1271
+ if (isRuleRejected(rawHost)) {
1272
+ log(`reject CONNECT ${rawHost}:${port} (egress rule)`);
1273
+ recordProxyConnect({ host: rawHost, port, note: 'connect (rejected by rule)' });
1274
+ try {
1275
+ socket.end(RULE_REJECT_RESPONSE);
1276
+ }
1277
+ catch { }
1278
+ return;
1279
+ }
515
1280
  socket.write('HTTP/1.1 200 Connection Established\r\n\r\n');
516
1281
  if (head && head.length)
517
1282
  socket.unshift(head);
518
- const bb = matchBypass(rawHost, deps.bypassHosts);
519
- if (bb.bypassed) {
520
- tunnel(socket, rawHost, port, undefined, bb.viaProxy);
1283
+ // A credential-less admission is legal only while the live config allows
1284
+ // it; remember the opened tunnel so a later `requireCredential` save can
1285
+ // retire it (admission itself is per-connection).
1286
+ if (!caller)
1287
+ trackUnauthenticatedTunnel(socket);
1288
+ if (ruleTunnels(rawHost)) {
1289
+ recordProxyConnect({ host: rawHost, port, note: 'connect (blind tunnel)' });
1290
+ // Any bytes that arrived with the CONNECT are ALREADY back in the socket's
1291
+ // read buffer (the unshift above), so no replay is passed here: doing so
1292
+ // would duplicate the client's first bytes upstream. The identity peek
1293
+ // rides the relay's tap, which is attached at dial time.
1294
+ tunnel(socket, rawHost, port);
521
1295
  return;
522
1296
  }
523
1297
  const chunks = [];
@@ -529,20 +1303,39 @@ export async function createForwardProxyServer(deps) {
529
1303
  chunks.push(d);
530
1304
  total += d.length;
531
1305
  const buf = Buffer.concat(chunks, total);
532
- const sni = parseClientHelloSNI(buf);
533
- if (sni) {
1306
+ const peek = peekClientHello(buf);
1307
+ if (!peek.isTls) {
1308
+ // Not a TLS handshake at all (SSH, IMAPS, a bespoke protocol): relay it
1309
+ // NOW. Waiting for a ClientHello that can never arrive used to stall
1310
+ // such a tunnel until 32 KiB had accumulated on the socket.
534
1311
  decided = true;
535
1312
  socket.pause();
536
1313
  socket.removeListener('data', onData);
537
- log(`MITM ${sni}`);
538
- void startMitm(socket, buf, sni);
1314
+ log(`tunnel ${rawHost}:${port} (not tls)`);
1315
+ recordProxyConnect({ host: rawHost, port, note: 'connect (not tls, blind tunnel)' });
1316
+ tunnel(socket, rawHost, port, buf);
1317
+ return;
1318
+ }
1319
+ if (peek.complete) {
1320
+ // A ClientHello WITHOUT SNI is still interceptable: the CONNECT
1321
+ // authority is the only identity the client offered (IP-literal
1322
+ // targets can never carry SNI — RFC 6066 forbids an IP there). Falling
1323
+ // back to a blind tunnel here let any client opt out of interception
1324
+ // simply by omitting the extension.
1325
+ const identity = peek.sni || rawHost;
1326
+ decided = true;
1327
+ socket.pause();
1328
+ socket.removeListener('data', onData);
1329
+ log(peek.sni ? `MITM ${identity}` : `MITM ${identity} (no SNI, authority identity)`);
1330
+ void startMitm(socket, buf, identity, port, peek.sni ? 'sni' : 'authority', caller);
539
1331
  return;
540
1332
  }
541
1333
  if (total > MAX_HELLO_BYTES) {
542
1334
  decided = true;
543
1335
  socket.pause();
544
1336
  socket.removeListener('data', onData);
545
- log(`tunnel ${rawHost}:${port} (no SNI parsed)`);
1337
+ log(`tunnel ${rawHost}:${port} (ClientHello never completed)`);
1338
+ recordProxyConnect({ host: rawHost, port, note: 'connect (hello incomplete, blind tunnel)' });
546
1339
  tunnel(socket, rawHost, port, buf);
547
1340
  }
548
1341
  };
@@ -554,9 +1347,14 @@ export async function createForwardProxyServer(deps) {
554
1347
  catch { }
555
1348
  });
556
1349
  }
557
- async function startMitm(socket, hello, sni) {
1350
+ async function startMitm(socket, hello, identity, connectPort, by, caller) {
558
1351
  try {
559
- const port = await hostTlsPort(sni);
1352
+ const port = await hostTlsPort(identity, connectPort, caller);
1353
+ recordProxyConnect({
1354
+ host: identity,
1355
+ port: connectPort,
1356
+ note: by === 'sni' ? 'connect (mitm)' : 'connect (mitm by authority, no sni)',
1357
+ });
560
1358
  const up = net.connect(port, '127.0.0.1', () => {
561
1359
  up.write(hello);
562
1360
  splice(socket, up);
@@ -575,8 +1373,9 @@ export async function createForwardProxyServer(deps) {
575
1373
  });
576
1374
  }
577
1375
  catch (err) {
578
- log(`MITM setup failed for ${sni}: ${err?.message || err} — blind tunnel fallback`);
579
- tunnel(socket, sni, 443);
1376
+ log(`MITM setup failed for ${identity}: ${err?.message || err} — blind tunnel fallback`);
1377
+ recordProxyConnect({ host: identity, port: connectPort, note: 'connect (mitm setup failed, blind tunnel fallback)' });
1378
+ tunnel(socket, identity, connectPort);
580
1379
  }
581
1380
  }
582
1381
  // ── outer proxy server: CONNECT + plain-HTTP absolute-URI requests ──
@@ -590,65 +1389,246 @@ export async function createForwardProxyServer(deps) {
590
1389
  }
591
1390
  catch { }
592
1391
  });
1392
+ /**
1393
+ * The ONLY proxy credential (ADR-0017): the Basic password must resolve to
1394
+ * an enabled, unexpired OCR API key, and the tunnel inherits its identity.
1395
+ * Username is ignored (browsers and several SDKs cannot set one; key names
1396
+ * are not unique). Loopback without a credential remains open (historical
1397
+ * posture) unless `forwardProxy.requireCredential` is enabled; a non-loopback
1398
+ * bind is `authRequired` and fails closed.
1399
+ */
1400
+ const authorize = (header) => {
1401
+ // Strict mode (hot-applies): `forwardProxy.requireCredential` closes the
1402
+ // loopback loophole, so a gateway plugin's bound key can never act as the
1403
+ // identity of an unauthenticated local process.
1404
+ const required = deps.authRequired === true || deps.liveForwardProxy?.()?.requireCredential === true;
1405
+ const raw = Array.isArray(header) ? header[0] : header;
1406
+ if (!raw)
1407
+ return required ? { ok: false } : { ok: true };
1408
+ const scheme = /^Basic\s+(.+)$/i.exec(raw.trim());
1409
+ if (!scheme)
1410
+ return { ok: false };
1411
+ let decoded;
1412
+ try {
1413
+ decoded = Buffer.from(scheme[1], 'base64').toString('utf8');
1414
+ }
1415
+ catch {
1416
+ return { ok: false };
1417
+ }
1418
+ const colon = decoded.indexOf(':');
1419
+ const secret = colon === -1 ? decoded : decoded.slice(colon + 1);
1420
+ const key = deps.resolveApiKey?.(secret);
1421
+ return key ? { ok: true, caller: { keyId: key.id, name: key.name } } : { ok: false };
1422
+ };
1423
+ // ── strict credential mode: retire tunnels admitted WITHOUT one ──
1424
+ // Admission is per-connection, so a CONNECT opened before the operator
1425
+ // enabled `forwardProxy.requireCredential` would otherwise keep its tunnel
1426
+ // (and its capture/egress) until the client closed it. Track exactly those
1427
+ // tunnels and close them as soon as the live config demands a credential;
1428
+ // the timer only exists while at least one such tunnel is open.
1429
+ const unauthenticatedTunnels = new Set();
1430
+ let strictSweep;
1431
+ function stopStrictSweepIfIdle() {
1432
+ if (unauthenticatedTunnels.size === 0 && strictSweep) {
1433
+ clearInterval(strictSweep);
1434
+ strictSweep = undefined;
1435
+ }
1436
+ }
1437
+ function trackUnauthenticatedTunnel(socket) {
1438
+ unauthenticatedTunnels.add(socket);
1439
+ socket.once('close', () => {
1440
+ unauthenticatedTunnels.delete(socket);
1441
+ stopStrictSweepIfIdle();
1442
+ });
1443
+ if (strictSweep)
1444
+ return;
1445
+ strictSweep = setInterval(() => {
1446
+ if (deps.liveForwardProxy?.()?.requireCredential !== true)
1447
+ return;
1448
+ for (const tunnel of unauthenticatedTunnels) {
1449
+ try {
1450
+ tunnel.destroy();
1451
+ }
1452
+ catch { }
1453
+ }
1454
+ unauthenticatedTunnels.clear();
1455
+ stopStrictSweepIfIdle();
1456
+ }, 1000);
1457
+ strictSweep.unref?.();
1458
+ }
1459
+ // ── inbound socket cap ──
1460
+ // Every tunneled/MITM'd socket costs TWO fds (the accepted socket plus its
1461
+ // decrypted loopback peer) and, when MITM'd, a TLS terminator — so an
1462
+ // unbounded proxy listener is a local fd-exhaustion vector: one client can
1463
+ // open CONNECTs faster than the OS reclaims them.
1464
+ //
1465
+ // The cap is enforced at ADMISSION (the two points where the proxy starts
1466
+ // spending resources: a CONNECT tunnel and a plain-HTTP request), not at
1467
+ // accept time, because Bun's node:http exposes none of the accept-side hooks
1468
+ // (verified on 1.3.14: no `'connection'` event on http.Server, and both
1469
+ // `server.maxConnections` and `server.timeout` are inert). A socket that
1470
+ // never sends a byte is therefore bounded only by the listen backlog; the
1471
+ // admission cap covers the part that multiplies. The cap is read per
1472
+ // admission, so a console save hot-applies.
1473
+ const liveSockets = new Set();
1474
+ let capWarnedAt = 0;
1475
+ const currentCap = () => deps.liveForwardProxy?.()?.maxConnections ?? deps.maxConnections ?? DEFAULT_FORWARD_PROXY_MAX_CONNECTIONS;
1476
+ /** true = this socket may proceed; false = it was already refused. */
1477
+ const admit = (socket) => {
1478
+ if (liveSockets.has(socket))
1479
+ return true;
1480
+ const cap = currentCap();
1481
+ if (liveSockets.size >= cap) {
1482
+ const now = Date.now();
1483
+ if (now - capWarnedAt > CLIENT_TLS_ERROR_DEDUPE_MS) {
1484
+ capWarnedAt = now;
1485
+ log(`connection cap reached (${cap}) — refusing new exchanges`);
1486
+ }
1487
+ return false;
1488
+ }
1489
+ liveSockets.add(socket);
1490
+ // Bun emits 'end' but NOT 'close' on the socket it hands to an http.Server
1491
+ // 'connect' handler (verified on 1.3.14), so releasing only on 'close'
1492
+ // would leak a slot per finished tunnel and wedge the cap shut. All three
1493
+ // terminal signals release; a double release is a no-op on a Set.
1494
+ const release = () => {
1495
+ liveSockets.delete(socket);
1496
+ };
1497
+ socket.once('close', release);
1498
+ socket.once('end', release);
1499
+ socket.once('error', release);
1500
+ return true;
1501
+ };
593
1502
  async function handlePlainProxyRequest(req, res) {
1503
+ const auth = authorize(req.headers['proxy-authorization']);
1504
+ if (!auth.ok) {
1505
+ const plainAuthHost = String(req.headers.host || req.socket.remoteAddress || 'unknown').split(':')[0];
1506
+ if (shouldRecordPreAdmission(`407:${plainAuthHost}`)) {
1507
+ recordProxyConnect({
1508
+ host: plainAuthHost,
1509
+ port: req.socket.remotePort || 0,
1510
+ note: `plain ${req.method || '?'} (407, missing or bad proxy auth)`,
1511
+ });
1512
+ }
1513
+ try {
1514
+ res.writeHead(407, {
1515
+ 'proxy-authenticate': `Basic realm="${PROXY_AUTH_REALM}"`,
1516
+ 'content-length': '0',
1517
+ connection: 'close',
1518
+ });
1519
+ res.end();
1520
+ }
1521
+ catch { }
1522
+ return;
1523
+ }
1524
+ markProxyCaller(req, auth.caller);
594
1525
  let target;
1526
+ let target0;
595
1527
  try {
596
1528
  target = new URL(req.url || '');
1529
+ target0 = target;
597
1530
  }
598
1531
  catch {
599
- res.writeHead(400, { 'content-type': 'text/plain; charset=utf-8' });
600
- res.end('Forward proxy requires an absolute-form request URI');
1532
+ const badReqHost = String(req.headers.host || req.socket.remoteAddress || 'unknown').split(':')[0];
1533
+ if (shouldRecordPreAdmission(`badreq:${badReqHost}`)) {
1534
+ recordProxyConnect({
1535
+ host: badReqHost,
1536
+ port: req.socket.remotePort || 0,
1537
+ note: `plain ${req.method || '?'} (400, not an absolute-form request URI)`,
1538
+ });
1539
+ }
1540
+ proxyFail(res, 400, 'Forward proxy requires an absolute-form request URI');
601
1541
  return;
602
1542
  }
603
- const bb = matchBypass(target.hostname, deps.bypassHosts);
1543
+ if (!admit(req.socket)) {
1544
+ if (shouldRecordPreAdmission(`cap:${target0.hostname}`)) {
1545
+ recordProxyConnect({
1546
+ host: target0.hostname,
1547
+ port: parseInt(target0.port || '0', 10),
1548
+ note: `plain ${req.method} (503, connection cap reached)`,
1549
+ });
1550
+ }
1551
+ proxyFail(res, 503, 'Forward proxy: connection limit reached');
1552
+ return;
1553
+ }
1554
+ const intercept = !ruleTunnels(target.hostname);
604
1555
  try {
605
- if (!bb.bypassed && (await deps.intercept(req, res)))
1556
+ // `ingress: 'passthrough'` = a blind tunnel: the intercept chain never
1557
+ // runs and the exchange is forwarded transparently.
1558
+ if (intercept && (await deps.intercept(req, res)))
1559
+ return;
1560
+ const tap = createAccessTap({
1561
+ host: target.hostname,
1562
+ port: parseInt(target.port || (target.protocol === 'https:' ? '443' : '80'), 10),
1563
+ method: req.method,
1564
+ path: req.url || '/',
1565
+ wire: String(req.headers.upgrade ?? '').toLowerCase().includes('websocket') ? 'ws' : 'h1',
1566
+ requestHeaders: req.headers,
1567
+ });
1568
+ if (isRuleRejected(target.hostname)) {
1569
+ tap?.finish(403, undefined, 'rejected by rule');
1570
+ proxyFail(res, 403, RULE_REJECTED_MESSAGE);
606
1571
  return;
1572
+ }
607
1573
  await forwardTo(req, res, {
608
1574
  host: target.hostname,
609
1575
  port: parseInt(target.port || (target.protocol === 'https:' ? '443' : '80'), 10),
610
1576
  path: target.pathname + target.search,
611
1577
  secure: target.protocol === 'https:',
612
- viaProxy: bb.bypassed ? bb.viaProxy : undefined,
613
- });
1578
+ tap,
1579
+ }, resolveUpstreamTls(deps.upstreamTls));
614
1580
  }
615
1581
  catch {
616
- try {
617
- if (!res.headersSent)
618
- res.writeHead(502, { 'content-type': 'text/plain; charset=utf-8' });
619
- res.end('Forward proxy error');
620
- }
621
- catch { }
1582
+ proxyFail(res, 502, 'Forward proxy error');
622
1583
  }
623
1584
  }
624
1585
  await listen(inner);
625
- const innerPort = inner.address().port;
1586
+ innerH1Port = inner.address().port;
1587
+ await listen(h2Inner);
1588
+ innerH2Port = h2Inner.address().port;
626
1589
  try {
627
1590
  await listen(proxy, deps.port, deps.host);
628
1591
  }
629
1592
  catch (err) {
630
- // Fault-tolerance: never leak the inner listener when our public listen
1593
+ // Fault-tolerance: never leak the inner listeners when our public listen
631
1594
  // fails (port busy etc.) — the caller logs the error and the gateway
632
1595
  // keeps running without the proxy.
633
1596
  try {
634
1597
  inner.close();
635
1598
  }
636
1599
  catch { }
1600
+ try {
1601
+ h2Inner.close();
1602
+ }
1603
+ catch { }
637
1604
  throw err;
638
1605
  }
639
1606
  const port = proxy.address().port;
640
- log(`listening on ${deps.host}:${port} (inner ${innerPort})`);
1607
+ log(`listening on ${deps.host}:${port} (inner h1 ${innerH1Port}, h2 ${innerH2Port})`);
641
1608
  return {
642
1609
  port,
643
1610
  caCertPem: ca.caCertPem,
1611
+ activeConnections: () => liveSockets.size,
644
1612
  close() {
645
1613
  return new Promise((resolve) => {
646
- for (const srv of hostServers.values()) {
1614
+ for (const terminator of terminators.values()) {
1615
+ try {
1616
+ terminator.srv.close();
1617
+ }
1618
+ catch { }
1619
+ }
1620
+ for (const terminator of drainingTerminators.values()) {
647
1621
  try {
648
- srv.close();
1622
+ terminator.srv.close();
649
1623
  }
650
1624
  catch { }
651
1625
  }
1626
+ if (strictSweep) {
1627
+ clearInterval(strictSweep);
1628
+ strictSweep = undefined;
1629
+ }
1630
+ unauthenticatedTunnels.clear();
1631
+ drainingTerminators.clear();
652
1632
  try {
653
1633
  proxy.close();
654
1634
  }
@@ -657,17 +1637,42 @@ export async function createForwardProxyServer(deps) {
657
1637
  inner.close();
658
1638
  }
659
1639
  catch { }
1640
+ try {
1641
+ h2Inner.close();
1642
+ }
1643
+ catch { }
1644
+ closeH2Pool();
660
1645
  resolve();
661
1646
  });
662
1647
  },
663
1648
  };
664
1649
  }
665
- function listen(server, port = 0, host = '127.0.0.1') {
666
- return new Promise((resolve, reject) => {
667
- server.once('error', reject);
668
- server.listen(port, host, () => {
669
- server.removeListener('error', reject);
670
- resolve();
671
- });
672
- });
1650
+ /**
1651
+ * Listen with one EADDRINUSE retry. Port 0 means the OS picks a free port, so
1652
+ * a collision should be impossible — but under concurrent test workers Bun has
1653
+ * been observed racing the ephemeral allocation (EADDRINUSE on port 0). The
1654
+ * retry keeps that infrastructure flake from masking real regressions.
1655
+ */
1656
+ async function listen(server, port = 0, host = '127.0.0.1') {
1657
+ for (let attempt = 0;; attempt++) {
1658
+ try {
1659
+ await new Promise((resolve, reject) => {
1660
+ server.once('error', reject);
1661
+ server.listen(port, host, () => {
1662
+ server.removeListener('error', reject);
1663
+ resolve();
1664
+ });
1665
+ });
1666
+ return;
1667
+ }
1668
+ catch (err) {
1669
+ if (attempt > 0 || err?.code !== 'EADDRINUSE')
1670
+ throw err;
1671
+ // Detach the dead listener state before retrying the same server.
1672
+ try {
1673
+ server.close();
1674
+ }
1675
+ catch { }
1676
+ }
1677
+ }
673
1678
  }