omnicell-router 0.3.1 → 0.8.1

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 (1077) 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 +172 -26
  24. package/backend/dist/cli/clients/base.js +150 -4
  25. package/backend/dist/cli/clients/claude.d.ts +2 -1
  26. package/backend/dist/cli/clients/claude.js +4 -3
  27. package/backend/dist/cli/clients/codex.d.ts +2 -1
  28. package/backend/dist/cli/clients/codex.js +4 -3
  29. package/backend/dist/cli/clients/core-adapters.d.ts +24 -0
  30. package/backend/dist/cli/clients/core-adapters.js +43 -0
  31. package/backend/dist/cli/clients/cursor-proxy.d.ts +88 -0
  32. package/backend/dist/cli/clients/cursor-proxy.js +421 -0
  33. package/backend/dist/cli/clients/dsh.d.ts +4 -2
  34. package/backend/dist/cli/clients/dsh.js +29 -18
  35. package/backend/dist/cli/clients/grok.d.ts +53 -0
  36. package/backend/dist/cli/clients/grok.js +249 -0
  37. package/backend/dist/cli/clients/index.d.ts +35 -19
  38. package/backend/dist/cli/clients/index.js +196 -72
  39. package/backend/dist/cli/clients/kimi.d.ts +75 -0
  40. package/backend/dist/cli/clients/kimi.js +316 -0
  41. package/backend/dist/cli/clients/launcher.d.ts +56 -0
  42. package/backend/dist/cli/clients/launcher.js +41 -0
  43. package/backend/dist/cli/clients/model-meta.js +1 -1
  44. package/backend/dist/cli/clients/omp.d.ts +9 -19
  45. package/backend/dist/cli/clients/omp.js +28 -155
  46. package/backend/dist/cli/clients/openclaw.d.ts +55 -0
  47. package/backend/dist/cli/clients/openclaw.js +525 -0
  48. package/backend/dist/cli/clients/opencode-proxy.d.ts +5 -10
  49. package/backend/dist/cli/clients/opencode-proxy.js +37 -58
  50. package/backend/dist/cli/clients/opencode.d.ts +6 -19
  51. package/backend/dist/cli/clients/opencode.js +32 -159
  52. package/backend/dist/cli/clients/pi.d.ts +6 -20
  53. package/backend/dist/cli/clients/pi.js +32 -221
  54. package/backend/dist/cli/clients/plugin-adapters.d.ts +22 -0
  55. package/backend/dist/cli/clients/plugin-adapters.js +65 -0
  56. package/backend/dist/cli/clients/qoder-proxy.d.ts +84 -0
  57. package/backend/dist/cli/clients/qoder-proxy.js +497 -0
  58. package/backend/dist/cli/clients/reserved.d.ts +47 -0
  59. package/backend/dist/cli/clients/reserved.js +55 -0
  60. package/backend/dist/cli/clients/workbuddy.d.ts +31 -0
  61. package/backend/dist/cli/clients/workbuddy.js +259 -0
  62. package/backend/dist/cli/daemon.d.ts +105 -27
  63. package/backend/dist/cli/daemon.js +509 -151
  64. package/backend/dist/cli/index.d.ts +6 -1
  65. package/backend/dist/cli/index.js +289 -22
  66. package/backend/dist/cli/paths.d.ts +86 -0
  67. package/backend/dist/cli/paths.js +269 -0
  68. package/backend/dist/cli/shim.d.ts +47 -1
  69. package/backend/dist/cli/shim.js +180 -13
  70. package/backend/dist/cli/types.d.ts +114 -16
  71. package/backend/dist/cli/types.js +5 -4
  72. package/backend/dist/compression/caveman.d.ts +2 -16
  73. package/backend/dist/compression/caveman.js +25 -37
  74. package/backend/dist/compression/headroom.d.ts +4 -3
  75. package/backend/dist/compression/headroom.js +2 -2
  76. package/backend/dist/compression/index.d.ts +5 -26
  77. package/backend/dist/compression/index.js +79 -17
  78. package/backend/dist/compression/tool-output.d.ts +2 -20
  79. package/backend/dist/compression/tool-output.js +40 -47
  80. package/backend/dist/config/comments-en.d.ts +17 -0
  81. package/backend/dist/config/comments-en.js +226 -0
  82. package/backend/dist/config/comments-zh.d.ts +10 -0
  83. package/backend/dist/config/comments-zh.js +211 -0
  84. package/backend/dist/config/defaults.d.ts +245 -2
  85. package/backend/dist/config/defaults.js +259 -2
  86. package/backend/dist/config/env-archive.js +77 -38
  87. package/backend/dist/config/env.d.ts +4 -0
  88. package/backend/dist/config/env.js +16 -0
  89. package/backend/dist/config/index.d.ts +55 -12
  90. package/backend/dist/config/index.js +817 -368
  91. package/backend/dist/config/layout.d.ts +29 -0
  92. package/backend/dist/config/layout.js +86 -0
  93. package/backend/dist/config/migrations/v0-to-v1.d.ts +105 -0
  94. package/backend/dist/config/migrations/v0-to-v1.js +78 -0
  95. package/backend/dist/config/migrations/v1-to-v2.d.ts +14 -0
  96. package/backend/dist/config/migrations/v1-to-v2.js +41 -0
  97. package/backend/dist/config/migrations/v2-to-v3.d.ts +34 -0
  98. package/backend/dist/config/migrations/v2-to-v3.js +66 -0
  99. package/backend/dist/config/migrations/v3-to-v4.d.ts +34 -0
  100. package/backend/dist/config/migrations/v3-to-v4.js +61 -0
  101. package/backend/dist/config/runtime.d.ts +13 -0
  102. package/backend/dist/config/runtime.js +26 -0
  103. package/backend/dist/config/schema.d.ts +28 -0
  104. package/backend/dist/config/schema.js +98 -0
  105. package/backend/dist/config/types.d.ts +540 -121
  106. package/backend/dist/forward-proxy/access-log.d.ts +173 -0
  107. package/backend/dist/forward-proxy/access-log.js +657 -0
  108. package/backend/dist/forward-proxy/ca-trust.d.ts +42 -0
  109. package/backend/dist/forward-proxy/ca-trust.js +242 -0
  110. package/backend/dist/forward-proxy/ca.d.ts +66 -2
  111. package/backend/dist/forward-proxy/ca.js +146 -11
  112. package/backend/dist/forward-proxy/caller-context.d.ts +18 -0
  113. package/backend/dist/forward-proxy/caller-context.js +20 -0
  114. package/backend/dist/forward-proxy/egress.d.ts +112 -0
  115. package/backend/dist/forward-proxy/egress.js +318 -0
  116. package/backend/dist/forward-proxy/h2-forward.d.ts +66 -0
  117. package/backend/dist/forward-proxy/h2-forward.js +526 -0
  118. package/backend/dist/forward-proxy/index.d.ts +13 -1
  119. package/backend/dist/forward-proxy/index.js +148 -7
  120. package/backend/dist/forward-proxy/interceptor.d.ts +16 -13
  121. package/backend/dist/forward-proxy/interceptor.js +35 -57
  122. package/backend/dist/forward-proxy/ordered-relay.d.ts +29 -0
  123. package/backend/dist/forward-proxy/ordered-relay.js +46 -0
  124. package/backend/dist/forward-proxy/relay.d.ts +21 -1
  125. package/backend/dist/forward-proxy/relay.js +48 -1
  126. package/backend/dist/forward-proxy/rules.d.ts +195 -0
  127. package/backend/dist/forward-proxy/rules.js +327 -0
  128. package/backend/dist/forward-proxy/server.d.ts +102 -9
  129. package/backend/dist/forward-proxy/server.js +1504 -350
  130. package/backend/dist/forward-proxy/sni.d.ts +29 -7
  131. package/backend/dist/forward-proxy/sni.js +109 -47
  132. package/backend/dist/forward-proxy/system-proxy.d.ts +112 -0
  133. package/backend/dist/forward-proxy/system-proxy.js +480 -0
  134. package/backend/dist/forward-proxy/upstream-tls.d.ts +46 -0
  135. package/backend/dist/forward-proxy/upstream-tls.js +105 -0
  136. package/backend/dist/forward-proxy/ws-frames.d.ts +45 -0
  137. package/backend/dist/forward-proxy/ws-frames.js +153 -0
  138. package/backend/dist/harness/common/catalog-registry.d.ts +63 -0
  139. package/backend/dist/harness/common/catalog-registry.js +77 -0
  140. package/backend/dist/harness/common/github.d.ts +6 -0
  141. package/backend/dist/harness/common/github.js +13 -0
  142. package/backend/dist/harness/common/market.d.ts +590 -0
  143. package/backend/dist/harness/common/market.js +1079 -0
  144. package/backend/dist/harness/common/marketplace-rescan-scheduler.d.ts +24 -0
  145. package/backend/dist/harness/common/marketplace-rescan-scheduler.js +62 -0
  146. package/backend/dist/harness/{catalog-npm.d.ts → common/npm-catalog.d.ts} +5 -5
  147. package/backend/dist/harness/{catalog-npm.js → common/npm-catalog.js} +7 -7
  148. package/backend/dist/harness/common/npm-source.d.ts +29 -0
  149. package/backend/dist/harness/common/npm-source.js +121 -0
  150. package/backend/dist/harness/common/pypi-source.d.ts +28 -0
  151. package/backend/dist/harness/common/pypi-source.js +71 -0
  152. package/backend/dist/harness/common/source-views.d.ts +22 -0
  153. package/backend/dist/harness/common/source-views.js +25 -0
  154. package/backend/dist/harness/{stars.d.ts → common/stars.d.ts} +1 -1
  155. package/backend/dist/harness/{stars.js → common/stars.js} +2 -2
  156. package/backend/dist/harness/common/text.d.ts +11 -0
  157. package/backend/dist/harness/common/text.js +18 -0
  158. package/backend/dist/harness/config-file.d.ts +14 -1
  159. package/backend/dist/harness/config-file.js +38 -0
  160. package/backend/dist/harness/db-probe.d.ts +29 -0
  161. package/backend/dist/harness/db-probe.js +270 -0
  162. package/backend/dist/harness/detail.d.ts +10 -1
  163. package/backend/dist/harness/detail.js +144 -7
  164. package/backend/dist/harness/host/adapters/amp.d.ts +19 -0
  165. package/backend/dist/harness/host/adapters/amp.js +21 -0
  166. package/backend/dist/harness/host/adapters/antigravity.d.ts +18 -0
  167. package/backend/dist/harness/host/adapters/antigravity.js +21 -0
  168. package/backend/dist/harness/host/adapters/base.d.ts +225 -0
  169. package/backend/dist/harness/host/adapters/base.js +521 -0
  170. package/backend/dist/harness/host/adapters/claude.d.ts +54 -0
  171. package/backend/dist/harness/host/adapters/claude.js +145 -0
  172. package/backend/dist/harness/host/adapters/cline.d.ts +18 -0
  173. package/backend/dist/harness/host/adapters/cline.js +20 -0
  174. package/backend/dist/harness/host/adapters/codex.d.ts +54 -0
  175. package/backend/dist/harness/host/adapters/codex.js +133 -0
  176. package/backend/dist/harness/host/adapters/cursor.d.ts +18 -0
  177. package/backend/dist/harness/host/adapters/cursor.js +24 -0
  178. package/backend/dist/harness/host/adapters/declarative.d.ts +22 -0
  179. package/backend/dist/harness/host/adapters/declarative.js +38 -0
  180. package/backend/dist/harness/host/adapters/dsh.d.ts +76 -0
  181. package/backend/dist/harness/host/adapters/dsh.js +253 -0
  182. package/backend/dist/harness/host/adapters/factory.d.ts +36 -0
  183. package/backend/dist/harness/host/adapters/factory.js +34 -0
  184. package/backend/dist/harness/host/adapters/gemini-cli.d.ts +17 -0
  185. package/backend/dist/harness/host/adapters/gemini-cli.js +19 -0
  186. package/backend/dist/harness/host/adapters/grok.d.ts +66 -0
  187. package/backend/dist/harness/host/adapters/grok.js +136 -0
  188. package/backend/dist/harness/{adapters → host/adapters}/index.d.ts +9 -4
  189. package/backend/dist/harness/{adapters → host/adapters}/index.js +31 -10
  190. package/backend/dist/harness/host/adapters/kimi.d.ts +30 -0
  191. package/backend/dist/harness/host/adapters/kimi.js +59 -0
  192. package/backend/dist/harness/host/adapters/omp.d.ts +55 -0
  193. package/backend/dist/harness/host/adapters/omp.js +90 -0
  194. package/backend/dist/harness/host/adapters/openclaw.d.ts +54 -0
  195. package/backend/dist/harness/host/adapters/openclaw.js +141 -0
  196. package/backend/dist/harness/host/adapters/opencode.d.ts +24 -0
  197. package/backend/dist/harness/host/adapters/opencode.js +48 -0
  198. package/backend/dist/harness/host/adapters/pi.d.ts +27 -0
  199. package/backend/dist/harness/host/adapters/pi.js +58 -0
  200. package/backend/dist/harness/host/adapters/types.d.ts +395 -0
  201. package/backend/dist/harness/host/adapters/types.js +17 -0
  202. package/backend/dist/harness/host/adapters/universal.d.ts +14 -0
  203. package/backend/dist/harness/host/adapters/universal.js +18 -0
  204. package/backend/dist/harness/host/adapters/windsurf.d.ts +20 -0
  205. package/backend/dist/harness/host/adapters/windsurf.js +22 -0
  206. package/backend/dist/harness/host/adapters/zed.d.ts +12 -0
  207. package/backend/dist/harness/host/adapters/zed.js +14 -0
  208. package/backend/dist/harness/host/claude-mcp-runtime.d.ts +6 -0
  209. package/backend/dist/harness/host/claude-mcp-runtime.js +56 -0
  210. package/backend/dist/harness/{discover.d.ts → host/discover.d.ts} +54 -18
  211. package/backend/dist/harness/{discover.js → host/discover.js} +314 -53
  212. package/backend/dist/harness/{drift.d.ts → host/drift.d.ts} +1 -1
  213. package/backend/dist/harness/{drift.js → host/drift.js} +1 -1
  214. package/backend/dist/harness/host/grok-mcp-runtime.d.ts +6 -0
  215. package/backend/dist/harness/host/grok-mcp-runtime.js +56 -0
  216. package/backend/dist/harness/{hosts.d.ts → host/hosts.d.ts} +3 -3
  217. package/backend/dist/harness/{hosts.js → host/hosts.js} +7 -3
  218. package/backend/dist/harness/host/index.d.ts +10 -0
  219. package/backend/dist/harness/host/index.js +12 -0
  220. package/backend/dist/harness/host/install-log.d.ts +22 -0
  221. package/backend/dist/harness/host/install-log.js +106 -0
  222. package/backend/dist/harness/{install.d.ts → host/install.d.ts} +32 -13
  223. package/backend/dist/harness/{install.js → host/install.js} +133 -50
  224. package/backend/dist/harness/host/inventory.d.ts +30 -0
  225. package/backend/dist/harness/{inventory.js → host/inventory.js} +107 -16
  226. package/backend/dist/harness/host/kimi-mcp-runtime.d.ts +6 -0
  227. package/backend/dist/harness/host/kimi-mcp-runtime.js +84 -0
  228. package/backend/dist/harness/{ledger.d.ts → host/ledger.d.ts} +1 -1
  229. package/backend/dist/harness/{ledger.js → host/ledger.js} +3 -3
  230. package/backend/dist/harness/{maintenance.d.ts → host/maintenance.d.ts} +23 -6
  231. package/backend/dist/harness/{maintenance.js → host/maintenance.js} +355 -63
  232. package/backend/dist/harness/{manifest.d.ts → host/manifest.d.ts} +11 -2
  233. package/backend/dist/harness/{manifest.js → host/manifest.js} +76 -15
  234. package/backend/dist/harness/host/marketplace-sync.d.ts +64 -0
  235. package/backend/dist/harness/host/marketplace-sync.js +231 -0
  236. package/backend/dist/harness/host/mcp-cli.d.ts +44 -0
  237. package/backend/dist/harness/host/mcp-cli.js +545 -0
  238. package/backend/dist/harness/host/mcp-edit.d.ts +89 -0
  239. package/backend/dist/harness/host/mcp-edit.js +342 -0
  240. package/backend/dist/harness/host/mcp-entry.d.ts +100 -0
  241. package/backend/dist/harness/host/mcp-entry.js +435 -0
  242. package/backend/dist/harness/host/mcp-inspector.d.ts +125 -0
  243. package/backend/dist/harness/host/mcp-inspector.js +634 -0
  244. package/backend/dist/harness/host/mcp-registry.d.ts +66 -0
  245. package/backend/dist/harness/host/mcp-registry.js +331 -0
  246. package/backend/dist/harness/host/mcp-runtime.d.ts +19 -0
  247. package/backend/dist/harness/host/mcp-runtime.js +22 -0
  248. package/backend/dist/harness/host/opencode-mcp-runtime.d.ts +7 -0
  249. package/backend/dist/harness/host/opencode-mcp-runtime.js +73 -0
  250. package/backend/dist/harness/{probe.d.ts → host/probe.d.ts} +4 -4
  251. package/backend/dist/harness/{probe.js → host/probe.js} +8 -8
  252. package/backend/dist/harness/{registry.d.ts → host/registry.d.ts} +1 -1
  253. package/backend/dist/harness/host/registry.js +28 -0
  254. package/backend/dist/harness/host/request.d.ts +56 -0
  255. package/backend/dist/harness/host/request.js +1 -0
  256. package/backend/dist/harness/{sources → host/resolvers}/clawhub.d.ts +1 -1
  257. package/backend/dist/harness/{sources → host/resolvers}/clawhub.js +1 -1
  258. package/backend/dist/harness/host/resolvers/git-marketplace.d.ts +16 -0
  259. package/backend/dist/harness/host/resolvers/git-marketplace.js +53 -0
  260. package/backend/dist/harness/{sources → host/resolvers}/github.d.ts +1 -1
  261. package/backend/dist/harness/{sources → host/resolvers}/github.js +2 -2
  262. package/backend/dist/harness/host/resolvers/npm.d.ts +2 -0
  263. package/backend/dist/harness/{sources → host/resolvers}/npm.js +16 -10
  264. package/backend/dist/harness/host/resolvers/pypi.d.ts +2 -0
  265. package/backend/dist/harness/host/resolvers/pypi.js +100 -0
  266. package/backend/dist/harness/host/scopes.d.ts +11 -0
  267. package/backend/dist/harness/host/scopes.js +12 -0
  268. package/backend/dist/harness/host/timeouts.d.ts +8 -0
  269. package/backend/dist/harness/host/timeouts.js +8 -0
  270. package/backend/dist/harness/host/writers/kimi-web.d.ts +70 -0
  271. package/backend/dist/harness/host/writers/kimi-web.js +222 -0
  272. package/backend/dist/harness/host/writers/mcp.d.ts +119 -0
  273. package/backend/dist/harness/host/writers/mcp.js +359 -0
  274. package/backend/dist/harness/host/writers/plugin.d.ts +176 -0
  275. package/backend/dist/harness/host/writers/plugin.js +528 -0
  276. package/backend/dist/harness/{writers → host/writers}/skill.d.ts +3 -3
  277. package/backend/dist/harness/{writers → host/writers}/skill.js +6 -3
  278. package/backend/dist/harness/lang.d.ts +14 -0
  279. package/backend/dist/harness/lang.js +33 -0
  280. package/backend/dist/harness/net.d.ts +33 -0
  281. package/backend/dist/harness/net.js +63 -0
  282. package/backend/dist/harness/plugin/adapters/antigravity.d.ts +11 -0
  283. package/backend/dist/harness/plugin/adapters/antigravity.js +14 -0
  284. package/backend/dist/harness/plugin/adapters/base.d.ts +107 -0
  285. package/backend/dist/harness/plugin/adapters/base.js +454 -0
  286. package/backend/dist/harness/plugin/adapters/claude.d.ts +28 -0
  287. package/backend/dist/harness/plugin/adapters/claude.js +63 -0
  288. package/backend/dist/harness/plugin/adapters/codex.d.ts +13 -0
  289. package/backend/dist/harness/plugin/adapters/codex.js +16 -0
  290. package/backend/dist/harness/plugin/adapters/cursor.d.ts +13 -0
  291. package/backend/dist/harness/plugin/adapters/cursor.js +16 -0
  292. package/backend/dist/harness/plugin/adapters/dsh-plugin-net.d.ts +20 -0
  293. package/backend/dist/harness/plugin/adapters/dsh-plugin-net.js +371 -0
  294. package/backend/dist/harness/plugin/adapters/dsh.d.ts +22 -0
  295. package/backend/dist/harness/plugin/adapters/dsh.js +50 -0
  296. package/backend/dist/harness/plugin/adapters/factory.d.ts +11 -0
  297. package/backend/dist/harness/plugin/adapters/factory.js +19 -0
  298. package/backend/dist/harness/plugin/adapters/gemini.d.ts +12 -0
  299. package/backend/dist/harness/plugin/adapters/gemini.js +22 -0
  300. package/backend/dist/harness/plugin/adapters/grok.d.ts +15 -0
  301. package/backend/dist/harness/plugin/adapters/grok.js +23 -0
  302. package/backend/dist/harness/plugin/adapters/index.d.ts +41 -0
  303. package/backend/dist/harness/plugin/adapters/index.js +143 -0
  304. package/backend/dist/harness/plugin/adapters/kimi.d.ts +6 -0
  305. package/backend/dist/harness/plugin/adapters/kimi.js +35 -0
  306. package/backend/dist/harness/plugin/adapters/omp.d.ts +19 -0
  307. package/backend/dist/harness/plugin/adapters/omp.js +26 -0
  308. package/backend/dist/harness/plugin/adapters/openclaw.d.ts +20 -0
  309. package/backend/dist/harness/plugin/adapters/openclaw.js +36 -0
  310. package/backend/dist/harness/plugin/adapters/pi-dev.d.ts +124 -0
  311. package/backend/dist/harness/plugin/adapters/pi-dev.js +420 -0
  312. package/backend/dist/harness/plugin/adapters/pi-github.d.ts +18 -0
  313. package/backend/dist/harness/plugin/adapters/pi-github.js +27 -0
  314. package/backend/dist/harness/plugin/adapters/universal.d.ts +11 -0
  315. package/backend/dist/harness/plugin/adapters/universal.js +18 -0
  316. package/backend/dist/harness/plugin/builtin.d.ts +13 -0
  317. package/backend/dist/harness/plugin/builtin.js +34 -0
  318. package/backend/dist/harness/plugin/catalog.d.ts +30 -0
  319. package/backend/dist/harness/plugin/catalog.js +200 -0
  320. package/backend/dist/harness/plugin/index.d.ts +9 -0
  321. package/backend/dist/harness/plugin/index.js +9 -0
  322. package/backend/dist/harness/plugin/types.d.ts +164 -0
  323. package/backend/dist/harness/plugin/types.js +1 -0
  324. package/backend/dist/harness/{clawhub.d.ts → skill/clawhub.d.ts} +28 -5
  325. package/backend/dist/harness/{clawhub.js → skill/clawhub.js} +170 -5
  326. package/backend/dist/harness/skill/skills-sh.d.ts +47 -0
  327. package/backend/dist/harness/skill/skills-sh.js +270 -0
  328. package/backend/dist/harness/skill/sources.d.ts +41 -0
  329. package/backend/dist/harness/skill/sources.js +131 -0
  330. package/backend/dist/harness/spi.d.ts +11 -7
  331. package/backend/dist/harness/tcp-reach.d.ts +30 -0
  332. package/backend/dist/harness/tcp-reach.js +61 -0
  333. package/backend/dist/harness/translation.d.ts +31 -13
  334. package/backend/dist/harness/translation.js +265 -80
  335. package/backend/dist/harness/types.d.ts +62 -17
  336. package/backend/dist/harness/types.js +1 -1
  337. package/backend/dist/index.js +183 -16
  338. package/backend/dist/ir/adapters/anthropic-messages-stream.d.ts +18 -0
  339. package/backend/dist/ir/adapters/anthropic-messages-stream.js +266 -0
  340. package/backend/dist/ir/adapters/anthropic-messages.d.ts +30 -0
  341. package/backend/dist/ir/adapters/anthropic-messages.js +870 -0
  342. package/backend/dist/ir/adapters/anthropic-stream.d.ts +18 -0
  343. package/backend/dist/ir/adapters/anthropic-stream.js +247 -0
  344. package/backend/dist/ir/adapters/anthropic.d.ts +29 -0
  345. package/backend/dist/ir/adapters/anthropic.js +788 -0
  346. package/backend/dist/ir/adapters/chat.d.ts +15 -0
  347. package/backend/dist/ir/adapters/chat.js +602 -0
  348. package/backend/dist/ir/adapters/google-gemini-stream.d.ts +22 -0
  349. package/backend/dist/ir/adapters/google-gemini-stream.js +246 -0
  350. package/backend/dist/ir/adapters/google-gemini.d.ts +9 -0
  351. package/backend/dist/ir/adapters/google-gemini.js +450 -0
  352. package/backend/dist/ir/adapters/google-stream.d.ts +22 -0
  353. package/backend/dist/ir/adapters/google-stream.js +242 -0
  354. package/backend/dist/ir/adapters/google.d.ts +9 -0
  355. package/backend/dist/ir/adapters/google.js +317 -0
  356. package/backend/dist/ir/adapters/openai-chat-stream.d.ts +41 -0
  357. package/backend/dist/ir/adapters/openai-chat-stream.js +369 -0
  358. package/backend/dist/ir/adapters/openai-chat.d.ts +17 -0
  359. package/backend/dist/ir/adapters/openai-chat.js +670 -0
  360. package/backend/dist/ir/adapters/openai-responses-output.d.ts +50 -0
  361. package/backend/dist/ir/adapters/openai-responses-output.js +356 -0
  362. package/backend/dist/ir/adapters/openai-responses-stream.d.ts +12 -0
  363. package/backend/dist/ir/adapters/openai-responses-stream.js +193 -0
  364. package/backend/dist/ir/adapters/openai-responses.d.ts +29 -0
  365. package/backend/dist/ir/adapters/openai-responses.js +695 -0
  366. package/backend/dist/ir/adapters/responses-output.d.ts +50 -0
  367. package/backend/dist/ir/adapters/responses-output.js +348 -0
  368. package/backend/dist/ir/adapters/responses-stream.d.ts +12 -0
  369. package/backend/dist/ir/adapters/responses-stream.js +178 -0
  370. package/backend/dist/ir/adapters/responses.d.ts +14 -0
  371. package/backend/dist/ir/adapters/responses.js +646 -0
  372. package/backend/dist/ir/capabilities.d.ts +41 -0
  373. package/backend/dist/ir/capabilities.js +147 -0
  374. package/backend/dist/ir/errors.d.ts +23 -0
  375. package/backend/dist/ir/errors.js +31 -0
  376. package/backend/dist/ir/index.d.ts +5 -0
  377. package/backend/dist/ir/index.js +5 -0
  378. package/backend/dist/ir/media.d.ts +2 -0
  379. package/backend/dist/ir/media.js +2 -0
  380. package/backend/dist/ir/stream.d.ts +17 -0
  381. package/backend/dist/ir/stream.js +250 -0
  382. package/backend/dist/ir/types.d.ts +524 -0
  383. package/backend/dist/ir/types.js +19 -0
  384. package/backend/dist/ir/validate.d.ts +18 -0
  385. package/backend/dist/ir/validate.js +272 -0
  386. package/backend/dist/metrics/request-cost.d.ts +11 -10
  387. package/backend/dist/metrics/request-cost.js +18 -27
  388. package/backend/dist/observability/failure-events.d.ts +20 -4
  389. package/backend/dist/observability/failure-events.js +9 -1
  390. package/backend/dist/observability/http-exchange.d.ts +75 -27
  391. package/backend/dist/observability/http-exchange.js +136 -39
  392. package/backend/dist/observability/request-identity.d.ts +40 -0
  393. package/backend/dist/observability/request-identity.js +102 -0
  394. package/backend/dist/observability/traffic-live-hidden.d.ts +24 -0
  395. package/backend/dist/observability/traffic-live-hidden.js +82 -0
  396. package/backend/dist/observability/upstream-body-redaction.d.ts +23 -0
  397. package/backend/dist/observability/upstream-body-redaction.js +72 -0
  398. package/backend/dist/observability/upstream-events.d.ts +90 -62
  399. package/backend/dist/observability/upstream-events.js +145 -64
  400. package/backend/dist/opencode/agents.d.ts +3 -2
  401. package/backend/dist/opencode/catalog/auto-pull.d.ts +35 -1
  402. package/backend/dist/opencode/catalog/auto-pull.js +169 -33
  403. package/backend/dist/opencode/catalog/ocr-store.d.ts +6 -6
  404. package/backend/dist/opencode/catalog/ocr-store.js +2 -2
  405. package/backend/dist/opencode/catalog/overrides-store.d.ts +6 -5
  406. package/backend/dist/opencode/catalog/overrides-store.js +28 -3
  407. package/backend/dist/opencode/catalog/repository.d.ts +4 -0
  408. package/backend/dist/opencode/catalog/repository.js +19 -0
  409. package/backend/dist/opencode/catalog/sources/models-dev.d.ts +4 -0
  410. package/backend/dist/opencode/catalog/sources/models-dev.js +15 -4
  411. package/backend/dist/opencode/catalog/types.d.ts +19 -7
  412. package/backend/dist/opencode/connector.d.ts +2 -2
  413. package/backend/dist/opencode/connector.js +2 -2
  414. package/backend/dist/opencode/credentials/def-materialize.d.ts +0 -5
  415. package/backend/dist/opencode/credentials/def-materialize.js +149 -11
  416. package/backend/dist/opencode/credentials/ocr-store.d.ts +18 -0
  417. package/backend/dist/opencode/credentials/ocr-store.js +88 -7
  418. package/backend/dist/opencode/credentials/opencode-v2-store.d.ts +24 -13
  419. package/backend/dist/opencode/credentials/opencode-v2-store.js +70 -29
  420. package/backend/dist/opencode/credentials/paths.d.ts +8 -0
  421. package/backend/dist/opencode/credentials/paths.js +10 -0
  422. package/backend/dist/opencode/credentials/sync.d.ts +1 -1
  423. package/backend/dist/opencode/credentials/sync.js +4 -4
  424. package/backend/dist/opencode/credentials/types.d.ts +38 -2
  425. package/backend/dist/opencode/probe.d.ts +33 -6
  426. package/backend/dist/opencode/probe.js +96 -19
  427. package/backend/dist/opencode/provider-defs.js +59 -2
  428. package/backend/dist/opencode/provider-package.d.ts +31 -0
  429. package/backend/dist/opencode/provider-package.js +70 -0
  430. package/backend/dist/opencode/user-config.d.ts +16 -17
  431. package/backend/dist/opencode/user-config.js +42 -66
  432. package/backend/dist/pipeline/credential-selection.d.ts +13 -0
  433. package/backend/dist/pipeline/credential-selection.js +29 -1
  434. package/backend/dist/pipeline/directives.d.ts +18 -22
  435. package/backend/dist/pipeline/directives.js +129 -71
  436. package/backend/dist/pipeline/orchestrator.d.ts +70 -34
  437. package/backend/dist/pipeline/orchestrator.js +901 -405
  438. package/backend/dist/pipeline/prompt-optimizer.d.ts +6 -13
  439. package/backend/dist/pipeline/prompt-optimizer.js +9 -52
  440. package/backend/dist/pipeline/streaming-posture.d.ts +29 -0
  441. package/backend/dist/pipeline/streaming-posture.js +27 -0
  442. package/backend/dist/pipeline/tool-pairing.d.ts +10 -0
  443. package/backend/dist/pipeline/tool-pairing.js +90 -0
  444. package/backend/dist/pipeline/unresolved-model.d.ts +33 -0
  445. package/backend/dist/pipeline/unresolved-model.js +43 -0
  446. package/backend/dist/plugins/builtin/model-gateway.d.ts +30 -0
  447. package/backend/dist/plugins/builtin/model-gateway.js +98 -0
  448. package/backend/dist/plugins/catalog-def.d.ts +143 -0
  449. package/backend/dist/plugins/catalog-def.js +177 -0
  450. package/backend/dist/plugins/config.d.ts +41 -0
  451. package/backend/dist/plugins/config.js +113 -0
  452. package/backend/dist/plugins/gateways.d.ts +157 -0
  453. package/backend/dist/plugins/gateways.js +288 -0
  454. package/backend/dist/plugins/host.d.ts +240 -0
  455. package/backend/dist/plugins/host.js +1726 -0
  456. package/backend/dist/plugins/manifest.d.ts +152 -0
  457. package/backend/dist/plugins/manifest.js +713 -0
  458. package/backend/dist/plugins/pack.d.ts +32 -0
  459. package/backend/dist/plugins/pack.js +248 -0
  460. package/backend/dist/plugins/seed.d.ts +53 -0
  461. package/backend/dist/plugins/seed.js +136 -0
  462. package/backend/dist/plugins/types.d.ts +887 -0
  463. package/backend/dist/plugins/types.js +1 -0
  464. package/backend/dist/projects/store.d.ts +56 -0
  465. package/backend/dist/projects/store.js +194 -0
  466. package/backend/dist/projects/types.d.ts +12 -0
  467. package/backend/dist/projects/types.js +1 -0
  468. package/backend/dist/protocols/chat-compat.d.ts +2 -0
  469. package/backend/dist/protocols/chat-compat.js +137 -0
  470. package/backend/dist/protocols/systemone/convert.d.ts +6 -4
  471. package/backend/dist/protocols/systemone/convert.js +78 -27
  472. package/backend/dist/protocols/systemone/decide.js +144 -57
  473. package/backend/dist/protocols/systemone/native.d.ts +1 -1
  474. package/backend/dist/protocols/systemone/native.js +6 -6
  475. package/backend/dist/providers/anthropic-messages.d.ts +12 -0
  476. package/backend/dist/providers/anthropic-messages.js +53 -0
  477. package/backend/dist/providers/anthropic.d.ts +7 -8
  478. package/backend/dist/providers/anthropic.js +36 -324
  479. package/backend/dist/providers/base.d.ts +18 -45
  480. package/backend/dist/providers/boot-direct.d.ts +20 -2
  481. package/backend/dist/providers/boot-direct.js +140 -61
  482. package/backend/dist/providers/compat/tool-markup-leak.d.ts +41 -0
  483. package/backend/dist/providers/compat/tool-markup-leak.js +57 -0
  484. package/backend/dist/providers/compat/tool-markup-recovery.d.ts +27 -0
  485. package/backend/dist/providers/compat/tool-markup-recovery.js +831 -0
  486. package/backend/dist/providers/dispatch.d.ts +5 -22
  487. package/backend/dist/providers/dispatch.js +49 -55
  488. package/backend/dist/providers/executors/anthropic-messages.d.ts +13 -0
  489. package/backend/dist/providers/executors/anthropic-messages.js +59 -0
  490. package/backend/dist/providers/executors/dispatch.d.ts +28 -0
  491. package/backend/dist/providers/executors/dispatch.js +101 -0
  492. package/backend/dist/providers/executors/google-gemini.d.ts +13 -0
  493. package/backend/dist/providers/executors/google-gemini.js +56 -0
  494. package/backend/dist/providers/executors/http-json.d.ts +19 -0
  495. package/backend/dist/providers/executors/http-json.js +125 -0
  496. package/backend/dist/providers/executors/http-stream.d.ts +53 -0
  497. package/backend/dist/providers/executors/http-stream.js +485 -0
  498. package/backend/dist/providers/executors/openai-chat.d.ts +14 -0
  499. package/backend/dist/providers/executors/openai-chat.js +92 -0
  500. package/backend/dist/providers/executors/openai-responses.d.ts +13 -0
  501. package/backend/dist/providers/executors/openai-responses.js +74 -0
  502. package/backend/dist/providers/executors/plugin-adapter.d.ts +9 -0
  503. package/backend/dist/providers/executors/plugin-adapter.js +31 -0
  504. package/backend/dist/providers/google-gemini.d.ts +12 -0
  505. package/backend/dist/providers/google-gemini.js +50 -0
  506. package/backend/dist/providers/google.d.ts +7 -8
  507. package/backend/dist/providers/google.js +35 -308
  508. package/backend/dist/providers/http-json.d.ts +19 -0
  509. package/backend/dist/providers/http-json.js +104 -0
  510. package/backend/dist/providers/http-stream.d.ts +52 -0
  511. package/backend/dist/providers/http-stream.js +423 -0
  512. package/backend/dist/providers/member-match.d.ts +4 -5
  513. package/backend/dist/providers/member-match.js +4 -5
  514. package/backend/dist/providers/openai-chat.d.ts +13 -0
  515. package/backend/dist/providers/openai-chat.js +99 -0
  516. package/backend/dist/providers/openai-compatible.d.ts +7 -4
  517. package/backend/dist/providers/openai-compatible.js +71 -368
  518. package/backend/dist/providers/openai-responses.d.ts +12 -0
  519. package/backend/dist/providers/openai-responses.js +68 -0
  520. package/backend/dist/providers/opencode-proxy.d.ts +5 -5
  521. package/backend/dist/providers/opencode-proxy.js +49 -125
  522. package/backend/dist/providers/plugin-adapter.d.ts +9 -0
  523. package/backend/dist/providers/plugin-adapter.js +31 -0
  524. package/backend/dist/providers/plugin-wires.d.ts +34 -0
  525. package/backend/dist/providers/plugin-wires.js +82 -0
  526. package/backend/dist/providers/pool-refresh.d.ts +14 -0
  527. package/backend/dist/providers/pool-refresh.js +13 -0
  528. package/backend/dist/providers/protocol.d.ts +4 -0
  529. package/backend/dist/providers/protocol.js +61 -0
  530. package/backend/dist/providers/provider-takedown.d.ts +59 -0
  531. package/backend/dist/providers/provider-takedown.js +135 -0
  532. package/backend/dist/providers/registry.d.ts +85 -44
  533. package/backend/dist/providers/registry.js +299 -162
  534. package/backend/dist/providers/responses.d.ts +7 -26
  535. package/backend/dist/providers/responses.js +45 -250
  536. package/backend/dist/providers/tool-markup-leak.d.ts +41 -0
  537. package/backend/dist/providers/tool-markup-leak.js +57 -0
  538. package/backend/dist/providers/tool-markup-recovery.d.ts +27 -0
  539. package/backend/dist/providers/tool-markup-recovery.js +786 -0
  540. package/backend/dist/providers/virtual-meta.d.ts +21 -2
  541. package/backend/dist/providers/virtual-meta.js +49 -9
  542. package/backend/dist/providers/vocabulary.d.ts +24 -6
  543. package/backend/dist/providers/vocabulary.js +75 -33
  544. package/backend/dist/providers/wire.d.ts +12 -17
  545. package/backend/dist/providers/wire.js +43 -91
  546. package/backend/dist/proxy/asset-download.d.ts +54 -0
  547. package/backend/dist/proxy/asset-download.js +420 -0
  548. package/backend/dist/proxy/manual-node-spec.d.ts +92 -0
  549. package/backend/dist/proxy/manual-node-spec.js +408 -0
  550. package/backend/dist/proxy/mihomo-binary.d.ts +54 -0
  551. package/backend/dist/proxy/mihomo-binary.js +278 -0
  552. package/backend/dist/proxy/mihomo-client.d.ts +94 -0
  553. package/backend/dist/proxy/mihomo-client.js +308 -0
  554. package/backend/dist/proxy/mihomo-config.d.ts +40 -0
  555. package/backend/dist/proxy/mihomo-config.js +161 -0
  556. package/backend/dist/proxy/mihomo-geo.d.ts +87 -0
  557. package/backend/dist/proxy/mihomo-geo.js +213 -0
  558. package/backend/dist/proxy/mihomo-logs.d.ts +27 -0
  559. package/backend/dist/proxy/mihomo-logs.js +70 -0
  560. package/backend/dist/proxy/mihomo-pac.d.ts +37 -0
  561. package/backend/dist/proxy/mihomo-pac.js +75 -0
  562. package/backend/dist/proxy/mihomo-rules-import.d.ts +43 -0
  563. package/backend/dist/proxy/mihomo-rules-import.js +193 -0
  564. package/backend/dist/proxy/mihomo-sidecar.d.ts +81 -0
  565. package/backend/dist/proxy/mihomo-sidecar.js +637 -0
  566. package/backend/dist/quota/adapters/minimax.js +36 -13
  567. package/backend/dist/quota/cli-login.d.ts +8 -0
  568. package/backend/dist/quota/cli-login.js +18 -0
  569. package/backend/dist/quota/declarations.js +10 -0
  570. package/backend/dist/quota/dsl.js +18 -5
  571. package/backend/dist/quota/engine.d.ts +31 -3
  572. package/backend/dist/quota/engine.js +189 -30
  573. package/backend/dist/quota/prober.d.ts +13 -4
  574. package/backend/dist/quota/prober.js +20 -12
  575. package/backend/dist/quota/types.d.ts +87 -8
  576. package/backend/dist/quota/verdict.d.ts +35 -0
  577. package/backend/dist/quota/verdict.js +135 -0
  578. package/backend/dist/ratelimit/admission.d.ts +131 -0
  579. package/backend/dist/ratelimit/admission.js +233 -0
  580. package/backend/dist/ratelimit/rate-limiter.d.ts +119 -6
  581. package/backend/dist/ratelimit/rate-limiter.js +364 -20
  582. package/backend/dist/ratelimit/window-store.d.ts +34 -0
  583. package/backend/dist/ratelimit/window-store.js +70 -0
  584. package/backend/dist/resilience/breaker-state.js +8 -1
  585. package/backend/dist/resilience/circuit-breaker-manager.d.ts +229 -132
  586. package/backend/dist/resilience/circuit-breaker-manager.js +566 -297
  587. package/backend/dist/resilience/circuit-breaker.d.ts +11 -0
  588. package/backend/dist/resilience/circuit-breaker.js +39 -7
  589. package/backend/dist/resilience/error-classifier.d.ts +31 -3
  590. package/backend/dist/resilience/error-classifier.js +159 -31
  591. package/backend/dist/resilience/health-prober.d.ts +21 -4
  592. package/backend/dist/resilience/health-prober.js +100 -18
  593. package/backend/dist/resilience/types.d.ts +54 -7
  594. package/backend/dist/resilience/types.js +1 -1
  595. package/backend/dist/router/index.d.ts +6 -29
  596. package/backend/dist/router/index.js +15 -61
  597. package/backend/dist/router/layer2-decision.d.ts +3 -3
  598. package/backend/dist/router/layer2-decision.js +26 -26
  599. package/backend/dist/router/request-traits.d.ts +4 -11
  600. package/backend/dist/router/request-traits.js +5 -13
  601. package/backend/dist/routes/console.js +2145 -259
  602. package/backend/dist/routes/environments.d.ts +3 -2
  603. package/backend/dist/routes/environments.js +8 -4
  604. package/backend/dist/routes/harness.d.ts +3 -1
  605. package/backend/dist/routes/harness.js +1162 -356
  606. package/backend/dist/routes/mihomo.d.ts +7 -0
  607. package/backend/dist/routes/mihomo.js +1187 -0
  608. package/backend/dist/routes/projects.d.ts +2 -0
  609. package/backend/dist/routes/projects.js +90 -0
  610. package/backend/dist/routes/responses.d.ts +107 -9
  611. package/backend/dist/routes/responses.js +378 -35
  612. package/backend/dist/routes/translation.d.ts +9 -0
  613. package/backend/dist/routes/translation.js +155 -0
  614. package/backend/dist/server.js +379 -73
  615. package/backend/dist/session/resp-store.d.ts +18 -49
  616. package/backend/dist/session/resp-store.js +114 -122
  617. package/backend/dist/session/session-manager.d.ts +228 -81
  618. package/backend/dist/session/session-manager.js +449 -190
  619. package/backend/dist/session/session-row.d.ts +81 -2
  620. package/backend/dist/session/session-row.js +69 -1
  621. package/backend/dist/surfaces/anthropic.d.ts +1 -15
  622. package/backend/dist/surfaces/anthropic.js +63 -44
  623. package/backend/dist/surfaces/chat-pipeline.d.ts +10 -6
  624. package/backend/dist/surfaces/chat-pipeline.js +119 -42
  625. package/backend/dist/surfaces/chat.d.ts +1 -9
  626. package/backend/dist/surfaces/chat.js +67 -29
  627. package/backend/dist/surfaces/decision-pipeline.js +32 -27
  628. package/backend/dist/surfaces/direct-forward.d.ts +3 -0
  629. package/backend/dist/surfaces/direct-forward.js +206 -0
  630. package/backend/dist/surfaces/gateway-chat.d.ts +53 -0
  631. package/backend/dist/surfaces/gateway-chat.js +204 -0
  632. package/backend/dist/surfaces/ocr-headers.d.ts +25 -4
  633. package/backend/dist/surfaces/ocr-headers.js +52 -6
  634. package/backend/dist/surfaces/rate-limit-response.d.ts +17 -0
  635. package/backend/dist/surfaces/rate-limit-response.js +57 -0
  636. package/backend/dist/surfaces/responses.d.ts +9 -1
  637. package/backend/dist/surfaces/responses.js +141 -141
  638. package/backend/dist/surfaces/systemone-probe.js +1 -1
  639. package/backend/dist/surfaces/systemone.d.ts +1 -1
  640. package/backend/dist/surfaces/systemone.js +1 -1
  641. package/backend/dist/surfaces/table.d.ts +15 -0
  642. package/backend/dist/surfaces/table.js +15 -0
  643. package/backend/dist/surfaces/transport-backpressure.d.ts +46 -0
  644. package/backend/dist/surfaces/transport-backpressure.js +122 -0
  645. package/backend/dist/surfaces/transport-fastify.js +92 -21
  646. package/backend/dist/surfaces/transport-node-http.js +92 -18
  647. package/backend/dist/surfaces/types.d.ts +85 -12
  648. package/backend/dist/trace/persist.d.ts +5 -0
  649. package/backend/dist/trace/persist.js +185 -24
  650. package/backend/dist/trace/tracker.d.ts +185 -17
  651. package/backend/dist/trace/tracker.js +106 -31
  652. package/backend/dist/translation/index.d.ts +151 -0
  653. package/backend/dist/translation/index.js +735 -0
  654. package/backend/dist/types/openai.d.ts +82 -1
  655. package/backend/dist/types/router.d.ts +104 -17
  656. package/backend/dist/types/router.js +68 -7
  657. package/backend/dist/update/check.d.ts +43 -0
  658. package/backend/dist/update/check.js +126 -0
  659. package/backend/dist/utils/chat-sse.d.ts +2 -22
  660. package/backend/dist/utils/chat-sse.js +1 -69
  661. package/backend/dist/utils/chat-stream.d.ts +23 -9
  662. package/backend/dist/utils/chat-stream.js +46 -9
  663. package/backend/dist/utils/client-envelope.d.ts +108 -0
  664. package/backend/dist/utils/client-envelope.js +305 -0
  665. package/backend/dist/utils/event-ring.d.ts +12 -1
  666. package/backend/dist/utils/event-ring.js +17 -5
  667. package/backend/dist/utils/harness-profiles.d.ts +51 -0
  668. package/backend/dist/utils/harness-profiles.js +70 -0
  669. package/backend/dist/utils/percentile.d.ts +16 -0
  670. package/backend/dist/utils/percentile.js +29 -0
  671. package/backend/dist/utils/popularity.d.ts +4 -0
  672. package/backend/dist/utils/popularity.js +58 -0
  673. package/backend/dist/utils/probe-interval.d.ts +12 -0
  674. package/backend/dist/utils/probe-interval.js +16 -0
  675. package/backend/dist/utils/proxy-node.d.ts +13 -0
  676. package/backend/dist/utils/proxy-node.js +471 -0
  677. package/backend/dist/utils/proxy.d.ts +19 -0
  678. package/backend/dist/utils/proxy.js +79 -14
  679. package/backend/dist/utils/retry-after.d.ts +21 -0
  680. package/backend/dist/utils/retry-after.js +36 -0
  681. package/backend/dist/utils/run-command.d.ts +42 -0
  682. package/backend/dist/utils/run-command.js +93 -0
  683. package/backend/dist/utils/self-url.d.ts +13 -0
  684. package/backend/dist/utils/self-url.js +90 -2
  685. package/backend/dist/utils/semver.d.ts +22 -0
  686. package/backend/dist/utils/semver.js +75 -0
  687. package/backend/dist/utils/stream-relay.d.ts +35 -0
  688. package/backend/dist/utils/stream-relay.js +1 -0
  689. package/backend/dist/utils/upstream-url-guard.d.ts +15 -0
  690. package/backend/dist/utils/upstream-url-guard.js +107 -0
  691. package/backend/dist/validator/parser.d.ts +2 -5
  692. package/backend/dist/validator/parser.js +12 -16
  693. package/backend/dist/validator/schema-assertion.d.ts +3 -2
  694. package/backend/dist/validator/schema-assertion.js +53 -8
  695. package/bin/ocr.js +2 -2
  696. package/frontend/dist/assets/index-Cn3QMOQx.js +1487 -0
  697. package/frontend/dist/assets/index-DxZ9MHKB.css +1 -0
  698. package/frontend/dist/assets/qoder.color-tVX5GCcD.svg +5 -0
  699. package/frontend/dist/index.html +2 -2
  700. package/frontend/dist/provider-logos/302ai.svg +7 -0
  701. package/frontend/dist/provider-logos/NOTICE.txt +39 -0
  702. package/frontend/dist/provider-logos/abacus.svg +14 -0
  703. package/frontend/dist/provider-logos/abliteration-ai.svg +6 -0
  704. package/frontend/dist/provider-logos/above.svg +3 -0
  705. package/frontend/dist/provider-logos/agentrouter.svg +4 -0
  706. package/frontend/dist/provider-logos/agnes.svg +1 -0
  707. package/frontend/dist/provider-logos/ai-router.svg +5 -0
  708. package/frontend/dist/provider-logos/ai21.svg +3 -0
  709. package/frontend/dist/provider-logos/aiand.svg +4 -0
  710. package/frontend/dist/provider-logos/aihubmix.svg +3 -0
  711. package/frontend/dist/provider-logos/aimlapi.svg +3 -0
  712. package/frontend/dist/provider-logos/ainetcafe.svg +1 -0
  713. package/frontend/dist/provider-logos/aixy.svg +4 -0
  714. package/frontend/dist/provider-logos/aki-io.svg +8 -0
  715. package/frontend/dist/provider-logos/alibaba-cn.svg +3 -0
  716. package/frontend/dist/provider-logos/alibaba-coding-plan-cn.svg +3 -0
  717. package/frontend/dist/provider-logos/alibaba-coding-plan.svg +3 -0
  718. package/frontend/dist/provider-logos/alibaba-token-plan-cn.svg +1 -0
  719. package/frontend/dist/provider-logos/alibaba-token-plan.svg +1 -0
  720. package/frontend/dist/provider-logos/alibaba.svg +3 -0
  721. package/frontend/dist/provider-logos/amazon-bedrock.svg +3 -0
  722. package/frontend/dist/provider-logos/ambient.svg +3 -0
  723. package/frontend/dist/provider-logos/amd.svg +3 -0
  724. package/frontend/dist/provider-logos/anthropic.svg +3 -0
  725. package/frontend/dist/provider-logos/anyapi.svg +3 -0
  726. package/frontend/dist/provider-logos/arcee.svg +3 -0
  727. package/frontend/dist/provider-logos/atomic-chat.svg +1 -0
  728. package/frontend/dist/provider-logos/auriko.svg +6 -0
  729. package/frontend/dist/provider-logos/azure-cognitive-services.svg +3 -0
  730. package/frontend/dist/provider-logos/azure.svg +3 -0
  731. package/frontend/dist/provider-logos/bailing.svg +3 -0
  732. package/frontend/dist/provider-logos/baseten.svg +3 -0
  733. package/frontend/dist/provider-logos/bee.svg +1 -0
  734. package/frontend/dist/provider-logos/berget.svg +3 -0
  735. package/frontend/dist/provider-logos/blueclaw.svg +3 -0
  736. package/frontend/dist/provider-logos/bothub.svg +33 -0
  737. package/frontend/dist/provider-logos/boundless.svg +12 -0
  738. package/frontend/dist/provider-logos/cerebras.svg +4 -0
  739. package/frontend/dist/provider-logos/chutes.svg +24 -0
  740. package/frontend/dist/provider-logos/clarifai.svg +3 -0
  741. package/frontend/dist/provider-logos/claudinio.svg +19 -0
  742. package/frontend/dist/provider-logos/cline-pass.svg +24 -0
  743. package/frontend/dist/provider-logos/cloudferro-sherlock.svg +5 -0
  744. package/frontend/dist/provider-logos/cloudflare-ai-gateway.svg +4 -0
  745. package/frontend/dist/provider-logos/cloudflare-workers-ai.svg +4 -0
  746. package/frontend/dist/provider-logos/cohere.svg +5 -0
  747. package/frontend/dist/provider-logos/commandcode.svg +11 -0
  748. package/frontend/dist/provider-logos/coralbricks.svg +6 -0
  749. package/frontend/dist/provider-logos/cortecs.svg +24 -0
  750. package/frontend/dist/provider-logos/crossmodel.svg +5 -0
  751. package/frontend/dist/provider-logos/crusoe.svg +23 -0
  752. package/frontend/dist/provider-logos/daoxe.svg +3 -0
  753. package/frontend/dist/provider-logos/databricks.svg +3 -0
  754. package/frontend/dist/provider-logos/deepinfra.svg +4 -0
  755. package/frontend/dist/provider-logos/deepseek.svg +3 -0
  756. package/frontend/dist/provider-logos/digitalocean.svg +6 -0
  757. package/frontend/dist/provider-logos/dinference.svg +1 -0
  758. package/frontend/dist/provider-logos/drun.svg +8 -0
  759. package/frontend/dist/provider-logos/ebcloud.svg +8 -0
  760. package/frontend/dist/provider-logos/echo.svg +7 -0
  761. package/frontend/dist/provider-logos/edenai.svg +8 -0
  762. package/frontend/dist/provider-logos/empiriolabs.svg +1 -0
  763. package/frontend/dist/provider-logos/engy.svg +1 -0
  764. package/frontend/dist/provider-logos/evroc.svg +3 -0
  765. package/frontend/dist/provider-logos/fastrouter.svg +3 -0
  766. package/frontend/dist/provider-logos/fireworks-ai.svg +3 -0
  767. package/frontend/dist/provider-logos/freemodel.svg +3 -0
  768. package/frontend/dist/provider-logos/friendli.svg +3 -0
  769. package/frontend/dist/provider-logos/frogbot.svg +36 -0
  770. package/frontend/dist/provider-logos/github-copilot.svg +3 -0
  771. package/frontend/dist/provider-logos/gitlab.svg +3 -0
  772. package/frontend/dist/provider-logos/gmicloud.svg +24 -0
  773. package/frontend/dist/provider-logos/google-vertex-anthropic.svg +10 -0
  774. package/frontend/dist/provider-logos/google-vertex.svg +10 -0
  775. package/frontend/dist/provider-logos/google.svg +3 -0
  776. package/frontend/dist/provider-logos/greenpt.svg +6 -0
  777. package/frontend/dist/provider-logos/groq.svg +3 -0
  778. package/frontend/dist/provider-logos/helicone.svg +6 -0
  779. package/frontend/dist/provider-logos/hetzner.svg +3 -0
  780. package/frontend/dist/provider-logos/hopper.svg +4 -0
  781. package/frontend/dist/provider-logos/hpc-ai.svg +446 -0
  782. package/frontend/dist/provider-logos/huggingface.svg +3 -0
  783. package/frontend/dist/provider-logos/hyper.svg +20 -0
  784. package/frontend/dist/provider-logos/impossibl.svg +3 -0
  785. package/frontend/dist/provider-logos/inception.svg +14 -0
  786. package/frontend/dist/provider-logos/inceptron.svg +14 -0
  787. package/frontend/dist/provider-logos/inco.svg +3 -0
  788. package/frontend/dist/provider-logos/infer.svg +4 -0
  789. package/frontend/dist/provider-logos/inference.svg +3 -0
  790. package/frontend/dist/provider-logos/inferx.svg +5 -0
  791. package/frontend/dist/provider-logos/infomaniak.svg +3 -0
  792. package/frontend/dist/provider-logos/io-net.svg +5 -0
  793. package/frontend/dist/provider-logos/iteracompute.svg +7 -0
  794. package/frontend/dist/provider-logos/jalapeno.svg +8 -0
  795. package/frontend/dist/provider-logos/jiekou.svg +4 -0
  796. package/frontend/dist/provider-logos/kenari.svg +4 -0
  797. package/frontend/dist/provider-logos/kilo.svg +4 -0
  798. package/frontend/dist/provider-logos/kimi-code-plan-cn.svg +3 -0
  799. package/frontend/dist/provider-logos/kimi-code-plan-global.svg +3 -0
  800. package/frontend/dist/provider-logos/klokintegration.svg +11 -0
  801. package/frontend/dist/provider-logos/kosmik.svg +28 -0
  802. package/frontend/dist/provider-logos/kuae-cloud-coding-plan.svg +3 -0
  803. package/frontend/dist/provider-logos/lilac.svg +6 -0
  804. package/frontend/dist/provider-logos/liquid.svg +1 -0
  805. package/frontend/dist/provider-logos/llmgateway-providers.svg +6 -0
  806. package/frontend/dist/provider-logos/llmgateway.svg +6 -0
  807. package/frontend/dist/provider-logos/llmtech.svg +6 -0
  808. package/frontend/dist/provider-logos/llmtr.svg +12 -0
  809. package/frontend/dist/provider-logos/lmstudio.svg +3 -0
  810. package/frontend/dist/provider-logos/longcat.svg +6 -0
  811. package/frontend/dist/provider-logos/lowrouter.svg +8 -0
  812. package/frontend/dist/provider-logos/lucidquery.svg +3 -0
  813. package/frontend/dist/provider-logos/lynkr.svg +1 -0
  814. package/frontend/dist/provider-logos/meganova.svg +3 -0
  815. package/frontend/dist/provider-logos/melious.svg +3 -0
  816. package/frontend/dist/provider-logos/merge-gateway.svg +4 -0
  817. package/frontend/dist/provider-logos/meta.svg +3 -0
  818. package/frontend/dist/provider-logos/minimax-cn-coding-plan.svg +3 -0
  819. package/frontend/dist/provider-logos/minimax-cn.svg +3 -0
  820. package/frontend/dist/provider-logos/minimax-coding-plan.svg +3 -0
  821. package/frontend/dist/provider-logos/minimax.svg +3 -0
  822. package/frontend/dist/provider-logos/mistral.svg +3 -0
  823. package/frontend/dist/provider-logos/mixlayer.svg +9 -0
  824. package/frontend/dist/provider-logos/moark.svg +3 -0
  825. package/frontend/dist/provider-logos/modal.svg +3 -0
  826. package/frontend/dist/provider-logos/model-oracle-ai.svg +11 -0
  827. package/frontend/dist/provider-logos/modelis.svg +1 -0
  828. package/frontend/dist/provider-logos/modelscope.svg +5 -0
  829. package/frontend/dist/provider-logos/modular.svg +3 -0
  830. package/frontend/dist/provider-logos/moonshotai-cn.svg +3 -0
  831. package/frontend/dist/provider-logos/moonshotai.svg +3 -0
  832. package/frontend/dist/provider-logos/morph.svg +24 -0
  833. package/frontend/dist/provider-logos/munito-eu.svg +1 -0
  834. package/frontend/dist/provider-logos/munito.svg +1 -0
  835. package/frontend/dist/provider-logos/nan.svg +1 -0
  836. package/frontend/dist/provider-logos/nano-gpt.svg +3 -0
  837. package/frontend/dist/provider-logos/nearai.svg +1 -0
  838. package/frontend/dist/provider-logos/nebius.svg +4 -0
  839. package/frontend/dist/provider-logos/neon.svg +3 -0
  840. package/frontend/dist/provider-logos/neosmith.svg +6 -0
  841. package/frontend/dist/provider-logos/neuralwatt.svg +27 -0
  842. package/frontend/dist/provider-logos/nova.svg +3 -0
  843. package/frontend/dist/provider-logos/novita-ai.svg +10 -0
  844. package/frontend/dist/provider-logos/nvidia.svg +3 -0
  845. package/frontend/dist/provider-logos/oci.svg +3 -0
  846. package/frontend/dist/provider-logos/ofox.svg +5 -0
  847. package/frontend/dist/provider-logos/ollama-cloud.svg +7 -0
  848. package/frontend/dist/provider-logos/openai.svg +3 -0
  849. package/frontend/dist/provider-logos/opencode-go.svg +4 -0
  850. package/frontend/dist/provider-logos/opencode.svg +4 -0
  851. package/frontend/dist/provider-logos/openreason.svg +8 -0
  852. package/frontend/dist/provider-logos/openrouter.svg +5 -0
  853. package/frontend/dist/provider-logos/opper.svg +3 -0
  854. package/frontend/dist/provider-logos/orcarouter.svg +2 -0
  855. package/frontend/dist/provider-logos/ovhcloud.svg +3 -0
  856. package/frontend/dist/provider-logos/pareto.svg +5 -0
  857. package/frontend/dist/provider-logos/pendra.svg +10 -0
  858. package/frontend/dist/provider-logos/perplexity-agent.svg +3 -0
  859. package/frontend/dist/provider-logos/perplexity.svg +3 -0
  860. package/frontend/dist/provider-logos/pioneer.svg +3 -0
  861. package/frontend/dist/provider-logos/poe.svg +7 -0
  862. package/frontend/dist/provider-logos/poolside.svg +3 -0
  863. package/frontend/dist/provider-logos/prime.svg +7 -0
  864. package/frontend/dist/provider-logos/privatemode-ai.svg +5 -0
  865. package/frontend/dist/provider-logos/qihang-ai.svg +9 -0
  866. package/frontend/dist/provider-logos/qiniu-ai.svg +7 -0
  867. package/frontend/dist/provider-logos/qvac.svg +6 -0
  868. package/frontend/dist/provider-logos/reflection.svg +3 -0
  869. package/frontend/dist/provider-logos/regolo-ai.svg +46 -0
  870. package/frontend/dist/provider-logos/requesty.svg +24 -0
  871. package/frontend/dist/provider-logos/routing-run.svg +4 -0
  872. package/frontend/dist/provider-logos/runinfra.svg +10 -0
  873. package/frontend/dist/provider-logos/sakana.svg +24 -0
  874. package/frontend/dist/provider-logos/salad-cloud.svg +15 -0
  875. package/frontend/dist/provider-logos/sambanova.svg +26 -0
  876. package/frontend/dist/provider-logos/sap-ai-core.svg +24 -0
  877. package/frontend/dist/provider-logos/sarvam.svg +24 -0
  878. package/frontend/dist/provider-logos/scaleway.svg +5 -0
  879. package/frontend/dist/provider-logos/scnet-token-plan.svg +8 -0
  880. package/frontend/dist/provider-logos/scx-ai.svg +1 -0
  881. package/frontend/dist/provider-logos/sensenova.svg +18 -0
  882. package/frontend/dist/provider-logos/siliconflow-cn.svg +3 -0
  883. package/frontend/dist/provider-logos/siliconflow.svg +3 -0
  884. package/frontend/dist/provider-logos/snowflake-cortex.svg +3 -0
  885. package/frontend/dist/provider-logos/stackit.svg +4 -0
  886. package/frontend/dist/provider-logos/standardcompute.svg +5 -0
  887. package/frontend/dist/provider-logos/stepfun-ai-step-plan.svg +16 -0
  888. package/frontend/dist/provider-logos/stepfun-ai.svg +16 -0
  889. package/frontend/dist/provider-logos/stepfun-step-plan.svg +16 -0
  890. package/frontend/dist/provider-logos/stepfun.svg +16 -0
  891. package/frontend/dist/provider-logos/subconscious.svg +3 -0
  892. package/frontend/dist/provider-logos/submodel.svg +3 -0
  893. package/frontend/dist/provider-logos/synthetic.svg +24 -0
  894. package/frontend/dist/provider-logos/tempr.svg +4 -0
  895. package/frontend/dist/provider-logos/tencent-coding-plan.svg +5 -0
  896. package/frontend/dist/provider-logos/tencent-token-plan.svg +3 -0
  897. package/frontend/dist/provider-logos/tencent-tokenhub.svg +3 -0
  898. package/frontend/dist/provider-logos/tensorx.svg +6 -0
  899. package/frontend/dist/provider-logos/the-grid-ai.svg +14 -0
  900. package/frontend/dist/provider-logos/thinkingmachines.svg +3 -0
  901. package/frontend/dist/provider-logos/tinfoil.svg +3 -0
  902. package/frontend/dist/provider-logos/togetherai.svg +4 -0
  903. package/frontend/dist/provider-logos/tokengo.svg +3 -0
  904. package/frontend/dist/provider-logos/tokenrouter.svg +4 -0
  905. package/frontend/dist/provider-logos/trustedrouter.svg +4 -0
  906. package/frontend/dist/provider-logos/umans-ai-coding-plan.svg +29 -0
  907. package/frontend/dist/provider-logos/umans-ai.svg +29 -0
  908. package/frontend/dist/provider-logos/unorouter.svg +7 -0
  909. package/frontend/dist/provider-logos/upstage.svg +24 -0
  910. package/frontend/dist/provider-logos/vancine.svg +6 -0
  911. package/frontend/dist/provider-logos/venice.svg +4 -0
  912. package/frontend/dist/provider-logos/vercel.svg +3 -0
  913. package/frontend/dist/provider-logos/vispark.svg +3 -0
  914. package/frontend/dist/provider-logos/vivgrid.svg +4 -0
  915. package/frontend/dist/provider-logos/volcengine-coding-plan.svg +1 -0
  916. package/frontend/dist/provider-logos/volcengine.svg +1 -0
  917. package/frontend/dist/provider-logos/vultr.svg +6 -0
  918. package/frontend/dist/provider-logos/wafer.ai.svg +3 -0
  919. package/frontend/dist/provider-logos/wallaby.svg +4 -0
  920. package/frontend/dist/provider-logos/wally.svg +1 -0
  921. package/frontend/dist/provider-logos/wandb.svg +6 -0
  922. package/frontend/dist/provider-logos/watsonx.svg +5 -0
  923. package/frontend/dist/provider-logos/xai.svg +3 -0
  924. package/frontend/dist/provider-logos/xiaomi-token-plan-ams.svg +3 -0
  925. package/frontend/dist/provider-logos/xiaomi-token-plan-cn.svg +3 -0
  926. package/frontend/dist/provider-logos/xiaomi-token-plan-sgp.svg +3 -0
  927. package/frontend/dist/provider-logos/xiaomi.svg +3 -0
  928. package/frontend/dist/provider-logos/xpersona.svg +8 -0
  929. package/frontend/dist/provider-logos/zai-coding-plan.svg +3 -0
  930. package/frontend/dist/provider-logos/zai.svg +3 -0
  931. package/frontend/dist/provider-logos/zeldoc.svg +3 -0
  932. package/frontend/dist/provider-logos/zenifra.svg +4 -0
  933. package/frontend/dist/provider-logos/zenmux.svg +4 -0
  934. package/frontend/dist/provider-logos/zhipuai-coding-plan.svg +3 -0
  935. package/frontend/dist/provider-logos/zhipuai.svg +3 -0
  936. package/package.json +13 -5
  937. package/backend/dist/budget/budget-manager.d.ts +0 -25
  938. package/backend/dist/budget/budget-manager.js +0 -54
  939. package/backend/dist/config/governance-limits.d.ts +0 -68
  940. package/backend/dist/config/governance-limits.js +0 -261
  941. package/backend/dist/flywheel/collector.d.ts +0 -74
  942. package/backend/dist/flywheel/collector.js +0 -235
  943. package/backend/dist/flywheel/dataset.d.ts +0 -130
  944. package/backend/dist/flywheel/dataset.js +0 -638
  945. package/backend/dist/flywheel/decision-capture.d.ts +0 -68
  946. package/backend/dist/flywheel/decision-capture.js +0 -85
  947. package/backend/dist/flywheel/prune.d.ts +0 -133
  948. package/backend/dist/flywheel/prune.js +0 -495
  949. package/backend/dist/flywheel/schema.d.ts +0 -108
  950. package/backend/dist/flywheel/schema.js +0 -117
  951. package/backend/dist/flywheel/trainer.d.ts +0 -84
  952. package/backend/dist/flywheel/trainer.js +0 -198
  953. package/backend/dist/forward-proxy/bypass.d.ts +0 -20
  954. package/backend/dist/forward-proxy/bypass.js +0 -28
  955. package/backend/dist/harness/adapters/amp.d.ts +0 -2
  956. package/backend/dist/harness/adapters/amp.js +0 -8
  957. package/backend/dist/harness/adapters/claude.d.ts +0 -2
  958. package/backend/dist/harness/adapters/claude.js +0 -8
  959. package/backend/dist/harness/adapters/cline.d.ts +0 -2
  960. package/backend/dist/harness/adapters/cline.js +0 -8
  961. package/backend/dist/harness/adapters/codex.d.ts +0 -2
  962. package/backend/dist/harness/adapters/codex.js +0 -8
  963. package/backend/dist/harness/adapters/cursor.d.ts +0 -5
  964. package/backend/dist/harness/adapters/cursor.js +0 -11
  965. package/backend/dist/harness/adapters/declarative.d.ts +0 -64
  966. package/backend/dist/harness/adapters/declarative.js +0 -216
  967. package/backend/dist/harness/adapters/dsh.d.ts +0 -5
  968. package/backend/dist/harness/adapters/dsh.js +0 -6
  969. package/backend/dist/harness/adapters/gemini-cli.d.ts +0 -2
  970. package/backend/dist/harness/adapters/gemini-cli.js +0 -8
  971. package/backend/dist/harness/adapters/github-copilot.d.ts +0 -5
  972. package/backend/dist/harness/adapters/github-copilot.js +0 -11
  973. package/backend/dist/harness/adapters/omp.d.ts +0 -11
  974. package/backend/dist/harness/adapters/omp.js +0 -22
  975. package/backend/dist/harness/adapters/opencode.d.ts +0 -2
  976. package/backend/dist/harness/adapters/opencode.js +0 -56
  977. package/backend/dist/harness/adapters/pi.d.ts +0 -1
  978. package/backend/dist/harness/adapters/pi.js +0 -23
  979. package/backend/dist/harness/adapters/types.d.ts +0 -189
  980. package/backend/dist/harness/adapters/types.js +0 -12
  981. package/backend/dist/harness/adapters/universal.d.ts +0 -6
  982. package/backend/dist/harness/adapters/universal.js +0 -10
  983. package/backend/dist/harness/adapters/windsurf.d.ts +0 -2
  984. package/backend/dist/harness/adapters/windsurf.js +0 -11
  985. package/backend/dist/harness/adapters/zed.d.ts +0 -2
  986. package/backend/dist/harness/adapters/zed.js +0 -8
  987. package/backend/dist/harness/awesome-opencode.d.ts +0 -40
  988. package/backend/dist/harness/awesome-opencode.js +0 -75
  989. package/backend/dist/harness/browse.d.ts +0 -202
  990. package/backend/dist/harness/browse.js +0 -1214
  991. package/backend/dist/harness/inventory.d.ts +0 -10
  992. package/backend/dist/harness/opencode-cafe.d.ts +0 -40
  993. package/backend/dist/harness/opencode-cafe.js +0 -85
  994. package/backend/dist/harness/opencode-ecosystem.d.ts +0 -34
  995. package/backend/dist/harness/opencode-ecosystem.js +0 -246
  996. package/backend/dist/harness/pi-dev.d.ts +0 -81
  997. package/backend/dist/harness/pi-dev.js +0 -187
  998. package/backend/dist/harness/registry.js +0 -26
  999. package/backend/dist/harness/scopes.d.ts +0 -21
  1000. package/backend/dist/harness/scopes.js +0 -22
  1001. package/backend/dist/harness/skills-sh.d.ts +0 -109
  1002. package/backend/dist/harness/skills-sh.js +0 -178
  1003. package/backend/dist/harness/smithery.d.ts +0 -64
  1004. package/backend/dist/harness/smithery.js +0 -146
  1005. package/backend/dist/harness/sources/awesome-opencode.d.ts +0 -11
  1006. package/backend/dist/harness/sources/awesome-opencode.js +0 -39
  1007. package/backend/dist/harness/sources/mcp-official.d.ts +0 -2
  1008. package/backend/dist/harness/sources/mcp-official.js +0 -110
  1009. package/backend/dist/harness/sources/npm.d.ts +0 -2
  1010. package/backend/dist/harness/sources/opencode-cafe.d.ts +0 -11
  1011. package/backend/dist/harness/sources/opencode-cafe.js +0 -41
  1012. package/backend/dist/harness/sources/smithery.d.ts +0 -2
  1013. package/backend/dist/harness/sources/smithery.js +0 -81
  1014. package/backend/dist/harness/writers/extension.d.ts +0 -116
  1015. package/backend/dist/harness/writers/extension.js +0 -219
  1016. package/backend/dist/harness/writers/mcp.d.ts +0 -72
  1017. package/backend/dist/harness/writers/mcp.js +0 -195
  1018. package/backend/dist/opencode/catalog/custom-store.d.ts +0 -50
  1019. package/backend/dist/opencode/catalog/custom-store.js +0 -144
  1020. package/backend/dist/opencode/credentials/push.d.ts +0 -38
  1021. package/backend/dist/opencode/credentials/push.js +0 -116
  1022. package/backend/dist/opencode/credentials/reconcile.d.ts +0 -49
  1023. package/backend/dist/opencode/credentials/reconcile.js +0 -216
  1024. package/backend/dist/opencode/sync.d.ts +0 -29
  1025. package/backend/dist/opencode/sync.js +0 -186
  1026. package/backend/dist/pipeline/account-selection.d.ts +0 -101
  1027. package/backend/dist/pipeline/account-selection.js +0 -112
  1028. package/backend/dist/providers/systemone.d.ts +0 -29
  1029. package/backend/dist/providers/systemone.js +0 -170
  1030. package/backend/dist/ratelimit/duration.d.ts +0 -24
  1031. package/backend/dist/ratelimit/duration.js +0 -43
  1032. package/backend/dist/ratelimit/governance-runtime.d.ts +0 -121
  1033. package/backend/dist/ratelimit/governance-runtime.js +0 -183
  1034. package/backend/dist/ratelimit/index.d.ts +0 -4
  1035. package/backend/dist/ratelimit/index.js +0 -4
  1036. package/backend/dist/ratelimit/limiter.d.ts +0 -157
  1037. package/backend/dist/ratelimit/limiter.js +0 -244
  1038. package/backend/dist/ratelimit/sliding-window-counter.d.ts +0 -63
  1039. package/backend/dist/ratelimit/sliding-window-counter.js +0 -103
  1040. package/backend/dist/ratelimit/subject.d.ts +0 -26
  1041. package/backend/dist/ratelimit/subject.js +0 -28
  1042. package/backend/dist/resilience/account-state.d.ts +0 -84
  1043. package/backend/dist/resilience/account-state.js +0 -228
  1044. package/backend/dist/router/layer1-classifier.d.ts +0 -111
  1045. package/backend/dist/router/layer1-classifier.js +0 -467
  1046. package/backend/dist/router/layer2-judge.d.ts +0 -111
  1047. package/backend/dist/router/layer2-judge.js +0 -373
  1048. package/backend/dist/router/retry-escalation.d.ts +0 -89
  1049. package/backend/dist/router/retry-escalation.js +0 -99
  1050. package/backend/dist/routes/flywheel.d.ts +0 -3
  1051. package/backend/dist/routes/flywheel.js +0 -268
  1052. package/backend/dist/routes/systemone.d.ts +0 -3
  1053. package/backend/dist/routes/systemone.js +0 -90
  1054. package/backend/dist/surfaces/governance-envelope.d.ts +0 -34
  1055. package/backend/dist/surfaces/governance-envelope.js +0 -47
  1056. package/backend/dist/utils/token-estimator.d.ts +0 -7
  1057. package/backend/dist/utils/token-estimator.js +0 -20
  1058. package/frontend/dist/assets/index-B7GKsUyU.js +0 -982
  1059. package/frontend/dist/assets/index-DLKLOkQJ.css +0 -1
  1060. package/frontend/dist/assets/inter-cyrillic-800-normal-C7MGvYyJ.woff2 +0 -0
  1061. package/frontend/dist/assets/inter-cyrillic-800-normal-CCHyn08d.woff +0 -0
  1062. package/frontend/dist/assets/inter-cyrillic-ext-800-normal-BZOjs1Xv.woff2 +0 -0
  1063. package/frontend/dist/assets/inter-cyrillic-ext-800-normal-Ca-gJeZY.woff +0 -0
  1064. package/frontend/dist/assets/inter-greek-800-normal-BU00tryP.woff +0 -0
  1065. package/frontend/dist/assets/inter-greek-800-normal-CLIouy3y.woff2 +0 -0
  1066. package/frontend/dist/assets/inter-greek-ext-800-normal-B--PVpEC.woff2 +0 -0
  1067. package/frontend/dist/assets/inter-greek-ext-800-normal-DUe57HfS.woff +0 -0
  1068. package/frontend/dist/assets/inter-latin-800-normal-BYj_oED-.woff2 +0 -0
  1069. package/frontend/dist/assets/inter-latin-800-normal-D1mf63XC.woff +0 -0
  1070. package/frontend/dist/assets/inter-latin-ext-800-normal-BOMpwxm3.woff +0 -0
  1071. package/frontend/dist/assets/inter-latin-ext-800-normal-DZJjya6U.woff2 +0 -0
  1072. package/frontend/dist/assets/inter-vietnamese-800-normal-Cm7tD1pz.woff2 +0 -0
  1073. package/frontend/dist/assets/inter-vietnamese-800-normal-DDlpr_Ee.woff +0 -0
  1074. /package/backend/dist/harness/{adapters → host/adapters}/skills-paths.d.ts +0 -0
  1075. /package/backend/dist/harness/{adapters → host/adapters}/skills-paths.js +0 -0
  1076. /package/backend/dist/harness/{skill-md.d.ts → skill/skill-md.d.ts} +0 -0
  1077. /package/backend/dist/harness/{skill-md.js → skill/skill-md.js} +0 -0
