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
@@ -1,45 +1,160 @@
1
- import crypto from 'node:crypto';
2
1
  import path from 'node:path';
3
- import { EFFORT_LADDER, TIER_RANK, downgradeReasoning } from '../types/router.js';
2
+ import { EFFORT_LADDER, TIER_RANK, downgradeReasoning, effortFromThinkingBudget } from '../types/router.js';
4
3
  import { PromptOptimizer } from './prompt-optimizer.js';
4
+ import { repairToolCallPairing } from './tool-pairing.js';
5
5
  import { applyCompression } from '../compression/index.js';
6
6
  import { RouterEngine, routingModeForceTier } from '../router/index.js';
7
- import { hasToolsOrSchema } from '../router/request-traits.js';
7
+ import { declaresJsonContract, hasToolsOrSchema } from '../router/request-traits.js';
8
8
  import { getRouteEntryStore, routeEntriesGate, promptHashOf, normalizePrompt, L2_CONFIDENT_THRESHOLD, } from '../router/route-entries.js';
9
- import { scanDirectives, applyTierDirectives, applyEffortDirectives } from './directives.js';
9
+ import { scanDirectives, scrubWireDirectives, applyTierDirectives, applyEffortDirectives } from './directives.js';
10
10
  import { directivesGate } from './directive-gate.js';
11
+ import { streamingPosture } from './streaming-posture.js';
11
12
  import { DEFAULT_LAYER2_EFFORT_FLOOR } from '../config/defaults.js';
12
13
  import { appendRoutingLedger } from '../router/routing-ledger.js';
13
14
  import { SchemaAssertion } from '../validator/schema-assertion.js';
14
15
  import { FallbackContextBuilder } from '../validator/parser.js';
15
16
  import { applyEffortMap } from '../providers/member-match.js';
17
+ import { protocolForWire } from '../providers/vocabulary.js';
18
+ import { capabilitiesFor } from '../ir/capabilities.js';
19
+ import { IrUnsupportedError } from '../ir/errors.js';
16
20
  import { computeRequestCost } from '../metrics/request-cost.js';
17
- import { getRateLimiter, credentialSubject, apiKeySubject } from '../ratelimit/rate-limiter.js';
21
+ import { getRateLimiter, credentialSubject, apiKeySubject, UPSTREAM_429_DEFAULT_COOLDOWN_MS, } from '../ratelimit/rate-limiter.js';
18
22
  import { recordRateLimitEvent } from '../ratelimit/event-log.js';
23
+ import { NO_TURN } from '../capture/turn-boundary.js';
19
24
  import { SessionManager } from '../session/session-manager.js';
20
25
  import { getEnvPaths } from '../config/env.js';
21
26
  import { TraceTracker } from '../trace/tracker.js';
22
27
  import { CaptureRecorder } from '../capture/recorder.js';
23
28
  import { emitClientRequest, captureKeyIdentity, setClientExchangeContext } from '../observability/http-exchange.js';
24
- import { resolveTraceId } from '../observability/trace-id.js';
29
+ import { resolveClientRequestId, mintRequestId } from '../observability/request-identity.js';
25
30
  import { getWarnThrottle } from '../observability/warn-throttle.js';
26
31
  import { recordFailureEvent } from '../observability/failure-events.js';
32
+ import { redactUpstreamBody } from '../observability/upstream-body-redaction.js';
33
+ import { displayPromptText, firstDisplayText } from '../utils/client-envelope.js';
34
+ import { harnessProfileOf } from '../utils/harness-profiles.js';
27
35
  import { ActiveHealthProber, ErrorClassifier } from '../resilience/index.js';
28
36
  import { isModelAllowed, isModelAllowedInTiers, tierFromVirtualEntry } from '../auth/model-access.js';
29
37
  import { DEFAULT_CREDENTIAL_AFFINITY_CACHE_TTL_MS, selectCredential, } from './credential-selection.js';
38
+ /** Key attribution: the in-process binding wins, else the request's authInfo. */
39
+ const keyIdentityOf = (ctx) => ctx?.clientKey ?? captureKeyIdentity(ctx?.fastifyRequest ?? ctx?.clientRequest);
40
+ /**
41
+ * A pause shorter than this reads as normal streaming rhythm; at or above it
42
+ * the screen is visibly frozen. Defines what the stall ratio counts.
43
+ */
44
+ const PERCEIVED_STALL_MS = 1000;
45
+ /**
46
+ * Accumulate-only relay for `streaming.upstream.mode: stream` on a turn whose
47
+ * client wants JSON. The executor pool drains the upstream SSE body through
48
+ * it, the registry accumulates the chunks into one `CanonicalResponse`,
49
+ * and the surface then sends that JSON. Nothing reaches the client, so
50
+ * `committed` is permanently false: in-place retries and failover stay legal
51
+ * (re-issuing upstream duplicates no output the client has seen).
52
+ */
53
+ /**
54
+ * Upstream status code carried on an arbitrary thrown error, if any — `in`
55
+ * narrowing instead of an unchecked cast, since `lastError` is untyped.
56
+ */
57
+ function statusCodeOf(err) {
58
+ if (err && typeof err === 'object' && 'statusCode' in err && typeof err.statusCode === 'number') {
59
+ return err.statusCode;
60
+ }
61
+ return undefined;
62
+ }
63
+ /**
64
+ * Gateway-authored error for an exhausted candidate pool. The upstream
65
+ * verdict (402/401/429/5xx) is the GATEWAY's routing state, never the
66
+ * client's problem: agent clients auto-retry 429 but hard-stop on 402, so
67
+ * forwarding an upstream "insufficient balance" wastes models that are
68
+ * still healthy. Two shapes:
69
+ * - `remaining` non-empty → status 429 when the failure class is
70
+ * routing-fixable (the client's own backoff retry re-peeks the pool and
71
+ * lands on a healthy model); other classes keep their truthful status
72
+ * (a 400 is the request's fault — retries cannot fix it);
73
+ * - `remaining` empty → truthful status, operator-directed message
74
+ * (breaker cooldowns are 12h for quota — retrying now cannot help).
75
+ * `remaining` is computed by the caller with a FRESH peek, so trips that
76
+ * happened during the run itself are counted.
77
+ */
78
+ function routeExhaustedError(routeLabel, failoverPath, lastErr, remaining) {
79
+ const attemptedPath = failoverPath.join(' → ') || 'none attempted';
80
+ const lastMsg = lastErr instanceof Error ? lastErr.message : 'unknown';
81
+ if (remaining.length > 0) {
82
+ const status = statusCodeOf(lastErr) ?? 0;
83
+ const routingFixable = [401, 402, 429].includes(status) || status >= 500;
84
+ return Object.assign(new Error(`Route exhausted after ${failoverPath.length} candidate(s) on ${routeLabel} (${attemptedPath}) — last upstream error: ${lastMsg}. ${remaining.length} model(s) on this route are still available; a retry routes to one of them automatically.`), { statusCode: routingFixable ? 429 : (statusCodeOf(lastErr) ?? 502) });
85
+ }
86
+ return Object.assign(new Error(`Every model on ${routeLabel} is cooling down (tried: ${attemptedPath}) — last upstream error: ${lastMsg}. Clear the cooldowns in the console breaker panel or add credentials; retrying will not help until then.`), { statusCode: statusCodeOf(lastErr) ?? 502 });
87
+ }
88
+ const UPSTREAM_SINK_RELAY = {
89
+ stageRouting: () => { },
90
+ onChunk: () => { },
91
+ get committed() {
92
+ return false;
93
+ },
94
+ };
95
+ /**
96
+ * True when a streamed chunk puts something on the user's screen: assistant
97
+ * text, a tool-call fragment, or reasoning/thinking text. Role-only openers,
98
+ * finish_reason frames and the trailing usage frame leave the screen unchanged,
99
+ * so they must NOT count as progress — otherwise a silent 8-second pause
100
+ * between two real chunks would be papered over by the frames arriving inside
101
+ * it, which is precisely the stall time this metric exists to expose.
102
+ *
103
+ * Reasoning counts because the relay forwards it VERBATIM (stream-relay.ts —
104
+ * "thinking still streams to the client"). Leaving it out charged a reasoning
105
+ * model's whole thinking phase as one giant pause, so the figure measured the
106
+ * effort setting instead of a freeze. Both wire spellings are accepted: the
107
+ * OpenAI-compatible `reasoning_content` convention the catalog declares, and
108
+ * OpenRouter's plain `reasoning` string delta.
109
+ */
110
+ function hasVisibleOutput(event) {
111
+ if (event.type === 'response.output_text.delta' || event.type === 'response.refusal.delta') {
112
+ return event.text.length > 0;
113
+ }
114
+ if (event.type === 'response.reasoning.delta' || event.type === 'response.reasoning_summary.delta') {
115
+ return event.text.length > 0;
116
+ }
117
+ if (event.type === 'response.function_call.arguments.delta')
118
+ return event.argumentsDelta.length > 0;
119
+ return event.type === 'response.output_item.added' && event.item.type === 'tool_call';
120
+ }
121
+ function responseMessageText(response) {
122
+ if (!response)
123
+ return '';
124
+ return response.output.map((item) => item.type === 'message'
125
+ ? item.content.map((part) => part.type === 'text' || part.type === 'refusal' ? part.text : '').join('')
126
+ : '').join('');
127
+ }
128
+ function messageText(message) {
129
+ if (!message)
130
+ return '';
131
+ return message.content.map((part) => part.type === 'text' || part.type === 'refusal' ? part.text : '').filter(Boolean).join(' ');
132
+ }
133
+ function lastUserMessage(input) {
134
+ for (let index = input.length - 1; index >= 0; index--) {
135
+ const item = input[index];
136
+ if (item.type === 'message' && item.role === 'user')
137
+ return item;
138
+ }
139
+ return undefined;
140
+ }
141
+ const effortOf = (request) => request.reasoning?.effort;
142
+ function setEffort(request, effort) {
143
+ request.reasoning = { ...request.reasoning, effort };
144
+ }
30
145
  /**
31
146
  * Pull a non-sensitive subset of inbound headers for the trace's
32
147
  * `clientHeaders` field. Three categories:
33
148
  * - user-agent / accept-language — client fingerprint.
34
- * - request id (x-request-id / x-trace-id / x-correlation-id / request-id /
35
- * traceparent) — cross-service correlation, NOT a credential.
36
- * Authorization / x-api-key / cookies / anything else are intentionally
37
- * omitted (raw headers carry API keys). Fastify surfaces headers as
149
+ * - clientRequestId (x-request-id / x-trace-id / x-correlation-id /
150
+ * request-id / traceparent) — the caller's correlation value, NOT a
151
+ * credential and never a key. Authorization / x-api-key / cookies /
152
+ * anything else are intentionally omitted (raw headers carry API keys).
153
+ * Fastify surfaces headers as
38
154
  * `string | string[] | undefined`; arrays collapse to their first value to
39
155
  * keep the field scalar. Returns undefined when nothing matched so the
40
156
  * trace stays compact for the common no-headers path.
41
157
  */
42
- const REQUEST_ID_KEYS = ['x-request-id', 'x-trace-id', 'x-correlation-id', 'request-id', 'traceparent'];
43
158
  /**
44
159
  * Pull the upstream target host from an inbound header map. On the MITM
45
160
  * forward-proxy path this is the ORIGINAL destination (the API host the
@@ -60,6 +175,44 @@ function pickHeaderHost(headers) {
60
175
  return raw[0];
61
176
  return undefined;
62
177
  }
178
+ /**
179
+ * First string value of an inbound header (Fastify's surface allows arrays
180
+ * and both case spellings). Display path only — nothing here steers routing.
181
+ */
182
+ function pickHeaderValue(headers, name) {
183
+ if (!headers)
184
+ return undefined;
185
+ const raw = headers[name] ?? headers[name.toLowerCase()];
186
+ const v = Array.isArray(raw) ? raw[0] : raw;
187
+ const s = typeof v === 'string' ? v.trim() : '';
188
+ return s || undefined;
189
+ }
190
+ /**
191
+ * Self-declared human prompt (envelope layer 0): a client that KNOWS which
192
+ * bytes are the human turn states them here instead of asking the gateway to
193
+ * infer it from markup. Adopted verbatim, so a harness whose envelope shape
194
+ * is unguessable is still titled correctly without a profile.
195
+ *
196
+ * Display-only and spoofable by whoever sends it — the value never reaches
197
+ * routing, capture bodies or the upstream request, so the cost of a forged
198
+ * header is one wrong session title.
199
+ */
200
+ const PROMPT_HINT_HEADER = 'x-ocr-prompt-hint';
201
+ /** Display cap every identification aid uses (title, per-turn summary, snippet). */
202
+ const DISPLAY_CAP_CHARS = 200;
203
+ /** Clip to the display cap with an ellipsis (already-normalized input). */
204
+ function clipDisplayText(text) {
205
+ return text.length <= DISPLAY_CAP_CHARS ? text : text.slice(0, DISPLAY_CAP_CHARS - 1) + '…';
206
+ }
207
+ function envelopeHintsOf(headers) {
208
+ const declared = pickHeaderValue(headers, PROMPT_HINT_HEADER);
209
+ return {
210
+ profile: harnessProfileOf(pickHeaderValue(headers, 'user-agent')),
211
+ // Declared text is the human's own words: whitespace is flattened for the
212
+ // one-line surfaces, never stripped of markup or truncated mid-tag.
213
+ declaredPrompt: declared ? clipDisplayText(declared.replace(/\s+/g, ' ').trim()) || undefined : undefined,
214
+ };
215
+ }
63
216
  function extractClientHeaders(headers) {
64
217
  if (!headers)
65
218
  return undefined;
@@ -73,18 +226,13 @@ function extractClientHeaders(headers) {
73
226
  };
74
227
  const ua = pick('user-agent');
75
228
  const al = pick('accept-language');
76
- let rid;
77
- for (const k of REQUEST_ID_KEYS) {
78
- rid = pick(k);
79
- if (rid)
80
- break;
81
- }
229
+ const rid = resolveClientRequestId({ headers }).clientRequestId;
82
230
  if (ua === undefined && al === undefined && rid === undefined)
83
231
  return undefined;
84
232
  return {
85
233
  ...(ua !== undefined ? { userAgent: ua } : {}),
86
234
  ...(al !== undefined ? { acceptLanguage: al } : {}),
87
- ...(rid !== undefined ? { requestId: rid } : {}),
235
+ ...(rid !== undefined ? { clientRequestId: rid } : {}),
88
236
  };
89
237
  }