@@ -1,45 +1,161 @@
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, modelSupportsEfforts } 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';
28
+ import { UpstreamEventContext } from '../observability/upstream-events.js';
23
29
  import { emitClientRequest, captureKeyIdentity, setClientExchangeContext } from '../observability/http-exchange.js';
24
- import { resolveTraceId } from '../observability/trace-id.js';
30
+ import { resolveClientRequestId, mintRequestId } from '../observability/request-identity.js';
25
31
  import { getWarnThrottle } from '../observability/warn-throttle.js';
26
32
  import { recordFailureEvent } from '../observability/failure-events.js';
33
+ import { redactUpstreamBody } from '../observability/upstream-body-redaction.js';
34
+ import { displayPromptText, firstDisplayText } from '../utils/client-envelope.js';
35
+ import { harnessProfileOf } from '../utils/harness-profiles.js';
27
36
  import { ActiveHealthProber, ErrorClassifier } from '../resilience/index.js';
28
37
  import { isModelAllowed, isModelAllowedInTiers, tierFromVirtualEntry } from '../auth/model-access.js';
29
38
  import { DEFAULT_CREDENTIAL_AFFINITY_CACHE_TTL_MS, selectCredential, } from './credential-selection.js';
39
+ /** Key attribution: the in-process binding wins, else the request's authInfo. */
40
+ const keyIdentityOf = (ctx) => ctx?.clientKey ?? captureKeyIdentity(ctx?.fastifyRequest ?? ctx?.clientRequest);
41
+ /**
42
+ * A pause shorter than this reads as normal streaming rhythm; at or above it
43
+ * the screen is visibly frozen. Defines what the stall ratio counts.
44
+ */
45
+ const PERCEIVED_STALL_MS = 1000;
46
+ /**
47
+ * Accumulate-only relay for `streaming.upstream.mode: stream` on a turn whose
48
+ * client wants JSON. The executor pool drains the upstream SSE body through
49
+ * it, the registry accumulates the chunks into one `CanonicalResponse`,
50
+ * and the surface then sends that JSON. Nothing reaches the client, so
51
+ * `committed` is permanently false: in-place retries and failover stay legal
52
+ * (re-issuing upstream duplicates no output the client has seen).
53
+ */
54
+ /**
55
+ * Upstream status code carried on an arbitrary thrown error, if any — `in`
56
+ * narrowing instead of an unchecked cast, since `lastError` is untyped.
57
+ */
58
+ function statusCodeOf(err) {
59
+ if (err && typeof err === 'object' && 'statusCode' in err && typeof err.statusCode === 'number') {
60
+ return err.statusCode;
61
+ }
62
+ return undefined;
63
+ }
64
+ /**
65
+ * Gateway-authored error for an exhausted candidate pool. The upstream
66
+ * verdict (402/401/429/5xx) is the GATEWAY's routing state, never the
67
+ * client's problem: agent clients auto-retry 429 but hard-stop on 402, so
68
+ * forwarding an upstream "insufficient balance" wastes models that are
69
+ * still healthy. Two shapes:
70
+ * - `remaining` non-empty → status 429 when the failure class is
71
+ * routing-fixable (the client's own backoff retry re-peeks the pool and
72
+ * lands on a healthy model); other classes keep their truthful status
73
+ * (a 400 is the request's fault — retries cannot fix it);
74
+ * - `remaining` empty → truthful status, operator-directed message
75
+ * (breaker cooldowns are 12h for quota — retrying now cannot help).
76
+ * `remaining` is computed by the caller with a FRESH peek, so trips that
77
+ * happened during the run itself are counted.
78
+ */
79
+ function routeExhaustedError(routeLabel, failoverPath, lastErr, remaining) {
80
+ const attemptedPath = failoverPath.join(' → ') || 'none attempted';
81
+ const lastMsg = lastErr instanceof Error ? lastErr.message : 'unknown';
82
+ if (remaining.length > 0) {
83
+ const status = statusCodeOf(lastErr) ?? 0;
84
+ const routingFixable = [401, 402, 429].includes(status) || status >= 500;
85
+ 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) });
86
+ }
87
+ 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 });
88
+ }
89
+ const UPSTREAM_SINK_RELAY = {
90
+ stageRouting: () => { },
91
+ onChunk: () => { },
92
+ get committed() {
93
+ return false;
94
+ },
95
+ };
96
+ /**
97
+ * True when a streamed chunk puts something on the user's screen: assistant
98
+ * text, a tool-call fragment, or reasoning/thinking text. Role-only openers,
99
+ * finish_reason frames and the trailing usage frame leave the screen unchanged,
100
+ * so they must NOT count as progress — otherwise a silent 8-second pause
101
+ * between two real chunks would be papered over by the frames arriving inside
102
+ * it, which is precisely the stall time this metric exists to expose.
103
+ *
104
+ * Reasoning counts because the relay forwards it VERBATIM (stream-relay.ts —
105
+ * "thinking still streams to the client"). Leaving it out charged a reasoning
106
+ * model's whole thinking phase as one giant pause, so the figure measured the
107
+ * effort setting instead of a freeze. Both wire spellings are accepted: the
108
+ * OpenAI-compatible `reasoning_content` convention the catalog declares, and
109
+ * OpenRouter's plain `reasoning` string delta.
110
+ */
111
+ function hasVisibleOutput(event) {
112
+ if (event.type === 'response.output_text.delta' || event.type === 'response.refusal.delta') {
113
+ return event.text.length > 0;
114
+ }
115
+ if (event.type === 'response.reasoning.delta' || event.type === 'response.reasoning_summary.delta') {
116
+ return event.text.length > 0;
117
+ }
118
+ if (event.type === 'response.function_call.arguments.delta')
119
+ return event.argumentsDelta.length > 0;
120
+ return event.type === 'response.output_item.added' && event.item.type === 'tool_call';
121
+ }
122
+ function responseMessageText(response) {
123
+ if (!response)
124
+ return '';
125
+ return response.output.map((item) => item.type === 'message'
126
+ ? item.content.map((part) => part.type === 'text' || part.type === 'refusal' ? part.text : '').join('')
127
+ : '').join('');
128
+ }
129
+ function messageText(message) {
130
+ if (!message)
131
+ return '';
132
+ return message.content.map((part) => part.type === 'text' || part.type === 'refusal' ? part.text : '').filter(Boolean).join(' ');
133
+ }
134
+ function lastUserMessage(input) {
135
+ for (let index = input.length - 1; index >= 0; index--) {
136
+ const item = input[index];
137
+ if (item.type === 'message' && item.role === 'user')
138
+ return item;
139
+ }
140
+ return undefined;
141
+ }
142
+ const effortOf = (request) => request.reasoning?.effort;
143
+ function setEffort(request, effort) {
144
+ request.reasoning = { ...request.reasoning, effort };
145
+ }
30
146
  /**
31
147
  * Pull a non-sensitive subset of inbound headers for the trace's
32
148
  * `clientHeaders` field. Three categories:
33
149
  * - 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
150
+ * - clientRequestId (x-request-id / x-trace-id / x-correlation-id /
151
+ * request-id / traceparent) — the caller's correlation value, NOT a
152
+ * credential and never a key. Authorization / x-api-key / cookies /
153
+ * anything else are intentionally omitted (raw headers carry API keys).
154
+ * Fastify surfaces headers as
38
155
  * `string | string[] | undefined`; arrays collapse to their first value to
39
156
  * keep the field scalar. Returns undefined when nothing matched so the
40
157
  * trace stays compact for the common no-headers path.
41
158
  */
42
- const REQUEST_ID_KEYS = ['x-request-id', 'x-trace-id', 'x-correlation-id', 'request-id', 'traceparent'];
43
159
  /**
44
160
  * Pull the upstream target host from an inbound header map. On the MITM
45
161
  * forward-proxy path this is the ORIGINAL destination (the API host the
@@ -60,6 +176,44 @@ function pickHeaderHost(headers) {
60
176
  return raw[0];
61
177
  return undefined;
62
178
  }
179
+ /**
180
+ * First string value of an inbound header (Fastify's surface allows arrays
181
+ * and both case spellings). Display path only — nothing here steers routing.
182
+ */
183
+ function pickHeaderValue(headers, name) {
184
+ if (!headers)
185
+ return undefined;
186
+ const raw = headers[name] ?? headers[name.toLowerCase()];
187
+ const v = Array.isArray(raw) ? raw[0] : raw;
188
+ const s = typeof v === 'string' ? v.trim() : '';
189
+ return s || undefined;
190
+ }
191
+ /**
192
+ * Self-declared human prompt (envelope layer 0): a client that KNOWS which
193
+ * bytes are the human turn states them here instead of asking the gateway to
194
+ * infer it from markup. Adopted verbatim, so a harness whose envelope shape
195
+ * is unguessable is still titled correctly without a profile.
196
+ *
197
+ * Display-only and spoofable by whoever sends it — the value never reaches
198
+ * routing, capture bodies or the upstream request, so the cost of a forged
199
+ * header is one wrong session title.
200
+ */
201
+ const PROMPT_HINT_HEADER = 'x-ocr-prompt-hint';
202
+ /** Display cap every identification aid uses (title, per-turn summary, snippet). */
203
+ const DISPLAY_CAP_CHARS = 200;
204
+ /** Clip to the display cap with an ellipsis (already-normalized input). */
205
+ function clipDisplayText(text) {
206
+ return text.length <= DISPLAY_CAP_CHARS ? text : text.slice(0, DISPLAY_CAP_CHARS - 1) + '…';
207
+ }
208
+ function envelopeHintsOf(headers) {
209
+ const declared = pickHeaderValue(headers, PROMPT_HINT_HEADER);
210
+ return {
211
+ profile: harnessProfileOf(pickHeaderValue(headers, 'user-agent')),
212
+ // Declared text is the human's own words: whitespace is flattened for the
213
+ // one-line surfaces, never stripped of markup or truncated mid-tag.
214
+ declaredPrompt: declared ? clipDisplayText(declared.replace(/\s+/g, ' ').trim()) || undefined : undefined,
215
+ };
216
+ }
63
217
  function extractClientHeaders(headers) {
64
218
  if (!headers)
65
219
  return undefined;
@@ -73,18 +227,13 @@ function extractClientHeaders(headers) {
73
227
  };
74
228
  const ua = pick('user-agent');
75
229
  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
- }
230
+ const rid = resolveClientRequestId({ headers }).clientRequestId;
82
231
  if (ua === undefined && al === undefined && rid === undefined)