90
238
  export class PipelineOrchestrator {
@@ -132,20 +280,20 @@ export class PipelineOrchestrator {
132
280
  /**
133
281
  * Auto-request routing with the experience table in front of the decision layer
134
282
  * (ADR-0011): an entry hit short-circuits L2 entirely — the table IS a
135
- * prior judgment. Explicit request tiers (`force_tier`, incl. the
283
+ * prior judgment. Explicit request tiers (`forceTier`, incl. the
136
284
  * mode-forced ones resolved in 1B) skip the table: an explicit choice is a
137
285
  * layer0 decision by definition. On an L2 judgment the router behaves
138
286
  * exactly as before (decision layer → plus baseline).
139
287
  */
140
288
  async routeAutoDecision(request, decisionCapture, sessionId, promptHash) {
141
289
  const gate = routeEntriesGate();
142
- if (gate.enabled !== false && promptHash && !request.router_options?.force_tier) {
290
+ if (gate.enabled !== false && promptHash && !request.routerOptions?.forceTier) {
143
291
  const entry = getRouteEntryStore().hit(promptHash, sessionId);
144
292
  if (entry) {
145
293
  // The entry's effort is part of the experience; a client-explicit
146
294
  // effort always outranks it.
147
- if (entry.effort && request.reasoning_effort === undefined) {
148
- request.reasoning_effort = entry.effort;
295
+ if (entry.effort && effortOf(request) === undefined) {
296
+ setEffort(request, entry.effort);
149
297
  }
150
298
  appendRoutingLedger({
151
299
  kind: 'entry_hit',
@@ -160,12 +308,12 @@ export class PipelineOrchestrator {
160
308
  reasonCode: 'entry.hit',
161
309
  reasonParams: { tier: entry.tier, source: entry.source, hits: entry.hitCount },
162
310
  layerUsed: 'entry',
163
- needsSchemaValidation: hasToolsOrSchema(request),
311
+ needsSchemaValidation: declaresJsonContract(request),
164
312
  };
165
313
  }
166
314
  }
167
315
  return RouterEngine.routeAsync(request, this.config.classifier, this.registry, this.config.systemone?.defaultModel,
168
- // Decision-call capture identity: the outer turn's trace/session (only
316
+ // Decision-call capture identity: the outer turn's requestId/sessionId (only
169
317
  // exists while the capture master is on). The LAYER 2 DECISION applies
170
318
  // the recorder master gate (requestCapture.enabled) — when off it
171
319
  // passes nothing further, so this arg alone changes nothing today.
@@ -182,6 +330,10 @@ export class PipelineOrchestrator {
182
330
  if (this.healthProber)
183
331
  this.healthProber.stop();
184
332
  }
333
+ /** The health prober's CLAMPED sweep interval (0 when probing is off). */
334
+ getProberIntervalMs() {
335
+ return this.healthProber?.getIntervalMs() ?? 0;
336
+ }
185
337
  /**
186
338
  * Public entry point — thin capture wrapper around processInternal.
187
339
  *
@@ -201,9 +353,23 @@ export class PipelineOrchestrator {
201
353
  * SANITIZED form (credential values masked per the deny-list in
202
354
  * observability/http-exchange.ts), never raw.
203
355
  */
356
+ /** One-shot allocation of the write-time turn identity (ADR-0024). */
357
+ allocateTurn(sessionId, input) {
358
+ // Retained traces seed the counter for sessions that predate the v3
359
+ // snapshot; the counter itself is authoritative once present.
360
+ const seed = this.traceTracker
361
+ .getTracesBySession(sessionId)
362
+ .reduce((max, t) => Math.max(max, t.turnIndex ?? 0), 0);
363
+ const a = this.sessionManager.allocateTurnIndex(sessionId, input, seed);
364
+ return {
365
+ turnIndex: a.turnIndex,
366
+ isPromptStart: a.isPromptStart,
367
+ turnDecision: a.turnDecision,
368
+ };
369
+ }
204
370
  async process(request, context,
205
371
  /**
206
- * Progressive-output relay (see utils/chat-stream). Offered by a transport
372
+ * Progressive-output relay (see utils/stream-relay). Offered by a transport
207
373
  * that can flush SSE bytes as they arrive. The orchestrator USES it only
208
374
  * where streaming is legal — same candidate pool, no schema-assertion
209
375
  * cascade, a wire with a streaming executor, mock mode off — and silently
@@ -212,40 +378,42 @@ export class PipelineOrchestrator {
212
378
  */
213
379
  relay) {
214
380
  const captureEnabled = this.captureRecorder.isEnabled();
215
- // Capture pipeline state — see observability/http-exchange.ts and
216
- // observability/upstream-events.ts for the wire emit contract. The
217
- // `traceId` shared across all four events is sourced from the inbound
218
- // request on BOTH legs (W3C `traceparent`, `x-request-id`, ...) so the
219
- // gateway stays transparent in distributed traces: the Fastify leg reads
220
- // its own request headers, the MITM leg the original clientRequest
221
- // headers, then plain `headers` (legacy/test callers). Only when NO
222
- // header source exists at all do we mint a fresh 32-hex id
223
- // (OpenTelemetry compliant).
381
+ // Turn identity (ADR-0021), minted ONCE per request:
382
+ // - `requestId` — the record key / console row id (ours);
383
+ // - `clientRequestId` — the caller's correlation value (optional, may
384
+ // repeat across requests; correlation only, never a key).
385
+ // Headers come from the transport that owns the leg: the Fastify leg
386
+ // reads its own request, the MITM leg the original clientRequest headers,
387
+ // then plain `headers` (in-process/test callers).
224
388
  const traceHeaders = context?.fastifyRequest?.headers ?? context?.clientRequest?.headers ?? context?.headers;
225
- const traceResolution = traceHeaders
226
- ? resolveTraceId({ headers: traceHeaders }, 'client-or-mint')
227
- : { traceId: crypto.randomUUID().replace(/-/g, '').slice(0, 32), source: 'minted' };
228
- const captureOutTraceId = traceResolution.traceId;
389
+ const clientRequest = traceHeaders ? resolveClientRequestId({ headers: traceHeaders }) : {};
390
+ const turnIdentity = {
391
+ requestId: mintRequestId(),
392
+ ...(clientRequest.clientRequestId ? { clientRequestId: clientRequest.clientRequestId } : {}),
393
+ turn: NO_TURN,
394
+ allocated: false,
395
+ };
229
396
  let captureSessionId = '';
230
397
  let preResolvedSession;
231
398
  let upstreamEventContext;
232
399
  if (captureEnabled) {
233
- // ADR-0011 §4: the SCRUBBED chain feeds capture, session-id and
234
- // conversation key — a reserved `@ocr-*` token must never reach the
235
- // archive, and anchor resolution must see the bytes the router sees.
236
- // scanDirectives is idempotent; processInternal scrubs the live
237
- // request again on its own path.
400
+ // ADR-0011 §4: reserved tokens never reach the archive. Session and
401
+ // conversation identity use the scrubbed IR chain; the client event uses
402
+ // a separately scrubbed projection of the original protocol envelope.
403
+ // scanDirectives is idempotent; processInternal scrubs the live request
404
+ // again on its own path.
238
405
  const normalizedMessages = PromptOptimizer.normalizeMessages(request);
239
406
  // Scrub with the LIVE gate (enabled flag + configured prefix), matching
240
407
  // processInternal — a relocated prefix or a disabled gate must not
241
408
  // desync capture/anchor bytes from what the router actually serves.
242
409
  const gate = directivesGate();
410
+ const snapshotScan = scanDirectives(normalizedMessages, gate.enabled ? gate.prefix : null, request.instructions);
243
411
  const snapshotRequest = {
244
412
  ...request,
245
- messages: scanDirectives(normalizedMessages, gate.enabled ? gate.prefix : null)
246
- .messages,
413
+ input: snapshotScan.input,
414
+ ...(request.instructions !== undefined ? { instructions: snapshotScan.instructions } : {}),
247
415
  };
248
- const keyIdentity = captureKeyIdentity(context?.fastifyRequest ?? context?.clientRequest);
416
+ const keyIdentity = keyIdentityOf(context);
249
417
  // Resolve ONCE here and hand the result to processInternal: cold-start
250
418
  // IDs carry fresh random entropy, so a second resolve of the same
251
419
  // request would mint a different ID and split capture from routing.
@@ -254,11 +422,16 @@ export class PipelineOrchestrator {
254
422
  headers: context?.headers,
255
423
  });
256
424
  captureSessionId = preResolvedSession.sessionId;
257
- // Deterministic conversation key stamped onto EVERY event of the turn:
425
+ // ADR-0024: allocate the turn boundary ONCE — after the final session
426
+ // binding, before the first event. Re-entries, retries, failover hops
427
+ // and the L2 decision leg copy it; none of them re-allocate.
428
+ turnIdentity.turn = this.allocateTurn(captureSessionId, snapshotRequest.input);
429
+ turnIdentity.allocated = true;
430
+ // Deterministic conversation key stamped onto EVERY event of the request:
258
431
  // the capture archive can regroup turns even when the volatile session
259
432
  // id shifts (content-addressed, never a credential, mirrors the
260
433
  // session-manager resolution input exactly).
261
- const conversationKey = SessionManager.conversationKey(snapshotRequest.messages || [], keyIdentity?.id) ?? undefined;
434
+ const conversationKey = SessionManager.conversationKey(snapshotRequest.input || [], keyIdentity?.id) ?? undefined;
262
435
  // CLIENT REQUEST event fires synchronously here — independent of any
263
436
  // response. Even if the upstream call hangs / times out / the handler
264
437
  // throws, the client request event is already on disk.
@@ -269,11 +442,14 @@ export class PipelineOrchestrator {
269
442
  const clientExchangeCtx = emitClientRequest({
270
443
  recorder: this.captureRecorder,
271
444
  req: context?.fastifyRequest ?? context?.clientRequest,
272
- body: snapshotRequest,
445
+ apiKey: keyIdentity,
446
+ body: scrubWireDirectives(context?.clientBody ?? snapshotRequest, gate.enabled ? gate.prefix : null),
273
447
  sessionId: captureSessionId,
274
- traceId: captureOutTraceId,
448
+ clientRequestId: turnIdentity.clientRequestId,
449
+ requestId: turnIdentity.requestId,
275
450
  model: request.model || 'auto',
276
451
  conversationKey,
452
+ turn: turnIdentity.turn,
277
453
  });
278
454
  if (context?.fastifyRequest) {
279
455
  setClientExchangeContext(context.fastifyRequest, clientExchangeCtx);
@@ -284,16 +460,40 @@ export class PipelineOrchestrator {
284
460
  upstreamEventContext = {
285
461
  recorder: this.captureRecorder,
286
462
  sessionId: captureSessionId,
287
- traceId: captureOutTraceId,
463
+ clientRequestId: turnIdentity.clientRequestId,
464
+ requestId: turnIdentity.requestId,
288
465
  model: request.model || 'auto',
289
466
  // Key attribution: the Fastify leg carries authInfo (attached by the
290
467
  // auth preHandler); MITM / master-key legs resolve to undefined and
291
468
  // their events simply omit the field — same as before this existed.
292
469
  apiKey: keyIdentity,
293
470
  conversationKey,
471
+ turn: turnIdentity.turn,
294
472
  };
295
473
  }
296
- return await this.processInternal(request, context, preResolvedSession, upstreamEventContext, captureOutTraceId, relay);
474
+ // Provider-leg transport (streaming.upstream.mode — ADR-0008 §1):
475
+ // buffered → never hand a relay to the executor pool (the historical
476
+ // `streaming.enabled: false` rollback);
477
+ // stream → hand the wire a relay even when the CLIENT wants JSON, so
478
+ // the upstream SSE reader runs and the accumulator builds the
479
+ // response. The sink never writes a byte, so `committed` stays
480
+ // false and retries/failover remain legal;
481
+ // follow → the client's own relay (or none) — historical behavior.
482
+ return await this.processInternal(request, context, preResolvedSession, upstreamEventContext, turnIdentity, this.resolveUpstreamRelay(relay));
483
+ }
484
+ /**
485
+ * Apply `streaming.upstream.mode` to the surface-supplied relay. The sink
486
+ * relay is a module constant: it carries no per-request state (it forwards
487
+ * nothing and never commits), so one instance serves every accumulated
488
+ * turn.
489
+ */
490
+ resolveUpstreamRelay(relay) {
491
+ const mode = streamingPosture().upstream;
492
+ if (mode === 'buffered')
493
+ return undefined;
494
+ if (relay)
495
+ return relay;
496
+ return mode === 'stream' ? UPSTREAM_SINK_RELAY : undefined;
297
497
  }
298
498
  /**
299
499
  * Complete orchestration workflow:
@@ -305,7 +505,9 @@ export class PipelineOrchestrator {
305
505
  * 6. FinOps accounting
306
506
  * 7. Post-turn prefix fingerprint registration
307
507
  */
308
- async processInternal(request, context, preResolvedSession, upstreamEventContext, traceId, relay) {
508
+ async processInternal(request, context, preResolvedSession, upstreamEventContext, turnIdentity, relay) {
509
+ const clientRequestId = turnIdentity?.clientRequestId;
510
+ const requestId = turnIdentity?.requestId ?? mintRequestId();
309
511
  const startTime = Date.now();
310
512
  // 1. Optimize message prefix order & resolve virtual routing models
311
513
  const normalizedMessages = PromptOptimizer.normalizeMessages(request);
@@ -319,15 +521,16 @@ export class PipelineOrchestrator {
319
521
  // disables the scan entirely, so tokens travel as ordinary text.
320
522
  const directiveGate = directivesGate();
321
523
  const directivePrefix = directiveGate.prefix;
322
- const directiveScan = scanDirectives(normalizedMessages, directiveGate.enabled ? directivePrefix : null);
524
+ const directiveScan = scanDirectives(normalizedMessages, directiveGate.enabled ? directivePrefix : null, request.instructions);
323
525
  if (directiveScan.droppedMessages > 0 &&
324
- !directiveScan.messages.some((m) => m.role === 'user')) {
526
+ !directiveScan.input.some((item) => item.type === 'message' && item.role === 'user')) {
325
527
  // A directive-only prompt with no history: nothing left to send.
326
528
  throw Object.assign(new Error(`Empty prompt — ${directivePrefix}* directives were the only content in the request`), { statusCode: 400 });
327
529
  }
328
530
  const normalizedRequest = {
329
531
  ...request,
330
- messages: directiveScan.messages,
532
+ input: directiveScan.input,
533
+ ...(request.instructions !== undefined ? { instructions: directiveScan.instructions } : {}),
331
534
  };
332
535
  let explicitModel;
333
536
  let variantUsed;
@@ -339,18 +542,18 @@ export class PipelineOrchestrator {
339
542
  const modelName = (request.model ?? '').trim();
340
543
  const bareTier = tierFromVirtualEntry(modelName);
341
544
  if (bareTier) {
342
- normalizedRequest.router_options = { ...normalizedRequest.router_options, force_tier: bareTier };
545
+ normalizedRequest.routerOptions = { ...normalizedRequest.routerOptions, forceTier: bareTier };
343
546
  }
344
547
  else if (modelName && modelName !== 'auto') {
345
548
  const specific = this.registry.getModel(modelName);
346
549
  if (specific) {
347
550
  // Exact-model pass-through: the client named a REGISTERED model id
348
551
  // (e.g. pinned via the Client Hub model slots). Route to exactly
349
- // this model — not merely its tier. Resilience is preserved: if its
350
- // breaker is tripped, executeCandidatePool drops it and fails over
351
- // within the tier.
552
+ // this model — not merely its tier. Resilience is preserved: in-place
553
+ // same-model retry and credential re-spread still apply; the model
554
+ // itself is never substituted (ADR-0014).
352
555
  explicitModel = specific;
353
- normalizedRequest.router_options = { ...normalizedRequest.router_options, force_tier: specific.tier };
556
+ normalizedRequest.routerOptions = { ...normalizedRequest.routerOptions, forceTier: specific.tier };
354
557
  }
355
558
  else {
356
559
  const variantRef = this.registry.resolveVariantRef(modelName);
@@ -363,9 +566,9 @@ export class PipelineOrchestrator {
363
566
  // applies its downgrade/honesty contract.
364
567
  explicitModel = variantRef.base;
365
568
  variantUsed = variantRef.variant.id;
366
- normalizedRequest.reasoning_effort = variantRef.variant.reasoningEffort;
569
+ setEffort(normalizedRequest, variantRef.variant.reasoningEffort);
367
570
  normalizedRequest.model = variantRef.base.id;
368
- normalizedRequest.router_options = { ...normalizedRequest.router_options, force_tier: variantRef.base.tier };
571
+ normalizedRequest.routerOptions = { ...normalizedRequest.routerOptions, forceTier: variantRef.base.tier };
369
572
  }
370
573
  else if (modelName.includes('#')) {
371
574
  // `#variant` is explicit syntax — a typo must fail loud instead of
@@ -388,8 +591,9 @@ export class PipelineOrchestrator {
388
591
  // sibling provider) and the gateway's own host matches no provider
389
592
  // baseUrl anyway. Cheapest-hit-first ordering picks the primary
390
593
  // otherwise. Same-name siblings stay reachable via the tier's
391
- // failover pool. Unresolved names keep the classifier contract
392
- // (intelligent-routing product behavior).
594
+ // failover pool. A full miss falls through to the classifier —
595
+ // ADR-0026 deleted the unresolved-model policy outright, so every
596
+ // leg resolves a name the same way.
393
597
  const bareHits = this.registry.getModelsByUpstreamName(modelName, pickHeaderHost(context?.clientRequest?.headers));
394
598
  // A live combo id claims this name for the gateway: the combo fork
395
599
  // below is the advertised meaning (/v1/models lists the id as a
@@ -399,15 +603,18 @@ export class PipelineOrchestrator {
399
603
  // models stay addressable by their full provider-prefixed id.
400
604
  if (bareHits.length > 0 && !this.registry.isCombo(modelName)) {
401
605
  explicitModel = bareHits[0];
402
- normalizedRequest.router_options = {
403
- ...normalizedRequest.router_options,
404
- force_tier: explicitModel.tier,
606
+ normalizedRequest.routerOptions = {
607
+ ...normalizedRequest.routerOptions,
608
+ forceTier: explicitModel.tier,
405
609
  };
406
610
  }
611
+ // Nothing matched: no policy, no mapping, no fallback. The name
612
+ // falls through to the classifier exactly like a native /v1 caller's
613
+ // would — ADR-0026 deleted the unresolved-model mechanism outright,
614
+ // so the MITM leg has no special posture of its own. A gateway
615
+ // plugin that wants "this name means that model" maps it BEFORE
616
+ // dispatch (it owns the decrypted wire); the pipeline never guesses.
407
617
  }
408
- // Other unregistered names (e.g. native `claude-opus-*` after a /model
409
- // switch inside Claude Code) are left untouched — the classifier
410
- // decides, which IS the intelligent-routing product behavior.
411
618
  }
412
619
  }
413
620
  // 1A. Custom model combo: the client named a configured combo id — the
@@ -415,9 +622,7 @@ export class PipelineOrchestrator {
415
622
  // session ratchet and schema-assertion escalation are all bypassed
416
623
  // (explicit user composition wins, mirroring the exact-model
417
624
  // pass-through above).
418
- const comboByName = !explicitModel && modelName && this.registry.isCombo(modelName)
419
- ? modelName
420
- : undefined;
625
+ const comboByName = !explicitModel && modelName && this.registry.isCombo(modelName) ? modelName : undefined;
421
626
  if (comboByName && this.registry.isComboDisabled(comboByName)) {
422
627
  // Fail fast like the empty-member case below: the combo is hidden from
423
628
  // /v1/models, so an in-flight client naming it must get a loud 404 —
@@ -428,7 +633,10 @@ export class PipelineOrchestrator {
428
633
  // Fail fast instead of silently degrading to classifier routing: the
429
634
  // combo is still advertised via /v1/models, so routing it as `auto`
430
635
  // would be invisible billing/model drift.
431
- throw new Error(`Combo '${comboByName}' has no registered member models — check that every id in config.combos exists in config.models.`);
636
+ // 404 like the disabled branch above: the combo is not currently
637
+ // routable (no member registered) — an operator-config gap must not
638
+ // read as an upstream 502.
639
+ throw Object.assign(new Error(`Combo '${comboByName}' has no registered member models — sync the member providers' model lists (console provider pull) or fix the ids in config.combos; boot logs name every provider excluded for zero models.`), { statusCode: 404 });
432
640
  }
433
641
  const comboId = comboByName ?? undefined;
434
642
  // Defense in depth: an explicitly named model outside the key's model
@@ -446,33 +654,45 @@ export class PipelineOrchestrator {
446
654
  }
447
655
  // 1B. Global routing mode (config.routing.mode) — cost/quality force the tier
448
656
  // for auto/tier-alias requests; explicit client choices always win.
449
- const modeTier = routingModeForceTier(normalizedRequest.model, normalizedRequest.router_options, this.config.routing?.mode);
657
+ const modeTier = routingModeForceTier(normalizedRequest.model, normalizedRequest.routerOptions, this.config.routing?.mode);
450
658
  if (modeTier) {
451
- normalizedRequest.router_options = { ...normalizedRequest.router_options, force_tier: modeTier };
659
+ normalizedRequest.routerOptions = { ...normalizedRequest.routerOptions, forceTier: modeTier };
452
660
  }
453
661
  // 2. Identify / track conversation session (zero-header layered resolution).
454
662
  // Reuse the capture-time resolve when present: both call sites normalize
455
- // identically, and one request must yield exactly one session ID.
663
+ // identically, and one request must yield exactly one session ID. The
664
+ // client conversation ref is resolved ONCE here and handed to both the
665
+ // resolver and the trace, so the console's "both ids" view and the session
666
+ // it names can never disagree.
667
+ const clientRef = SessionManager.clientRefOf(normalizedRequest);
456
668
  const sessionResolve = preResolvedSession ??
457
669
  this.sessionManager.resolveSessionId(normalizedRequest, {
458
- keyId: captureKeyIdentity(context?.fastifyRequest ?? context?.clientRequest)?.id,
670
+ keyId: keyIdentityOf(context)?.id,
459
671
  headers: context?.headers,
672
+ clientRef: clientRef ?? undefined,
460
673
  });
461
674
  const sessionId = sessionResolve.sessionId;
462
- // 2B. Token-saver compression (toolOutput tool-output compression → headroom
463
- // sidecar → outputStyle injection). All stages fail open. Snapshot the
464
- // PRE-compression
465
- // messages for the post-turn prefix fingerprint: the client always sends
466
- // uncompressed bytes, so the session chain must be indexed on the original
467
- // content — matching registerCompletedTurn below against compressed bytes
468
- // would break zero-header session resolution from the next turn onward.
469
- // (The upstream-facing compressed prefix stays byte-stable across turns
470
- // because the tool-output compressors are deterministic and headroom
471
- // runs in session mode.)
472
- const fingerprintMessages = normalizedRequest.messages.map(m => ({
473
- role: m.role,
474
- content: Array.isArray(m.content) ? m.content.map(p => ({ ...p })) : m.content,
475
- }));
675
+ // Capture-disabled requests reach the admission gate only here; allocate
676
+ // exactly once so the trace plane carries the same identity regardless of
677
+ // the capture switch. `allocated` makes the two gates mutually exclusive.
678
+ if (turnIdentity && !turnIdentity.allocated) {
679
+ turnIdentity.turn = this.allocateTurn(sessionId, normalizedRequest.input);
680
+ turnIdentity.allocated = true;
681
+ }
682
+ const requestTurn = turnIdentity?.turn ?? NO_TURN;
683
+ // 2B. Snapshot canonical strings before pairing/compression. Session
684
+ // anchors must describe the bytes the client sent, not a compressed or
685
+ // repaired upstream projection. Serialization avoids a deep content clone.
686
+ const fingerprintItems = SessionManager.serializeInput(normalizedRequest.input);
687
+ // Repair unmatched/duplicate tool results after fingerprinting and before
688
+ // any carrier renders the request. Unchanged histories keep their array.
689
+ const pairing = repairToolCallPairing(normalizedRequest.input);
690
+ if (pairing.input !== normalizedRequest.input) {
691
+ console.log(`[pipeline:tool-pairing] repaired history: ${pairing.synthesized} missing repl${pairing.synthesized === 1 ? 'y' : 'ies'}, ` +
692
+ `${pairing.duplicates} duplicate repl${pairing.duplicates === 1 ? 'y' : 'ies'}, ` +
693
+ `${pairing.orphans} orphan repl${pairing.orphans === 1 ? 'y' : 'ies'}`);
694
+ normalizedRequest.input = pairing.input;
695
+ }
476
696
  await applyCompression(normalizedRequest, this.config.compression, sessionId);
477
697
  // 2C. Route-entry experience (ADR-0011). One normalized prompt hash feeds
478
698
  // the experience-table lookup and write. Directives were scrubbed above, so
@@ -480,13 +700,8 @@ export class PipelineOrchestrator {
480
700
  // no double rows, no prefix drift.
481
701
  const routeGate = routeEntriesGate();
482
702
  const routeEntriesOn = routeGate.enabled !== false;
483
- const lastUserMsgEarly = normalizedRequest.messages.filter((m) => m.role === 'user').pop();
484
- const lastUserText = typeof lastUserMsgEarly?.content === 'string'
485
- ? lastUserMsgEarly.content
486
- : Array.isArray(lastUserMsgEarly?.content)
487
- ? (lastUserMsgEarly.content.map((p) => p.text || '').join(' ')).trim()
488
- : '';
489
- const normalizedPrompt = normalizePrompt(lastUserText ?? '');
703
+ const lastUserText = messageText(lastUserMessage(normalizedRequest.input)).trim();
704
+ const normalizedPrompt = normalizePrompt(lastUserText);
490
705
  // A directive-only ("just continue") turn carries no prompt of its own:
491
706
  // hashing the previous user message would attribute this turn's outcome to
492
707
  // the OLD prompt and let it rewrite that prompt's experience row.
@@ -517,7 +732,7 @@ export class PipelineOrchestrator {
517
732
  // injection below, the `@ocr-effort-*` directive, model defaultEffort). The
518
733
  // local `requestedEffort` read later is the EFFECTIVE ask the machinery
519
734
  // served against; `effortSource` says whose ask it was.
520
- const clientEffort = normalizedRequest.reasoning_effort;
735
+ const clientEffort = effortOf(normalizedRequest);
521
736
  const initialDecision = comboId
522
737
  ? {
523
738
  targetTier: 'plus',
@@ -530,7 +745,7 @@ export class PipelineOrchestrator {
530
745
  }
531
746
  : await this.routeAutoDecision(normalizedRequest, upstreamEventContext, sessionId, promptHash);
532
747
  // Explicit-model honesty: the engine's 'forced' code here reflects the
533
- // force_tier the 1B resolver INJECTED from the named model's registration
748
+ // forceTier the 1B resolver INJECTED from the named model's registration
534
749
  // (full id / variant / bare name) — the client named a model, not a tier.
535
750
  // A dedicated code keeps the trace truthful: `tier` stays in params for
536
751
  // tooltips, but the console template carries no {tier} slot, so no tier
@@ -549,11 +764,11 @@ export class PipelineOrchestrator {
549
764
  if (!comboId &&
550
765
  initialDecision.layerUsed === 'layer2' &&
551
766
  initialDecision.effort &&
552
- normalizedRequest.reasoning_effort === undefined) {
767
+ effortOf(normalizedRequest) === undefined) {
553
768
  const floor = this.config.classifier?.layer2?.effortFloor ?? DEFAULT_LAYER2_EFFORT_FLOOR;
554
769
  const floorRank = EFFORT_LADDER.indexOf(floor);
555
770
  const servedEffort = EFFORT_LADDER.indexOf(initialDecision.effort) < floorRank ? floor : initialDecision.effort;
556
- normalizedRequest.reasoning_effort = servedEffort;
771
+ setEffort(normalizedRequest, servedEffort);
557
772
  initialDecision.reasonParams = {
558
773
  ...(initialDecision.reasonParams ?? {}),
559
774
  effort: servedEffort,
@@ -582,7 +797,7 @@ export class PipelineOrchestrator {
582
797
  // Directive and model-default writes re-attribute at their own sites below.
583
798
  let effortSource = clientEffort !== undefined
584
799
  ? 'client'
585
- : normalizedRequest.reasoning_effort !== undefined
800
+ : effortOf(normalizedRequest) !== undefined
586
801
  ? initialDecision.layerUsed === 'entry'
587
802
  ? 'entry'
588
803
  : 'l2-decision'
@@ -593,7 +808,7 @@ export class PipelineOrchestrator {
593
808
  // downgrade intercepted, pin honored)
594
809
  // - 'explicit' : a client-authored choice — a named model OR a forced
595
810
  // tier (tier aliases / the global mode lever /
596
- // router_options.force_tier). Turn recorded, a higher
811
+ // router_options.forceTier). Turn recorded, a higher
597
812
  // proposal still escalates the ceiling, but the session
598
813
  // NEVER rewrites the proposal and the pin is neither
599
814
  // read nor followed — a forced lite must serve lite even
@@ -602,19 +817,19 @@ export class PipelineOrchestrator {
602
817
  // composition IS the decision
603
818
  const sessionMode = comboId
604
819
  ? 'bypass'
605
- : explicitModel || normalizedRequest.router_options?.force_tier
820
+ : explicitModel || normalizedRequest.routerOptions?.forceTier
606
821
  ? 'explicit'
607
822
  : 'ratchet';
608
823
  let decision;
609
824
  let ratchetApplied = false;
610
- let sessionTurnCount;
825
+ let sessionRequestCount;
611
826
  if (sessionMode === 'bypass') {
612
827
  decision = { ...initialDecision, sessionId, sessionRatchetApplied: false, sessionLookupType: sessionResolve.lookupType };
613
828
  // Bypass never mints a session entity, so getSession reads undefined
614
829
  // every turn and stamped every combo request #1 in the console's
615
830
  // request-detail table. Dedicated counter instead — display-only
616
831
  // bookkeeping, no pin/tier state (ADR-0002).
617
- sessionTurnCount = this.sessionManager.recordBypassTurn(sessionId);
832
+ sessionRequestCount = this.sessionManager.recordBypassTurn(sessionId);
618
833
  }
619
834
  else {
620
835
  const ratchetResult = this.sessionManager.applyRatchet(sessionId, initialDecision,
@@ -631,15 +846,65 @@ export class PipelineOrchestrator {
631
846
  decision.sessionRatchetApplied = ratchetResult.ratchetApplied;
632
847
  decision.sessionLookupType = sessionResolve.lookupType;
633
848
  ratchetApplied = ratchetResult.ratchetApplied;
634
- sessionTurnCount = ratchetResult.session.turnCount;
849
+ sessionRequestCount = ratchetResult.session.requestCount;
635
850
  }
851
+ // Traces already recorded for this session (this turn's trace is written
852
+ // in step 8). Read once: the birth title is re-stamped from them, and the
853
+ // per-turn prompt summary needs the previous message count.
854
+ const prevTraces = this.traceTracker.getTracesBySession(sessionId);
855
+ // Envelope resolution inputs (display only): the harness vocabulary scoped
856
+ // from this request's User-Agent and any self-declared prompt. Headers come
857
+ // from whichever transport owns the leg — same precedence as the trace
858
+ // identity below (Fastify request, MITM client request, plain headers) —
859
+ // and the result is resolved ONCE here for the title, the per-turn summary
860
+ // and the route snippet.
861
+ const envelopeHints = envelopeHintsOf((context?.fastifyRequest?.headers ??
862
+ context?.clientRequest?.headers ??
863
+ context?.headers));
864
+ // Session title: the FIRST user message carrying human text, flattened and
865
+ // capped like the capture preview (array content is joined, never dropped —
866
+ // a multimodal opening message must still name the session). Client
867
+ // metadata envelopes are skipped, not quoted: Cursor's agent opens with a
868
+ // standalone `<timestamp>` message or a whole `<user_info>`/`<rules>`/…
869
+ // context bundle, which would otherwise title the session with a clock
870
+ // reading or an OS banner; Claude Code MIXES `<system-reminder>` + a
871
+ // `/clear` record with the human prompt in ONE message (see
872
+ // utils/client-envelope.ts for the four rules and
873
+ // utils/harness-profiles.ts for the scoped vocabulary). Strict runs
874
+ // first so an unrecognized envelope never outranks a later human turn in
875
+ // the same request; only when the whole request carries no recognized
876
+ // human text does the permissive pass keep a tag-only message (a prompt
877
+ // that is itself markup) rather than naming the session nothing. Once
878
+ // written, every later turn copies the birth value verbatim, so the trace
879
+ // ring can evict the birth trace without blanking the console title.
880
+ // Written to two places from this ONE value: the live entity
881
+ // (attachOrigin, below) and the trace (step 8) — a row rebuilt from traces
882
+ // alone has no entity at all.
883
+ const firstUserSummary =
884
+ // A declared prompt (layer 0) is authoritative and outranks inference on
885
+ // every later turn too — but the frozen birth value still wins, because
886
+ // the title is a birth attribute.
887
+ prevTraces[0]?.request.firstUserSummary ??
888
+ envelopeHints.declaredPrompt ??
889
+ (() => {
890
+ const userTexts = [];
891
+ for (const item of normalizedRequest.input) {
892
+ if (item.type !== 'message' || item.role !== 'user')
893
+ continue;
894
+ const raw = messageText(item);
895
+ if (raw)
896
+ userTexts.push(raw);
897
+ }
898
+ // Strict-then-permissive pass lives in the normalizer, shared with the
899
+ // capture-session preview (one derivation, three surfaces).
900
+ return firstDisplayText(userTexts, DISPLAY_CAP_CHARS, { profile: envelopeHints.profile });
901
+ })();
636
902
  // Birth metadata: attach once per session (first-write-wins inside the
637
903
  // manager), recording the inbound wire, the layer that resolved the id,
638
- // the client ip and a first-message snippet for UI identification.
904
+ // the client ip and the first-message snippet for UI identification.
639
905
  const bornSession = this.sessionManager.getSession(sessionId);
640
- if (bornSession && bornSession.turnCount === 1) {
641
- const firstUser = normalizedRequest.messages.find((m) => m.role === 'user');
642
- this.sessionManager.attachOrigin(sessionId, { wire: context?.wire, lookupType: sessionResolve.lookupType }, context?.clientIp, typeof firstUser?.content === 'string' ? firstUser.content : undefined);
906
+ if (bornSession && bornSession.requestCount === 1) {
907
+ this.sessionManager.attachOrigin(sessionId, { wire: context?.wire, lookupType: sessionResolve.lookupType }, context?.clientIp, firstUserSummary);
643
908
  }
644
909
  // 4A. Directives (`<prefix>tier-up` / `<prefix>tier-down`, ADR-0011
645
910
  // rewrite) — TIER axis. Deliberately
@@ -752,8 +1017,8 @@ export class PipelineOrchestrator {
752
1017
  // removal can. Checked with healthyOnly=false so health never
753
1018
  // masquerades as config intent (and vice versa below).
754
1019
  // HEALTH (runtime reality, model CAPABILITY view —
755
- // registry.modelHealthView): evict ONLY at 'unavailable' — the
756
- // model breaker hard-OPEN, or every credential pair out of service
1020
+ // registry.modelHealthView): evict ONLY at 'unavailable' — every
1021
+ // credential tuple out of service
757
1022
  // as hard-OPEN / credential-SUSPECT / operator-DISABLED, so a full
758
1023
  // credential takedown evicts the pin even though the model stays
759
1024
  // configured. PARTIAL disablement is not eviction: the credential
@@ -802,12 +1067,12 @@ export class PipelineOrchestrator {
802
1067
  // prefix exists in the new provider's chain (prefer continuity —
803
1068
  // same key material, same cache economics), and otherwise treats it
804
1069
  // as stale and re-spreads with a FORCED rebind persisted after the
805
- // first success. Explicitly rebinding here to the new chain head
1070
+ // first success. Explicitly rebinding here to the new default credential
806
1071
  // would pick an credential the model was never verified against.
807
1072
  }
808
1073
  }
809
1074
  }
810
- else if (sessionMode === 'explicit' && !explicitModel && normalizedRequest.router_options?.force_tier) {
1075
+ else if (sessionMode === 'explicit' && !explicitModel && normalizedRequest.routerOptions?.forceTier) {
811
1076
  // Forced-tier turn (ADR-0014): the session pin is followed ONLY when it
812
1077
  // lives in the forced tier — then following is pure KV affinity (the
813
1078
  // pin IS a model of the tier the client forced, so serving it cannot
@@ -883,8 +1148,24 @@ export class PipelineOrchestrator {
883
1148
  // selected model declares a default → pin it as the requested level so
884
1149
  // every downstream step (effort matching, payload thinking block,
885
1150
  // X-OCR-Thinking-* observability) treats it as a normal request.
886
- if (normalizedRequest.reasoning_effort === undefined && actualModel.defaultEffort) {
887
- normalizedRequest.reasoning_effort = actualModel.defaultEffort;
1151
+ // A native token budget (Anthropic `thinking.budget_tokens`, Responses
1152
+ // `reasoning.max_tokens`) has no OpenAI-chat spelling. On wires without a
1153
+ // native budget field, translate it to the equivalent ladder level BEFORE
1154
+ // the default pin / effort matching below, so capability clamps and the
1155
+ // X-OCR-Thinking-* headers see it; the budget itself stays on the request
1156
+ // for wires that consume it natively.
1157
+ const servedWire = actualModel.wire ?? 'openai-chat';
1158
+ const budgetTokens = normalizedRequest.reasoning?.budgetTokens;
1159
+ if (effortOf(normalizedRequest) === undefined &&
1160
+ typeof budgetTokens === 'number' &&
1161
+ budgetTokens > 0 &&
1162
+ servedWire !== 'anthropic-messages' &&
1163
+ servedWire !== 'google-gemini' &&
1164
+ servedWire !== 'openai-responses') {
1165
+ setEffort(normalizedRequest, effortFromThinkingBudget(budgetTokens));
1166
+ }
1167
+ if (effortOf(normalizedRequest) === undefined && actualModel.defaultEffort) {
1168
+ setEffort(normalizedRequest, actualModel.defaultEffort);
888
1169
  effortSource = 'default'; // ADR-0012: the model pin owns the ask
889
1170
  }
890
1171
  // Effort directives (`<prefix>effort-up` / `<prefix>effort-down`,
@@ -899,13 +1180,13 @@ export class PipelineOrchestrator {
899
1180
  if (directivesApplicable) {
900
1181
  const supportedEfforts = actualModel.supportedReasoningEfforts
901
1182
  ?? (actualModel.supportsReasoningEffort ? EFFORT_LADDER : undefined);
902
- const before = normalizedRequest.reasoning_effort;
1183
+ const before = effortOf(normalizedRequest);
903
1184
  const effortDirective = applyEffortDirectives(directiveActions, before, supportedEfforts);
904
1185
  if (effortDirective.applied) {
905
1186
  const suffix = effortDirective.suffix ?? (effortDirective.delta > 0 ? 'effort-up' : 'effort-down');
906
1187
  const token = `${directivePrefix}${suffix}`;
907
1188
  if (effortDirective.changed && effortDirective.effort) {
908
- normalizedRequest.reasoning_effort = effortDirective.effort;
1189
+ setEffort(normalizedRequest, effortDirective.effort);
909
1190
  effortSource = 'directive'; // the user's own instruction owns the ask
910
1191
  decision.reasonParams = {
911
1192
  ...(decision.reasonParams ?? {}),
@@ -953,7 +1234,7 @@ export class PipelineOrchestrator {
953
1234
  });
954
1235
  }
955
1236
  }
956
- const requestedEffort = normalizedRequest.reasoning_effort;
1237
+ const requestedEffort = effortOf(normalizedRequest);
957
1238
  let actualEffort;
958
1239
  let reasoningDegraded = false;
959
1240
  const effortPick = (() => {
@@ -982,8 +1263,8 @@ export class PipelineOrchestrator {
982
1263
  // Write the resolved effort back so provider builders construct the
983
1264
  // correct upstream payload (Anthropic budget_tokens, Gemini
984
1265
  // thinkingBudget, Responses thinkingEffort, etc.).
985
- if (actualEffort !== requestedEffort) {
986
- normalizedRequest.reasoning_effort = actualEffort;
1266
+ if (actualEffort !== undefined && actualEffort !== requestedEffort) {
1267
+ setEffort(normalizedRequest, actualEffort);
987
1268
  }
988
1269
  }
989
1270
  else if (preferredModel) {
@@ -1004,7 +1285,7 @@ export class PipelineOrchestrator {
1004
1285
  reasoningDegraded =
1005
1286
  EFFORT_LADDER.indexOf(recomputed) < EFFORT_LADDER.indexOf(requestedEffort ?? 'none');
1006
1287
  if (recomputed !== requestedEffort) {
1007
- normalizedRequest.reasoning_effort = recomputed;
1288
+ setEffort(normalizedRequest, recomputed);
1008
1289
  }
1009
1290
  }
1010
1291
  }
@@ -1029,6 +1310,10 @@ export class PipelineOrchestrator {
1029
1310
  // the final answer (no re-assertion follows), so it streams exactly like
1030
1311
  // the direct path and stamps timing the same way.
1031
1312
  let poolTiming = undefined;
1313
+ // Upstream transport of the SERVED attempt (registry-reported; ADR-0008
1314
+ // §1). Buffered by construction on the cascade's lite lead (it is never
1315
+ // given a relay) and whenever `streaming.upstream.mode` is `buffered`.
1316
+ let upstreamStream = undefined;
1032
1317
  // 5. Execution with Cascading Fallback & Schema Assertion
1033
1318
  // (lite-lead cascade is skipped for explicit model choices, combos AND
1034
1319
  // forced tiers — the client named exactly what to run. A forced tier is
@@ -1040,10 +1325,10 @@ export class PipelineOrchestrator {
1040
1325
  const tierCrossPolicy = retryConfig?.failover?.tierCrossPolicy ?? 'allow_escalate';
1041
1326
  if (decision.needsSchemaValidation &&
1042
1327
  this.config.fallback.enabled &&
1043
- !request.router_options?.disable_fallback &&
1328
+ !request.routerOptions?.disableFallback &&
1044
1329
  !explicitModel &&
1045
1330
  !comboId &&
1046
- !normalizedRequest.router_options?.force_tier) {
1331
+ !normalizedRequest.routerOptions?.forceTier) {
1047
1332
  // 5A: Lite Tier lead - Deploy Lite Tier first with resilience
1048
1333
  const litePool = this.registry.getCandidateModelsForTier('lite', true);
1049
1334
  const liteResult = await this.executeCandidatePool(normalizedRequest, {
@@ -1060,9 +1345,9 @@ export class PipelineOrchestrator {
1060
1345
  let assertionError = '';
1061
1346
  if (liteResult.success && liteResult.response) {
1062
1347
  liteRes = liteResult.response;
1063
- const content = liteRes.choices[0]?.message?.content || '';
1348
+ const content = responseMessageText(liteRes);
1064
1349
  // Local static AST / Schema assertion (Zero extra LLM cost!)
1065
- const validation = SchemaAssertion.validate(content, normalizedRequest.response_format);
1350
+ const validation = SchemaAssertion.validate(content, normalizedRequest.text?.format);
1066
1351
  if (validation.valid) {
1067
1352
  assertionPassed = true;
1068
1353
  finalResponse = liteRes;
@@ -1072,7 +1357,7 @@ export class PipelineOrchestrator {
1072
1357
  // may have served a model whose translation/capability differs from
1073
1358
  // the tier-pick prediction (helper: map → clamp → mirror).
1074
1359
  {
1075
- const r = this.resolveServedEffort(actualModel, requestedEffort, actualTier);
1360
+ const r = this.resolveServedEffort(actualModel, requestedEffort, actualTier, budgetTokens);
1076
1361
  actualEffort = r.actualEffort;
1077
1362
  reasoningDegraded = r.degraded;
1078
1363
  }
@@ -1081,6 +1366,7 @@ export class PipelineOrchestrator {
1081
1366
  failoverPath = liteResult.failoverPath;
1082
1367
  inplaceRetries += liteResult.inplaceRetries;
1083
1368
  servedCredentialPrefix = liteResult.servedCredentialPrefix;
1369
+ upstreamStream = liteResult.transport;
1084
1370
  }
1085
1371
  else {
1086
1372
  assertionError = validation.error || 'Schema validation assertion failed';
@@ -1094,7 +1380,7 @@ export class PipelineOrchestrator {
1094
1380
  fallbackOccurred = true;
1095
1381
  fallbackReason = assertionError;
1096
1382
  const escalateTier = this.config.fallback.escalateTier || 'plus';
1097
- const failedContent = liteRes?.choices[0]?.message?.content || '';
1383
+ const failedContent = responseMessageText(liteRes);
1098
1384
  const fallbackReq = FallbackContextBuilder.buildEscalationRequest(normalizedRequest, failedContent, assertionError, escalateTier);
1099
1385
  const plusResult = await this.executeCandidatePool(fallbackReq, {
1100
1386
  chain: this.registry.getCandidateModelsForTier(escalateTier, true),
@@ -1106,13 +1392,13 @@ export class PipelineOrchestrator {
1106
1392
  sessionId,
1107
1393
  // The escalation response is final (no re-assertion below), so it
1108
1394
  // streams under the same commit-point contract as the direct path.
1109
- relay: this.config.streaming?.enabled === false ? undefined : relay,
1395
+ relay,
1110
1396
  streamRouting: {
1111
1397
  layerUsed: decision.layerUsed || 'layer0',
1112
1398
  sessionId,
1113
1399
  sessionRatchetApplied: ratchetApplied,
1114
1400
  sessionLookupType: sessionResolve.lookupType,
1115
- traceId: traceId ?? 'unknown',
1401
+ requestId,
1116
1402
  requestedEffort,
1117
1403
  variantUsed,
1118
1404
  },
@@ -1121,7 +1407,15 @@ export class PipelineOrchestrator {
1121
1407
  if (plusResult.policyDenied) {
1122
1408
  throw Object.assign(new Error(`API key model policy denies every '${escalateTier}' candidate model for fallback`), { statusCode: 403 });
1123
1409
  }
1124
- throw plusResult.lastError || new Error(`Plus escalation failed for tier '${escalateTier}'`);
1410
+ const escErr = plusResult.lastError;
1411
+ if (escErr instanceof IrUnsupportedError)
1412
+ throw escErr;
1413
+ const accessPolicy = context?.modelAccess;
1414
+ const escRemaining = this.registry
1415
+ .getCandidateModelsForTier(escalateTier, true)
1416
+ .filter((m) => !plusResult.failoverPath.includes(m.id) &&
1417
+ (!accessPolicy || isModelAllowedInTiers(m.id, accessPolicy, this.registry.tiersOf(m))));
1418
+ throw routeExhaustedError(`escalation tier '${escalateTier}'`, plusResult.failoverPath, escErr, escRemaining);
1125
1419
  }
1126
1420
  finalResponse = plusResult.response;
1127
1421
  actualTier = escalateTier;
@@ -1129,7 +1423,7 @@ export class PipelineOrchestrator {
1129
1423
  // Recompute effort against the actually-served model (same contract
1130
1424
  // as the direct path).
1131
1425
  {
1132
- const r = this.resolveServedEffort(actualModel, requestedEffort, actualTier);
1426
+ const r = this.resolveServedEffort(actualModel, requestedEffort, actualTier, budgetTokens);
1133
1427
  actualEffort = r.actualEffort;
1134
1428
  reasoningDegraded = r.degraded;
1135
1429
  }
@@ -1139,6 +1433,7 @@ export class PipelineOrchestrator {
1139
1433
  inplaceRetries += plusResult.inplaceRetries;
1140
1434
  servedCredentialPrefix = plusResult.servedCredentialPrefix;
1141
1435
  poolTiming = plusResult.timing;
1436
+ upstreamStream = plusResult.transport;
1142
1437
  }
1143
1438
  }
1144
1439
  else {
@@ -1167,45 +1462,60 @@ export class PipelineOrchestrator {
1167
1462
  accessTierMode = 'member-home';
1168
1463
  }
1169
1464
  else {
1170
- // Auto & explicit: tier pool (peek-filtered; fall back to the full
1171
- // pool when everything is tripped — the loop force-tries the last
1172
- // candidate). Head = pinned model (auto, post-eviction) or the
1173
- // explicit model, so KV-cache affinity is preserved.
1174
- let pool = this.registry.getCandidateModelsForTier(actualTier, true);
1175
- if (pool.length === 0)
1176
- pool = this.registry.getCandidateModelsForTier(actualTier, false);
1177
- // Bare-auto under a model-access policy: the classifier may land in a
1178
- // tier that holds no admissible model (allow: none whitelisted in that
1179
- // tier; deny: every model of that tier tier-denied) — widen the pool
1180
- // to every allowed model across tiers (chosen tier first, then by
1181
- // tier proximity) instead of failing with a policy 403. "auto"
1182
- // promises SOME allowed model, not a specific tier.
1183
- const accessPolicy = context?.modelAccess;
1184
- const isBareAuto = !normalizedRequest.model || normalizedRequest.model === 'auto';
1185
- if (accessPolicy && isBareAuto && !explicitModel && !comboId) {
1186
- const rank = TIER_RANK;
1187
- // Multi-membership admit: allowed when the id or ANY membership
1188
- // tier passes (allow mode); denied when the id or ANY membership
1189
- // tier is denied (deny mode).
1190
- const widened = this.registry
1191
- .getAllModels()
1192
- .filter((m) => isModelAllowedInTiers(m.id, accessPolicy, this.registry.tiersOf(m)))
1193
- .sort((a, b) => Math.abs((rank[a.tier] ?? 9) - (rank[actualTier] ?? 9)) - Math.abs((rank[b.tier] ?? 9) - (rank[actualTier] ?? 9)) ||
1194
- (rank[a.tier] ?? 9) - (rank[b.tier] ?? 9));
1195
- if (widened.length > 0)
1196
- pool = widened;
1197
- }
1465
+ // Explicit: the named model serves — the chain is [explicitModel] ONLY.
1466
+ // Cross-model substitution of a named model is a fidelity breach (the
1467
+ // OpenAI wire serves the named model or errors); in-place same-model
1468
+ // retry and credential re-spread stay unconditional. A client that
1469
+ // WANTS substitution opts in per request via router_options.failover.
1470
+ const explicitFailover = explicitModel && normalizedRequest.routerOptions?.failover === true;
1198
1471
  const head = explicitModel ?? preferredModel;
1199
- chain = head ? [head, ...pool.filter(m => m.id !== head.id)] : pool;
1200
- // Auto keeps the configured failover budget; explicit/combo are
1201
- // bounded by their own chain length (failover.maxAttempts governs
1202
- // auto routing only). Cross-tier escalation is an AUTO-routing
1203
- // policy — forced tiers (tier aliases / mode lever) and explicit models
1204
- // fail over within their tier by contract (ADR-0014).
1205
- attemptCap = explicitModel ? Math.max(1, chain.length) : maxFailoverCandidates;
1472
+ if (explicitModel && !explicitFailover) {
1473
+ // The named model IS the contract: a one-model chain, no
1474
+ // substitution (ADR-0014). No pool is built at all — nothing to
1475
+ // fail over to.
1476
+ chain = [explicitModel];
1477
+ attemptCap = 1;
1478
+ }
1479
+ else {
1480
+ // Auto (or an explicit request that opted in via
1481
+ // router_options.failover): the tier pool (peek-filtered; fall back
1482
+ // to the full pool when everything is tripped — the loop force-tries
1483
+ // the last candidate) follows the head, so KV-cache affinity is
1484
+ // preserved on the first candidate.
1485
+ let pool = this.registry.getCandidateModelsForTier(actualTier, true);
1486
+ if (pool.length === 0)
1487
+ pool = this.registry.getCandidateModelsForTier(actualTier, false);
1488
+ // Bare-auto under a model-access policy: the classifier may land in a
1489
+ // tier that holds no admissible model (allow: none whitelisted in that
1490
+ // tier; deny: every model of that tier tier-denied) — widen the pool
1491
+ // to every allowed model across tiers (chosen tier first, then by
1492
+ // tier proximity) instead of failing with a policy 403. "auto"
1493
+ // promises SOME allowed model, not a specific tier.
1494
+ const accessPolicy = context?.modelAccess;
1495
+ const isBareAuto = !normalizedRequest.model || normalizedRequest.model === 'auto';
1496
+ if (accessPolicy && isBareAuto && !explicitModel && !comboId) {
1497
+ const rank = TIER_RANK;
1498
+ // Multi-membership admit: allowed when the id or ANY membership
1499
+ // tier passes (allow mode); denied when the id or ANY membership
1500
+ // tier is denied (deny mode).
1501
+ const widened = this.registry
1502
+ .getAllModels()
1503
+ .filter((m) => isModelAllowedInTiers(m.id, accessPolicy, this.registry.tiersOf(m)))
1504
+ .sort((a, b) => Math.abs((rank[a.tier] ?? 9) - (rank[actualTier] ?? 9)) - Math.abs((rank[b.tier] ?? 9) - (rank[actualTier] ?? 9)) ||
1505
+ (rank[a.tier] ?? 9) - (rank[b.tier] ?? 9));
1506
+ if (widened.length > 0)
1507
+ pool = widened;
1508
+ }
1509
+ chain = head ? [head, ...pool.filter(m => m.id !== head.id)] : pool;
1510
+ // Auto keeps the configured failover budget; an explicit opt-in is
1511
+ // bounded by its own chain length (failover.maxAttempts governs
1512
+ // auto routing only). Cross-tier escalation is an AUTO-routing
1513
+ // policy — forced tiers never escape their tier.
1514
+ attemptCap = explicitModel ? Math.max(1, chain.length) : maxFailoverCandidates;
1515
+ }
1206
1516
  allowEscalate =
1207
1517
  !explicitModel &&
1208
- !normalizedRequest.router_options?.force_tier &&
1518
+ !normalizedRequest.routerOptions?.forceTier &&
1209
1519
  tierCrossPolicy === 'allow_escalate' &&
1210
1520
  actualTier === 'lite';
1211
1521
  }
@@ -1225,13 +1535,13 @@ export class PipelineOrchestrator {
1225
1535
  // the full `message.content` before its verdict, and that verdict can
1226
1536
  // re-ask the whole turn on a bigger tier — relaying it would commit
1227
1537
  // output the cascade is about to throw away.
1228
- relay: this.config.streaming?.enabled === false ? undefined : relay,
1538
+ relay,
1229
1539
  streamRouting: {
1230
1540
  layerUsed: decision.layerUsed || 'layer0',
1231
1541
  sessionId,
1232
1542
  sessionRatchetApplied: ratchetApplied,
1233
1543
  sessionLookupType: sessionResolve.lookupType,
1234
- traceId: traceId ?? 'unknown',
1544
+ requestId,
1235
1545
  requestedEffort,
1236
1546
  variantUsed,
1237
1547
  },
@@ -1240,18 +1550,56 @@ export class PipelineOrchestrator {
1240
1550
  if (execResult.policyDenied) {
1241
1551
  throw Object.assign(new Error(`API key model policy (${context?.modelAccess?.mode}) admits no candidate model for this request`), { statusCode: 403 });
1242
1552
  }
1243
- throw execResult.lastError || new Error(`Execution failed for tier '${actualTier}'`);
1553
+ if (explicitModel && chain.length === 1) {
1554
+ // An explicit chain that exhausted without a substitute (failover
1555
+ // off — the default) must fail LOUD and name the model: the client
1556
+ // asked for exactly this model and deserves to know it did not
1557
+ // serve, not a generic tier-level message (mirrors policyDenied).
1558
+ const lastErr = execResult.lastError;
1559
+ const unsupported = lastErr instanceof IrUnsupportedError;
1560
+ throw Object.assign(new Error(`Explicit model '${explicitModel.id}' did not serve the request (a named model is never substituted; opt in per request with router_options.failover to allow tier-pool failover). Last error: ${lastErr?.message ?? 'unknown'}`), {
1561
+ statusCode: statusCodeOf(lastErr) ?? 502,
1562
+ ...(unsupported ? { name: 'IrUnsupportedError', code: 'unsupported_parameter' } : {}),
1563
+ });
1564
+ }
1565
+ // Pool exhausted with a non-policy failure. The upstream verdict is
1566
+ // the GATEWAY's routing state, never the client's problem: agent
1567
+ // clients auto-retry 429 but hard-stop on 402, so a forwarded
1568
+ // "insufficient balance" wastes models that are still healthy.
1569
+ // Two gateway-authored shapes:
1570
+ // - untried healthy models remain → 429: the client's own backoff
1571
+ // retry re-peeks the pool and lands on one of them, no user
1572
+ // action needed (only routing-fixable classes remap — a 400 is
1573
+ // the request's fault and retries cannot fix it);
1574
+ // - every candidate is cooling down → keep the truthful status,
1575
+ // say what the operator must do (console breaker panel /
1576
+ // credentials).
1577
+ // Remaining = the executed CHAIN (covers combo member lists that span
1578
+ // tiers, where a tier-peek would read the wrong pool) minus the
1579
+ // attempted path, gated by the non-consuming per-model breaker peek —
1580
+ // so trips that happened during this very run are counted — and by
1581
+ // the key's model-access policy, which the pool filter applied
1582
+ // inside executeCandidatePool.
1583
+ const lastErr = execResult.lastError;
1584
+ if (lastErr instanceof IrUnsupportedError)
1585
+ throw lastErr;
1586
+ const accessPolicy = context?.modelAccess;
1587
+ const remaining = chain.filter((m) => !execResult.failoverPath.includes(m.id) &&
1588
+ this.getCircuitBreakerManager().isAvailable(m.id) &&
1589
+ (!accessPolicy || isModelAllowedInTiers(m.id, accessPolicy, this.registry.tiersOf(m))));
1590
+ throw routeExhaustedError(comboId ? `combo '${comboId}'` : `tier '${actualTier}'`, execResult.failoverPath, lastErr, remaining);
1244
1591
  }
1245
1592
  finalResponse = execResult.response;
1246
1593
  actualModel = execResult.modelUsed;
1247
1594
  actualTier = execResult.tierUsed;
1248
1595
  poolTiming = execResult.timing;
1596
+ upstreamStream = execResult.transport;
1249
1597
  // Recompute `actualEffort` against the model that ACTUALLY served the
1250
1598
  // request — failover may have shifted to a different model than the
1251
1599
  // one `pickModelForEffort` originally picked, with a different effort
1252
1600
  // translation/ceiling. The header / ExecutionResult must reflect reality.
1253
1601
  {
1254
- const r = this.resolveServedEffort(actualModel, requestedEffort, actualTier);
1602
+ const r = this.resolveServedEffort(actualModel, requestedEffort, actualTier, budgetTokens);
1255
1603
  actualEffort = r.actualEffort;
1256
1604
  reasoningDegraded = r.degraded;
1257
1605
  }
@@ -1284,7 +1632,7 @@ export class PipelineOrchestrator {
1284
1632
  // persisted the bind/rebind right after the successful call (this point
1285
1633
  // would only ever see a still-unbound session when no multi-credential chain
1286
1634
  // was in play — nothing to bind).
1287
- this.sessionManager.registerCompletedTurn(sessionId, fingerprintMessages, finalResponse.choices[0]?.message ?? '');
1635
+ this.sessionManager.registerCompletedTurn(sessionId, fingerprintItems, finalResponse.output);
1288
1636
  // 7. Post-turn observability
1289
1637
  const latencyMs = Date.now() - startTime;
1290
1638
  // Streaming decode timing (industry TTFT/TPS split), from the committed
@@ -1296,6 +1644,12 @@ export class PipelineOrchestrator {
1296
1644
  // execution, relay off, or a relay whose wire had no streaming executor).
1297
1645
  const ttftMs = poolTiming ? poolTiming.firstChunkAt - startTime : undefined;
1298
1646
  const genMs = poolTiming ? poolTiming.streamEndAt - poolTiming.firstChunkAt : undefined;
1647
+ // Perceived stall ratio numerator: total time the committed stream spent
1648
+ // frozen in gaps of ≥ PERCEIVED_STALL_MS. Carried straight through —
1649
+ // measured, not derived, so there is no second definition to drift from.
1650
+ // The session divides the summed value by its summed decode windows
1651
+ // (stallRatio).
1652
+ const stalledMs = poolTiming?.stalledMs;
1299
1653
  // Thinking-level observability. Two cases that warrant a warn:
1300
1654
  // 1. Client asked for thinking but the actually-served model can't do
1301
1655
  // thinking at all — payload builder silently dropped the fields.
@@ -1308,9 +1662,9 @@ export class PipelineOrchestrator {
1308
1662
  // `'none'` is a real effort value meaning "no thinking" — NOT a request
1309
1663
  // for thinking that the model failed to honor. An omitted field is also
1310
1664
  // not a request for thinking (model uses its own default).
1311
- const wantsThinking = (normalizedRequest.reasoning_effort != null &&
1312
- normalizedRequest.reasoning_effort !== 'none') ||
1313
- (typeof normalizedRequest.max_thinking_tokens === 'number' && normalizedRequest.max_thinking_tokens > 0);
1665
+ const servedEffort = effortOf(normalizedRequest);
1666
+ const wantsThinking = (servedEffort != null && servedEffort !== 'none') ||
1667
+ (typeof budgetTokens === 'number' && budgetTokens > 0);
1314
1668
  // 5-level default: `none` is a client toggle, not a capability.
1315
1669
  const modelEfforts = actualModel.supportedReasoningEfforts
1316
1670
  ?? (actualModel.supportsReasoningEffort ? EFFORT_LADDER : []);
@@ -1323,8 +1677,8 @@ export class PipelineOrchestrator {
1323
1677
  // without becoming noise.
1324
1678
  const throttle = getWarnThrottle();
1325
1679
  if (wantsThinking && !supportsAnyThinking) {
1326
- const key = `no-capability|${actualModel.id}|${actualModel.wire ?? 'openai'}`;
1327
- throttle.warn(key, `[ocr] thinking-level request served by '${actualModel.id}' (${actualModel.wire ?? 'openai'} wire) — ` +
1680
+ const key = `no-capability|${actualModel.id}|${actualModel.wire ?? 'openai-chat'}`;
1681
+ throttle.warn(key, `[ocr] thinking-level request served by '${actualModel.id}' (${actualModel.wire ?? 'openai-chat'} wire) — ` +
1328
1682
  `model has no thinking-effort capability, thinking controls were silently dropped.`);
1329
1683
  }
1330
1684
  if (reasoningDegraded &&
@@ -1339,14 +1693,15 @@ export class PipelineOrchestrator {
1339
1693
  `served '${actualEffort}' on model '${actualModel.id}' (gap=${gap} levels, ` +
1340
1694
  `model supports [${modelEfforts.join(', ') || 'none'}])`);
1341
1695
  }
1342
- const cachedTokens = PromptOptimizer.extractCachedTokens(finalResponse.usage);
1696
+ const usage = finalResponse.usage;
1697
+ const cachedTokens = PromptOptimizer.extractCachedTokens(usage);
1343
1698
  this.tracker.record({
1344
1699
  tier: actualTier,
1345
1700
  fallbackOccurred,
1346
- inputTokens: finalResponse.usage?.prompt_tokens || 0,
1347
- cachedTokens: cachedTokens,
1348
- outputTokens: finalResponse.usage?.completion_tokens || 0,
1349
- reasoningTokens: finalResponse.usage?.completion_tokens_details?.reasoning_tokens || 0,
1701
+ inputTokens: usage.inputTokens,
1702
+ cachedTokens,
1703
+ outputTokens: usage.outputTokens,
1704
+ reasoningTokens: usage.reasoningTokens ?? 0,
1350
1705
  latencyMs,
1351
1706
  });
1352
1707
  // 7b. Sliding-window accounting (ratelimit engine). A completed
@@ -1354,19 +1709,18 @@ export class PipelineOrchestrator {
1354
1709
  // only path that produces usage, and the request slots were already
1355
1710
  // consumed at the gates (inbound: auth preHandler, outbound: dispatch
1356
1711
  // above), so failed turns carry usage: 0 without a second ledger write.
1357
- // Tokens = prompt + completion (cached ⊂ prompt, reasoning ⊂ completion);
1358
- // cost = the same request-time pricing snapshot the trace row records.
1712
+ // Cached tokens are included in input; reasoning tokens in output.
1359
1713
  const rlUsage = {
1360
- tokens: (finalResponse.usage?.prompt_tokens || 0) + (finalResponse.usage?.completion_tokens || 0),
1361
- costUsd: computeRequestCost(finalResponse.usage, actualModel.pricing),
1714
+ tokens: usage.inputTokens + usage.outputTokens,
1715
+ costUsd: computeRequestCost(usage, actualModel.pricing),
1362
1716
  };
1363
1717
  let usageCredentialPrefix;
1364
1718
  {
1365
1719
  const rl = getRateLimiter();
1366
- const clientKeyId = captureKeyIdentity(context?.fastifyRequest)?.id;
1720
+ const clientKeyId = keyIdentityOf(context)?.id;
1367
1721
  if (clientKeyId)
1368
1722
  rl.recordUsage(apiKeySubject(clientKeyId), rlUsage);
1369
- // The credential that SERVED (same chain-head degeneracy as the pool gate,
1723
+ // The credential that SERVED (same default-credential degeneracy as the pool gate,
1370
1724
  // so single-credential providers carry usage too). `servedUsagePrefix`
1371
1725
  // also feeds the trace record below (execution.credentialKeyHashPrefix):
1372
1726
  // one credential attribution, two consumers (ratelimit subject + quota
@@ -1393,7 +1747,17 @@ export class PipelineOrchestrator {
1393
1747
  effort: actualEffort,
1394
1748
  source: 'l2_confident',
1395
1749
  confidence: decision.confidence,
1396
- snippet: routeGate.snippetEnabled === false ? undefined : lastUserText ? lastUserText.slice(0, 200) : undefined, // same 200-char display-aid precedent as session attachOrigin
1750
+ // Display aid only: client metadata envelopes (Cursor's
1751
+ // `<timestamp>`, Claude Code's `<system-reminder>`) are dropped so
1752
+ // the snippet names the prompt, not a clock reading or harness
1753
+ // boilerplate — same 200-char display-aid precedent as the session
1754
+ // attachOrigin, same harness profile as the title.
1755
+ snippet: routeGate.snippetEnabled === false
1756
+ ? undefined
1757
+ : (envelopeHints.declaredPrompt ??
1758
+ (lastUserText
1759
+ ? clipDisplayText(displayPromptText(lastUserText, { profile: envelopeHints.profile })) || undefined
1760
+ : undefined)),
1397
1761
  }, sessionId);
1398
1762
  appendRoutingLedger({
1399
1763
  kind: 'entry_write',
@@ -1403,63 +1767,47 @@ export class PipelineOrchestrator {
1403
1767
  });
1404
1768
  }
1405
1769
  }
1406
- // 8. Session Trajectory Recording — the traceId is shared with the
1407
- // capture event stream (the OTel traceId sourced from the client request
1408
- // — see resolveTraceId). One id now joins capture events and the trace
1409
- // record, so a console reader can pull both streams by traceId.
1410
- const sharedTraceId = traceId ?? 'unknown';
1411
- // Multimodal content parts: keep the text ones (mirrors the early
1412
- // lastUserText join at 2C without the `any` cast).
1413
- const textPartOf = (p) => {
1414
- if (typeof p !== 'object' || p === null || !('text' in p))
1415
- return '';
1416
- const text = p.text;
1417
- return typeof text === 'string' ? text : '';
1418
- };
1419
- // The summary names the user message THAT TRIGGERED this turn. A
1420
- // tool-result continuation turn carries the whole history, so its last
1421
- // user message is the PREVIOUS turn's prompt — recording it again makes
1422
- // every continuation row in the console's request detail read as a
1423
- // duplicate (an empty summary renders the "no new user message"
1424
- // fallback glyph). The message is stale when its index already existed
1425
- // at the session's previous turn: clients append, so a genuinely new
1426
- // user message always lands at or past the previous messageCount.
1427
- // Both counts are post-compression snapshots — a heavy compression
1428
- // shrink may over-mark; that only hides a display aid, never data.
1429
- const lastUserIdx = (() => {
1430
- for (let i = normalizedRequest.messages.length - 1; i >= 0; i--) {
1431
- if (normalizedRequest.messages[i].role === 'user')
1432
- return i;
1433
- }
1434
- return -1;
1435
- })();
1436
- const lastUserMsg = lastUserIdx >= 0 ? normalizedRequest.messages[lastUserIdx] : undefined;
1437
- let userPromptSummary = typeof lastUserMsg?.content === 'string'
1438
- ? lastUserMsg.content.slice(0, 200)
1439
- : Array.isArray(lastUserMsg?.content)
1440
- ? (lastUserMsg.content.map(textPartOf).join(' ')).slice(0, 200)
1441
- : '';
1442
- if (userPromptSummary) {
1443
- const prevTraces = this.traceTracker.getTracesBySession(sessionId);
1444
- const prevMessageCount = prevTraces[prevTraces.length - 1]?.request.messageCount ?? 0;
1445
- if (lastUserIdx < prevMessageCount)
1446
- userPromptSummary = '';
1447
- }
1770
+ // 8. Session Trajectory Recording. The record is keyed by its own
1771
+ // `requestId` (ADR-0021); the caller's `clientRequestId` is stored beside
1772
+ // it as correlation only, because a caller may reuse one value for every
1773
+ // request of a conversation.
1774
+ // Display-only prompt text. The write-time boundary decides whether this
1775
+ // request opened a turn; a tool-result continuation carries the previous
1776
+ // prompt in its history and must not render a duplicate header. Text is
1777
+ // never consulted to DECIDE that boundary — `isPromptStart` is.
1778
+ const lastUserTextForSummary = messageText(lastUserMessage(normalizedRequest.input));
1779
+ const userPromptSummary = requestTurn.isPromptStart
1780
+ ? (envelopeHints.declaredPrompt ??
1781
+ clipDisplayText(displayPromptText(lastUserTextForSummary, { profile: envelopeHints.profile })))
1782
+ : '';
1448
1783
  this.traceTracker.record({
1449
- traceId: sharedTraceId,
1784
+ requestId,
1785
+ ...(clientRequestId ? { clientRequestId } : {}),
1450
1786
  sessionId,
1451
- turnNumber: sessionTurnCount,
1787
+ requestNumber: sessionRequestCount,
1788
+ turnIndex: requestTurn.turnIndex,
1789
+ isPromptStart: requestTurn.isPromptStart,
1790
+ turnDecision: requestTurn.turnDecision,
1452
1791
  timestamp: startTime,
1453
1792
  // Key attribution on the lightweight session trajectory as well (works
1454
1793
  // even with capture disabled): which application's key drove this turn.
1455
- apiKey: captureKeyIdentity(context?.fastifyRequest),
1794
+ apiKey: keyIdentityOf(context),
1456
1795
  request: {
1457
1796
  model: request.model || 'auto',
1458
1797
  userPromptSummary,
1459
- messageCount: normalizedRequest.messages.length,
1460
- hasSystemPrompt: normalizedRequest.messages.some(m => m.role === 'system'),
1461
- hasToolsOrSchema: Boolean(decision.needsSchemaValidation),
1798
+ ...(firstUserSummary ? { firstUserSummary } : {}),
1799
+ messageCount: normalizedRequest.input.length,
1800
+ hasSystemPrompt: Boolean(normalizedRequest.instructions)
1801
+ || normalizedRequest.input.some((item) => item.type === 'message' && (item.role === 'system' || item.role === 'developer')),
1802
+ hasToolsOrSchema: hasToolsOrSchema(normalizedRequest),
1803
+ // Response shape actually written to the client (surface-owned: the
1804
+ // C-3-normalized ask, or `client.mode: always` forcing SSE).
1805
+ clientStream: context?.clientStream === true,
1806
+ // Inbound protocol surface the client addressed (chat / anthropic /
1807
+ // responses) — the console's protocol column reads it directly.
1808
+ inboundWire: context?.wire,
1462
1809
  clientHeaders: extractClientHeaders(context?.headers),
1810
+ ...(clientRef ? { clientRef } : {}),
1463
1811
  },
1464
1812
  routing: {
1465
1813
  layerUsed: (decision.layerUsed || 'layer0'),
@@ -1477,9 +1825,17 @@ export class PipelineOrchestrator {
1477
1825
  credentialKeyHashPrefix: usageCredentialPrefix,
1478
1826
  tierUsed: actualTier,
1479
1827
  latencyMs,
1828
+ // OUTBOUND protocol wire the served attempt ran on (distinct from the
1829
+ // inbound surface unless the turn is a passthrough).
1830
+ wireKind: actualModel.wire,
1480
1831
  ttftMs,
1481
1832
  genMs,
1833
+ stalledMs,
1482
1834
  fallbackOccurred,
1835
+ // Provider-leg transport of the served attempt — the OUTBOUND stream
1836
+ // tag (ADR-0008 §1). 'sse' with clientStream:false is the accumulate
1837
+ // mode: the gateway read a stream and answered in JSON.
1838
+ upstreamStream,
1483
1839
  fallbackReason,
1484
1840
  failoverOccurred,
1485
1841
  failoverAttempts,
@@ -1495,13 +1851,13 @@ export class PipelineOrchestrator {
1495
1851
  effortSource,
1496
1852
  },
1497
1853
  finops: {
1498
- inputTokens: finalResponse.usage?.prompt_tokens || 0,
1499
- outputTokens: finalResponse.usage?.completion_tokens || 0,
1500
- cachedTokens: cachedTokens,
1854
+ inputTokens: usage.inputTokens,
1855
+ outputTokens: usage.outputTokens,
1856
+ cachedTokens,
1501
1857
  costUsd: rlUsage.costUsd,
1502
1858
  },
1503
1859
  });
1504
- const breakerState = cbManager.getBreaker(actualModel.id)?.getState() || 'CLOSED';
1860
+ const breakerState = cbManager.getSnapshot(actualModel.id)?.state ?? 'CLOSED';
1505
1861
  // additive keys only — older readers keep reading
1506
1862
  // breakerState alone: when the turn ran in pair mode, expose the serving
1507
1863
  // credential's pair snapshot and the model's availability aggregate.
@@ -1512,6 +1868,7 @@ export class PipelineOrchestrator {
1512
1868
  tierUsed: actualTier,
1513
1869
  modelUsed: actualModel.id,
1514
1870
  layerUsed: decision.layerUsed || 'layer0',
1871
+ protocolUsed: protocolForWire(actualModel.wire ?? 'openai-chat'),
1515
1872
  fallbackOccurred,
1516
1873
  fallbackReason,
1517
1874
  failoverOccurred,
@@ -1525,8 +1882,13 @@ export class PipelineOrchestrator {
1525
1882
  sessionId,
1526
1883
  sessionRatchetApplied: ratchetApplied,
1527
1884
  sessionLookupType: sessionResolve.lookupType,
1528
- traceId: sharedTraceId,
1885
+ requestId,
1529
1886
  latencyMs,
1887
+ ttftMs,
1888
+ genMs,
1889
+ stalledMs,
1890
+ clientStream: context?.clientStream === true,
1891
+ upstreamStream,
1530
1892
  // Reasoning-effort observability — server.ts reads these to set
1531
1893
  // X-OCR-Thinking-{Requested,Actual,Degraded} headers so the client
1532
1894
  // can see whether they got the level they asked for.
@@ -1547,11 +1909,18 @@ export class PipelineOrchestrator {
1547
1909
  * value against what the client asked (`undefined` / `'none'` count as the
1548
1910
  * none level).
1549
1911
  */
1550
- resolveServedEffort(model, requestedEffort, servedTier) {
1551
- const ask = requestedEffort ?? 'none';
1912
+ wireConsumesBudgetNatively(wire) {
1913
+ return wire === 'anthropic-messages' || wire === 'google-gemini' || wire === 'openai-responses';
1914
+ }
1915
+ resolveServedEffort(model, requestedEffort, servedTier, budgetTokens) {
1916
+ const effectiveRequested = requestedEffort ??
1917
+ (typeof budgetTokens === 'number' && budgetTokens > 0 && !this.wireConsumesBudgetNatively(model.wire)
1918
+ ? effortFromThinkingBudget(budgetTokens)
1919
+ : undefined);
1920
+ const ask = effectiveRequested ?? 'none';
1552
1921
  const target = applyEffortMap(this.registry.effortMapFor(model, servedTier), ask);
1553
1922
  if (target === 'none' && ask === 'none')
1554
- return { actualEffort: requestedEffort, degraded: false };
1923
+ return { actualEffort: effectiveRequested, degraded: false };
1555
1924
  const supported = model.supportedReasoningEfforts ?? (model.supportsReasoningEffort ? EFFORT_LADDER : []);
1556
1925
  const actual = target === 'none' ? 'none' : downgradeReasoning(target, supported);
1557
1926
  return {
@@ -1582,7 +1951,8 @@ export class PipelineOrchestrator {
1582
1951
  * rejection costs nothing upstream — when the whole chain is down this is
1583
1952
  * the last-resort attempt). `attemptCap` bounds real attempts: the
1584
1953
  * configured retry.failover.maxAttempts for auto routing, the full chain
1585
- * length for explicit/combo chains.
1954
+ * length for opt-in/combo chains (an explicit model's chain is ONE — it
1955
+ * is never substituted).
1586
1956
  *
1587
1957
  * Breaker gate: canExecuteScoped() here is the ONLY probe-consuming check in
1588
1958
  * the request path — every selection/filtering site uses the non-consuming
@@ -1704,7 +2074,7 @@ export class PipelineOrchestrator {
1704
2074
  }
1705
2075
  // Outbound sliding-window gate (`credentials:` overlay) — evaluated BEFORE the
1706
2076
  // breaker gate so an at-cap credential never burns a half-open canary.
1707
- // The chain head stands in when the selector degenerated (single-credential
2077
+ // The default credential stands in when the selector degenerated (single-credential
1708
2078
  // / sessionless paths — the head IS the boot-baked credential registry.execute
1709
2079
  // serves with, registry invariant), so caps fire on one-key providers too.
1710
2080
  // NON-CONSUMING peek: the request slot is taken below only when the call
@@ -1799,22 +2169,50 @@ export class PipelineOrchestrator {
1799
2169
  // byte-identical request when nothing is in play).
1800
2170
  let candidateReq = request;
1801
2171
  {
1802
- const ask = opts.requestedEffort ?? 'none';
2172
+ const budgetAsk = opts.requestedEffort === undefined &&
2173
+ typeof request.reasoning?.budgetTokens === 'number' &&
2174
+ request.reasoning.budgetTokens > 0 &&
2175
+ !this.wireConsumesBudgetNatively(candidate.wire)
2176
+ ? effortFromThinkingBudget(request.reasoning.budgetTokens)
2177
+ : undefined;
2178
+ const ask = opts.requestedEffort ?? budgetAsk ?? 'none';
1803
2179
  const target = applyEffortMap(candidateEffortMap, ask);
1804
2180
  if (!(target === 'none' && ask === 'none')) {
1805
2181
  const supported = candidate.supportedReasoningEfforts ?? (candidate.supportsReasoningEffort ? EFFORT_LADDER : []);
1806
2182
  const candidateEffort = target === 'none' ? 'none' : downgradeReasoning(target, supported);
1807
- if (candidateEffort !== request.reasoning_effort) {
1808
- candidateReq = { ...request, reasoning_effort: candidateEffort };
2183
+ if (candidateEffort !== effortOf(request)) {
2184
+ candidateReq = {
2185
+ ...request,
2186
+ reasoning: { ...request.reasoning, effort: candidateEffort },
2187
+ };
1809
2188
  }
1810
2189
  }
1811
2190
  }
2191
+ // On cross-protocol failover candidates, strip non-portable reasoning
2192
+ // signatures / encrypted blobs so long multi-turn threads can still fail over
2193
+ // to Chat-only upstreams instead of failing with 400 on the backup model.
2194
+ if (failoverAttempts > 1 &&
2195
+ !capabilitiesFor(protocolForWire(candidate.wire ?? 'openai-chat')).reasoningSignature &&
2196
+ candidateReq.input.some((item) => item.type === 'reasoning' && (item.signature !== undefined || item.encrypted !== undefined))) {
2197
+ const strippedInput = candidateReq.input.flatMap((item) => {
2198
+ if (item.type !== 'reasoning' || (item.signature === undefined && item.encrypted === undefined))
2199
+ return [item];
2200
+ const { signature: _sig, encrypted: _enc, ...rest } = item;
2201
+ return rest.text || rest.summary ? [rest] : [];
2202
+ });
2203
+ candidateReq = { ...candidateReq, input: strippedInput };
2204
+ }
1812
2205
  // Stage this attempt's routing facts BEFORE the call: a relay that gets
1813
2206
  // bytes flushes them with the first forwarded chunk, and only an attempt
1814
2207
  // that actually proceeds can commit any (earlier attempts never got that
1815
2208
  // far, and each later attempt simply overwrites the staged set).
1816
2209
  if (opts.relay) {
1817
- opts.relay.stageRouting({ ...opts.streamRouting, modelUsed: candidate.id, tierUsed: candidateAccessTier });
2210
+ opts.relay.stageRouting({
2211
+ ...opts.streamRouting,
2212
+ modelUsed: candidate.id,
2213
+ tierUsed: candidateAccessTier,
2214
+ protocolUsed: protocolForWire(candidate.wire ?? 'openai-chat'),
2215
+ });
1818
2216
  }
1819
2217
  // In-place retry loop on the SAME candidate model
1820
2218
  let candidateSucceeded = false;
@@ -1830,12 +2228,44 @@ export class PipelineOrchestrator {
1830
2228
  // bytes-to-client boundary).
1831
2229
  let firstChunkAt;
1832
2230
  let streamEndAt;
2231
+ // Perceived stall bookkeeping: the stream's own cadence, not its
2232
+ // average. Only chunks that carry VISIBLE output advance `lastVisibleAt`
2233
+ // — answer text, tool-call fragments AND reasoning/thinking deltas (all
2234
+ // forwarded to the client). A role-only opener, a finish_reason frame or
2235
+ // the trailing usage frame produces nothing on the user's screen, so
2236
+ // treating them as progress would hide exactly the pause this metric
2237
+ // exists to catch — and counting thinking as silence would invent one.
2238
+ // Every gap ≥ PERCEIVED_STALL_MS is ADDED UP: the session-level figure
2239
+ // is a share of the decode window, which keeps repeated stutters and one
2240
+ // long freeze on the same scale (a single maximum cannot).
2241
+ let lastVisibleAt;
2242
+ let stalledMs;
2243
+ // Transport the served attempt actually used (registry-reported, once
2244
+ // per attempt). Reset per attempt: a retry re-issues with a fresh tag.
2245
+ let transport;
1833
2246
  const timingRelay = opts.relay
1834
2247
  ? {
1835
2248
  stageRouting: (facts) => opts.relay.stageRouting(facts),
2249
+ onTransport: (kind) => {
2250
+ transport = kind;
2251
+ opts.relay.onTransport?.(kind);
2252
+ },
1836
2253
  onChunk: (chunk) => {
1837
- firstChunkAt ??= Date.now();
1838
- opts.relay.onChunk(chunk);
2254
+ const now = Date.now();
2255
+ firstChunkAt ??= now;
2256
+ if (hasVisibleOutput(chunk)) {
2257
+ if (lastVisibleAt !== undefined) {
2258
+ const gap = now - lastVisibleAt;
2259
+ // The first measured gap proves this turn HAS a stream
2260
+ // cadence: 0 means "measured and smooth", undefined stays
2261
+ // reserved for fewer than two output chunks.
2262
+ stalledMs ??= 0;
2263
+ if (gap >= PERCEIVED_STALL_MS)
2264
+ stalledMs += gap;
2265
+ }
2266
+ lastVisibleAt = now;
2267
+ }
2268
+ return opts.relay.onChunk(chunk);
1839
2269
  },
1840
2270
  get committed() {
1841
2271
  return opts.relay.committed;
@@ -1856,11 +2286,42 @@ export class PipelineOrchestrator {
1856
2286
  catch (err) {
1857
2287
  lastError = err;
1858
2288
  const diagnosis = ErrorClassifier.classify(err, candidate.id, candidate.provider, this.config.circuitBreaker, this.config.retry);
1859
- // The classifier already read the registry-stamped usedCredentialKeyHashPrefix
1860
- // (tripScope + credentialSuspect); this call expands the verdict over the
1861
- // diagnosed blast radius when a prefix attributes it, and routes the
1862
- // bare model breaker when not (today's semantics).
1863
- cbManager.recordFailureScoped(candidate.id, diagnosis, candidate.provider, credentialPrefix);
2289
+ // Breaker accounting is per logical request, NOT per in-place
2290
+ // attempt: a retried attempt that eventually succeeds leaves no
2291
+ // failure on the breaker, and an abandoned candidate records
2292
+ // exactly one failure. Counting every attempt let a single request
2293
+ // burn the whole trip threshold by itself (retry amplification).
2294
+ // The final attempt's diagnosis is the one recorded — it carries
2295
+ // the same registry-stamped usedCredentialKeyHashPrefix
2296
+ // (tripScope + credentialSuspect + usedKeyHashPrefix); the manager
2297
+ // attributes from `credentialPrefix` OR that stamp, so a
2298
+ // credential-fault error cools its credential even when selection
2299
+ // returned no prefix (all-unhealthy / no-session): the manager then
2300
+ // attributes from the diagnosis stamp itself. Only a chain-less
2301
+ // provider (no stamp at all) stays on the sentinel tuple.
2302
+ // A committed attempt can never actually in-place retry (the commit
2303
+ // check below returns first), so `committed` belongs in this
2304
+ // condition: without it a mid-stream CONNECTION_RESET on a streamed
2305
+ // turn would skip BOTH the retry and the record — zero breaker
2306
+ // evidence from clients dying mid-body on a dying upstream.
2307
+ // Single source for BOTH the recording decision above and the step-2
2308
+ // retry decision below — the committed check at the commit point
2309
+ // returns first, so the two can never disagree.
2310
+ const willRetryInPlace = diagnosis.isInPlaceRetriable && attempt < maxInplaceAttempts && !opts.relay?.committed;
2311
+ if (!willRetryInPlace) {
2312
+ cbManager.recordFailureScoped(candidate.id, diagnosis, candidate.provider, credentialPrefix, this.registry.getCredentialChain(candidate.provider)?.map((c) => c.keyHashPrefix));
2313
+ }
2314
+ // Upstream-429 feedback into the local shaping window: the provider
2315
+ // just TOLD us this credential is at-cap — feed the declared wait
2316
+ // (or a 60s default when the 429 carries no Retry-After) into the
2317
+ // rate limiter so NEW-session steering avoids this credential
2318
+ // immediately instead of re-discovering the wall. The breaker keeps
2319
+ // its own independent cooldown below; this only sharpens the peek()
2320
+ // shaping input. No ledger entry: the failure event above already
2321
+ // records the 429 fact.
2322
+ if (diagnosis.category === 'RATE_LIMITED' && limitSubject) {
2323
+ getRateLimiter().penalize(limitSubject, diagnosis.retryAfterSeconds ? diagnosis.retryAfterSeconds * 1000 : UPSTREAM_429_DEFAULT_COOLDOWN_MS);
2324
+ }
1864
2325
  // Failure-ledger emission (serving role): the attempt's classifier
1865
2326
  // verdict is in hand — record the failed call regardless of whether
1866
2327
  // a later candidate rescues the turn (failover outcome is routing;
@@ -1869,9 +2330,15 @@ export class PipelineOrchestrator {
1869
2330
  recordFailureEvent({
1870
2331
  model: candidate.id,
1871
2332
  provider: candidate.provider,
2333
+ // Pair attribution: the credential this call actually ran on — the
2334
+ // selector's prefix, else the registry stamp on the error (a
2335
+ // selection that degenerated to the default credential still attributes).
2336
+ keyHashPrefix: credentialPrefix ?? diagnosis.usedKeyHashPrefix,
1872
2337
  errorClass: diagnosis.category,
1873
2338
  status: diagnosis.statusCode,
1874
- message: err?.message ?? String(err),
2339
+ // Belt-and-suspenders: UpstreamError paths already redact, but
2340
+ // non-Upstream errors can still carry echoed secrets in message.
2341
+ message: redactUpstreamBody(err?.message ?? String(err)),
1875
2342
  role: 'serving',
1876
2343
  sessionId: opts.sessionId,
1877
2344
  });
@@ -1902,7 +2369,7 @@ export class PipelineOrchestrator {
1902
2369
  };
1903
2370
  }
1904
2371
  // 2. Can we in-place retry on the SAME candidate model to preserve KV Cache?
1905
- if (diagnosis.isInPlaceRetriable && attempt < maxInplaceAttempts) {
2372
+ if (willRetryInPlace) {
1906
2373
  let sleepMs = backoffMs + Math.random() * jitterMs;
1907
2374
  if (diagnosis.networkCause === 'RATE_LIMIT_BURST' && diagnosis.retryAfterSeconds) {
1908
2375
  sleepMs = Math.max(sleepMs, diagnosis.retryAfterSeconds * 1000);
@@ -1945,8 +2412,11 @@ export class PipelineOrchestrator {
1945
2412
  inplaceRetries: totalInplaceRetries,
1946
2413
  servedCredentialPrefix: credentialPrefix,
1947
2414
  timing: firstChunkAt !== undefined && streamEndAt !== undefined
1948
- ? { firstChunkAt, streamEndAt }
2415
+ ? { firstChunkAt, streamEndAt, stalledMs }
1949
2416
  : undefined,
2417
+ // Served-attempt transport tag. `opts.relay` absent = the executor
2418
+ // was never given a relay, so the buffered call is certain.
2419
+ transport: opts.relay ? transport : 'buffered',
1950
2420
  };
1951
2421
  }
1952
2422
  }