83
232
  return undefined;
84
233
  return {
85
234
  ...(ua !== undefined ? { userAgent: ua } : {}),
86
235
  ...(al !== undefined ? { acceptLanguage: al } : {}),
87
- ...(rid !== undefined ? { requestId: rid } : {}),
236
+ ...(rid !== undefined ? { clientRequestId: rid } : {}),
88
237
  };
89
238
  }
90
239
  export class PipelineOrchestrator {
@@ -129,23 +278,34 @@ export class PipelineOrchestrator {
129
278
  getCircuitBreakerManager() {
130
279
  return this.registry.getCircuitBreakerManager();
131
280
  }
281
+ /**
282
+ * The pool a model serves from, derived from its HOME tier — the single-tier
283
+ * question "is this pinned model still config-intended?". A model with no
284
+ * home tier serves from NO pool (empty list): every pool filters it out, so
285
+ * a pin on it is config-evicted and falls through to the ordinary
286
+ * replacement path. Callers must not treat the empty list as "tier down";
287
+ * that judgement belongs to `getModelForTier`.
288
+ */
289
+ poolOfHomedModel(model) {
290
+ return model.tier ? this.registry.getCandidateModelsForTier(model.tier, false) : [];
291
+ }
132
292
  /**
133
293
  * Auto-request routing with the experience table in front of the decision layer
134
294
  * (ADR-0011): an entry hit short-circuits L2 entirely — the table IS a
135
- * prior judgment. Explicit request tiers (`force_tier`, incl. the
295
+ * prior judgment. Explicit request tiers (`forceTier`, incl. the
136
296
  * mode-forced ones resolved in 1B) skip the table: an explicit choice is a
137
297
  * layer0 decision by definition. On an L2 judgment the router behaves
138
298
  * exactly as before (decision layer → plus baseline).
139
299
  */
140
300
  async routeAutoDecision(request, decisionCapture, sessionId, promptHash) {
141
301
  const gate = routeEntriesGate();
142
- if (gate.enabled !== false && promptHash && !request.router_options?.force_tier) {
302
+ if (gate.enabled !== false && promptHash && !request.routerOptions?.forceTier) {
143
303
  const entry = getRouteEntryStore().hit(promptHash, sessionId);
144
304
  if (entry) {
145
305
  // The entry's effort is part of the experience; a client-explicit
146
306
  // effort always outranks it.
147
- if (entry.effort && request.reasoning_effort === undefined) {
148
- request.reasoning_effort = entry.effort;
307
+ if (entry.effort && effortOf(request) === undefined) {
308
+ setEffort(request, entry.effort);
149
309
  }
150
310
  appendRoutingLedger({
151
311
  kind: 'entry_hit',
@@ -160,15 +320,14 @@ export class PipelineOrchestrator {
160
320
  reasonCode: 'entry.hit',
161
321
  reasonParams: { tier: entry.tier, source: entry.source, hits: entry.hitCount },
162
322
  layerUsed: 'entry',
163
- needsSchemaValidation: hasToolsOrSchema(request),
323
+ needsSchemaValidation: declaresJsonContract(request),
164
324
  };
165
325
  }
166
326
  }
167
327
  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
169
- // exists while the capture master is on). The LAYER 2 DECISION applies
170
- // the recorder master gate (requestCapture.enabled) — when off it
171
- // passes nothing further, so this arg alone changes nothing today.
328
+ // Archive label for the decision wire, present only while capture is on.
329
+ // The conversation id itself is `sessionId` above; the decision leg
330
+ // copies it onto events and does not own the session.
172
331
  decisionCapture,
173
332
  // Failure attribution: decision layer wire failures land in the failure_events
174
333
  // ledger tagged with THIS conversation, whatever the capture switch.
@@ -182,28 +341,35 @@ export class PipelineOrchestrator {
182
341
  if (this.healthProber)
183
342
  this.healthProber.stop();
184
343
  }
344
+ /** The health prober's CLAMPED sweep interval (0 when probing is off). */
345
+ getProberIntervalMs() {
346
+ return this.healthProber?.getIntervalMs() ?? 0;
347
+ }
348
+ /** One-shot allocation of the write-time turn identity (ADR-0024). */
349
+ allocateTurn(sessionId, input) {
350
+ // Retained traces seed the counter for sessions that predate the v3
351
+ // snapshot; the counter itself is authoritative once present.
352
+ const seed = this.traceTracker
353
+ .getTracesBySession(sessionId)
354
+ .reduce((max, t) => Math.max(max, t.turnIndex ?? 0), 0);
355
+ const a = this.sessionManager.allocateTurnIndex(sessionId, input, seed);
356
+ return {
357
+ turnIndex: a.turnIndex,
358
+ isPromptStart: a.isPromptStart,
359
+ turnDecision: a.turnDecision,
360
+ };
361
+ }
185
362
  /**
186
- * Public entry point — thin capture wrapper around processInternal.
187
- *
188
- * Records the full request/response into the opt-in CaptureRecorder audit
189
- * log on BOTH the success and the failure path (debugging failed requests
190
- * is the primary use case). Implemented as a wrapper instead of an inline
191
- * hook so processInternal stays untouched: the session-id resolution and
192
- * the PRE-compression message snapshot are rebuilt here with the same pure
193
- * functions (PromptOptimizer.normalizeMessages / scanDirectives /
194
- * resolveSessionId) — all deterministic and run in the same synchronous
195
- * segment, so the wrapper snapshot is byte-identical to the scrubbed chain
196
- * processInternal routes on before applyCompression mutates the request
197
- * (ADR-0011 §4: the scrubbed chain feeds hashing, snippets, traces AND
198
- * capture — reserved tokens never reach the archive, and session /
199
- * conversation anchor resolution sees the same bytes the router sees).
200
- * Request headers are captured in
201
- * SANITIZED form (credential values masked per the deny-list in
202
- * observability/http-exchange.ts), never raw.
363
+ * Public entry point. The admission gate scrubs the chain once, resolves
364
+ * the conversation and allocates its turn, before anything else. The rest
365
+ * of the pipeline uses that scrubbed request and that session. Capture,
366
+ * when on, copies the id into the audit log. When it is off, no context
367
+ * is built and no event is written. Captured headers are sanitized
368
+ * (credential values masked in observability/http-exchange.ts).
203
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,53 +378,55 @@ 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).
224
- 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;
229
- let captureSessionId = '';
230
- let preResolvedSession;
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).
388
+ const admissionHeaders = context?.headers ?? context?.clientRequest?.headers ?? context?.fastifyRequest?.headers;
389
+ const clientRequest = admissionHeaders ? resolveClientRequestId({ headers: admissionHeaders }) : {};
390
+ const turnIdentity = {
391
+ requestId: mintRequestId(),
392
+ ...(clientRequest.clientRequestId ? { clientRequestId: clientRequest.clientRequestId } : {}),
393
+ turn: NO_TURN,
394
+ };
395
+ // Conversation identity is the admission gate's job. Cold-start ids carry
396
+ // fresh entropy, so this resolve is the only one for the request;
397
+ // processInternal reuses it. Capture copies the id onto events and does
398
+ // not resolve a second one.
399
+ const gate = directivesGate();
400
+ const normalizedMessages = PromptOptimizer.normalizeMessages(request);
401
+ const snapshotScan = scanDirectives(normalizedMessages, gate.enabled ? gate.prefix : null, request.instructions);
402
+ if (snapshotScan.droppedMessages > 0 &&
403
+ !snapshotScan.input.some((item) => item.type === 'message' && item.role === 'user')) {
404
+ throw Object.assign(new Error(`Empty prompt — ${gate.prefix}* directives were the only content in the request`), { statusCode: 400 });
405
+ }
406
+ const snapshotRequest = {
407
+ ...request,
408
+ input: snapshotScan.input,
409
+ ...(request.instructions !== undefined ? { instructions: snapshotScan.instructions } : {}),
410
+ };
411
+ // A name the gateway will not serve is not a conversation. These throws
412
+ // happen before the session resolve, so a 404 or a policy 403 does not
413
+ // allocate a turn or claim a session.
414
+ const addressed = this.resolveAddressedModel(snapshotRequest, context);
415
+ const keyIdentity = keyIdentityOf(context);
416
+ const admissionRef = SessionManager.clientRefOf(snapshotRequest);
417
+ const preResolvedSession = this.sessionManager.resolveSessionId(snapshotRequest, {
418
+ keyId: keyIdentity?.id,
419
+ headers: admissionHeaders,
420
+ clientRef: admissionRef ?? undefined,
421
+ });
422
+ const admissionSessionId = preResolvedSession.sessionId;
423
+ // ADR-0024: one turn boundary, after the session is bound, before any
424
+ // event. Retries, failover and the decision leg copy it.
425
+ turnIdentity.turn = this.allocateTurn(admissionSessionId, snapshotRequest.input);
231
426
  let upstreamEventContext;
232
427
  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.
238
- const normalizedMessages = PromptOptimizer.normalizeMessages(request);
239
- // Scrub with the LIVE gate (enabled flag + configured prefix), matching
240
- // processInternal — a relocated prefix or a disabled gate must not
241
- // desync capture/anchor bytes from what the router actually serves.
242
- const gate = directivesGate();
243
- const snapshotRequest = {
244
- ...request,
245
- messages: scanDirectives(normalizedMessages, gate.enabled ? gate.prefix : null)
246
- .messages,
247
- };
248
- const keyIdentity = captureKeyIdentity(context?.fastifyRequest ?? context?.clientRequest);
249
- // Resolve ONCE here and hand the result to processInternal: cold-start
250
- // IDs carry fresh random entropy, so a second resolve of the same
251
- // request would mint a different ID and split capture from routing.
252
- preResolvedSession = this.sessionManager.resolveSessionId(snapshotRequest, {
253
- keyId: keyIdentity?.id,
254
- headers: context?.headers,
255
- });
256
- captureSessionId = preResolvedSession.sessionId;
257
- // Deterministic conversation key stamped onto EVERY event of the turn:
258
- // the capture archive can regroup turns even when the volatile session
259
- // id shifts (content-addressed, never a credential, mirrors the
260
- // session-manager resolution input exactly).
261
- const conversationKey = SessionManager.conversationKey(snapshotRequest.messages || [], keyIdentity?.id) ?? undefined;
428
+ // Content-addressed regroup key for the archive only. Not a session id.
429
+ const conversationKey = SessionManager.conversationKey(snapshotRequest.input || [], keyIdentity?.id) ?? undefined;
262
430
  // CLIENT REQUEST event fires synchronously here — independent of any
263
431
  // response. Even if the upstream call hangs / times out / the handler
264
432
  // throws, the client request event is already on disk.
@@ -269,11 +437,14 @@ export class PipelineOrchestrator {
269
437
  const clientExchangeCtx = emitClientRequest({
270
438
  recorder: this.captureRecorder,
271
439
  req: context?.fastifyRequest ?? context?.clientRequest,
272
- body: snapshotRequest,
273
- sessionId: captureSessionId,
274
- traceId: captureOutTraceId,
440
+ apiKey: keyIdentity,
441
+ body: scrubWireDirectives(context?.clientBody ?? snapshotRequest, gate.enabled ? gate.prefix : null),
442
+ sessionId: admissionSessionId,
443
+ clientRequestId: turnIdentity.clientRequestId,
444
+ requestId: turnIdentity.requestId,
275
445
  model: request.model || 'auto',
276
446
  conversationKey,
447
+ turn: turnIdentity.turn,
277
448
  });
278
449
  if (context?.fastifyRequest) {
279
450
  setClientExchangeContext(context.fastifyRequest, clientExchangeCtx);
@@ -281,54 +452,52 @@ export class PipelineOrchestrator {
281
452
  else if (context?.onClientExchange) {
282
453
  context.onClientExchange(clientExchangeCtx);
283
454
  }
284
- upstreamEventContext = {
455
+ upstreamEventContext = new UpstreamEventContext({
285
456
  recorder: this.captureRecorder,
286
- sessionId: captureSessionId,
287
- traceId: captureOutTraceId,
457
+ sessionId: admissionSessionId,
458
+ clientRequestId: turnIdentity.clientRequestId,
459
+ requestId: turnIdentity.requestId,
288
460
  model: request.model || 'auto',
289
461
  // Key attribution: the Fastify leg carries authInfo (attached by the
290
462
  // auth preHandler); MITM / master-key legs resolve to undefined and
291
463
  // their events simply omit the field — same as before this existed.
292
464
  apiKey: keyIdentity,
293
465
  conversationKey,
294
- };
466
+ turn: turnIdentity.turn,
467
+ });
295
468
  }
296
- return await this.processInternal(request, context, preResolvedSession, upstreamEventContext, captureOutTraceId, relay);
469
+ // Provider-leg transport (streaming.upstream.mode — ADR-0008 §1):
470
+ // buffered → never hand a relay to the executor pool (the historical
471
+ // `streaming.enabled: false` rollback);
472
+ // stream → hand the wire a relay even when the CLIENT wants JSON, so
473
+ // the upstream SSE reader runs and the accumulator builds the
474
+ // response. The sink never writes a byte, so `committed` stays
475
+ // false and retries/failover remain legal;
476
+ // follow → the client's own relay (or none) — historical behavior.
477
+ return await this.processInternal(snapshotRequest, snapshotScan, addressed, context, preResolvedSession, upstreamEventContext, turnIdentity, this.resolveUpstreamRelay(relay));
297
478
  }
298
479
  /**
299
- * Complete orchestration workflow:
300
- * 1. Prompt normalization (canonical order)
301
- * 2. Zero-header session identification & prefix fingerprinting
302
- * 3. Multi-Layer hierarchical routing (Layer 0 -> Layer 2)
303
- * 4. Monotonic Ratchet session state enforcement + Session-Pin Eviction
304
- * 5. Execution with Circuit Breaker, Transparent Failover & Schema Assertion
305
- * 6. FinOps accounting
306
- * 7. Post-turn prefix fingerprint registration
480
+ * Apply `streaming.upstream.mode` to the surface-supplied relay. The sink
481
+ * relay is a module constant: it carries no per-request state (it forwards
482
+ * nothing and never commits), so one instance serves every accumulated
483
+ * turn.
307
484
  */
308
- async processInternal(request, context, preResolvedSession, upstreamEventContext, traceId, relay) {
309
- const startTime = Date.now();
310
- // 1. Optimize message prefix order & resolve virtual routing models
311
- const normalizedMessages = PromptOptimizer.normalizeMessages(request);
312
- // 1.0 Control directives (ADR-0011 rewrite): SCRUB first, before anything
313
- // reads or forwards the chain. Every reserved token is removed from every
314
- // role and text part, and directive-only messages are dropped, so the
315
- // upstream payload is byte-equivalent to one that never carried a directive
316
- // (stable prefix cache, no reserved word at any vendor). Only the LAST user
317
- // message's tokens are actionable — and only for this turn. The namespace
318
- // comes from the hot-applied gate (`directives.prefix`); `enabled: false`
319
- // disables the scan entirely, so tokens travel as ordinary text.
320
- const directiveGate = directivesGate();
321
- const directivePrefix = directiveGate.prefix;
322
- const directiveScan = scanDirectives(normalizedMessages, directiveGate.enabled ? directivePrefix : null);
323
- if (directiveScan.droppedMessages > 0 &&
324
- !directiveScan.messages.some((m) => m.role === 'user')) {
325
- // A directive-only prompt with no history: nothing left to send.
326
- throw Object.assign(new Error(`Empty prompt — ${directivePrefix}* directives were the only content in the request`), { statusCode: 400 });
327
- }
328
- const normalizedRequest = {
329
- ...request,
330
- messages: directiveScan.messages,
331
- };
485
+ resolveUpstreamRelay(relay) {
486
+ const mode = streamingPosture().upstream;
487
+ if (mode === 'buffered')
488
+ return undefined;
489
+ if (relay)
490
+ return relay;
491
+ return mode === 'stream' ? UPSTREAM_SINK_RELAY : undefined;
492
+ }
493
+ /**
494
+ * Names the model the client addressed. Throws 404 for an unknown variant
495
+ * or an unusable combo, and 403 when the key's model policy denies an
496
+ * explicit model. A bare name that matches nothing falls through to the
497
+ * classifier. Mutates `request` with the tier and effort that name implies.
498
+ * Does not resolve a session.
499
+ */
500
+ resolveAddressedModel(request, context) {
332
501
  let explicitModel;
333
502
  let variantUsed;
334
503
  // Routing-name matching trims once. `request.model` itself stays verbatim
@@ -339,18 +508,18 @@ export class PipelineOrchestrator {
339
508
  const modelName = (request.model ?? '').trim();
340
509
  const bareTier = tierFromVirtualEntry(modelName);
341
510
  if (bareTier) {
342
- normalizedRequest.router_options = { ...normalizedRequest.router_options, force_tier: bareTier };
511
+ request.routerOptions = { ...request.routerOptions, forceTier: bareTier };
343
512
  }
344
513
  else if (modelName && modelName !== 'auto') {
345
514
  const specific = this.registry.getModel(modelName);
346
515
  if (specific) {
347
516
  // Exact-model pass-through: the client named a REGISTERED model id
348
517
  // (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.
518
+ // this model — not merely its tier. Resilience is preserved: in-place
519
+ // same-model retry and credential re-spread still apply; the model
520
+ // itself is never substituted (ADR-0014).
352
521
  explicitModel = specific;
353
- normalizedRequest.router_options = { ...normalizedRequest.router_options, force_tier: specific.tier };
522
+ request.routerOptions = { ...request.routerOptions, forceTier: specific.tier };
354
523
  }
355
524
  else {
356
525
  const variantRef = this.registry.resolveVariantRef(modelName);
@@ -363,9 +532,9 @@ export class PipelineOrchestrator {
363
532
  // applies its downgrade/honesty contract.
364
533
  explicitModel = variantRef.base;
365
534
  variantUsed = variantRef.variant.id;
366
- normalizedRequest.reasoning_effort = variantRef.variant.reasoningEffort;
367
- normalizedRequest.model = variantRef.base.id;
368
- normalizedRequest.router_options = { ...normalizedRequest.router_options, force_tier: variantRef.base.tier };
535
+ setEffort(request, variantRef.variant.reasoningEffort);
536
+ request.model = variantRef.base.id;
537
+ request.routerOptions = { ...request.routerOptions, forceTier: variantRef.base.tier };
369
538
  }
370
539
  else if (modelName.includes('#')) {
371
540
  // `#variant` is explicit syntax — a typo must fail loud instead of
@@ -388,8 +557,9 @@ export class PipelineOrchestrator {
388
557
  // sibling provider) and the gateway's own host matches no provider
389
558
  // baseUrl anyway. Cheapest-hit-first ordering picks the primary
390
559
  // otherwise. Same-name siblings stay reachable via the tier's
391
- // failover pool. Unresolved names keep the classifier contract
392
- // (intelligent-routing product behavior).
560
+ // failover pool. A full miss falls through to the classifier —
561
+ // ADR-0026 deleted the unresolved-model policy outright, so every
562
+ // leg resolves a name the same way.
393
563
  const bareHits = this.registry.getModelsByUpstreamName(modelName, pickHeaderHost(context?.clientRequest?.headers));
394
564
  // A live combo id claims this name for the gateway: the combo fork
395
565
  // below is the advertised meaning (/v1/models lists the id as a
@@ -399,80 +569,81 @@ export class PipelineOrchestrator {
399
569
  // models stay addressable by their full provider-prefixed id.
400
570
  if (bareHits.length > 0 && !this.registry.isCombo(modelName)) {
401
571
  explicitModel = bareHits[0];
402
- normalizedRequest.router_options = {
403
- ...normalizedRequest.router_options,
404
- force_tier: explicitModel.tier,
572
+ request.routerOptions = {
573
+ ...request.routerOptions,
574
+ forceTier: explicitModel.tier,
405
575
  };
406
576
  }
577
+ // Nothing matched: no policy, no mapping, no fallback. The name
578
+ // falls through to the classifier exactly like a native /v1 caller's
579
+ // would — ADR-0026 deleted the unresolved-model mechanism outright,
580
+ // so the MITM leg has no special posture of its own. A gateway
581
+ // plugin that wants "this name means that model" maps it BEFORE
582
+ // dispatch (it owns the decrypted wire); the pipeline never guesses.
407
583
  }
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
584
  }
412
585
  }
413
- // 1A. Custom model combo: the client named a configured combo id — the
414
- // combo's member list IS the candidate pool. Classifier tier routing,
586
+ // Custom model combo: the client named a configured combo id — the
587
+ // combo's member list IS the candidate pool. Tier-pool routing,
415
588
  // session ratchet and schema-assertion escalation are all bypassed
416
589
  // (explicit user composition wins, mirroring the exact-model
417
590
  // pass-through above).
418
- const comboByName = !explicitModel && modelName && this.registry.isCombo(modelName)
419
- ? modelName
420
- : undefined;
591
+ const comboByName = !explicitModel && modelName && this.registry.isCombo(modelName) ? modelName : undefined;
421
592
  if (comboByName && this.registry.isComboDisabled(comboByName)) {
422
- // Fail fast like the empty-member case below: the combo is hidden from
423
- // /v1/models, so an in-flight client naming it must get a loud 404 —
424
- // routing it as `auto` would be invisible billing/model drift.
425
593
  throw Object.assign(new Error(`Combo '${comboByName}' is disabled — re-enable it in the console or choose another model.`), { statusCode: 404 });
426
594
  }
427
595
  if (comboByName && this.registry.resolveCombo(comboByName).length === 0) {
428
- // Fail fast instead of silently degrading to classifier routing: the
429
- // combo is still advertised via /v1/models, so routing it as `auto`
430
- // 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.`);
596
+ 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
597
  }
433
598
  const comboId = comboByName ?? undefined;
434
- // Defense in depth: an explicitly named model outside the key's model
435
- // policy fails loud here (HTTP routes entry-check this too; direct
436
- // orchestrator callers might not). The model's FULL membership set is
437
- // passed so TIER-level entries (lite/plus/pro/ultra) match exactly
438
- // as they do in the execution pool filter (executeCandidatePool) — a
439
- // tier-denied explicit model must not slip through the bare-name/variant
440
- // resolution paths, and a multi-pool model is admitted when any of its
441
- // memberships passes.
599
+ // An explicitly named model outside the key's model policy fails loud
600
+ // here (HTTP routes entry-check this too; direct orchestrator callers
601
+ // might not). The model's FULL membership set is passed so TIER-level
602
+ // entries match the execution pool filter.
442
603
  if (explicitModel &&
443
604
  context?.modelAccess &&
444
605
  !isModelAllowedInTiers(explicitModel.id, context.modelAccess, this.registry.tiersOf(explicitModel))) {
445
606
  throw Object.assign(new Error(`API key model policy denies model '${explicitModel.id}'`), { statusCode: 403 });
446
607
  }
608
+ return { explicitModel, variantUsed, comboId };
609
+ }
610
+ /**
611
+ * Routing and execution after admission. The request is already scrubbed,
612
+ * the addressed model is already accepted, and the session and turn
613
+ * already exist. A rejected request never reaches this function.
614
+ */
615
+ async processInternal(request, directiveScan, addressed, context, preResolvedSession, upstreamEventContext, turnIdentity, relay) {
616
+ const clientRequestId = turnIdentity.clientRequestId;
617
+ const requestId = turnIdentity.requestId;
618
+ const startTime = Date.now();
619
+ // Admission already scrubbed this request (ADR-0011). Routing mutates the copy.
620
+ const normalizedRequest = request;
621
+ const directivePrefix = directivesGate().prefix;
622
+ const { explicitModel, variantUsed, comboId } = addressed;
447
623
  // 1B. Global routing mode (config.routing.mode) — cost/quality force the tier
448
624
  // for auto/tier-alias requests; explicit client choices always win.
449
- const modeTier = routingModeForceTier(normalizedRequest.model, normalizedRequest.router_options, this.config.routing?.mode);
625
+ const modeTier = routingModeForceTier(normalizedRequest.model, normalizedRequest.routerOptions, this.config.routing?.mode);
450
626
  if (modeTier) {
451
- normalizedRequest.router_options = { ...normalizedRequest.router_options, force_tier: modeTier };
627
+ normalizedRequest.routerOptions = { ...normalizedRequest.routerOptions, forceTier: modeTier };
628
+ }
629
+ // 2. The admission gate resolved this conversation and allocated its turn.
630
+ // clientRef is read again only so the trace row names the ref that was bound.
631
+ const clientRef = SessionManager.clientRefOf(normalizedRequest);
632
+ const sessionId = preResolvedSession.sessionId;
633
+ const requestTurn = turnIdentity.turn;
634
+ // 2B. Snapshot canonical strings before pairing/compression. Session
635
+ // anchors must describe the bytes the client sent, not a compressed or
636
+ // repaired upstream projection. Serialization avoids a deep content clone.
637
+ const fingerprintItems = SessionManager.serializeInput(normalizedRequest.input);
638
+ // Repair unmatched/duplicate tool results after fingerprinting and before
639
+ // any carrier renders the request. Unchanged histories keep their array.
640
+ const pairing = repairToolCallPairing(normalizedRequest.input);
641
+ if (pairing.input !== normalizedRequest.input) {
642
+ console.log(`[pipeline:tool-pairing] repaired history: ${pairing.synthesized} missing repl${pairing.synthesized === 1 ? 'y' : 'ies'}, ` +
643
+ `${pairing.duplicates} duplicate repl${pairing.duplicates === 1 ? 'y' : 'ies'}, ` +
644
+ `${pairing.orphans} orphan repl${pairing.orphans === 1 ? 'y' : 'ies'}`);
645
+ normalizedRequest.input = pairing.input;
452
646
  }
453
- // 2. Identify / track conversation session (zero-header layered resolution).
454
- // Reuse the capture-time resolve when present: both call sites normalize
455
- // identically, and one request must yield exactly one session ID.
456
- const sessionResolve = preResolvedSession ??
457
- this.sessionManager.resolveSessionId(normalizedRequest, {
458
- keyId: captureKeyIdentity(context?.fastifyRequest ?? context?.clientRequest)?.id,
459
- headers: context?.headers,
460
- });
461
- 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
- }));
476
647
  await applyCompression(normalizedRequest, this.config.compression, sessionId);
477
648
  // 2C. Route-entry experience (ADR-0011). One normalized prompt hash feeds
478
649
  // the experience-table lookup and write. Directives were scrubbed above, so
@@ -480,13 +651,8 @@ export class PipelineOrchestrator {
480
651
  // no double rows, no prefix drift.
481
652
  const routeGate = routeEntriesGate();
482
653
  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 ?? '');
654
+ const lastUserText = messageText(lastUserMessage(normalizedRequest.input)).trim();
655
+ const normalizedPrompt = normalizePrompt(lastUserText);
490
656
  // A directive-only ("just continue") turn carries no prompt of its own:
491
657
  // hashing the previous user message would attribute this turn's outcome to
492
658
  // the OLD prompt and let it rewrite that prompt's experience row.
@@ -517,7 +683,7 @@ export class PipelineOrchestrator {
517
683
  // injection below, the `@ocr-effort-*` directive, model defaultEffort). The
518
684
  // local `requestedEffort` read later is the EFFECTIVE ask the machinery
519
685
  // served against; `effortSource` says whose ask it was.
520
- const clientEffort = normalizedRequest.reasoning_effort;
686
+ const clientEffort = effortOf(normalizedRequest);
521
687
  const initialDecision = comboId
522
688
  ? {
523
689
  targetTier: 'plus',
@@ -530,7 +696,7 @@ export class PipelineOrchestrator {
530
696
  }
531
697
  : await this.routeAutoDecision(normalizedRequest, upstreamEventContext, sessionId, promptHash);
532
698
  // Explicit-model honesty: the engine's 'forced' code here reflects the
533
- // force_tier the 1B resolver INJECTED from the named model's registration
699
+ // forceTier the 1B resolver INJECTED from the named model's registration
534
700
  // (full id / variant / bare name) — the client named a model, not a tier.
535
701
  // A dedicated code keeps the trace truthful: `tier` stays in params for
536
702
  // tooltips, but the console template carries no {tier} slot, so no tier
@@ -538,7 +704,7 @@ export class PipelineOrchestrator {
538
704
  if (explicitModel && initialDecision.reasonCode === 'forced') {
539
705
  initialDecision.reasonCode = 'explicit.model';
540
706
  initialDecision.reason = `Explicit model '${explicitModel.id}' — routed to the named model, no tier judgment`;
541
- initialDecision.reasonParams = { model: explicitModel.id, tier: explicitModel.tier };
707
+ initialDecision.reasonParams = { model: explicitModel.id, ...(explicitModel.tier ? { tier: explicitModel.tier } : {}) };
542
708
  }
543
709
  // ADR-0012 §1 + ADR-0011 floor: L2-decided effort joins the request
544
710
  // exactly like a route-entry hit — only into an omitted field (the
@@ -549,11 +715,11 @@ export class PipelineOrchestrator {
549
715
  if (!comboId &&
550
716
  initialDecision.layerUsed === 'layer2' &&
551
717
  initialDecision.effort &&
552
- normalizedRequest.reasoning_effort === undefined) {
718
+ effortOf(normalizedRequest) === undefined) {
553
719
  const floor = this.config.classifier?.layer2?.effortFloor ?? DEFAULT_LAYER2_EFFORT_FLOOR;
554
720
  const floorRank = EFFORT_LADDER.indexOf(floor);
555
721
  const servedEffort = EFFORT_LADDER.indexOf(initialDecision.effort) < floorRank ? floor : initialDecision.effort;
556
- normalizedRequest.reasoning_effort = servedEffort;
722
+ setEffort(normalizedRequest, servedEffort);
557
723
  initialDecision.reasonParams = {
558
724
  ...(initialDecision.reasonParams ?? {}),
559
725
  effort: servedEffort,
@@ -582,7 +748,7 @@ export class PipelineOrchestrator {
582
748
  // Directive and model-default writes re-attribute at their own sites below.
583
749
  let effortSource = clientEffort !== undefined
584
750
  ? 'client'
585
- : normalizedRequest.reasoning_effort !== undefined
751
+ : effortOf(normalizedRequest) !== undefined
586
752
  ? initialDecision.layerUsed === 'entry'
587
753
  ? 'entry'
588
754
  : 'l2-decision'
@@ -593,7 +759,7 @@ export class PipelineOrchestrator {
593
759
  // downgrade intercepted, pin honored)
594
760
  // - 'explicit' : a client-authored choice — a named model OR a forced
595
761
  // tier (tier aliases / the global mode lever /
596
- // router_options.force_tier). Turn recorded, a higher
762
+ // router_options.forceTier). Turn recorded, a higher
597
763
  // proposal still escalates the ceiling, but the session
598
764
  // NEVER rewrites the proposal and the pin is neither
599
765
  // read nor followed — a forced lite must serve lite even
@@ -602,26 +768,26 @@ export class PipelineOrchestrator {
602
768
  // composition IS the decision
603
769
  const sessionMode = comboId
604
770
  ? 'bypass'
605
- : explicitModel || normalizedRequest.router_options?.force_tier
771
+ : explicitModel || normalizedRequest.routerOptions?.forceTier
606
772
  ? 'explicit'
607
773
  : 'ratchet';
608
774
  let decision;
609
775
  let ratchetApplied = false;
610
- let sessionTurnCount;
776
+ let sessionRequestCount;
611
777
  if (sessionMode === 'bypass') {
612
- decision = { ...initialDecision, sessionId, sessionRatchetApplied: false, sessionLookupType: sessionResolve.lookupType };
778
+ decision = { ...initialDecision, sessionId, sessionRatchetApplied: false, sessionLookupType: preResolvedSession.lookupType };
613
779
  // Bypass never mints a session entity, so getSession reads undefined
614
780
  // every turn and stamped every combo request #1 in the console's
615
781
  // request-detail table. Dedicated counter instead — display-only
616
782
  // bookkeeping, no pin/tier state (ADR-0002).
617
- sessionTurnCount = this.sessionManager.recordBypassTurn(sessionId);
783
+ sessionRequestCount = this.sessionManager.recordBypassTurn(sessionId);
618
784
  }
619
785
  else {
620
786
  const ratchetResult = this.sessionManager.applyRatchet(sessionId, initialDecision,
621
787
  // Tier representative for session bookkeeping (pin birth). An
622
788
  // explicitly named model IS the representative of its own turn —
623
789
  // consulting the pool for it would hard-throw in a pool-less
624
- // deployment where every registered model is unclassified, even
790
+ // deployment where no member list claims any registered model, even
625
791
  // though the request itself is directly callable by design. Bare
626
792
  // `auto` keeps resolving through the pool (its empty-pool throw is
627
793
  // the honest "add tier members" answer).
@@ -629,17 +795,67 @@ export class PipelineOrchestrator {
629
795
  decision = ratchetResult.finalDecision;
630
796
  decision.sessionId = sessionId;
631
797
  decision.sessionRatchetApplied = ratchetResult.ratchetApplied;
632
- decision.sessionLookupType = sessionResolve.lookupType;
798
+ decision.sessionLookupType = preResolvedSession.lookupType;
633
799
  ratchetApplied = ratchetResult.ratchetApplied;
634
- sessionTurnCount = ratchetResult.session.turnCount;
800
+ sessionRequestCount = ratchetResult.session.requestCount;
635
801
  }
802
+ // Traces already recorded for this session (this turn's trace is written
803
+ // in step 8). Read once: the birth title is re-stamped from them, and the
804
+ // per-turn prompt summary needs the previous message count.
805
+ const prevTraces = this.traceTracker.getTracesBySession(sessionId);
806
+ // Envelope resolution inputs (display only): the harness vocabulary scoped
807
+ // from this request's User-Agent and any self-declared prompt. Headers come
808
+ // from whichever transport owns the leg — same precedence as the trace
809
+ // identity below (Fastify request, MITM client request, plain headers) —
810
+ // and the result is resolved ONCE here for the title, the per-turn summary
811
+ // and the route snippet.
812
+ const envelopeHints = envelopeHintsOf((context?.fastifyRequest?.headers ??
813
+ context?.clientRequest?.headers ??
814
+ context?.headers));
815
+ // Session title: the FIRST user message carrying human text, flattened and
816
+ // capped like the capture preview (array content is joined, never dropped —
817
+ // a multimodal opening message must still name the session). Client
818
+ // metadata envelopes are skipped, not quoted: Cursor's agent opens with a
819
+ // standalone `<timestamp>` message or a whole `<user_info>`/`<rules>`/…
820
+ // context bundle, which would otherwise title the session with a clock
821
+ // reading or an OS banner; Claude Code MIXES `<system-reminder>` + a
822
+ // `/clear` record with the human prompt in ONE message (see
823
+ // utils/client-envelope.ts for the four rules and
824
+ // utils/harness-profiles.ts for the scoped vocabulary). Strict runs
825
+ // first so an unrecognized envelope never outranks a later human turn in
826
+ // the same request; only when the whole request carries no recognized
827
+ // human text does the permissive pass keep a tag-only message (a prompt
828
+ // that is itself markup) rather than naming the session nothing. Once
829
+ // written, every later turn copies the birth value verbatim, so the trace
830
+ // ring can evict the birth trace without blanking the console title.
831
+ // Written to two places from this ONE value: the live entity
832
+ // (attachOrigin, below) and the trace (step 8) — a row rebuilt from traces
833
+ // alone has no entity at all.
834
+ const firstUserSummary =
835
+ // A declared prompt (layer 0) is authoritative and outranks inference on
836
+ // every later turn too — but the frozen birth value still wins, because
837
+ // the title is a birth attribute.
838
+ prevTraces[0]?.request.firstUserSummary ??
839
+ envelopeHints.declaredPrompt ??
840
+ (() => {
841
+ const userTexts = [];
842
+ for (const item of normalizedRequest.input) {
843
+ if (item.type !== 'message' || item.role !== 'user')
844
+ continue;
845
+ const raw = messageText(item);
846
+ if (raw)
847
+ userTexts.push(raw);
848
+ }
849
+ // Strict-then-permissive pass lives in the normalizer, shared with the
850
+ // capture-session preview (one derivation, three surfaces).
851
+ return firstDisplayText(userTexts, DISPLAY_CAP_CHARS, { profile: envelopeHints.profile });
852
+ })();
636
853
  // Birth metadata: attach once per session (first-write-wins inside the
637
854
  // manager), recording the inbound wire, the layer that resolved the id,
638
- // the client ip and a first-message snippet for UI identification.
855
+ // the client ip and the first-message snippet for UI identification.
639
856
  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);
857
+ if (bornSession && bornSession.requestCount === 1) {
858
+ this.sessionManager.attachOrigin(sessionId, { wire: context?.wire, lookupType: preResolvedSession.lookupType }, context?.clientIp, firstUserSummary);
643
859
  }
644
860
  // 4A. Directives (`<prefix>tier-up` / `<prefix>tier-down`, ADR-0011
645
861
  // rewrite) — TIER axis. Deliberately
@@ -742,18 +958,18 @@ export class PipelineOrchestrator {
742
958
  // (removed from config.models; the unresolvable-pin / zombie case,
743
959
  // which pre-fix silently re-fell back through the getModelForTier
744
960
  // head below every turn without ever writing the pin back), it reads
745
- // `unclassified` (removed from every tier member list / no glob
746
- // claims it any more), or the global denylist (tiers.exclude) vetoes
747
- // it. A model MOVED to another tier is NOT evicted: the new tier's
748
- // member list claims it, so it still joins that pool (multi-membership
749
- // included — eviction fires only when NO pool claims the id).
750
- // Hand-configured models (no tierMatch) are reclassification-immune —
751
- // member-list edits never evict them; only the denylist or a registry
961
+ // `unclaimed` (no tier member list claims it any more), or the global
962
+ // denylist (tiers.exclude) vetoes it. A model MOVED to another tier is
963
+ // NOT evicted: the new tier's member list claims it, so it still joins
964
+ // that pool (multi-membership included — eviction fires only when NO
965
+ // pool claims the id).
966
+ // Hand-configured models (no autoTier stamp) never move
967
+ // — member-list edits never evict them; only the denylist or a registry
752
968
  // removal can. Checked with healthyOnly=false so health never
753
969
  // masquerades as config intent (and vice versa below).
754
970
  // 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
971
+ // registry.modelHealthView): evict ONLY at 'unavailable' — every
972
+ // credential tuple out of service
757
973
  // as hard-OPEN / credential-SUSPECT / operator-DISABLED, so a full
758
974
  // credential takedown evicts the pin even though the model stays
759
975
  // configured. PARTIAL disablement is not eviction: the credential
@@ -770,7 +986,7 @@ export class PipelineOrchestrator {
770
986
  // session on a model that cannot serve now.
771
987
  const configEvicted = pinnedId !== undefined &&
772
988
  (preferredModel === null ||
773
- !this.registry.getCandidateModelsForTier(preferredModel.tier, false).some((m) => m.id === pinnedId));
989
+ !this.poolOfHomedModel(preferredModel).some((m) => m.id === pinnedId));
774
990
  const healthEvicted = preferredModel !== null && this.registry.modelHealthView(preferredModel) === 'unavailable';
775
991
  if (pinnedId && (configEvicted || healthEvicted)) {
776
992
  const healthyReplacement = this.registry.getModelForTier(actualTier, true);
@@ -802,12 +1018,12 @@ export class PipelineOrchestrator {
802
1018
  // prefix exists in the new provider's chain (prefer continuity —
803
1019
  // same key material, same cache economics), and otherwise treats it
804
1020
  // as stale and re-spreads with a FORCED rebind persisted after the
805
- // first success. Explicitly rebinding here to the new chain head
1021
+ // first success. Explicitly rebinding here to the new default credential
806
1022
  // would pick an credential the model was never verified against.
807
1023
  }
808
1024
  }
809
1025
  }
810
- else if (sessionMode === 'explicit' && !explicitModel && normalizedRequest.router_options?.force_tier) {
1026
+ else if (sessionMode === 'explicit' && !explicitModel && normalizedRequest.routerOptions?.forceTier) {
811
1027
  // Forced-tier turn (ADR-0014): the session pin is followed ONLY when it
812
1028
  // lives in the forced tier — then following is pure KV affinity (the
813
1029
  // pin IS a model of the tier the client forced, so serving it cannot
@@ -818,18 +1034,25 @@ export class PipelineOrchestrator {
818
1034
  const pinnedId = this.sessionManager.getSession(sessionId)?.pinnedModel;
819
1035
  preferredModel = pinnedId ? this.registry.getModel(pinnedId) ?? null : null;
820
1036
  // Follow gates: a same-tier pin (pure KV affinity — serving it cannot
821
- // cross the contract), the EMPTY-tier degraded landing (the pin IS the
822
- // model getModelForTier degrades to), or a zombie id (repair to the
823
- // forced tier's healthy head). Anything else — a pin in another tier
1037
+ // cross the contract), a pin with NO home tier (nothing to compare
1038
+ // against, so the affinity argument does not apply and eviction decides
1039
+ // its fate), the EMPTY-tier degraded landing (the pin IS the model
1040
+ // getModelForTier degrades to), or a zombie id (repair to the forced
1041
+ // tier's healthy head). Anything else — a pin homed in another tier
824
1042
  // while the forced pool has members — is neither followed nor
825
1043
  // rewritten (ADR-0014).
826
1044
  const tierPool = this.registry.getCandidateModelsForTier(actualTier, false);
827
1045
  const degradeLanding = preferredModel !== null &&
828
1046
  tierPool.length === 0 &&
829
1047
  this.registry.getModelForTier(actualTier).id === preferredModel.id;
830
- if (pinnedId && (preferredModel === null || preferredModel.tier === actualTier || degradeLanding)) {
1048
+ const unhomed = preferredModel !== null && preferredModel.tier === undefined;
1049
+ if (pinnedId &&
1050
+ (preferredModel === null ||
1051
+ unhomed ||
1052
+ preferredModel.tier === actualTier ||
1053
+ degradeLanding)) {
831
1054
  const configEvicted = preferredModel === null ||
832
- !this.registry.getCandidateModelsForTier(preferredModel.tier, false).some((m) => m.id === pinnedId);
1055
+ !this.poolOfHomedModel(preferredModel).some((m) => m.id === pinnedId);
833
1056
  const healthEvicted = preferredModel !== null && this.registry.modelHealthView(preferredModel) === 'unavailable';
834
1057
  if (configEvicted || healthEvicted) {
835
1058
  const healthyReplacement = this.registry.getModelForTier(actualTier, true);
@@ -856,7 +1079,7 @@ export class PipelineOrchestrator {
856
1079
  // resolution must not consult the tier pool when the request already
857
1080
  // carries its own model: a combo is the sanctioned way to address
858
1081
  // pool-less models, and an explicitly named model stays directly
859
- // callable by design — when every registered model is unclassified the
1082
+ // callable by design — when no member list claims any registered model the
860
1083
  // tier lookup hard-throws and would kill both (and the placeholder is
861
1084
  // overwritten by the executed member after the pool run regardless).
862
1085
  // The combo's first resolved member is the honestest combo placeholder;
@@ -883,8 +1106,24 @@ export class PipelineOrchestrator {
883
1106
  // selected model declares a default → pin it as the requested level so
884
1107
  // every downstream step (effort matching, payload thinking block,
885
1108
  // X-OCR-Thinking-* observability) treats it as a normal request.
886
- if (normalizedRequest.reasoning_effort === undefined && actualModel.defaultEffort) {
887
- normalizedRequest.reasoning_effort = actualModel.defaultEffort;
1109
+ // A native token budget (Anthropic `thinking.budget_tokens`, Responses
1110
+ // `reasoning.max_tokens`) has no OpenAI-chat spelling. On wires without a
1111
+ // native budget field, translate it to the equivalent ladder level BEFORE
1112
+ // the default pin / effort matching below, so capability clamps and the
1113
+ // X-OCR-Thinking-* headers see it; the budget itself stays on the request
1114
+ // for wires that consume it natively.
1115
+ const servedWire = actualModel.wire ?? 'openai-chat';
1116
+ const budgetTokens = normalizedRequest.reasoning?.budgetTokens;
1117
+ if (effortOf(normalizedRequest) === undefined &&
1118
+ typeof budgetTokens === 'number' &&
1119
+ budgetTokens > 0 &&
1120
+ servedWire !== 'anthropic-messages' &&
1121
+ servedWire !== 'google-gemini' &&
1122
+ servedWire !== 'openai-responses') {
1123
+ setEffort(normalizedRequest, effortFromThinkingBudget(budgetTokens));
1124
+ }
1125
+ if (effortOf(normalizedRequest) === undefined && actualModel.defaultEffort) {
1126
+ setEffort(normalizedRequest, actualModel.defaultEffort);
888
1127
  effortSource = 'default'; // ADR-0012: the model pin owns the ask
889
1128
  }
890
1129
  // Effort directives (`<prefix>effort-up` / `<prefix>effort-down`,
@@ -897,15 +1136,23 @@ export class PipelineOrchestrator {
897
1136
  // model pick can honour a raised level. Per-turn: it writes the request
898
1137
  // for this call only and never records session state.
899
1138
  if (directivesApplicable) {
900
- const supportedEfforts = actualModel.supportedReasoningEfforts
901
- ?? (actualModel.supportsReasoningEffort ? EFFORT_LADDER : undefined);
902
- const before = normalizedRequest.reasoning_effort;
903
- const effortDirective = applyEffortDirectives(directiveActions, before, supportedEfforts);
1139
+ // An EXPLICIT empty support set (a toggle model: `[]` from
1140
+ // effortLadderFor) must stay `[]` here — applyEffortDirectives reads it
1141
+ // as "no level control, directives are a no-op". modelSupportsEfforts
1142
+ // collapses `[]` to undefined (the registry's "cannot serve a mapped
1143
+ // level" rule), which would silently re-enable directives on toggle
1144
+ // models, so the empty declaration is preserved before the resolution.
1145
+ const declared = actualModel.supportedReasoningEfforts;
1146
+ const supportedEfforts = declared && declared.length === 0
1147
+ ? declared
1148
+ : modelSupportsEfforts(declared, actualModel.supportsReasoningEffort, actualModel.reasoningDisableable);
1149
+ const before = effortOf(normalizedRequest);
1150
+ const effortDirective = applyEffortDirectives(directiveActions, before, supportedEfforts, actualModel.reasoningDisableable === false);
904
1151
  if (effortDirective.applied) {
905
1152
  const suffix = effortDirective.suffix ?? (effortDirective.delta > 0 ? 'effort-up' : 'effort-down');
906
1153
  const token = `${directivePrefix}${suffix}`;
907
1154
  if (effortDirective.changed && effortDirective.effort) {
908
- normalizedRequest.reasoning_effort = effortDirective.effort;
1155
+ setEffort(normalizedRequest, effortDirective.effort);
909
1156
  effortSource = 'directive'; // the user's own instruction owns the ask
910
1157
  decision.reasonParams = {
911
1158
  ...(decision.reasonParams ?? {}),
@@ -953,7 +1200,7 @@ export class PipelineOrchestrator {
953
1200
  });
954
1201
  }
955
1202
  }
956
- const requestedEffort = normalizedRequest.reasoning_effort;
1203
+ const requestedEffort = effortOf(normalizedRequest);
957
1204
  let actualEffort;
958
1205
  let reasoningDegraded = false;
959
1206
  const effortPick = (() => {
@@ -982,29 +1229,34 @@ export class PipelineOrchestrator {
982
1229
  // Write the resolved effort back so provider builders construct the
983
1230
  // correct upstream payload (Anthropic budget_tokens, Gemini
984
1231
  // thinkingBudget, Responses thinkingEffort, etc.).
985
- if (actualEffort !== requestedEffort) {
986
- normalizedRequest.reasoning_effort = actualEffort;
1232
+ if (actualEffort !== undefined && actualEffort !== requestedEffort) {
1233
+ setEffort(normalizedRequest, actualEffort);
987
1234
  }
988
1235
  }
989
1236
  else if (preferredModel) {
990
1237
  // Explicit model choice / session pin: never re-route, but translate by
991
1238
  // the model's pool effortMap first (none included), then clamp to what
992
1239
  // it can serve and write back the truth.
1240
+ const supported = modelSupportsEfforts(preferredModel.supportedReasoningEfforts, preferredModel.supportsReasoningEffort, preferredModel.reasoningDisableable) ?? [];
1241
+ const alwaysThink = preferredModel.reasoningDisableable === false;
1242
+ // ADR-0035: an always-think model with a declared ladder never serves
1243
+ // `none`, even for an explicit none ask or an effortMap→none translation.
1244
+ const forbidsNone = alwaysThink && supported.length > 0;
993
1245
  const target = applyEffortMap(this.registry.effortMapFor(preferredModel, actualTier), requestedEffort ?? 'none');
994
- if (target === 'none') {
1246
+ if (target === 'none' && !forbidsNone) {
995
1247
  actualEffort = requestedEffort; // nothing in play — mirror exactly
996
1248
  }
997
1249
  else {
998
- const supported = preferredModel.supportedReasoningEfforts
999
- ?? (preferredModel.supportsReasoningEffort
1000
- ? EFFORT_LADDER
1001
- : []);
1002
- const recomputed = downgradeReasoning(target, supported);
1250
+ let recomputed = downgradeReasoning(target, supported, alwaysThink);
1251
+ // Same contradictory-data rule as resolveServedEffort: an empty resolved
1252
+ // ladder on an always-think model never rewrites to the forbidden `none`.
1253
+ if (recomputed === 'none' && alwaysThink && supported.length === 0)
1254
+ recomputed = target;
1003
1255
  actualEffort = recomputed;
1004
1256
  reasoningDegraded =
1005
1257
  EFFORT_LADDER.indexOf(recomputed) < EFFORT_LADDER.indexOf(requestedEffort ?? 'none');
1006
1258
  if (recomputed !== requestedEffort) {
1007
- normalizedRequest.reasoning_effort = recomputed;
1259
+ setEffort(normalizedRequest, recomputed);
1008
1260
  }
1009
1261
  }
1010
1262
  }
@@ -1029,6 +1281,15 @@ export class PipelineOrchestrator {
1029
1281
  // the final answer (no re-assertion follows), so it streams exactly like
1030
1282
  // the direct path and stamps timing the same way.
1031
1283
  let poolTiming = undefined;
1284
+ // Upstream transport of the SERVED attempt (registry-reported; ADR-0008
1285
+ // §1). Buffered by construction on the cascade's lite lead (it is never
1286
+ // given a relay) and whenever `streaming.upstream.mode` is `buffered`.
1287
+ let upstreamStream = undefined;
1288
+ // Outbound egress of the SERVED attempt (ADR-0018). Resolved at the dial
1289
+ // (see executeCandidatePool), never at trace time — the proxy config
1290
+ // hot-applies, so a read after a long stream can describe a different
1291
+ // dial. undefined = unknown (plugin transport / mock), never direct.
1292
+ let servedEgress = undefined;
1032
1293
  // 5. Execution with Cascading Fallback & Schema Assertion
1033
1294
  // (lite-lead cascade is skipped for explicit model choices, combos AND
1034
1295
  // forced tiers — the client named exactly what to run. A forced tier is
@@ -1040,10 +1301,10 @@ export class PipelineOrchestrator {
1040
1301
  const tierCrossPolicy = retryConfig?.failover?.tierCrossPolicy ?? 'allow_escalate';
1041
1302
  if (decision.needsSchemaValidation &&
1042
1303
  this.config.fallback.enabled &&
1043
- !request.router_options?.disable_fallback &&
1304
+ !request.routerOptions?.disableFallback &&
1044
1305
  !explicitModel &&
1045
1306
  !comboId &&
1046
- !normalizedRequest.router_options?.force_tier) {
1307
+ !normalizedRequest.routerOptions?.forceTier) {
1047
1308
  // 5A: Lite Tier lead - Deploy Lite Tier first with resilience
1048
1309
  const litePool = this.registry.getCandidateModelsForTier('lite', true);
1049
1310
  const liteResult = await this.executeCandidatePool(normalizedRequest, {
@@ -1060,9 +1321,9 @@ export class PipelineOrchestrator {
1060
1321
  let assertionError = '';
1061
1322
  if (liteResult.success && liteResult.response) {
1062
1323
  liteRes = liteResult.response;
1063
- const content = liteRes.choices[0]?.message?.content || '';
1324
+ const content = responseMessageText(liteRes);
1064
1325
  // Local static AST / Schema assertion (Zero extra LLM cost!)
1065
- const validation = SchemaAssertion.validate(content, normalizedRequest.response_format);
1326
+ const validation = SchemaAssertion.validate(content, normalizedRequest.text?.format);
1066
1327
  if (validation.valid) {
1067
1328
  assertionPassed = true;
1068
1329
  finalResponse = liteRes;
@@ -1072,7 +1333,7 @@ export class PipelineOrchestrator {
1072
1333
  // may have served a model whose translation/capability differs from
1073
1334
  // the tier-pick prediction (helper: map → clamp → mirror).
1074
1335
  {
1075
- const r = this.resolveServedEffort(actualModel, requestedEffort, actualTier);
1336
+ const r = this.resolveServedEffort(actualModel, requestedEffort, actualTier, budgetTokens);
1076
1337
  actualEffort = r.actualEffort;
1077
1338
  reasoningDegraded = r.degraded;
1078
1339
  }
@@ -1081,6 +1342,8 @@ export class PipelineOrchestrator {
1081
1342
  failoverPath = liteResult.failoverPath;
1082
1343
  inplaceRetries += liteResult.inplaceRetries;
1083
1344
  servedCredentialPrefix = liteResult.servedCredentialPrefix;
1345
+ upstreamStream = liteResult.transport;
1346
+ servedEgress = liteResult.egress;
1084
1347
  }
1085
1348
  else {
1086
1349
  assertionError = validation.error || 'Schema validation assertion failed';
@@ -1094,7 +1357,7 @@ export class PipelineOrchestrator {
1094
1357
  fallbackOccurred = true;
1095
1358
  fallbackReason = assertionError;
1096
1359
  const escalateTier = this.config.fallback.escalateTier || 'plus';
1097
- const failedContent = liteRes?.choices[0]?.message?.content || '';
1360
+ const failedContent = responseMessageText(liteRes);
1098
1361
  const fallbackReq = FallbackContextBuilder.buildEscalationRequest(normalizedRequest, failedContent, assertionError, escalateTier);
1099
1362
  const plusResult = await this.executeCandidatePool(fallbackReq, {
1100
1363
  chain: this.registry.getCandidateModelsForTier(escalateTier, true),
@@ -1106,13 +1369,13 @@ export class PipelineOrchestrator {
1106
1369
  sessionId,
1107
1370
  // The escalation response is final (no re-assertion below), so it
1108
1371
  // streams under the same commit-point contract as the direct path.
1109
- relay: this.config.streaming?.enabled === false ? undefined : relay,
1372
+ relay,
1110
1373
  streamRouting: {
1111
1374
  layerUsed: decision.layerUsed || 'layer0',
1112
1375
  sessionId,
1113
1376
  sessionRatchetApplied: ratchetApplied,
1114
- sessionLookupType: sessionResolve.lookupType,
1115
- traceId: traceId ?? 'unknown',
1377
+ sessionLookupType: preResolvedSession.lookupType,
1378
+ requestId,
1116
1379
  requestedEffort,
1117
1380
  variantUsed,
1118
1381
  },
@@ -1121,7 +1384,15 @@ export class PipelineOrchestrator {
1121
1384
  if (plusResult.policyDenied) {
1122
1385
  throw Object.assign(new Error(`API key model policy denies every '${escalateTier}' candidate model for fallback`), { statusCode: 403 });
1123
1386
  }
1124
- throw plusResult.lastError || new Error(`Plus escalation failed for tier '${escalateTier}'`);
1387
+ const escErr = plusResult.lastError;
1388
+ if (escErr instanceof IrUnsupportedError)
1389
+ throw escErr;
1390
+ const accessPolicy = context?.modelAccess;
1391
+ const escRemaining = this.registry
1392
+ .getCandidateModelsForTier(escalateTier, true)
1393
+ .filter((m) => !plusResult.failoverPath.includes(m.id) &&
1394
+ (!accessPolicy || isModelAllowedInTiers(m.id, accessPolicy, this.registry.tiersOf(m))));
1395
+ throw routeExhaustedError(`escalation tier '${escalateTier}'`, plusResult.failoverPath, escErr, escRemaining);
1125
1396
  }
1126
1397
  finalResponse = plusResult.response;
1127
1398
  actualTier = escalateTier;
@@ -1129,7 +1400,7 @@ export class PipelineOrchestrator {
1129
1400
  // Recompute effort against the actually-served model (same contract
1130
1401
  // as the direct path).
1131
1402
  {
1132
- const r = this.resolveServedEffort(actualModel, requestedEffort, actualTier);
1403
+ const r = this.resolveServedEffort(actualModel, requestedEffort, actualTier, budgetTokens);
1133
1404
  actualEffort = r.actualEffort;
1134
1405
  reasoningDegraded = r.degraded;
1135
1406
  }
@@ -1139,6 +1410,8 @@ export class PipelineOrchestrator {
1139
1410
  inplaceRetries += plusResult.inplaceRetries;
1140
1411
  servedCredentialPrefix = plusResult.servedCredentialPrefix;
1141
1412
  poolTiming = plusResult.timing;
1413
+ upstreamStream = plusResult.transport;
1414
+ servedEgress = plusResult.egress;
1142
1415
  }
1143
1416
  }
1144
1417
  else {
@@ -1167,45 +1440,64 @@ export class PipelineOrchestrator {
1167
1440
  accessTierMode = 'member-home';
1168
1441
  }
1169
1442
  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
- }
1443
+ // Explicit: the named model serves — the chain is [explicitModel] ONLY.
1444
+ // Cross-model substitution of a named model is a fidelity breach (the
1445
+ // OpenAI wire serves the named model or errors); in-place same-model
1446
+ // retry and credential re-spread stay unconditional. A client that
1447
+ // WANTS substitution opts in per request via router_options.failover.
1448
+ const explicitFailover = explicitModel && normalizedRequest.routerOptions?.failover === true;
1198
1449
  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;
1450
+ if (explicitModel && !explicitFailover) {
1451
+ // The named model IS the contract: a one-model chain, no
1452
+ // substitution (ADR-0014). No pool is built at all — nothing to
1453
+ // fail over to.
1454
+ chain = [explicitModel];
1455
+ attemptCap = 1;
1456
+ }
1457
+ else {
1458
+ // Auto (or an explicit request that opted in via
1459
+ // router_options.failover): the tier pool (peek-filtered; fall back
1460
+ // to the full pool when everything is tripped — the loop force-tries
1461
+ // the last candidate) follows the head, so KV-cache affinity is
1462
+ // preserved on the first candidate.
1463
+ let pool = this.registry.getCandidateModelsForTier(actualTier, true);
1464
+ if (pool.length === 0)
1465
+ pool = this.registry.getCandidateModelsForTier(actualTier, false);
1466
+ // Bare-auto under a model-access policy: the classifier may land in a
1467
+ // tier that holds no admissible model (allow: none whitelisted in that
1468
+ // tier; deny: every model of that tier tier-denied) — widen the pool
1469
+ // to every allowed model across tiers (chosen tier first, then by
1470
+ // tier proximity) instead of failing with a policy 403. "auto"
1471
+ // promises SOME allowed model, not a specific tier.
1472
+ const accessPolicy = context?.modelAccess;
1473
+ const isBareAuto = !normalizedRequest.model || normalizedRequest.model === 'auto';
1474
+ if (accessPolicy && isBareAuto && !explicitModel && !comboId) {
1475
+ const rank = TIER_RANK;
1476
+ // A model with no home tier ranks BELOW every pool tier — it serves
1477
+ // from no pool, so "closest tier" is meaningless; it sorts last
1478
+ // rather than being silently ranked as `plus`.
1479
+ const rankOf = (m) => (m.tier ? rank[m.tier] : undefined) ?? Number.MAX_SAFE_INTEGER;
1480
+ // Multi-membership admit: allowed when the id or ANY membership
1481
+ // tier passes (allow mode); denied when the id or ANY membership
1482
+ // tier is denied (deny mode).
1483
+ const widened = this.registry
1484
+ .getAllModels()
1485
+ .filter((m) => isModelAllowedInTiers(m.id, accessPolicy, this.registry.tiersOf(m)))
1486
+ .sort((a, b) => Math.abs(rankOf(a) - (rank[actualTier] ?? 9)) - Math.abs(rankOf(b) - (rank[actualTier] ?? 9)) ||
1487
+ rankOf(a) - rankOf(b));
1488
+ if (widened.length > 0)
1489
+ pool = widened;
1490
+ }
1491
+ chain = head ? [head, ...pool.filter(m => m.id !== head.id)] : pool;
1492
+ // Auto keeps the configured failover budget; an explicit opt-in is
1493
+ // bounded by its own chain length (failover.maxAttempts governs
1494
+ // auto routing only). Cross-tier escalation is an AUTO-routing
1495
+ // policy — forced tiers never escape their tier.
1496
+ attemptCap = explicitModel ? Math.max(1, chain.length) : maxFailoverCandidates;
1497
+ }
1206
1498
  allowEscalate =
1207
1499
  !explicitModel &&
1208
- !normalizedRequest.router_options?.force_tier &&
1500
+ !normalizedRequest.routerOptions?.forceTier &&
1209
1501
  tierCrossPolicy === 'allow_escalate' &&
1210
1502
  actualTier === 'lite';
1211
1503
  }
@@ -1225,13 +1517,13 @@ export class PipelineOrchestrator {
1225
1517
  // the full `message.content` before its verdict, and that verdict can
1226
1518
  // re-ask the whole turn on a bigger tier — relaying it would commit
1227
1519
  // output the cascade is about to throw away.
1228
- relay: this.config.streaming?.enabled === false ? undefined : relay,
1520
+ relay,
1229
1521
  streamRouting: {
1230
1522
  layerUsed: decision.layerUsed || 'layer0',
1231
1523
  sessionId,
1232
1524
  sessionRatchetApplied: ratchetApplied,
1233
- sessionLookupType: sessionResolve.lookupType,
1234
- traceId: traceId ?? 'unknown',
1525
+ sessionLookupType: preResolvedSession.lookupType,
1526
+ requestId,
1235
1527
  requestedEffort,
1236
1528
  variantUsed,
1237
1529
  },
@@ -1240,18 +1532,57 @@ export class PipelineOrchestrator {
1240
1532
  if (execResult.policyDenied) {
1241
1533
  throw Object.assign(new Error(`API key model policy (${context?.modelAccess?.mode}) admits no candidate model for this request`), { statusCode: 403 });
1242
1534
  }
1243
- throw execResult.lastError || new Error(`Execution failed for tier '${actualTier}'`);
1535
+ if (explicitModel && chain.length === 1) {
1536
+ // An explicit chain that exhausted without a substitute (failover
1537
+ // off — the default) must fail LOUD and name the model: the client
1538
+ // asked for exactly this model and deserves to know it did not
1539
+ // serve, not a generic tier-level message (mirrors policyDenied).
1540
+ const lastErr = execResult.lastError;
1541
+ const unsupported = lastErr instanceof IrUnsupportedError;
1542
+ 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'}`), {
1543
+ statusCode: statusCodeOf(lastErr) ?? 502,
1544
+ ...(unsupported ? { name: 'IrUnsupportedError', code: 'unsupported_parameter' } : {}),
1545
+ });
1546
+ }
1547
+ // Pool exhausted with a non-policy failure. The upstream verdict is
1548
+ // the GATEWAY's routing state, never the client's problem: agent
1549
+ // clients auto-retry 429 but hard-stop on 402, so a forwarded
1550
+ // "insufficient balance" wastes models that are still healthy.
1551
+ // Two gateway-authored shapes:
1552
+ // - untried healthy models remain → 429: the client's own backoff
1553
+ // retry re-peeks the pool and lands on one of them, no user
1554
+ // action needed (only routing-fixable classes remap — a 400 is
1555
+ // the request's fault and retries cannot fix it);
1556
+ // - every candidate is cooling down → keep the truthful status,
1557
+ // say what the operator must do (console breaker panel /
1558
+ // credentials).
1559
+ // Remaining = the executed CHAIN (covers combo member lists that span
1560
+ // tiers, where a tier-peek would read the wrong pool) minus the
1561
+ // attempted path, gated by the non-consuming per-model breaker peek —
1562
+ // so trips that happened during this very run are counted — and by
1563
+ // the key's model-access policy, which the pool filter applied
1564
+ // inside executeCandidatePool.
1565
+ const lastErr = execResult.lastError;
1566
+ if (lastErr instanceof IrUnsupportedError)
1567
+ throw lastErr;
1568
+ const accessPolicy = context?.modelAccess;
1569
+ const remaining = chain.filter((m) => !execResult.failoverPath.includes(m.id) &&
1570
+ this.getCircuitBreakerManager().isAvailable(m.id) &&
1571
+ (!accessPolicy || isModelAllowedInTiers(m.id, accessPolicy, this.registry.tiersOf(m))));
1572
+ throw routeExhaustedError(comboId ? `combo '${comboId}'` : `tier '${actualTier}'`, execResult.failoverPath, lastErr, remaining);
1244
1573
  }
1245
1574
  finalResponse = execResult.response;
1246
1575
  actualModel = execResult.modelUsed;
1247
1576
  actualTier = execResult.tierUsed;
1248
1577
  poolTiming = execResult.timing;
1578
+ upstreamStream = execResult.transport;
1579
+ servedEgress = execResult.egress;
1249
1580
  // Recompute `actualEffort` against the model that ACTUALLY served the
1250
1581
  // request — failover may have shifted to a different model than the
1251
1582
  // one `pickModelForEffort` originally picked, with a different effort
1252
1583
  // translation/ceiling. The header / ExecutionResult must reflect reality.
1253
1584
  {
1254
- const r = this.resolveServedEffort(actualModel, requestedEffort, actualTier);
1585
+ const r = this.resolveServedEffort(actualModel, requestedEffort, actualTier, budgetTokens);
1255
1586
  actualEffort = r.actualEffort;
1256
1587
  reasoningDegraded = r.degraded;
1257
1588
  }
@@ -1284,7 +1615,7 @@ export class PipelineOrchestrator {
1284
1615
  // persisted the bind/rebind right after the successful call (this point
1285
1616
  // would only ever see a still-unbound session when no multi-credential chain
1286
1617
  // was in play — nothing to bind).
1287
- this.sessionManager.registerCompletedTurn(sessionId, fingerprintMessages, finalResponse.choices[0]?.message ?? '');
1618
+ this.sessionManager.registerCompletedTurn(sessionId, fingerprintItems, finalResponse.output);
1288
1619
  // 7. Post-turn observability
1289
1620
  const latencyMs = Date.now() - startTime;
1290
1621
  // Streaming decode timing (industry TTFT/TPS split), from the committed
@@ -1296,6 +1627,12 @@ export class PipelineOrchestrator {
1296
1627
  // execution, relay off, or a relay whose wire had no streaming executor).
1297
1628
  const ttftMs = poolTiming ? poolTiming.firstChunkAt - startTime : undefined;
1298
1629
  const genMs = poolTiming ? poolTiming.streamEndAt - poolTiming.firstChunkAt : undefined;
1630
+ // Perceived stall ratio numerator: total time the committed stream spent
1631
+ // frozen in gaps of ≥ PERCEIVED_STALL_MS. Carried straight through —
1632
+ // measured, not derived, so there is no second definition to drift from.
1633
+ // The session divides the summed value by its summed decode windows
1634
+ // (stallRatio).
1635
+ const stalledMs = poolTiming?.stalledMs;
1299
1636
  // Thinking-level observability. Two cases that warrant a warn:
1300
1637
  // 1. Client asked for thinking but the actually-served model can't do
1301
1638
  // thinking at all — payload builder silently dropped the fields.
@@ -1308,12 +1645,11 @@ export class PipelineOrchestrator {
1308
1645
  // `'none'` is a real effort value meaning "no thinking" — NOT a request
1309
1646
  // for thinking that the model failed to honor. An omitted field is also
1310
1647
  // 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);
1648
+ const servedEffort = effortOf(normalizedRequest);
1649
+ const wantsThinking = (servedEffort != null && servedEffort !== 'none') ||
1650
+ (typeof budgetTokens === 'number' && budgetTokens > 0);
1314
1651
  // 5-level default: `none` is a client toggle, not a capability.
1315
- const modelEfforts = actualModel.supportedReasoningEfforts
1316
- ?? (actualModel.supportsReasoningEffort ? EFFORT_LADDER : []);
1652
+ const modelEfforts = modelSupportsEfforts(actualModel.supportedReasoningEfforts, actualModel.supportsReasoningEffort, actualModel.reasoningDisableable) ?? [];
1317
1653
  const supportsAnyThinking = modelEfforts.some((e) => e !== 'none');
1318
1654
  // Both warn paths go through the dedup + rate-limit warn throttle: at
1319
1655
  // QPS a misconfigured pool would otherwise print one warn per request.
@@ -1323,8 +1659,8 @@ export class PipelineOrchestrator {
1323
1659
  // without becoming noise.
1324
1660
  const throttle = getWarnThrottle();
1325
1661
  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) — ` +
1662
+ const key = `no-capability|${actualModel.id}|${actualModel.wire ?? 'openai-chat'}`;
1663
+ throttle.warn(key, `[ocr] thinking-level request served by '${actualModel.id}' (${actualModel.wire ?? 'openai-chat'} wire) — ` +
1328
1664
  `model has no thinking-effort capability, thinking controls were silently dropped.`);
1329
1665
  }
1330
1666
  if (reasoningDegraded &&
@@ -1339,14 +1675,15 @@ export class PipelineOrchestrator {
1339
1675
  `served '${actualEffort}' on model '${actualModel.id}' (gap=${gap} levels, ` +
1340
1676
  `model supports [${modelEfforts.join(', ') || 'none'}])`);
1341
1677
  }
1342
- const cachedTokens = PromptOptimizer.extractCachedTokens(finalResponse.usage);
1678
+ const usage = finalResponse.usage;
1679
+ const cachedTokens = PromptOptimizer.extractCachedTokens(usage);
1343
1680
  this.tracker.record({
1344
1681
  tier: actualTier,
1345
1682
  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,
1683
+ inputTokens: usage.inputTokens,
1684
+ cachedTokens,
1685
+ outputTokens: usage.outputTokens,
1686
+ reasoningTokens: usage.reasoningTokens ?? 0,
1350
1687
  latencyMs,
1351
1688
  });
1352
1689
  // 7b. Sliding-window accounting (ratelimit engine). A completed
@@ -1354,19 +1691,18 @@ export class PipelineOrchestrator {
1354
1691
  // only path that produces usage, and the request slots were already
1355
1692
  // consumed at the gates (inbound: auth preHandler, outbound: dispatch
1356
1693
  // 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.
1694
+ // Cached tokens are included in input; reasoning tokens in output.
1359
1695
  const rlUsage = {
1360
- tokens: (finalResponse.usage?.prompt_tokens || 0) + (finalResponse.usage?.completion_tokens || 0),
1361
- costUsd: computeRequestCost(finalResponse.usage, actualModel.pricing),
1696
+ tokens: usage.inputTokens + usage.outputTokens,
1697
+ costUsd: computeRequestCost(usage, actualModel.pricing),
1362
1698
  };
1363
1699
  let usageCredentialPrefix;
1364
1700
  {
1365
1701
  const rl = getRateLimiter();
1366
- const clientKeyId = captureKeyIdentity(context?.fastifyRequest)?.id;
1702
+ const clientKeyId = keyIdentityOf(context)?.id;
1367
1703
  if (clientKeyId)
1368
1704
  rl.recordUsage(apiKeySubject(clientKeyId), rlUsage);
1369
- // The credential that SERVED (same chain-head degeneracy as the pool gate,
1705
+ // The credential that SERVED (same default-credential degeneracy as the pool gate,
1370
1706
  // so single-credential providers carry usage too). `servedUsagePrefix`
1371
1707
  // also feeds the trace record below (execution.credentialKeyHashPrefix):
1372
1708
  // one credential attribution, two consumers (ratelimit subject + quota
@@ -1393,7 +1729,17 @@ export class PipelineOrchestrator {
1393
1729
  effort: actualEffort,
1394
1730
  source: 'l2_confident',
1395
1731
  confidence: decision.confidence,
1396
- snippet: routeGate.snippetEnabled === false ? undefined : lastUserText ? lastUserText.slice(0, 200) : undefined, // same 200-char display-aid precedent as session attachOrigin
1732
+ // Display aid only: client metadata envelopes (Cursor's
1733
+ // `<timestamp>`, Claude Code's `<system-reminder>`) are dropped so
1734
+ // the snippet names the prompt, not a clock reading or harness
1735
+ // boilerplate — same 200-char display-aid precedent as the session
1736
+ // attachOrigin, same harness profile as the title.
1737
+ snippet: routeGate.snippetEnabled === false
1738
+ ? undefined
1739
+ : (envelopeHints.declaredPrompt ??
1740
+ (lastUserText
1741
+ ? clipDisplayText(displayPromptText(lastUserText, { profile: envelopeHints.profile })) || undefined
1742
+ : undefined)),
1397
1743
  }, sessionId);
1398
1744
  appendRoutingLedger({
1399
1745
  kind: 'entry_write',
@@ -1403,63 +1749,47 @@ export class PipelineOrchestrator {
1403
1749
  });
1404
1750
  }
1405
1751
  }
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
- }
1752
+ // 8. Session Trajectory Recording. The record is keyed by its own
1753
+ // `requestId` (ADR-0021); the caller's `clientRequestId` is stored beside
1754
+ // it as correlation only, because a caller may reuse one value for every
1755
+ // request of a conversation.
1756
+ // Display-only prompt text. The write-time boundary decides whether this
1757
+ // request opened a turn; a tool-result continuation carries the previous
1758
+ // prompt in its history and must not render a duplicate header. Text is
1759
+ // never consulted to DECIDE that boundary — `isPromptStart` is.
1760
+ const lastUserTextForSummary = messageText(lastUserMessage(normalizedRequest.input));
1761
+ const userPromptSummary = requestTurn.isPromptStart
1762
+ ? (envelopeHints.declaredPrompt ??
1763
+ clipDisplayText(displayPromptText(lastUserTextForSummary, { profile: envelopeHints.profile })))
1764
+ : '';
1448
1765
  this.traceTracker.record({
1449
- traceId: sharedTraceId,
1766
+ requestId,
1767
+ ...(clientRequestId ? { clientRequestId } : {}),
1450
1768
  sessionId,
1451
- turnNumber: sessionTurnCount,
1769
+ requestNumber: sessionRequestCount,
1770
+ turnIndex: requestTurn.turnIndex,
1771
+ isPromptStart: requestTurn.isPromptStart,
1772
+ turnDecision: requestTurn.turnDecision,
1452
1773
  timestamp: startTime,
1453
1774
  // Key attribution on the lightweight session trajectory as well (works
1454
1775
  // even with capture disabled): which application's key drove this turn.
1455
- apiKey: captureKeyIdentity(context?.fastifyRequest),
1776
+ apiKey: keyIdentityOf(context),
1456
1777
  request: {
1457
1778
  model: request.model || 'auto',
1458
1779
  userPromptSummary,
1459
- messageCount: normalizedRequest.messages.length,
1460
- hasSystemPrompt: normalizedRequest.messages.some(m => m.role === 'system'),
1461
- hasToolsOrSchema: Boolean(decision.needsSchemaValidation),
1780
+ ...(firstUserSummary ? { firstUserSummary } : {}),
1781
+ messageCount: normalizedRequest.input.length,
1782
+ hasSystemPrompt: Boolean(normalizedRequest.instructions)
1783
+ || normalizedRequest.input.some((item) => item.type === 'message' && (item.role === 'system' || item.role === 'developer')),
1784
+ hasToolsOrSchema: hasToolsOrSchema(normalizedRequest),
1785
+ // Response shape actually written to the client (surface-owned: the
1786
+ // C-3-normalized ask, or `client.mode: always` forcing SSE).
1787
+ clientStream: context?.clientStream === true,
1788
+ // Inbound protocol surface the client addressed (chat / anthropic /
1789
+ // responses) — the console's protocol column reads it directly.
1790
+ inboundWire: context?.wire,
1462
1791
  clientHeaders: extractClientHeaders(context?.headers),
1792
+ ...(clientRef ? { clientRef } : {}),
1463
1793
  },
1464
1794
  routing: {
1465
1795
  layerUsed: (decision.layerUsed || 'layer0'),
@@ -1469,7 +1799,7 @@ export class PipelineOrchestrator {
1469
1799
  reasonCode: decision.reasonCode,
1470
1800
  reasonParams: decision.reasonParams,
1471
1801
  sessionRatchetApplied: ratchetApplied,
1472
- sessionLookupType: sessionResolve.lookupType,
1802
+ sessionLookupType: preResolvedSession.lookupType,
1473
1803
  },
1474
1804
  execution: {
1475
1805
  modelUsed: actualModel.id,
@@ -1477,9 +1807,26 @@ export class PipelineOrchestrator {
1477
1807
  credentialKeyHashPrefix: usageCredentialPrefix,
1478
1808
  tierUsed: actualTier,
1479
1809
  latencyMs,
1810
+ // OUTBOUND protocol wire the served attempt ran on (distinct from the
1811
+ // inbound surface unless the turn is a passthrough).
1812
+ wireKind: actualModel.wire,
1480
1813
  ttftMs,
1481
1814
  genMs,
1815
+ stalledMs,
1482
1816
  fallbackOccurred,
1817
+ // Provider-leg transport of the served attempt — the OUTBOUND stream
1818
+ // tag (ADR-0008 §1). 'sse' with clientStream:false is the accumulate
1819
+ // mode: the gateway read a stream and answered in JSON.
1820
+ upstreamStream,
1821
+ // Outbound egress of the served attempt (ADR-0018 vocabulary), as
1822
+ // resolved at the dial. Absent = unknown (legacy row / plugin-owned
1823
+ // transport / mock), never read as direct.
1824
+ ...(servedEgress
1825
+ ? {
1826
+ egress: servedEgress.mode,
1827
+ ...(servedEgress.mode === 'proxy' ? { egressProxy: servedEgress.origin } : {}),
1828
+ }
1829
+ : {}),
1483
1830
  fallbackReason,
1484
1831
  failoverOccurred,
1485
1832
  failoverAttempts,
@@ -1495,13 +1842,13 @@ export class PipelineOrchestrator {
1495
1842
  effortSource,
1496
1843
  },
1497
1844
  finops: {
1498
- inputTokens: finalResponse.usage?.prompt_tokens || 0,
1499
- outputTokens: finalResponse.usage?.completion_tokens || 0,
1500
- cachedTokens: cachedTokens,
1845
+ inputTokens: usage.inputTokens,
1846
+ outputTokens: usage.outputTokens,
1847
+ cachedTokens,
1501
1848
  costUsd: rlUsage.costUsd,
1502
1849
  },
1503
1850
  });
1504
- const breakerState = cbManager.getBreaker(actualModel.id)?.getState() || 'CLOSED';
1851
+ const breakerState = cbManager.getSnapshot(actualModel.id)?.state ?? 'CLOSED';
1505
1852
  // additive keys only — older readers keep reading
1506
1853
  // breakerState alone: when the turn ran in pair mode, expose the serving
1507
1854
  // credential's pair snapshot and the model's availability aggregate.
@@ -1512,6 +1859,7 @@ export class PipelineOrchestrator {
1512
1859
  tierUsed: actualTier,
1513
1860
  modelUsed: actualModel.id,
1514
1861
  layerUsed: decision.layerUsed || 'layer0',
1862
+ protocolUsed: protocolForWire(actualModel.wire ?? 'openai-chat'),
1515
1863
  fallbackOccurred,
1516
1864
  fallbackReason,
1517
1865
  failoverOccurred,
@@ -1524,9 +1872,14 @@ export class PipelineOrchestrator {
1524
1872
  modelAvailability,
1525
1873
  sessionId,
1526
1874
  sessionRatchetApplied: ratchetApplied,
1527
- sessionLookupType: sessionResolve.lookupType,
1528
- traceId: sharedTraceId,
1875
+ sessionLookupType: preResolvedSession.lookupType,
1876
+ requestId,
1529
1877
  latencyMs,
1878
+ ttftMs,
1879
+ genMs,
1880
+ stalledMs,
1881
+ clientStream: context?.clientStream === true,
1882
+ upstreamStream,
1530
1883
  // Reasoning-effort observability — server.ts reads these to set
1531
1884
  // X-OCR-Thinking-{Requested,Actual,Degraded} headers so the client
1532
1885
  // can see whether they got the level they asked for.
@@ -1547,13 +1900,36 @@ export class PipelineOrchestrator {
1547
1900
  * value against what the client asked (`undefined` / `'none'` count as the
1548
1901
  * none level).
1549
1902
  */
1550
- resolveServedEffort(model, requestedEffort, servedTier) {
1551
- const ask = requestedEffort ?? 'none';
1903
+ wireConsumesBudgetNatively(wire) {
1904
+ return wire === 'anthropic-messages' || wire === 'google-gemini' || wire === 'openai-responses';
1905
+ }
1906
+ resolveServedEffort(model, requestedEffort, servedTier, budgetTokens) {
1907
+ const effectiveRequested = requestedEffort ??
1908
+ (typeof budgetTokens === 'number' && budgetTokens > 0 && !this.wireConsumesBudgetNatively(model.wire)
1909
+ ? effortFromThinkingBudget(budgetTokens)
1910
+ : undefined);
1911
+ const ask = effectiveRequested ?? 'none';
1552
1912
  const target = applyEffortMap(this.registry.effortMapFor(model, servedTier), ask);
1553
- if (target === 'none' && ask === 'none')
1554
- return { actualEffort: requestedEffort, degraded: false };
1555
- const supported = model.supportedReasoningEfforts ?? (model.supportsReasoningEffort ? EFFORT_LADDER : []);
1556
- const actual = target === 'none' ? 'none' : downgradeReasoning(target, supported);
1913
+ const supported = modelSupportsEfforts(model.supportedReasoningEfforts, model.supportsReasoningEffort, model.reasoningDisableable) ?? [];
1914
+ const alwaysThink = model.reasoningDisableable === false;
1915
+ // ADR-0035 absolute withholding: an always-think model with a declared
1916
+ // ladder can NEVER serve `none` — not even for an explicit client none-ask
1917
+ // or an effortMap that translates to none. It clamps to its lowest rung.
1918
+ const forbidsNone = alwaysThink && supported.length > 0;
1919
+ if (target === 'none' && ask === 'none' && !forbidsNone)
1920
+ return { actualEffort: effectiveRequested, degraded: false };
1921
+ // `downgradeReasoning` carries the always-think floor: a below-floor ask on
1922
+ // a model whose vendor forbids thinking-off serves its lowest declared rung,
1923
+ // never the `none` that earns a 400 (ADR-0035).
1924
+ let actual = target === 'none' && !forbidsNone ? 'none' : downgradeReasoning(target, supported, alwaysThink);
1925
+ // Contradictory data: the vendor says always-think but the resolved ladder
1926
+ // is EMPTY (e.g. an operator override of only `none`, stripped to []).
1927
+ // There is no declared rung to clamp to; minting `none` would write the
1928
+ // forbidden thinking-off. Mirror the ask instead and let the vendor's own
1929
+ // wire-side clamp / replay be the net — never rewrite to `none` here.
1930
+ if (actual === 'none' && alwaysThink && supported.length === 0) {
1931
+ actual = ask;
1932
+ }
1557
1933
  return {
1558
1934
  actualEffort: actual,
1559
1935
  degraded: EFFORT_LADDER.indexOf(actual) < EFFORT_LADDER.indexOf(ask),
@@ -1582,7 +1958,8 @@ export class PipelineOrchestrator {
1582
1958
  * rejection costs nothing upstream — when the whole chain is down this is
1583
1959
  * the last-resort attempt). `attemptCap` bounds real attempts: the
1584
1960
  * configured retry.failover.maxAttempts for auto routing, the full chain
1585
- * length for explicit/combo chains.
1961
+ * length for opt-in/combo chains (an explicit model's chain is ONE — it
1962
+ * is never substituted).
1586
1963
  *
1587
1964
  * Breaker gate: canExecuteScoped() here is the ONLY probe-consuming check in
1588
1965
  * the request path — every selection/filtering site uses the non-consuming
@@ -1612,7 +1989,11 @@ export class PipelineOrchestrator {
1612
1989
  // Each entry carries its ACCESS tier (pool tier vs member home tier, see
1613
1990
  // accessTierMode) and the effort translation that applies to it — a model
1614
1991
  // holding membership in several tiers translates per serving pool.
1615
- const accessTierOf = (m) => opts.accessTierMode === 'member-home' ? m.tier : tier;
1992
+ // `member-home` on a model with NO home tier (it serves from no pool)
1993
+ // falls back to the EXECUTION tier: the candidate is being tried from
1994
+ // this chain, so this chain's tier is the only tier that truthfully
1995
+ // describes the attempt.
1996
+ const accessTierOf = (m) => opts.accessTierMode === 'member-home' ? (m.tier ?? tier) : tier;
1616
1997
  let candidateList = opts.chain.map((m) => ({
1617
1998
  model: m,
1618
1999
  accessTier: accessTierOf(m),
@@ -1704,7 +2085,7 @@ export class PipelineOrchestrator {
1704
2085
  }
1705
2086
  // Outbound sliding-window gate (`credentials:` overlay) — evaluated BEFORE the
1706
2087
  // 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
2088
+ // The default credential stands in when the selector degenerated (single-credential
1708
2089
  // / sessionless paths — the head IS the boot-baked credential registry.execute
1709
2090
  // serves with, registry invariant), so caps fire on one-key providers too.
1710
2091
  // NON-CONSUMING peek: the request slot is taken below only when the call
@@ -1799,22 +2180,58 @@ export class PipelineOrchestrator {
1799
2180
  // byte-identical request when nothing is in play).
1800
2181
  let candidateReq = request;
1801
2182
  {
1802
- const ask = opts.requestedEffort ?? 'none';
2183
+ const budgetAsk = opts.requestedEffort === undefined &&
2184
+ typeof request.reasoning?.budgetTokens === 'number' &&
2185
+ request.reasoning.budgetTokens > 0 &&
2186
+ !this.wireConsumesBudgetNatively(candidate.wire)
2187
+ ? effortFromThinkingBudget(request.reasoning.budgetTokens)
2188
+ : undefined;
2189
+ const ask = opts.requestedEffort ?? budgetAsk ?? 'none';
1803
2190
  const target = applyEffortMap(candidateEffortMap, ask);
1804
- if (!(target === 'none' && ask === 'none')) {
1805
- const supported = candidate.supportedReasoningEfforts ?? (candidate.supportsReasoningEffort ? EFFORT_LADDER : []);
1806
- const candidateEffort = target === 'none' ? 'none' : downgradeReasoning(target, supported);
1807
- if (candidateEffort !== request.reasoning_effort) {
1808
- candidateReq = { ...request, reasoning_effort: candidateEffort };
2191
+ const supported = modelSupportsEfforts(candidate.supportedReasoningEfforts, candidate.supportsReasoningEffort, candidate.reasoningDisableable) ?? [];
2192
+ const candidateAlwaysThink = candidate.reasoningDisableable === false;
2193
+ // ADR-0035: an always-think model with a declared ladder never serves
2194
+ // `none` — the rewire must run even for an explicit none ask so the
2195
+ // upstream payload carries the clamped rung, not the forbidden none.
2196
+ const forbidsNone = candidateAlwaysThink && supported.length > 0;
2197
+ if (!(target === 'none' && ask === 'none') || forbidsNone) {
2198
+ let candidateEffort = target === 'none' && !forbidsNone ? 'none' : downgradeReasoning(target, supported, candidateAlwaysThink);
2199
+ if (candidateEffort === 'none' && candidateAlwaysThink && supported.length === 0) {
2200
+ candidateEffort = ask;
2201
+ }
2202
+ if (candidateEffort !== effortOf(request)) {
2203
+ candidateReq = {
2204
+ ...request,
2205
+ reasoning: { ...request.reasoning, effort: candidateEffort },
2206
+ };
1809
2207
  }
1810
2208
  }
1811
2209
  }
2210
+ // On cross-protocol failover candidates, strip non-portable reasoning
2211
+ // signatures / encrypted blobs so long multi-turn threads can still fail over
2212
+ // to Chat-only upstreams instead of failing with 400 on the backup model.
2213
+ if (failoverAttempts > 1 &&
2214
+ !capabilitiesFor(protocolForWire(candidate.wire ?? 'openai-chat')).reasoningSignature &&
2215
+ candidateReq.input.some((item) => item.type === 'reasoning' && (item.signature !== undefined || item.encrypted !== undefined))) {
2216
+ const strippedInput = candidateReq.input.flatMap((item) => {
2217
+ if (item.type !== 'reasoning' || (item.signature === undefined && item.encrypted === undefined))
2218
+ return [item];
2219
+ const { signature: _sig, encrypted: _enc, ...rest } = item;
2220
+ return rest.text || rest.summary ? [rest] : [];
2221
+ });
2222
+ candidateReq = { ...candidateReq, input: strippedInput };
2223
+ }
1812
2224
  // Stage this attempt's routing facts BEFORE the call: a relay that gets
1813
2225
  // bytes flushes them with the first forwarded chunk, and only an attempt
1814
2226
  // that actually proceeds can commit any (earlier attempts never got that
1815
2227
  // far, and each later attempt simply overwrites the staged set).
1816
2228
  if (opts.relay) {
1817
- opts.relay.stageRouting({ ...opts.streamRouting, modelUsed: candidate.id, tierUsed: candidateAccessTier });
2229
+ opts.relay.stageRouting({
2230
+ ...opts.streamRouting,
2231
+ modelUsed: candidate.id,
2232
+ tierUsed: candidateAccessTier,
2233
+ protocolUsed: protocolForWire(candidate.wire ?? 'openai-chat'),
2234
+ });
1818
2235
  }
1819
2236
  // In-place retry loop on the SAME candidate model
1820
2237
  let candidateSucceeded = false;
@@ -1830,12 +2247,46 @@ export class PipelineOrchestrator {
1830
2247
  // bytes-to-client boundary).
1831
2248
  let firstChunkAt;
1832
2249
  let streamEndAt;
2250
+ // Perceived stall bookkeeping: the stream's own cadence, not its
2251
+ // average. Only chunks that carry VISIBLE output advance `lastVisibleAt`
2252
+ // — answer text, tool-call fragments AND reasoning/thinking deltas (all
2253
+ // forwarded to the client). A role-only opener, a finish_reason frame or
2254
+ // the trailing usage frame produces nothing on the user's screen, so
2255
+ // treating them as progress would hide exactly the pause this metric
2256
+ // exists to catch — and counting thinking as silence would invent one.
2257
+ // Every gap ≥ PERCEIVED_STALL_MS is ADDED UP: the session-level figure
2258
+ // is a share of the decode window, which keeps repeated stutters and one
2259
+ // long freeze on the same scale (a single maximum cannot).
2260
+ let lastVisibleAt;
2261
+ let stalledMs;
2262
+ // Transport the served attempt actually used (registry-reported, once
2263
+ // per attempt). Reset per attempt: a retry re-issues with a fresh tag.
2264
+ let transport;
2265
+ // Outbound egress resolved at THIS attempt's dial (AttemptEgress).
2266
+ let attemptEgress;
1833
2267
  const timingRelay = opts.relay
1834
2268
  ? {
1835
2269
  stageRouting: (facts) => opts.relay.stageRouting(facts),
2270
+ onTransport: (kind) => {
2271
+ transport = kind;
2272
+ opts.relay.onTransport?.(kind);
2273
+ },
1836
2274
  onChunk: (chunk) => {
1837
- firstChunkAt ??= Date.now();
1838
- opts.relay.onChunk(chunk);
2275
+ const now = Date.now();
2276
+ firstChunkAt ??= now;
2277
+ if (hasVisibleOutput(chunk)) {
2278
+ if (lastVisibleAt !== undefined) {
2279
+ const gap = now - lastVisibleAt;
2280
+ // The first measured gap proves this turn HAS a stream
2281
+ // cadence: 0 means "measured and smooth", undefined stays
2282
+ // reserved for fewer than two output chunks.
2283
+ stalledMs ??= 0;
2284
+ if (gap >= PERCEIVED_STALL_MS)
2285
+ stalledMs += gap;
2286
+ }
2287
+ lastVisibleAt = now;
2288
+ }
2289
+ return opts.relay.onChunk(chunk);
1839
2290
  },
1840
2291
  get committed() {
1841
2292
  return opts.relay.committed;
@@ -1844,7 +2295,10 @@ export class PipelineOrchestrator {
1844
2295
  : undefined;
1845
2296
  for (let attempt = 0; attempt <= maxInplaceAttempts; attempt++) {
1846
2297
  try {
1847
- candidateResponse = await this.registry.execute(candidateReq, candidate, upstreamEventContext, credentialPrefix, timingRelay);
2298
+ // Resolve egress at the dial: the proxy config hot-applies, so a
2299
+ // read at trace time could describe a different dial than this one.
2300
+ attemptEgress = this.registry.egressFor(candidate);
2301
+ candidateResponse = await this.registry.execute(candidateReq, candidate, upstreamEventContext, credentialPrefix, timingRelay, opts.sessionId);
1848
2302
  if (firstChunkAt !== undefined)
1849
2303
  streamEndAt = Date.now();
1850
2304
  // Scope-aware success: undefined prefix degenerates to the exact
@@ -1856,11 +2310,42 @@ export class PipelineOrchestrator {
1856
2310
  catch (err) {
1857
2311
  lastError = err;
1858
2312
  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);
2313
+ // Breaker accounting is per logical request, NOT per in-place
2314
+ // attempt: a retried attempt that eventually succeeds leaves no
2315
+ // failure on the breaker, and an abandoned candidate records
2316
+ // exactly one failure. Counting every attempt let a single request
2317
+ // burn the whole trip threshold by itself (retry amplification).
2318
+ // The final attempt's diagnosis is the one recorded — it carries
2319
+ // the same registry-stamped usedCredentialKeyHashPrefix
2320
+ // (tripScope + credentialSuspect + usedKeyHashPrefix); the manager
2321
+ // attributes from `credentialPrefix` OR that stamp, so a
2322
+ // credential-fault error cools its credential even when selection
2323
+ // returned no prefix (all-unhealthy / no-session): the manager then
2324
+ // attributes from the diagnosis stamp itself. Only a chain-less
2325
+ // provider (no stamp at all) stays on the sentinel tuple.
2326
+ // A committed attempt can never actually in-place retry (the commit
2327
+ // check below returns first), so `committed` belongs in this
2328
+ // condition: without it a mid-stream CONNECTION_RESET on a streamed
2329
+ // turn would skip BOTH the retry and the record — zero breaker
2330
+ // evidence from clients dying mid-body on a dying upstream.
2331
+ // Single source for BOTH the recording decision above and the step-2
2332
+ // retry decision below — the committed check at the commit point
2333
+ // returns first, so the two can never disagree.
2334
+ const willRetryInPlace = diagnosis.isInPlaceRetriable && attempt < maxInplaceAttempts && !opts.relay?.committed;
2335
+ if (!willRetryInPlace) {
2336
+ cbManager.recordFailureScoped(candidate.id, diagnosis, candidate.provider, credentialPrefix, this.registry.getCredentialChain(candidate.provider)?.map((c) => c.keyHashPrefix));
2337
+ }
2338
+ // Upstream-429 feedback into the local shaping window: the provider
2339
+ // just TOLD us this credential is at-cap — feed the declared wait
2340
+ // (or a 60s default when the 429 carries no Retry-After) into the
2341
+ // rate limiter so NEW-session steering avoids this credential
2342
+ // immediately instead of re-discovering the wall. The breaker keeps
2343
+ // its own independent cooldown below; this only sharpens the peek()
2344
+ // shaping input. No ledger entry: the failure event above already
2345
+ // records the 429 fact.
2346
+ if (diagnosis.category === 'RATE_LIMITED' && limitSubject) {
2347
+ getRateLimiter().penalize(limitSubject, diagnosis.retryAfterSeconds ? diagnosis.retryAfterSeconds * 1000 : UPSTREAM_429_DEFAULT_COOLDOWN_MS);
2348
+ }
1864
2349
  // Failure-ledger emission (serving role): the attempt's classifier
1865
2350
  // verdict is in hand — record the failed call regardless of whether
1866
2351
  // a later candidate rescues the turn (failover outcome is routing;
@@ -1869,9 +2354,15 @@ export class PipelineOrchestrator {
1869
2354
  recordFailureEvent({
1870
2355
  model: candidate.id,
1871
2356
  provider: candidate.provider,
2357
+ // Pair attribution: the credential this call actually ran on — the
2358
+ // selector's prefix, else the registry stamp on the error (a
2359
+ // selection that degenerated to the default credential still attributes).
2360
+ keyHashPrefix: credentialPrefix ?? diagnosis.usedKeyHashPrefix,
1872
2361
  errorClass: diagnosis.category,
1873
2362
  status: diagnosis.statusCode,
1874
- message: err?.message ?? String(err),
2363
+ // Belt-and-suspenders: UpstreamError paths already redact, but
2364
+ // non-Upstream errors can still carry echoed secrets in message.
2365
+ message: redactUpstreamBody(err?.message ?? String(err)),
1875
2366
  role: 'serving',
1876
2367
  sessionId: opts.sessionId,
1877
2368
  });
@@ -1902,7 +2393,7 @@ export class PipelineOrchestrator {
1902
2393
  };
1903
2394
  }
1904
2395
  // 2. Can we in-place retry on the SAME candidate model to preserve KV Cache?
1905
- if (diagnosis.isInPlaceRetriable && attempt < maxInplaceAttempts) {
2396
+ if (willRetryInPlace) {
1906
2397
  let sleepMs = backoffMs + Math.random() * jitterMs;
1907
2398
  if (diagnosis.networkCause === 'RATE_LIMIT_BURST' && diagnosis.retryAfterSeconds) {
1908
2399
  sleepMs = Math.max(sleepMs, diagnosis.retryAfterSeconds * 1000);
@@ -1945,8 +2436,13 @@ export class PipelineOrchestrator {
1945
2436
  inplaceRetries: totalInplaceRetries,
1946
2437
  servedCredentialPrefix: credentialPrefix,
1947
2438
  timing: firstChunkAt !== undefined && streamEndAt !== undefined
1948
- ? { firstChunkAt, streamEndAt }
2439
+ ? { firstChunkAt, streamEndAt, stalledMs }
1949
2440
  : undefined,
2441
+ // Served-attempt transport tag. `opts.relay` absent = the executor
2442
+ // was never given a relay, so the buffered call is certain.
2443
+ transport: opts.relay ? transport : 'buffered',
2444
+ // Served-attempt egress, resolved at the dial by this pool.
2445
+ egress: attemptEgress,
1950
2446
  };
1951
2447
  }
1952
2448
  }