omnicell-router 0.8.4 → 0.10.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (363) hide show
  1. package/README.md +26 -7
  2. package/README.zh-CN.md +18 -5
  3. package/backend/dist/capture/recorder.d.ts +4 -10
  4. package/backend/dist/capture/recorder.js +6 -58
  5. package/backend/dist/cli/clients/base.d.ts +36 -11
  6. package/backend/dist/cli/clients/base.js +31 -15
  7. package/backend/dist/cli/clients/claude.d.ts +9 -0
  8. package/backend/dist/cli/clients/claude.js +6 -0
  9. package/backend/dist/cli/clients/codex.d.ts +8 -0
  10. package/backend/dist/cli/clients/codex.js +5 -0
  11. package/backend/dist/cli/clients/core-adapters.d.ts +1 -1
  12. package/backend/dist/cli/clients/core-adapters.js +1 -1
  13. package/backend/dist/cli/clients/dsh.d.ts +8 -0
  14. package/backend/dist/cli/clients/dsh.js +5 -0
  15. package/backend/dist/cli/clients/grok.d.ts +15 -1
  16. package/backend/dist/cli/clients/grok.js +16 -2
  17. package/backend/dist/cli/clients/index.d.ts +13 -1
  18. package/backend/dist/cli/clients/index.js +97 -19
  19. package/backend/dist/cli/clients/kimi.d.ts +6 -0
  20. package/backend/dist/cli/clients/kimi.js +3 -0
  21. package/backend/dist/cli/clients/launcher.d.ts +1 -1
  22. package/backend/dist/cli/clients/model-meta.js +6 -3
  23. package/backend/dist/cli/clients/omp.d.ts +6 -0
  24. package/backend/dist/cli/clients/omp.js +3 -0
  25. package/backend/dist/cli/clients/openclaw.d.ts +6 -0
  26. package/backend/dist/cli/clients/openclaw.js +3 -0
  27. package/backend/dist/cli/clients/opencode.d.ts +8 -0
  28. package/backend/dist/cli/clients/opencode.js +5 -0
  29. package/backend/dist/cli/clients/pi.d.ts +6 -0
  30. package/backend/dist/cli/clients/pi.js +3 -0
  31. package/backend/dist/cli/clients/update-check.d.ts +37 -0
  32. package/backend/dist/cli/clients/update-check.js +309 -0
  33. package/backend/dist/cli/clients/workbuddy.d.ts +19 -0
  34. package/backend/dist/cli/clients/workbuddy.js +66 -0
  35. package/backend/dist/cli/index.js +5 -4
  36. package/backend/dist/cli/paths.js +8 -0
  37. package/backend/dist/cli/types.d.ts +92 -16
  38. package/backend/dist/config/comments-en.js +31 -26
  39. package/backend/dist/config/comments-zh.js +29 -24
  40. package/backend/dist/config/defaults.d.ts +194 -33
  41. package/backend/dist/config/defaults.js +193 -32
  42. package/backend/dist/config/env.d.ts +10 -0
  43. package/backend/dist/config/env.js +3 -2
  44. package/backend/dist/config/index.d.ts +7 -0
  45. package/backend/dist/config/index.js +184 -43
  46. package/backend/dist/config/migrations/v0-to-v1.d.ts +2 -2
  47. package/backend/dist/config/migrations/v10-to-v11.d.ts +38 -0
  48. package/backend/dist/config/migrations/v10-to-v11.js +43 -0
  49. package/backend/dist/config/migrations/v6-to-v7.d.ts +45 -0
  50. package/backend/dist/config/migrations/v6-to-v7.js +97 -0
  51. package/backend/dist/config/migrations/v7-to-v8.d.ts +36 -0
  52. package/backend/dist/config/migrations/v7-to-v8.js +43 -0
  53. package/backend/dist/config/migrations/v8-to-v9.d.ts +38 -0
  54. package/backend/dist/config/migrations/v8-to-v9.js +43 -0
  55. package/backend/dist/config/migrations/v9-to-v10.d.ts +51 -0
  56. package/backend/dist/config/migrations/v9-to-v10.js +71 -0
  57. package/backend/dist/config/runtime.js +1 -1
  58. package/backend/dist/config/schema.d.ts +3 -3
  59. package/backend/dist/config/schema.js +14 -4
  60. package/backend/dist/config/types.d.ts +167 -38
  61. package/backend/dist/egress-proxy/asset-download.d.ts +54 -0
  62. package/backend/dist/egress-proxy/asset-download.js +420 -0
  63. package/backend/dist/egress-proxy/manual-node-spec.d.ts +92 -0
  64. package/backend/dist/egress-proxy/manual-node-spec.js +408 -0
  65. package/backend/dist/egress-proxy/mihomo-binary.d.ts +54 -0
  66. package/backend/dist/egress-proxy/mihomo-binary.js +278 -0
  67. package/backend/dist/egress-proxy/mihomo-client.d.ts +94 -0
  68. package/backend/dist/egress-proxy/mihomo-client.js +308 -0
  69. package/backend/dist/egress-proxy/mihomo-config.d.ts +40 -0
  70. package/backend/dist/egress-proxy/mihomo-config.js +161 -0
  71. package/backend/dist/egress-proxy/mihomo-geo.d.ts +87 -0
  72. package/backend/dist/egress-proxy/mihomo-geo.js +213 -0
  73. package/backend/dist/egress-proxy/mihomo-logs.d.ts +43 -0
  74. package/backend/dist/egress-proxy/mihomo-logs.js +84 -0
  75. package/backend/dist/egress-proxy/mihomo-pac.d.ts +37 -0
  76. package/backend/dist/egress-proxy/mihomo-pac.js +75 -0
  77. package/backend/dist/egress-proxy/mihomo-rules-import.d.ts +43 -0
  78. package/backend/dist/egress-proxy/mihomo-rules-import.js +193 -0
  79. package/backend/dist/egress-proxy/mihomo-sidecar.d.ts +81 -0
  80. package/backend/dist/egress-proxy/mihomo-sidecar.js +637 -0
  81. package/backend/dist/forward-proxy/egress.d.ts +50 -11
  82. package/backend/dist/forward-proxy/egress.js +50 -17
  83. package/backend/dist/forward-proxy/h2-forward.js +36 -10
  84. package/backend/dist/forward-proxy/index.d.ts +11 -8
  85. package/backend/dist/forward-proxy/index.js +22 -60
  86. package/backend/dist/forward-proxy/interceptor.d.ts +3 -2
  87. package/backend/dist/forward-proxy/interceptor.js +4 -4
  88. package/backend/dist/forward-proxy/relay.js +3 -3
  89. package/backend/dist/forward-proxy/rules.d.ts +4 -4
  90. package/backend/dist/forward-proxy/rules.js +25 -4
  91. package/backend/dist/forward-proxy/server.d.ts +0 -16
  92. package/backend/dist/forward-proxy/server.js +124 -156
  93. package/backend/dist/harness/host/hosts.js +3 -2
  94. package/backend/dist/index.js +53 -18
  95. package/backend/dist/ingress-proxy/access-log.d.ts +176 -0
  96. package/backend/dist/ingress-proxy/access-log.js +774 -0
  97. package/backend/dist/ingress-proxy/ca-inventory.d.ts +106 -0
  98. package/backend/dist/ingress-proxy/ca-inventory.js +525 -0
  99. package/backend/dist/ingress-proxy/ca-trust.d.ts +96 -0
  100. package/backend/dist/ingress-proxy/ca-trust.js +315 -0
  101. package/backend/dist/ingress-proxy/ca.d.ts +104 -0
  102. package/backend/dist/ingress-proxy/ca.js +273 -0
  103. package/backend/dist/ingress-proxy/data-dir.d.ts +28 -0
  104. package/backend/dist/ingress-proxy/data-dir.js +45 -0
  105. package/backend/dist/ingress-proxy/egress.d.ts +151 -0
  106. package/backend/dist/ingress-proxy/egress.js +364 -0
  107. package/backend/dist/ingress-proxy/h2-forward.d.ts +66 -0
  108. package/backend/dist/ingress-proxy/h2-forward.js +561 -0
  109. package/backend/dist/ingress-proxy/index.d.ts +24 -0
  110. package/backend/dist/ingress-proxy/index.js +144 -0
  111. package/backend/dist/ingress-proxy/interceptor.d.ts +25 -0
  112. package/backend/dist/ingress-proxy/interceptor.js +52 -0
  113. package/backend/dist/ingress-proxy/ordered-relay.d.ts +29 -0
  114. package/backend/dist/ingress-proxy/ordered-relay.js +46 -0
  115. package/backend/dist/ingress-proxy/relay.d.ts +54 -0
  116. package/backend/dist/ingress-proxy/relay.js +188 -0
  117. package/backend/dist/ingress-proxy/rules.d.ts +195 -0
  118. package/backend/dist/ingress-proxy/rules.js +348 -0
  119. package/backend/dist/ingress-proxy/server.d.ts +153 -0
  120. package/backend/dist/ingress-proxy/server.js +2065 -0
  121. package/backend/dist/ingress-proxy/sni.d.ts +35 -0
  122. package/backend/dist/ingress-proxy/sni.js +124 -0
  123. package/backend/dist/ingress-proxy/status.d.ts +32 -0
  124. package/backend/dist/ingress-proxy/status.js +15 -0
  125. package/backend/dist/ingress-proxy/system-proxy.d.ts +112 -0
  126. package/backend/dist/ingress-proxy/system-proxy.js +481 -0
  127. package/backend/dist/ingress-proxy/traffic-delete.d.ts +21 -0
  128. package/backend/dist/ingress-proxy/traffic-delete.js +64 -0
  129. package/backend/dist/ingress-proxy/traffic-delete.worker.d.ts +44 -0
  130. package/backend/dist/ingress-proxy/traffic-delete.worker.js +228 -0
  131. package/backend/dist/ingress-proxy/traffic-files.d.ts +10 -0
  132. package/backend/dist/ingress-proxy/traffic-files.js +10 -0
  133. package/backend/dist/ingress-proxy/upstream-tls.d.ts +46 -0
  134. package/backend/dist/ingress-proxy/upstream-tls.js +105 -0
  135. package/backend/dist/ingress-proxy/ws-frames.d.ts +45 -0
  136. package/backend/dist/ingress-proxy/ws-frames.js +153 -0
  137. package/backend/dist/ir/adapters/anthropic-messages-stream.js +6 -1
  138. package/backend/dist/ir/adapters/anthropic-messages.js +12 -5
  139. package/backend/dist/ir/adapters/google-gemini-stream.js +7 -2
  140. package/backend/dist/ir/adapters/google-gemini.js +5 -2
  141. package/backend/dist/ir/adapters/openai-chat-stream.js +5 -1
  142. package/backend/dist/ir/adapters/openai-chat.d.ts +25 -0
  143. package/backend/dist/ir/adapters/openai-chat.js +45 -3
  144. package/backend/dist/ir/adapters/openai-responses-output.d.ts +1 -0
  145. package/backend/dist/ir/adapters/openai-responses-output.js +67 -21
  146. package/backend/dist/ir/adapters/openai-responses-stream.d.ts +13 -0
  147. package/backend/dist/ir/adapters/openai-responses-stream.js +34 -1
  148. package/backend/dist/ir/adapters/openai-responses.d.ts +82 -24
  149. package/backend/dist/ir/adapters/openai-responses.js +146 -37
  150. package/backend/dist/ir/media.d.ts +20 -0
  151. package/backend/dist/ir/media.js +41 -0
  152. package/backend/dist/ir/tool-identity.d.ts +35 -0
  153. package/backend/dist/ir/tool-identity.js +40 -0
  154. package/backend/dist/ir/types.d.ts +9 -1
  155. package/backend/dist/local/build-jobs.d.ts +66 -0
  156. package/backend/dist/local/build-jobs.js +243 -0
  157. package/backend/dist/local/detect.d.ts +32 -0
  158. package/backend/dist/local/detect.js +145 -0
  159. package/backend/dist/local/draft-match.d.ts +58 -0
  160. package/backend/dist/local/draft-match.js +124 -0
  161. package/backend/dist/local/engine-runtime.d.ts +522 -0
  162. package/backend/dist/local/engine-runtime.js +1 -0
  163. package/backend/dist/local/engines.d.ts +241 -0
  164. package/backend/dist/local/engines.js +651 -0
  165. package/backend/dist/local/gguf.d.ts +35 -0
  166. package/backend/dist/local/gguf.js +314 -0
  167. package/backend/dist/local/hf.d.ts +120 -0
  168. package/backend/dist/local/hf.js +304 -0
  169. package/backend/dist/local/install.d.ts +90 -0
  170. package/backend/dist/local/install.js +421 -0
  171. package/backend/dist/local/llamacpp.d.ts +55 -0
  172. package/backend/dist/local/llamacpp.js +177 -0
  173. package/backend/dist/local/local-provider.d.ts +81 -0
  174. package/backend/dist/local/local-provider.js +301 -0
  175. package/backend/dist/local/machine-stats.d.ts +87 -0
  176. package/backend/dist/local/machine-stats.js +332 -0
  177. package/backend/dist/local/model-store.d.ts +347 -0
  178. package/backend/dist/local/model-store.js +1215 -0
  179. package/backend/dist/local/part-sweep.d.ts +32 -0
  180. package/backend/dist/local/part-sweep.js +156 -0
  181. package/backend/dist/local/plan.d.ts +65 -0
  182. package/backend/dist/local/plan.js +146 -0
  183. package/backend/dist/local/resources.d.ts +49 -0
  184. package/backend/dist/local/resources.js +64 -0
  185. package/backend/dist/local/run-stats.d.ts +95 -0
  186. package/backend/dist/local/run-stats.js +195 -0
  187. package/backend/dist/local/runner.d.ts +235 -0
  188. package/backend/dist/local/runner.js +1392 -0
  189. package/backend/dist/local/settings.d.ts +79 -0
  190. package/backend/dist/local/settings.js +180 -0
  191. package/backend/dist/local/strata-catalog.d.ts +30 -0
  192. package/backend/dist/local/strata-catalog.js +511 -0
  193. package/backend/dist/local/strata-drafting.d.ts +46 -0
  194. package/backend/dist/local/strata-drafting.js +265 -0
  195. package/backend/dist/local/strata.d.ts +278 -0
  196. package/backend/dist/local/strata.js +1392 -0
  197. package/backend/dist/local/tar.d.ts +20 -0
  198. package/backend/dist/local/tar.js +367 -0
  199. package/backend/dist/local/transport.d.ts +35 -0
  200. package/backend/dist/local/transport.js +89 -0
  201. package/backend/dist/local/tune.d.ts +58 -0
  202. package/backend/dist/local/tune.js +324 -0
  203. package/backend/dist/observability/http-exchange.d.ts +2 -2
  204. package/backend/dist/opencode/catalog/auto-pull.d.ts +14 -3
  205. package/backend/dist/opencode/catalog/auto-pull.js +276 -70
  206. package/backend/dist/opencode/catalog/ocr-store.js +3 -1
  207. package/backend/dist/opencode/catalog/overrides-store.d.ts +10 -1
  208. package/backend/dist/opencode/catalog/overrides-store.js +6 -0
  209. package/backend/dist/opencode/catalog/reasoning-declaration.d.ts +35 -0
  210. package/backend/dist/opencode/catalog/reasoning-declaration.js +66 -0
  211. package/backend/dist/opencode/catalog/repository.js +25 -2
  212. package/backend/dist/opencode/catalog/sources/models-dev.js +13 -3
  213. package/backend/dist/opencode/catalog/types.d.ts +35 -3
  214. package/backend/dist/opencode/catalog/types.js +38 -1
  215. package/backend/dist/opencode/credentials/ocr-store.js +11 -2
  216. package/backend/dist/opencode/credentials/sync.js +12 -3
  217. package/backend/dist/opencode/credentials/types.d.ts +31 -4
  218. package/backend/dist/opencode/credentials/types.js +25 -0
  219. package/backend/dist/opencode/probe.d.ts +21 -4
  220. package/backend/dist/opencode/probe.js +34 -10
  221. package/backend/dist/pipeline/directives.d.ts +9 -4
  222. package/backend/dist/pipeline/directives.js +14 -10
  223. package/backend/dist/pipeline/orchestrator.d.ts +42 -13
  224. package/backend/dist/pipeline/orchestrator.js +497 -165
  225. package/backend/dist/plugins/environment-ack.d.ts +51 -0
  226. package/backend/dist/plugins/environment-ack.js +81 -0
  227. package/backend/dist/plugins/gateways.d.ts +6 -6
  228. package/backend/dist/plugins/gateways.js +2 -2
  229. package/backend/dist/plugins/host.d.ts +98 -14
  230. package/backend/dist/plugins/host.js +622 -87
  231. package/backend/dist/plugins/install-run.d.ts +27 -0
  232. package/backend/dist/plugins/install-run.js +99 -0
  233. package/backend/dist/plugins/manifest.d.ts +84 -32
  234. package/backend/dist/plugins/manifest.js +149 -45
  235. package/backend/dist/plugins/market-install.d.ts +18 -0
  236. package/backend/dist/plugins/market-install.js +111 -0
  237. package/backend/dist/plugins/market-source.d.ts +100 -0
  238. package/backend/dist/plugins/market-source.js +449 -0
  239. package/backend/dist/plugins/market-updates.d.ts +70 -0
  240. package/backend/dist/plugins/market-updates.js +97 -0
  241. package/backend/dist/plugins/market.d.ts +677 -0
  242. package/backend/dist/plugins/market.js +2113 -0
  243. package/backend/dist/plugins/source-index.d.ts +155 -0
  244. package/backend/dist/plugins/source-index.js +217 -0
  245. package/backend/dist/plugins/types.d.ts +402 -37
  246. package/backend/dist/projects/worktrees.d.ts +88 -0
  247. package/backend/dist/projects/worktrees.js +220 -0
  248. package/backend/dist/providers/boot-direct.d.ts +41 -7
  249. package/backend/dist/providers/boot-direct.js +252 -36
  250. package/backend/dist/providers/compat/tool-markup-recovery.js +31 -6
  251. package/backend/dist/providers/executors/dispatch.d.ts +17 -7
  252. package/backend/dist/providers/executors/dispatch.js +28 -9
  253. package/backend/dist/providers/executors/openai-chat.js +14 -2
  254. package/backend/dist/providers/executors/plugin-adapter.d.ts +23 -1
  255. package/backend/dist/providers/executors/plugin-adapter.js +59 -3
  256. package/backend/dist/providers/member-match.d.ts +32 -9
  257. package/backend/dist/providers/member-match.js +65 -21
  258. package/backend/dist/providers/model-resolution.d.ts +62 -0
  259. package/backend/dist/providers/model-resolution.js +62 -0
  260. package/backend/dist/providers/price-order.d.ts +51 -0
  261. package/backend/dist/providers/price-order.js +54 -0
  262. package/backend/dist/providers/provider-takedown.d.ts +5 -2
  263. package/backend/dist/providers/registry.d.ts +84 -25
  264. package/backend/dist/providers/registry.js +209 -114
  265. package/backend/dist/providers/selection.d.ts +91 -0
  266. package/backend/dist/providers/selection.js +158 -0
  267. package/backend/dist/providers/virtual-meta.d.ts +33 -2
  268. package/backend/dist/providers/virtual-meta.js +74 -18
  269. package/backend/dist/quota/cli-login.d.ts +25 -4
  270. package/backend/dist/quota/cli-login.js +35 -5
  271. package/backend/dist/quota/coverage-generation.d.ts +24 -0
  272. package/backend/dist/quota/coverage-generation.js +29 -0
  273. package/backend/dist/quota/declarations.js +8 -4
  274. package/backend/dist/quota/engine.js +2 -2
  275. package/backend/dist/quota/prober.d.ts +43 -2
  276. package/backend/dist/quota/prober.js +97 -22
  277. package/backend/dist/ratelimit/rate-limiter.d.ts +1 -1
  278. package/backend/dist/resilience/error-classifier.js +29 -0
  279. package/backend/dist/router/index.d.ts +1 -1
  280. package/backend/dist/router/index.js +17 -1
  281. package/backend/dist/router/layer2-decision.d.ts +1 -1
  282. package/backend/dist/router/layer2-decision.js +2 -2
  283. package/backend/dist/routes/console.js +928 -310
  284. package/backend/dist/routes/environments.js +1 -1
  285. package/backend/dist/routes/local-models.d.ts +2 -0
  286. package/backend/dist/routes/local-models.js +1414 -0
  287. package/backend/dist/routes/mihomo.d.ts +2 -2
  288. package/backend/dist/routes/mihomo.js +20 -11
  289. package/backend/dist/routes/projects.js +121 -0
  290. package/backend/dist/server.js +318 -13
  291. package/backend/dist/session/session-manager.d.ts +42 -5
  292. package/backend/dist/session/session-manager.js +64 -11
  293. package/backend/dist/session/session-row.d.ts +29 -8
  294. package/backend/dist/session/session-row.js +18 -13
  295. package/backend/dist/snapshot/bundle.d.ts +40 -0
  296. package/backend/dist/snapshot/bundle.js +177 -0
  297. package/backend/dist/snapshot/handoff/compress.d.ts +46 -0
  298. package/backend/dist/snapshot/handoff/compress.js +77 -0
  299. package/backend/dist/snapshot/handoff/index.d.ts +119 -0
  300. package/backend/dist/snapshot/handoff/index.js +160 -0
  301. package/backend/dist/snapshot/handoff/jsonl-writer.d.ts +78 -0
  302. package/backend/dist/snapshot/handoff/jsonl-writer.js +175 -0
  303. package/backend/dist/snapshot/handoff/opencode-writer.d.ts +51 -0
  304. package/backend/dist/snapshot/handoff/opencode-writer.js +214 -0
  305. package/backend/dist/snapshot/handoff/summarize.d.ts +39 -0
  306. package/backend/dist/snapshot/handoff/summarize.js +118 -0
  307. package/backend/dist/snapshot/handoff/transcript.d.ts +71 -0
  308. package/backend/dist/snapshot/handoff/transcript.js +167 -0
  309. package/backend/dist/snapshot/media-fs.d.ts +10 -0
  310. package/backend/dist/snapshot/media-fs.js +50 -0
  311. package/backend/dist/snapshot/media.d.ts +32 -0
  312. package/backend/dist/snapshot/media.js +87 -0
  313. package/backend/dist/snapshot/store.d.ts +226 -0
  314. package/backend/dist/snapshot/store.js +887 -0
  315. package/backend/dist/snapshot/tree.d.ts +112 -0
  316. package/backend/dist/snapshot/tree.js +207 -0
  317. package/backend/dist/snapshot/types.d.ts +212 -0
  318. package/backend/dist/snapshot/types.js +14 -0
  319. package/backend/dist/snapshot/view.d.ts +19 -0
  320. package/backend/dist/snapshot/view.js +57 -0
  321. package/backend/dist/snapshot/write-worker.d.ts +67 -0
  322. package/backend/dist/snapshot/write-worker.js +129 -0
  323. package/backend/dist/surfaces/body-admission.d.ts +67 -2
  324. package/backend/dist/surfaces/body-admission.js +218 -13
  325. package/backend/dist/surfaces/chat-pipeline.js +8 -0
  326. package/backend/dist/surfaces/decision-pipeline.js +10 -7
  327. package/backend/dist/surfaces/gateway-catalog.d.ts +26 -0
  328. package/backend/dist/surfaces/gateway-catalog.js +202 -0
  329. package/backend/dist/surfaces/gateway-chat.d.ts +7 -11
  330. package/backend/dist/surfaces/gateway-chat.js +50 -12
  331. package/backend/dist/surfaces/ocr-headers.d.ts +6 -4
  332. package/backend/dist/surfaces/ocr-headers.js +11 -7
  333. package/backend/dist/surfaces/systemone.js +1 -1
  334. package/backend/dist/surfaces/transport-fastify.js +32 -5
  335. package/backend/dist/surfaces/transport-node-http.d.ts +9 -3
  336. package/backend/dist/surfaces/transport-node-http.js +6 -19
  337. package/backend/dist/surfaces/types.d.ts +11 -3
  338. package/backend/dist/trace/persist.js +21 -1
  339. package/backend/dist/trace/tracker.d.ts +35 -3
  340. package/backend/dist/trace/tracker.js +23 -0
  341. package/backend/dist/types/openai.d.ts +8 -0
  342. package/backend/dist/types/router.d.ts +17 -6
  343. package/backend/dist/types/router.js +14 -2
  344. package/backend/dist/utils/client-families.d.ts +66 -0
  345. package/backend/dist/utils/client-families.js +127 -0
  346. package/backend/dist/utils/event-ring.d.ts +1 -1
  347. package/backend/dist/utils/event-ring.js +1 -1
  348. package/backend/dist/utils/proxy-node.js +1 -1
  349. package/backend/dist/utils/proxy.d.ts +135 -11
  350. package/backend/dist/utils/proxy.js +144 -29
  351. package/backend/dist/utils/run-command.d.ts +21 -1
  352. package/backend/dist/utils/run-command.js +64 -4
  353. package/backend/dist/utils/server-liveness.d.ts +3 -2
  354. package/backend/dist/utils/server-liveness.js +3 -2
  355. package/backend/dist/utils/session-file.d.ts +28 -0
  356. package/backend/dist/utils/session-file.js +34 -0
  357. package/frontend/dist/assets/antigravity.color-DXFfVr6X.svg +39 -0
  358. package/frontend/dist/assets/gemini-cli.color-BfquLd1p.svg +1 -0
  359. package/frontend/dist/assets/index-CTZNvn1d.js +1707 -0
  360. package/frontend/dist/assets/{index-KI1OW5x6.css → index-CqDSOPQ0.css} +1 -1
  361. package/frontend/dist/index.html +2 -2
  362. package/package.json +3 -1
  363. package/frontend/dist/assets/index-Dk76uc7e.js +0 -1522
@@ -1,5 +1,5 @@
1
1
  import path from 'node:path';
2
- import { EFFORT_LADDER, TIER_RANK, downgradeReasoning, effortFromThinkingBudget, modelSupportsEfforts } from '../types/router.js';
2
+ import { EFFORT_LADDER, TIER_RANK, COST_MODE_TIER_CEILING, clampTierToCeiling, downgradeReasoning, effortFromThinkingBudget, modelSupportsEfforts } from '../types/router.js';
3
3
  import { PromptOptimizer } from './prompt-optimizer.js';
4
4
  import { repairToolCallPairing } from './tool-pairing.js';
5
5
  import { applyCompression } from '../compression/index.js';
@@ -13,8 +13,10 @@ import { DEFAULT_LAYER2_EFFORT_FLOOR } from '../config/defaults.js';
13
13
  import { appendRoutingLedger } from '../router/routing-ledger.js';
14
14
  import { SchemaAssertion } from '../validator/schema-assertion.js';
15
15
  import { FallbackContextBuilder } from '../validator/parser.js';
16
+ import { resolveModel } from '../providers/model-resolution.js';
16
17
  import { pickDialWire } from '../providers/dial-wire.js';
17
18
  import { applyEffortMap } from '../providers/member-match.js';
19
+ import { comparePriceBucket } from '../providers/price-order.js';
18
20
  import { protocolForWire } from '../providers/vocabulary.js';
19
21
  import { capabilitiesFor } from '../ir/capabilities.js';
20
22
  import { IrUnsupportedError } from '../ir/errors.js';
@@ -22,10 +24,13 @@ import { computeRequestCost } from '../metrics/request-cost.js';
22
24
  import { getRateLimiter, credentialSubject, apiKeySubject, UPSTREAM_429_DEFAULT_COOLDOWN_MS, } from '../ratelimit/rate-limiter.js';
23
25
  import { recordRateLimitEvent } from '../ratelimit/event-log.js';
24
26
  import { NO_TURN } from '../capture/turn-boundary.js';
27
+ import { CLIENT_HINT_HEADER } from '../utils/client-families.js';
25
28
  import { SessionManager } from '../session/session-manager.js';
26
29
  import { getEnvPaths } from '../config/env.js';
27
30
  import { TraceTracker } from '../trace/tracker.js';
28
31
  import { CaptureRecorder } from '../capture/recorder.js';
32
+ import { SessionSnapshotStore } from '../snapshot/store.js';
33
+ import { snapshotRequestViewOf } from '../snapshot/view.js';
29
34
  import { UpstreamEventContext } from '../observability/upstream-events.js';
30
35
  import { emitClientRequest, captureKeyIdentity, setClientExchangeContext } from '../observability/http-exchange.js';
31
36
  import { resolveClientRequestId, mintRequestId } from '../observability/request-identity.js';
@@ -35,7 +40,7 @@ import { redactUpstreamBody } from '../observability/upstream-body-redaction.js'
35
40
  import { displayPromptText, firstDisplayText } from '../utils/client-envelope.js';
36
41
  import { harnessProfileOf } from '../utils/harness-profiles.js';
37
42
  import { ActiveHealthProber, ErrorClassifier } from '../resilience/index.js';
38
- import { isModelAllowed, isModelAllowedInTiers, tierFromVirtualEntry } from '../auth/model-access.js';
43
+ import { isModelAllowed, isModelAllowedInTiers } from '../auth/model-access.js';
39
44
  import { DEFAULT_CREDENTIAL_AFFINITY_CACHE_TTL_MS, selectCredential, } from './credential-selection.js';
40
45
  /** Key attribution: the in-process binding wins, else the request's authInfo. */
41
46
  const keyIdentityOf = (ctx) => ctx?.clientKey ?? captureKeyIdentity(ctx?.fastifyRequest ?? ctx?.clientRequest);
@@ -144,6 +149,32 @@ const effortOf = (request) => request.reasoning?.effort;
144
149
  function setEffort(request, effort) {
145
150
  request.reasoning = { ...request.reasoning, effort };
146
151
  }
152
+ /**
153
+ * Has the model's registration EXPLICITLY declared "no level control"? That is
154
+ * `supportedReasoningEfforts: []` — the shape `effortLadderFor` emits for a
155
+ * catalog toggle / always-on row. It is deliberately distinct from `undefined`
156
+ * (nothing declared — the legacy "model handles effort internally" case, which
157
+ * still clamps to `none`). A level the model cannot honour is never sent for a
158
+ * declared-empty model, so writing `'none'` back would put a positive
159
+ * thinking-off on the wire that no client asked for.
160
+ */
161
+ function isDeclaredNoControl(supported) {
162
+ return Array.isArray(supported) && supported.length === 0;
163
+ }
164
+ /**
165
+ * The model DECLARES a level table that does not include `none`. Thinking-off
166
+ * is then INEXPRESSIBLE for it: the official APIs answer HTTP 400 to
167
+ * `reasoning_effort: 'none'` / `thinkingBudget: 0` on such models (OpenAI
168
+ * documents this for `gpt-5` / `gpt-6-astra`; Gemini forbids disabling
169
+ * thinking on 3.x+), and the vendor's own default governs instead. So `none`
170
+ * must never reach the wire — the honest move is to OMIT the field.
171
+ *
172
+ * Distinct from the other two shapes: `[]` = no level control at all;
173
+ * `undefined` = nothing declared (the legacy clamp to `none` still applies).
174
+ */
175
+ function declaresLadderWithoutNone(supported) {
176
+ return Array.isArray(supported) && supported.length > 0 && !supported.includes('none');
177
+ }
147
178
  /**
148
179
  * Pull a non-sensitive subset of inbound headers for the trace's
149
180
  * `clientHeaders` field. Three categories:
@@ -159,7 +190,7 @@ function setEffort(request, effort) {
159
190
  */
160
191
  /**
161
192
  * Pull the upstream target host from an inbound header map. On the MITM
162
- * forward-proxy path this is the ORIGINAL destination (the API host the
193
+ * ingress-proxy path this is the ORIGINAL destination (the API host the
163
194
  * client dialed — `clientRequest.headers.host` survives TLS termination),
164
195
  * which pins bare-name model resolution to the right provider. The native
165
196
  * /v1 leg is deliberately excluded from this call: there `headers.host` is
@@ -215,6 +246,13 @@ function envelopeHintsOf(headers) {
215
246
  declaredPrompt: declared ? clipDisplayText(declared.replace(/\s+/g, ' ').trim()) || undefined : undefined,
216
247
  };
217
248
  }
249
+ /**
250
+ * Non-sensitive client-identification subset of the inbound headers. The
251
+ * self-declared `x-ocr-client` hint is read because a browser webview strips
252
+ * a script-set `User-Agent` on `fetch` — the hint is what identifies the
253
+ * console playground (see `utils/client-families.ts`). Display-only: the
254
+ * family it produces is never an identity or routing input (ADR-0002).
255
+ */
218
256
  function extractClientHeaders(headers) {
219
257
  if (!headers)
220
258
  return undefined;
@@ -229,12 +267,14 @@ function extractClientHeaders(headers) {
229
267
  const ua = pick('user-agent');
230
268
  const al = pick('accept-language');
231
269
  const rid = resolveClientRequestId({ headers }).clientRequestId;
232
- if (ua === undefined && al === undefined && rid === undefined)
270
+ const hint = pick(CLIENT_HINT_HEADER);
271
+ if (ua === undefined && al === undefined && rid === undefined && hint === undefined)
233
272
  return undefined;
234
273
  return {
235
274
  ...(ua !== undefined ? { userAgent: ua } : {}),
236
275
  ...(al !== undefined ? { acceptLanguage: al } : {}),
237
276
  ...(rid !== undefined ? { clientRequestId: rid } : {}),
277
+ ...(hint !== undefined ? { clientHint: hint } : {}),
238
278
  };
239
279
  }
240
280
  export class PipelineOrchestrator {
@@ -244,6 +284,7 @@ export class PipelineOrchestrator {
244
284
  sessionManager;
245
285
  traceTracker;
246
286
  captureRecorder;
287
+ snapshotStore;
247
288
  healthProber;
248
289
  constructor(config, registry, tracker, sessionManager) {
249
290
  this.config = config;
@@ -257,6 +298,10 @@ export class PipelineOrchestrator {
257
298
  new SessionManager(config.session, path.join(getEnvPaths().dataDir, 'sessions.json'));
258
299
  this.traceTracker = new TraceTracker(5000, config.tracePersist);
259
300
  this.captureRecorder = new CaptureRecorder(config.requestCapture);
301
+ // Session-snapshot handoff plane (ADR-0038) — separate from capture: an
302
+ // incremental, semantic transcript written for conversation MOVES, not a
303
+ // byte-faithful debug log.
304
+ this.snapshotStore = new SessionSnapshotStore(config.sessionSnapshots);
260
305
  if (config.circuitBreaker?.activeProbing?.enabled) {
261
306
  this.healthProber = new ActiveHealthProber(this.registry.getCircuitBreakerManager(), this.registry, config.circuitBreaker.activeProbing.intervalMs);
262
307
  }
@@ -273,6 +318,9 @@ export class PipelineOrchestrator {
273
318
  getCaptureRecorder() {
274
319
  return this.captureRecorder;
275
320
  }
321
+ getSnapshotStore() {
322
+ return this.snapshotStore;
323
+ }
276
324
  getRegistry() {
277
325
  return this.registry;
278
326
  }
@@ -293,14 +341,14 @@ export class PipelineOrchestrator {
293
341
  /**
294
342
  * Auto-request routing with the experience table in front of the decision layer
295
343
  * (ADR-0011): an entry hit short-circuits L2 entirely — the table IS a
296
- * prior judgment. Explicit request tiers (`forceTier`, incl. the
297
- * mode-forced ones resolved in 1B) skip the table: an explicit choice is a
298
- * layer0 decision by definition. On an L2 judgment the router behaves
299
- * exactly as before (decision layer → plus baseline).
344
+ * prior judgment. Explicit request tiers (`forceTier`) and the global
345
+ * routing mode's tier pin (`modeTier`) skip the table: both are layer0
346
+ * decisions by definition. On an L2 judgment the router behaves exactly as
347
+ * before (decision layer → plus baseline).
300
348
  */
301
- async routeAutoDecision(request, decisionCapture, sessionId, promptHash) {
349
+ async routeAutoDecision(request, decisionCapture, sessionId, promptHash, modeTier) {
302
350
  const gate = routeEntriesGate();
303
- if (gate.enabled !== false && promptHash && !request.routerOptions?.forceTier) {
351
+ if (gate.enabled !== false && promptHash && !request.routerOptions?.forceTier && !modeTier) {
304
352
  const entry = getRouteEntryStore().hit(promptHash, sessionId);
305
353
  if (entry) {
306
354
  // The entry's effort is part of the experience; a client-explicit
@@ -332,7 +380,7 @@ export class PipelineOrchestrator {
332
380
  decisionCapture,
333
381
  // Failure attribution: decision layer wire failures land in the failure_events
334
382
  // ledger tagged with THIS conversation, whatever the capture switch.
335
- sessionId);
383
+ sessionId, modeTier);
336
384
  }
337
385
  startProber() {
338
386
  if (this.healthProber)
@@ -475,7 +523,67 @@ export class PipelineOrchestrator {
475
523
  // response. The sink never writes a byte, so `committed` stays
476
524
  // false and retries/failover remain legal;
477
525
  // follow → the client's own relay (or none) — historical behavior.
478
- return await this.processInternal(snapshotRequest, snapshotScan, addressed, context, preResolvedSession, upstreamEventContext, turnIdentity, this.resolveUpstreamRelay(relay));
526
+ const upstreamRelay = this.resolveUpstreamRelay(relay);
527
+ try {
528
+ return await this.processInternal(snapshotRequest, snapshotScan, addressed, context, preResolvedSession, upstreamEventContext, turnIdentity, upstreamRelay);
529
+ }
530
+ catch (err) {
531
+ // ABORT SEAM (ADR-0040): the request threw before the success path could
532
+ // record it. Record it as terminated with its reason so the transcript does
533
+ // not silently lose where a conversation was interrupted. `processInternal`
534
+ // records on the success path itself, so this only fires on a throw.
535
+ if (this.snapshotStore.isEnabled()) {
536
+ const committed = upstreamRelay?.committed === true;
537
+ const clientGone = this.isClientAborted(context);
538
+ const outcome = committed ? 'aborted' : 'failed';
539
+ const reason = clientGone
540
+ ? 'client-abort'
541
+ : statusCodeOf(err) !== undefined && statusCodeOf(err) < 500 && statusCodeOf(err) >= 400
542
+ ? 'client-native-error'
543
+ : 'upstream-error';
544
+ this.snapshotStore.recordTurn({
545
+ sessionId: admissionSessionId,
546
+ turnIndex: turnIdentity.turn.turnIndex,
547
+ requestId: turnIdentity.requestId,
548
+ ts: Date.now(),
549
+ servedModel: '',
550
+ outcome,
551
+ abortReason: reason,
552
+ request: snapshotRequestViewOf(snapshotRequest),
553
+ response: {
554
+ status: outcome === 'aborted' ? 'incomplete' : 'failed',
555
+ reason,
556
+ // A committed abort already streamed a fragment to the client; that
557
+ // fragment is NOT this turn's output (the pipeline never got it back
558
+ // on this path), so the stored output is empty and `partialChars`
559
+ // stays 0 — the console says "interrupted" from `outcome`, not from
560
+ // a fabricated fragment.
561
+ output: [],
562
+ usage: { inputTokens: 0, outputTokens: 0 },
563
+ partialChars: committed ? undefined : 0,
564
+ },
565
+ });
566
+ }
567
+ throw err;
568
+ }
569
+ }
570
+ /**
571
+ * Did the CLIENT disconnect for this request? Best-effort, from the transport's
572
+ * socket state: `destroyed` on the raw request with the readable side not
573
+ * ended is the signature of a peer that hung up mid-response. Absent transport
574
+ * (in-process callers / tests) always reads as "not gone" — the turn is then
575
+ * attributed to the upstream, which is the honest default when we cannot tell.
576
+ */
577
+ isClientAborted(context) {
578
+ try {
579
+ if (context?.isClientGone?.() === true)
580
+ return true;
581
+ const raw = context?.fastifyRequest?.raw;
582
+ return raw !== undefined && raw.destroyed === true && raw.readableEnded === false;
583
+ }
584
+ catch {
585
+ return false;
586
+ }
479
587
  }
480
588
  /**
481
589
  * Apply `streaming.upstream.mode` to the surface-supplied relay. The sink
@@ -492,111 +600,53 @@ export class PipelineOrchestrator {
492
600
  return mode === 'stream' ? UPSTREAM_SINK_RELAY : undefined;
493
601
  }
494
602
  /**
495
- * Names the model the client addressed. Throws 404 for an unknown variant
496
- * or an unusable combo, and 403 when the key's model policy denies an
497
- * explicit model. A bare name that matches nothing falls through to the
498
- * classifier. Mutates `request` with the tier and effort that name implies.
499
- * Does not resolve a session.
603
+ * Names the model the client addressed — the execution-side consumer of
604
+ * `resolveModel` (the pure, draw-free ladder lives there, shared with
605
+ * every other reader). Applies the mutations the name implies (forceTier,
606
+ * variant rewrite + effort pin) and enforces the key's model policy for an
607
+ * explicitly named model. Does not resolve a session.
500
608
  */
501
609
  resolveAddressedModel(request, context) {
502
610
  let explicitModel;
503
611
  let variantUsed;
504
- // Routing-name matching trims once. `request.model` itself stays verbatim
505
- // end-to-end (surface contract: wire/capture bytes and the forwarded copy
506
- // are never rewritten) — this restores the trim tolerance the old inline
507
- // /v1/chat handler had before dispatch, and gives both legs (Fastify +
508
- // MITM, which historically never trimmed) identical matching semantics.
509
- const modelName = (request.model ?? '').trim();
510
- const bareTier = tierFromVirtualEntry(modelName);
511
- if (bareTier) {
512
- request.routerOptions = { ...request.routerOptions, forceTier: bareTier };
513
- }
514
- else if (modelName && modelName !== 'auto') {
515
- const specific = this.registry.getModel(modelName);
516
- if (specific) {
517
- // Exact-model pass-through: the client named a REGISTERED model id
518
- // (e.g. pinned via the Client Hub model slots). Route to exactly
519
- // this model — not merely its tier. Resilience is preserved: in-place
520
- // same-model retry and credential re-spread still apply; the model
521
- // itself is never substituted (ADR-0014).
522
- explicitModel = specific;
523
- request.routerOptions = { ...request.routerOptions, forceTier: specific.tier };
524
- }
525
- else {
526
- const variantRef = this.registry.resolveVariantRef(modelName);
527
- if (variantRef) {
528
- // Variant request (sibling id `base-variant` or `base#variant`):
529
- // route to the BASE model exactly and pin the variant's effort as
530
- // if the client had asked for that level. The variant choice is
531
- // the more explicit signal, so it wins over any client-sent
532
- // `reasoning_effort`; the effort-matching block below still
533
- // applies its downgrade/honesty contract.
534
- explicitModel = variantRef.base;
535
- variantUsed = variantRef.variant.id;
536
- setEffort(request, variantRef.variant.reasoningEffort);
537
- request.model = variantRef.base.id;
538
- request.routerOptions = { ...request.routerOptions, forceTier: variantRef.base.tier };
539
- }
540
- else if (modelName.includes('#')) {
541
- // `#variant` is explicit syntax — a typo must fail loud instead of
542
- // silently classifier-routing (invisible model drift is exactly
543
- // the failure mode variant ids exist to prevent).
544
- const hash = modelName.indexOf('#');
545
- throw Object.assign(new Error(`Variant '${modelName.slice(hash + 1)}' not found for model '${modelName.slice(0, hash)}'`), { statusCode: 404 });
546
- }
547
- else {
548
- // Bare upstream name (no provider prefix — clients that address a
549
- // model the way its own catalog names it, e.g. `qwen3.8-flash`).
550
- // The full-id lookup above missed, but a registered model may still
551
- // carry this exact name as its upstreamModel: resolve to it so the
552
- // client's explicit choice is honored instead of silently
553
- // classifier-routing. Provider pinning reads ONLY the MITM leg's
554
- // clientRequest headers — after TLS termination its `host` is the
555
- // ORIGINAL host the client dialed (the design intent of the pin).
556
- // The native /v1 leg never pins: its `headers.host` is client-
557
- // controlled (a forged Host could steer resolution to a same-named
558
- // sibling provider) and the gateway's own host matches no provider
559
- // baseUrl anyway. Cheapest-hit-first ordering picks the primary
560
- // otherwise. Same-name siblings stay reachable via the tier's
561
- // failover pool. A full miss falls through to the classifier —
562
- // ADR-0026 deleted the unresolved-model policy outright, so every
563
- // leg resolves a name the same way.
564
- const bareHits = this.registry.getModelsByUpstreamName(modelName, pickHeaderHost(context?.clientRequest?.headers));
565
- // A live combo id claims this name for the gateway: the combo fork
566
- // below is the advertised meaning (/v1/models lists the id as a
567
- // virtual model), and resolving the same name to one physical
568
- // same-named member would be the single-model billing/model drift
569
- // the combo fail-fast contract exists to forbid. The physical
570
- // models stay addressable by their full provider-prefixed id.
571
- if (bareHits.length > 0 && !this.registry.isCombo(modelName)) {
572
- explicitModel = bareHits[0];
573
- request.routerOptions = {
574
- ...request.routerOptions,
575
- forceTier: explicitModel.tier,
576
- };
577
- }
578
- // Nothing matched: no policy, no mapping, no fallback. The name
579
- // falls through to the classifier exactly like a native /v1 caller's
580
- // would — ADR-0026 deleted the unresolved-model mechanism outright,
581
- // so the MITM leg has no special posture of its own. A gateway
582
- // plugin that wants "this name means that model" maps it BEFORE
583
- // dispatch (it owns the decrypted wire); the pipeline never guesses.
584
- }
585
- }
586
- }
587
- // Custom model combo: the client named a configured combo id — the
588
- // combo's member list IS the candidate pool. Tier-pool routing,
589
- // session ratchet and schema-assertion escalation are all bypassed
590
- // (explicit user composition wins, mirroring the exact-model
591
- // pass-through above).
592
- const comboByName = !explicitModel && modelName && this.registry.isCombo(modelName) ? modelName : undefined;
593
- if (comboByName && this.registry.isComboDisabled(comboByName)) {
594
- throw Object.assign(new Error(`Combo '${comboByName}' is disabled — re-enable it in the console or choose another model.`), { statusCode: 404 });
612
+ const resolved = resolveModel(request.model, this.registry, {
613
+ // Provider pinning reads ONLY the MITM leg's clientRequest headers:
614
+ // after TLS termination its `host` is the ORIGINAL host the client
615
+ // dialed. The native /v1 leg passes nothing because its `Host` header
616
+ // is client-controlled.
617
+ upstreamHost: pickHeaderHost(context?.clientRequest?.headers),
618
+ });
619
+ if (resolved.kind === 'error') {
620
+ throw Object.assign(new Error(resolved.message), { statusCode: resolved.statusCode });
595
621
  }
596
- if (comboByName && this.registry.resolveCombo(comboByName).length === 0) {
597
- 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 });
622
+ switch (resolved.kind) {
623
+ case 'tier':
624
+ request.routerOptions = { ...request.routerOptions, forceTier: resolved.tier };
625
+ break;
626
+ case 'registered':
627
+ case 'legacy':
628
+ // Exact-model pass-through: route to exactly this model — not merely
629
+ // its tier. Resilience is preserved (same-model retry + credential
630
+ // re-spread); the model itself is never substituted (ADR-0014).
631
+ explicitModel = resolved.model;
632
+ request.routerOptions = { ...request.routerOptions, forceTier: resolved.model.tier };
633
+ break;
634
+ case 'variant':
635
+ // Variant request: route to the BASE model exactly and pin the
636
+ // variant's effort as if the client had asked for that level. The
637
+ // variant choice outranks any client-sent `reasoning_effort`.
638
+ explicitModel = resolved.model;
639
+ variantUsed = resolved.variantId;
640
+ setEffort(request, resolved.effort);
641
+ request.model = resolved.model.id;
642
+ request.routerOptions = { ...request.routerOptions, forceTier: resolved.model.tier };
643
+ break;
644
+ case 'combo':
645
+ case 'auto':
646
+ case 'unresolved':
647
+ break;
598
648
  }
599
- const comboId = comboByName ?? undefined;
649
+ const comboId = resolved.kind === 'combo' ? resolved.comboId : undefined;
600
650
  // An explicitly named model outside the key's model policy fails loud
601
651
  // here (HTTP routes entry-check this too; direct orchestrator callers
602
652
  // might not). The model's FULL membership set is passed so TIER-level
@@ -621,12 +671,26 @@ export class PipelineOrchestrator {
621
671
  const normalizedRequest = request;
622
672
  const directivePrefix = directivesGate().prefix;
623
673
  const { explicitModel, variantUsed, comboId } = addressed;
624
- // 1B. Global routing mode (config.routing.mode) — cost/quality force the tier
625
- // for auto/tier-alias requests; explicit client choices always win.
674
+ // 1B. Global routing mode (config.routing.mode) — cost/quality pin the tier
675
+ // for auto/tier-alias requests; explicit client choices always win. The pin
676
+ // rides as a dedicated routing input, NOT `routerOptions.forceTier`:
677
+ // `forceTier` is the CLIENT-authored contract (never cascaded, never
678
+ // escaped), while a mode pin is server policy and still gains the
679
+ // structured-output quality floor (ADR-0001 §1–§2).
626
680
  const modeTier = routingModeForceTier(normalizedRequest.model, normalizedRequest.routerOptions, this.config.routing?.mode);
627
- if (modeTier) {
628
- normalizedRequest.routerOptions = { ...normalizedRequest.routerOptions, forceTier: modeTier };
629
- }
681
+ // cost mode's failure policy: 'to_fallback_tier' (default) lets a failing
682
+ // lite leg escalate, but every escalation target is clamped to the shared
683
+ // COST_MODE_TIER_CEILING (plus); 'never' is a hard lite pin. Read per
684
+ // request so the knob hot-applies like the rest of `routing`.
685
+ const costEscalation = this.config.routing?.costEscalation === 'never' ? 'never' : 'to_fallback_tier';
686
+ // Cost mode's tier-INTERIOR policy (ADR-0001 §2): inside every pool this
687
+ // request touches, the cheapest priced member leads and the failover chain
688
+ // walks ascending price. Smart/quality keep the operator's declared order
689
+ // (weights ARE the quality statement; price-sorting pro would turn quality
690
+ // mode into "cheapest pro"). Server policy only: explicit models, client
691
+ // forceTier and tier aliases resolve modeTier undefined, so a client's
692
+ // choice is never price-redirected.
693
+ const costOrder = modeTier === 'lite';
630
694
  // 2. The admission gate resolved this conversation and allocated its turn.
631
695
  // clientRef is read again only so the trace row names the ref that was bound.
632
696
  const clientRef = SessionManager.clientRefOf(normalizedRequest);
@@ -645,6 +709,21 @@ export class PipelineOrchestrator {
645
709
  `${pairing.orphans} orphan repl${pairing.orphans === 1 ? 'y' : 'ies'}`);
646
710
  normalizedRequest.input = pairing.input;
647
711
  }
712
+ // 2B'. Freeze the PRE-compression request for the snapshot handoff plane
713
+ // (ADR-0038). After tool-pair repair (the history is now forwardable) and
714
+ // before compression (which rewrites tool outputs in place for this
715
+ // upstream). A private clone the snapshot store owns — null when the plane
716
+ // is off, so a disabled feature costs nothing on the hot path.
717
+ const snapshotRequest = this.snapshotStore.isEnabled()
718
+ ? snapshotRequestViewOf(normalizedRequest)
719
+ : undefined;
720
+ // Guards the ONE snapshot write for this request: the success path (§8B) and
721
+ // the abort seam in `process()` are mutually exclusive. `process()` records an
722
+ // `aborted`/`failed` record when this function THROWS (ADR-0040); the success
723
+ // path records `completed` here. `snapshotRecorded` is set only by the success
724
+ // path, which is why the abort seam can safely assume "a throw means nothing
725
+ // was recorded yet".
726
+ let snapshotRecorded = false;
648
727
  await applyCompression(normalizedRequest, this.config.compression, sessionId);
649
728
  // 2C. Route-entry experience (ADR-0011). One normalized prompt hash feeds
650
729
  // the experience-table lookup and write. Directives were scrubbed above, so
@@ -695,10 +774,12 @@ export class PipelineOrchestrator {
695
774
  layerUsed: 'layer0',
696
775
  needsSchemaValidation: false,
697
776
  }
698
- : await this.routeAutoDecision(normalizedRequest, upstreamEventContext, sessionId, promptHash);
777
+ : await this.routeAutoDecision(normalizedRequest, upstreamEventContext, sessionId, promptHash, modeTier);
699
778
  // Explicit-model honesty: the engine's 'forced' code here reflects the
700
- // forceTier the 1B resolver INJECTED from the named model's registration
779
+ // forceTier address resolution INJECTED from the named model's registration
701
780
  // (full id / variant / bare name) — the client named a model, not a tier.
781
+ // The global mode pin never writes `forceTier` (it rides `modeTier` and
782
+ // emits reasonCode 'mode'), so this rename stays client-authored only.
702
783
  // A dedicated code keeps the trace truthful: `tier` stays in params for
703
784
  // tooltips, but the console template carries no {tier} slot, so no tier
704
785
  // badge is ever inferred from a registration-table lookup.
@@ -758,9 +839,9 @@ export class PipelineOrchestrator {
758
839
  // resolved once here (the unified policy seam for all entry modes):
759
840
  // - 'ratchet' : auto routing — full monotonic ratchet (upgrade allowed,
760
841
  // downgrade intercepted, pin honored)
761
- // - 'explicit' : a client-authored choice — a named model OR a forced
762
- // tier (tier aliases / the global mode lever /
763
- // router_options.forceTier). Turn recorded, a higher
842
+ // - 'explicit' : a client-authored choice — a named model, a forced tier
843
+ // (tier aliases / `router_options.forceTier`), or the global
844
+ // mode's tier pin (`modeTier`). Turn recorded, a higher
764
845
  // proposal still escalates the ceiling, but the session
765
846
  // NEVER rewrites the proposal and the pin is neither
766
847
  // read nor followed — a forced lite must serve lite even
@@ -769,7 +850,7 @@ export class PipelineOrchestrator {
769
850
  // composition IS the decision
770
851
  const sessionMode = comboId
771
852
  ? 'bypass'
772
- : explicitModel || normalizedRequest.routerOptions?.forceTier
853
+ : explicitModel || normalizedRequest.routerOptions?.forceTier || modeTier
773
854
  ? 'explicit'
774
855
  : 'ratchet';
775
856
  let decision;
@@ -784,6 +865,12 @@ export class PipelineOrchestrator {
784
865
  sessionRequestCount = this.sessionManager.recordBypassTurn(sessionId);
785
866
  }
786
867
  else {
868
+ // The birth pin IS served: ratchet turns serve it, and a forced-tier
869
+ // turn follows a same-tier pin for KV affinity (below), so its pick is
870
+ // real and may advance the strategy cursor. Only the stateless /
871
+ // disabled branch throws its representative away — it must not consume
872
+ // a pick, because the per-request chain head takes the one pick then.
873
+ const ratchetConsumesPick = this.sessionManager.pinsModels();
787
874
  const ratchetResult = this.sessionManager.applyRatchet(sessionId, initialDecision,
788
875
  // Tier representative for session bookkeeping (pin birth). An
789
876
  // explicitly named model IS the representative of its own turn —
@@ -792,7 +879,22 @@ export class PipelineOrchestrator {
792
879
  // though the request itself is directly callable by design. Bare
793
880
  // `auto` keeps resolving through the pool (its empty-pool throw is
794
881
  // the honest "add tier members" answer).
795
- (tier) => explicitModel ?? this.registry.getModelForTier(tier), { allowIntercept: sessionMode === 'ratchet' });
882
+ // The representative also honours the request's `costOrder`: a cost-mode
883
+ // session must be BORN on its cheapest member, since the birth pin is
884
+ // what every later turn follows by KV affinity (ADR-0001 §2).
885
+ (tier) => {
886
+ if (explicitModel)
887
+ return explicitModel;
888
+ if (!ratchetConsumesPick) {
889
+ const pool = this.registry.getCandidateModelsForTier(tier, true, { costOrder });
890
+ if (pool.length > 0)
891
+ return pool[0];
892
+ const anyPool = this.registry.getCandidateModelsForTier(tier, false, { costOrder });
893
+ if (anyPool.length > 0)
894
+ return anyPool[0];
895
+ }
896
+ return this.registry.getModelForTier(tier, true, costOrder);
897
+ }, { allowIntercept: sessionMode === 'ratchet' });
796
898
  decision = ratchetResult.finalDecision;
797
899
  decision.sessionId = sessionId;
798
900
  decision.sessionRatchetApplied = ratchetResult.ratchetApplied;
@@ -865,7 +967,18 @@ export class PipelineOrchestrator {
865
967
  // scope). It is also the ONLY legal automatic-path downgrade. Explicit
866
968
  // client choices (named model / forced tier / combo) outrank a directive —
867
969
  // the client already decided — and say so in the ledger.
868
- const directivesApplicable = sessionMode === 'ratchet';
970
+ // A directive is a per-turn USER override. It outranks SERVER policy (the
971
+ // global mode tier pin) but never a client-authored choice (named model /
972
+ // forced tier / combo). A mode-pin turn stays classified `explicit` for
973
+ // ratchet/pin purposes (a cost pin must not be dragged up by the session
974
+ // high-water mark, ADR-0014), yet its directive axes still apply —
975
+ // otherwise cost/quality mode silently swallows the user's tier/effort
976
+ // directives (ADR-0011).
977
+ const modePinnedTurn = modeTier !== undefined &&
978
+ !explicitModel &&
979
+ !comboId &&
980
+ normalizedRequest.routerOptions?.forceTier === undefined;
981
+ const directivesApplicable = sessionMode === 'ratchet' || modePinnedTurn;
869
982
  if (!directivesApplicable && directiveScan.effective.length > 0) {
870
983
  appendRoutingLedger({
871
984
  kind: 'directive_ignored',
@@ -887,6 +1000,7 @@ export class PipelineOrchestrator {
887
1000
  });
888
1001
  }
889
1002
  let tierDirectiveChanged = false;
1003
+ let effortDirectiveChanged = false;
890
1004
  if (directivesApplicable) {
891
1005
  const tierDirective = applyTierDirectives(directiveActions, decision.targetTier);
892
1006
  if (tierDirective.applied) {
@@ -990,7 +1104,7 @@ export class PipelineOrchestrator {
990
1104
  !this.poolOfHomedModel(preferredModel).some((m) => m.id === pinnedId));
991
1105
  const healthEvicted = preferredModel !== null && this.registry.modelHealthView(preferredModel) === 'unavailable';
992
1106
  if (pinnedId && (configEvicted || healthEvicted)) {
993
- const healthyReplacement = this.registry.getModelForTier(actualTier, true);
1107
+ const healthyReplacement = this.registry.getModelForTier(actualTier, true, costOrder);
994
1108
  // Guard: getModelForTier degrades across tiers when the whole tier is
995
1109
  // down — a cross-tier landing is legitimate (the registry logs it with
996
1110
  // reason=empty-pool) and repinModel moves the model pin only, never
@@ -1024,7 +1138,7 @@ export class PipelineOrchestrator {
1024
1138
  }
1025
1139
  }
1026
1140
  }
1027
- else if (sessionMode === 'explicit' && !explicitModel && normalizedRequest.routerOptions?.forceTier) {
1141
+ else if (sessionMode === 'explicit' && !explicitModel && (normalizedRequest.routerOptions?.forceTier || modeTier)) {
1028
1142
  // Forced-tier turn (ADR-0014): the session pin is followed ONLY when it
1029
1143
  // lives in the forced tier — then following is pure KV affinity (the
1030
1144
  // pin IS a model of the tier the client forced, so serving it cannot
@@ -1045,7 +1159,7 @@ export class PipelineOrchestrator {
1045
1159
  const tierPool = this.registry.getCandidateModelsForTier(actualTier, false);
1046
1160
  const degradeLanding = preferredModel !== null &&
1047
1161
  tierPool.length === 0 &&
1048
- this.registry.getModelForTier(actualTier).id === preferredModel.id;
1162
+ this.registry.getModelForTier(actualTier, true, costOrder).id === preferredModel.id;
1049
1163
  const unhomed = preferredModel !== null && preferredModel.tier === undefined;
1050
1164
  if (pinnedId &&
1051
1165
  (preferredModel === null ||
@@ -1056,7 +1170,7 @@ export class PipelineOrchestrator {
1056
1170
  !this.poolOfHomedModel(preferredModel).some((m) => m.id === pinnedId);
1057
1171
  const healthEvicted = preferredModel !== null && this.registry.modelHealthView(preferredModel) === 'unavailable';
1058
1172
  if (configEvicted || healthEvicted) {
1059
- const healthyReplacement = this.registry.getModelForTier(actualTier, true);
1173
+ const healthyReplacement = this.registry.getModelForTier(actualTier, true, costOrder);
1060
1174
  if (healthyReplacement &&
1061
1175
  healthyReplacement.id !== pinnedId &&
1062
1176
  this.registry.modelAvailable(healthyReplacement).available) {
@@ -1087,10 +1201,48 @@ export class PipelineOrchestrator {
1087
1201
  // the zero-member case fails fast above, so index 0 exists whenever
1088
1202
  // comboId is set. Bare `auto` still resolves through the pool — its
1089
1203
  // empty-pool throw is the honest "add members on the /tiers page" answer.
1204
+ // One strategy pick for the no-pin auto path (stateless / disabled
1205
+ // sessions): the same model leads the serving chain below (the direct
1206
+ // path reuses `autoLeader`), so the cursor advances exactly once per
1207
+ // request and effort prep sees the model that will actually serve. A
1208
+ // session pin (preferredModel) and combos resolve without touching this
1209
+ // cursor.
1210
+ //
1211
+ // The lite-lead cascade below picks its OWN leader per tier, so this
1212
+ // pre-execution draw must be skipped when the cascade will decide the
1213
+ // route: a round here would advance the cursor for a model the request
1214
+ // never serves, and the placeholder is discarded anyway. Hoisting the
1215
+ // cascade predicate keeps the two sites from ever disagreeing.
1216
+ const cascadeEligible = decision.needsSchemaValidation &&
1217
+ this.config.fallback.enabled &&
1218
+ !request.routerOptions?.disableFallback &&
1219
+ !explicitModel &&
1220
+ !comboId &&
1221
+ !normalizedRequest.routerOptions?.forceTier &&
1222
+ // A mode pin may gain the structured-output floor only from the lite
1223
+ // lead: quality mode is pinned to pro, and a lite-first cascade would
1224
+ // downgrade it. Smart (no modeTier) keeps the original behaviour. A
1225
+ // 'never' cost-escalation policy refuses the escalation outright.
1226
+ (modeTier === undefined || (modeTier === 'lite' && costEscalation !== 'never'));
1227
+ const autoLeader = preferredModel || comboId || explicitModel || cascadeEligible
1228
+ ? null
1229
+ : this.registry.getModelForTier(actualTier, true, costOrder);
1090
1230
  let actualModel = preferredModel ||
1091
1231
  (comboId ? this.registry.resolveCombo(comboId)[0] : undefined) ||
1092
1232
  explicitModel ||
1093
- this.registry.getModelForTier(actualTier, true);
1233
+ autoLeader ||
1234
+ // Cascade-eligible placeholder: the cascade executes its own leaders, so
1235
+ // this only feeds the pre-execution effort preview and the directive
1236
+ // ledger — take a pool head WITHOUT a rotation draw. Healthy head first,
1237
+ // then the all-health head: `getModelForTier` is only reached when the
1238
+ // tier pool is empty at every health level, where it resolves a cross-tier
1239
+ // representative without touching a cursor. Reaching a `pickPrimary` draw
1240
+ // here would advance the same projection cursor (`${tier}:${strategy}`,
1241
+ // `:cost`-suffixed under a price projection) the cascade then draws on
1242
+ // (double advance for one request).
1243
+ this.registry.getCandidateModelsForTier(actualTier, true, { costOrder })[0] ||
1244
+ this.registry.getCandidateModelsForTier(actualTier, false, { costOrder })[0] ||
1245
+ this.registry.getModelForTier(actualTier, true, costOrder);
1094
1246
  // Reasoning-effort matching. `requestedEffort` is the
1095
1247
  // literal value the client sent (undefined if the field was omitted —
1096
1248
  // distinct from `'none'`, which is the client EXPLICITLY asking for no
@@ -1135,8 +1287,12 @@ export class PipelineOrchestrator {
1135
1287
  // Baseline = the effective ask already in play (client value, else the
1136
1288
  // entry/L2 injection, else the model default pinned just above), so the
1137
1289
  // step is relative to what this turn WOULD have served — symmetric with the
1138
- // tier axis, which steps from the post-ratchet decision. Capability-clamped
1139
- // with the same degraded-or-equal rule as everything else. Runs BEFORE the effort matching below so a
1290
+ // tier axis, which steps from the post-ratchet decision. Capability handling
1291
+ // belongs to the SERVING model, exactly like a client field: a STEP is
1292
+ // range-clamped against the pre-pick model's declared ladder, while a PIN
1293
+ // is written here as the raw ask and translated (effortMap) + clamped by
1294
+ // the pipeline below — clamping a pin here would bypass a `high->xhigh`
1295
+ // map and read an arbitrary pool head. Runs BEFORE the effort matching so a
1140
1296
  // model pick can honour a raised level. Per-turn: it writes the request
1141
1297
  // for this call only and never records session state.
1142
1298
  if (directivesApplicable) {
@@ -1152,6 +1308,7 @@ export class PipelineOrchestrator {
1152
1308
  : modelSupportsEfforts(declared, actualModel.supportsReasoningEffort, actualModel.reasoningDisableable);
1153
1309
  const before = effortOf(normalizedRequest);
1154
1310
  const effortDirective = applyEffortDirectives(directiveActions, before, supportedEfforts, actualModel.reasoningDisableable === false);
1311
+ effortDirectiveChanged = effortDirective.changed;
1155
1312
  if (effortDirective.applied) {
1156
1313
  const suffix = effortDirective.suffix ?? (effortDirective.delta > 0 ? 'effort-up' : 'effort-down');
1157
1314
  const token = `${directivePrefix}${suffix}`;
@@ -1207,6 +1364,13 @@ export class PipelineOrchestrator {
1207
1364
  const requestedEffort = effortOf(normalizedRequest);
1208
1365
  let actualEffort;
1209
1366
  let reasoningDegraded = false;
1367
+ // Tier-cross policy, resolved here (before the effort pick) so a
1368
+ // `same_tier_only` deployment OR a client-forced tier forbids the
1369
+ // effort-aware pick from leaving its tier. Reused verbatim below for the
1370
+ // cross-tier escalation tail.
1371
+ const tierCrossPolicy = this.config.retry?.failover?.tierCrossPolicy ?? 'allow_escalate';
1372
+ const sameTierEffortPick = tierCrossPolicy !== 'allow_escalate' ||
1373
+ normalizedRequest.routerOptions?.forceTier !== undefined;
1210
1374
  const effortPick = (() => {
1211
1375
  // Skip effort-based pick when the request is an explicit model choice
1212
1376
  // OR a combo — both are pinned by the caller and must not be re-routed
@@ -1221,10 +1385,10 @@ export class PipelineOrchestrator {
1221
1385
  // No explicit level asked — still engage when a member rule
1222
1386
  // maps `none` to a real level (e.g. none→high) — the pick becomes
1223
1387
  // effort-aware. Otherwise leave the default tier pick alone.
1224
- const mapped = this.registry.pickModelForEffort(actualTier, 'none', true);
1388
+ const mapped = this.registry.pickModelForEffort(actualTier, 'none', true, costOrder, modeTier === 'lite' ? COST_MODE_TIER_CEILING : undefined, sameTierEffortPick);
1225
1389
  return mapped && mapped.actualEffort !== 'none' ? mapped : null;
1226
1390
  }
1227
- return this.registry.pickModelForEffort(actualTier, requestedEffort, true);
1391
+ return this.registry.pickModelForEffort(actualTier, requestedEffort, true, costOrder, modeTier === 'lite' ? COST_MODE_TIER_CEILING : undefined, sameTierEffortPick);
1228
1392
  })();
1229
1393
  if (effortPick) {
1230
1394
  actualModel = effortPick.model;
@@ -1250,6 +1414,26 @@ export class PipelineOrchestrator {
1250
1414
  if (target === 'none' && !forbidsNone) {
1251
1415
  actualEffort = requestedEffort; // nothing in play — mirror exactly
1252
1416
  }
1417
+ else if (
1418
+ // The always-think clamp (below) owns a disableable:false model whose
1419
+ // ladder has no `none`: its declared rung is the honest floor, never an
1420
+ // omission. Only the two NO-RUNG-TO-CLAMP-TO shapes route here.
1421
+ !(preferredModel.reasoningDisableable === false && supported.length > 0) &&
1422
+ ((isDeclaredNoControl(preferredModel.supportedReasoningEfforts) && target !== 'none') ||
1423
+ (target === 'none' && requestedEffort !== undefined && declaresLadderWithoutNone(preferredModel.supportedReasoningEfforts)))) {
1424
+ // Two shapes where the ask is NOT a level the model can honour, and the
1425
+ // honest serve is "send nothing, let the vendor decide" rather than a
1426
+ // rewritten `none` (which is a positive thinking-off on the chat wire,
1427
+ // or an HTTP 400 on models whose table omits `none`):
1428
+ // - EXPLICITLY declared no level control (`supportedReasoningEfforts: []`
1429
+ // — a toggle / always-on catalog row);
1430
+ // - a declared table WITHOUT `none` (OpenAI `gpt-5`/`gpt-6-astra`,
1431
+ // Gemini 3.x — `none` is inexpressible, `400` otherwise).
1432
+ // (An UNDECLARED support set — `undefined` — is the legacy "model
1433
+ // handles effort internally" case and still clamps to `none` below.)
1434
+ actualEffort = target === 'none' ? undefined : requestedEffort;
1435
+ reasoningDegraded = requestedEffort !== undefined && requestedEffort !== 'none';
1436
+ }
1253
1437
  else {
1254
1438
  let recomputed = downgradeReasoning(target, supported, alwaysThink);
1255
1439
  // Same contradictory-data rule as resolveServedEffort: an empty resolved
@@ -1296,25 +1480,35 @@ export class PipelineOrchestrator {
1296
1480
  let servedEgress = undefined;
1297
1481
  // 5. Execution with Cascading Fallback & Schema Assertion
1298
1482
  // (lite-lead cascade is skipped for explicit model choices, combos AND
1299
- // forced tiers — the client named exactly what to run. A forced tier is
1300
- // a contract in BOTH directions: no lite-lead downgrade of a forced
1301
- // plus/pro/ultra, no plus escape of a forced lite. ADR-0014.)
1483
+ // client-forced tiers — the client named exactly what to run. A forced
1484
+ // tier is a contract in BOTH directions: no lite-lead downgrade of a
1485
+ // forced plus/pro/ultra, no plus escape of a forced lite. A MODE pin is
1486
+ // server policy, not a client contract: cost mode (lite) still earns the
1487
+ // structured-output floor, while quality mode (pro) never takes a lite
1488
+ // lead. A session pin does NOT skip the cascade: the structured-output
1489
+ // probe is a cost decision and each leg it serves draws its own leader.
1490
+ // ADR-0014.)
1302
1491
  const retryConfig = this.config.retry;
1303
1492
  const failoverEnabled = retryConfig?.enabled !== false && retryConfig?.failover?.enabled !== false;
1304
1493
  const maxFailoverCandidates = failoverEnabled ? (retryConfig?.failover?.maxAttempts ?? 2) : 1;
1305
- const tierCrossPolicy = retryConfig?.failover?.tierCrossPolicy ?? 'allow_escalate';
1306
- if (decision.needsSchemaValidation &&
1307
- this.config.fallback.enabled &&
1308
- !request.routerOptions?.disableFallback &&
1309
- !explicitModel &&
1310
- !comboId &&
1311
- !normalizedRequest.routerOptions?.forceTier) {
1494
+ // `tierCrossPolicy` was resolved above (the effort pick needs it).
1495
+ // Where a failing lite leg escalates to: the operator's configured target
1496
+ // in smart/quality, clamped to the shared ceiling in cost mode. ONE value
1497
+ // feeds the 5A lite-lead tail, the 5B escalation and the direct path's
1498
+ // cross-tier tail, so none of them invents its own 'plus' (S3 drift twin).
1499
+ const configuredEscalateTier = this.config.fallback?.escalateTier || 'plus';
1500
+ const escalateTier = modeTier === 'lite'
1501
+ ? clampTierToCeiling(configuredEscalateTier, COST_MODE_TIER_CEILING)
1502
+ : configuredEscalateTier;
1503
+ if (cascadeEligible) {
1312
1504
  // 5A: Lite Tier lead - Deploy Lite Tier first with resilience
1313
- const litePool = this.registry.getCandidateModelsForTier('lite', true);
1505
+ const litePool = this.registry.getCandidateModelsForTier('lite', true, { costOrder });
1506
+ const liteCandidates = litePool.length > 0 ? litePool : this.registry.getCandidateModelsForTier('lite', false, { costOrder });
1314
1507
  const liteResult = await this.executeCandidatePool(normalizedRequest, {
1315
- chain: litePool.length > 0 ? litePool : this.registry.getCandidateModelsForTier('lite', false),
1508
+ chain: this.registry.orderChain('lite', liteCandidates, costOrder),
1316
1509
  tier: 'lite',
1317
1510
  allowEscalate: tierCrossPolicy === 'allow_escalate',
1511
+ escalateTier,
1318
1512
  attemptCap: maxFailoverCandidates,
1319
1513
  modelAccess: context?.modelAccess,
1320
1514
  requestedEffort,
@@ -1360,11 +1554,13 @@ export class PipelineOrchestrator {
1360
1554
  if (!assertionPassed) {
1361
1555
  fallbackOccurred = true;
1362
1556
  fallbackReason = assertionError;
1363
- const escalateTier = this.config.fallback.escalateTier || 'plus';
1557
+ // Cost mode never spends above its ceiling; other modes honor the
1558
+ // operator's configured target unchanged. `escalateTier` was resolved
1559
+ // above from `fallback.escalateTier` (ceiling-clamped in cost mode).
1364
1560
  const failedContent = responseMessageText(liteRes);
1365
1561
  const fallbackReq = FallbackContextBuilder.buildEscalationRequest(normalizedRequest, failedContent, assertionError, escalateTier);
1366
1562
  const plusResult = await this.executeCandidatePool(fallbackReq, {
1367
- chain: this.registry.getCandidateModelsForTier(escalateTier, true),
1563
+ chain: this.registry.orderChain(escalateTier, this.registry.getCandidateModelsForTier(escalateTier, true, { costOrder }), costOrder),
1368
1564
  tier: escalateTier,
1369
1565
  allowEscalate: false,
1370
1566
  attemptCap: maxFailoverCandidates,
@@ -1394,7 +1590,7 @@ export class PipelineOrchestrator {
1394
1590
  throw escErr;
1395
1591
  const accessPolicy = context?.modelAccess;
1396
1592
  const escRemaining = this.registry
1397
- .getCandidateModelsForTier(escalateTier, true)
1593
+ .getCandidateModelsForTier(escalateTier, true, { costOrder })
1398
1594
  .filter((m) => !plusResult.failoverPath.includes(m.id) &&
1399
1595
  (!accessPolicy || isModelAllowedInTiers(m.id, accessPolicy, this.registry.tiersOf(m))));
1400
1596
  throw routeExhaustedError(`escalation tier '${escalateTier}'`, plusResult.failoverPath, escErr, escRemaining);
@@ -1465,9 +1661,9 @@ export class PipelineOrchestrator {
1465
1661
  // to the full pool when everything is tripped — the loop force-tries
1466
1662
  // the last candidate) follows the head, so KV-cache affinity is
1467
1663
  // preserved on the first candidate.
1468
- let pool = this.registry.getCandidateModelsForTier(actualTier, true);
1664
+ let pool = this.registry.getCandidateModelsForTier(actualTier, true, { costOrder });
1469
1665
  if (pool.length === 0)
1470
- pool = this.registry.getCandidateModelsForTier(actualTier, false);
1666
+ pool = this.registry.getCandidateModelsForTier(actualTier, false, { costOrder });
1471
1667
  // Bare-auto under a model-access policy: the classifier may land in a
1472
1668
  // tier that holds no admissible model (allow: none whitelisted in that
1473
1669
  // tier; deny: every model of that tier tier-denied) — widen the pool
@@ -1488,12 +1684,44 @@ export class PipelineOrchestrator {
1488
1684
  const widened = this.registry
1489
1685
  .getAllModels()
1490
1686
  .filter((m) => isModelAllowedInTiers(m.id, accessPolicy, this.registry.tiersOf(m)))
1491
- .sort((a, b) => Math.abs(rankOf(a) - (rank[actualTier] ?? 9)) - Math.abs(rankOf(b) - (rank[actualTier] ?? 9)) ||
1687
+ .sort((a, b) =>
1688
+ // Cost mode: the cheapest allowed model leads regardless of
1689
+ // tier proximity (ADR-0001 §2) — otherwise widening would be
1690
+ // the one cost-mode path that ignores price.
1691
+ (costOrder ? comparePriceBucket(a, b) : 0) ||
1692
+ Math.abs(rankOf(a) - (rank[actualTier] ?? 9)) - Math.abs(rankOf(b) - (rank[actualTier] ?? 9)) ||
1492
1693
  rankOf(a) - rankOf(b));
1493
1694
  if (widened.length > 0)
1494
1695
  pool = widened;
1495
1696
  }
1496
- chain = head ? [head, ...pool.filter(m => m.id !== head.id)] : pool;
1697
+ if (head) {
1698
+ chain = [head, ...pool.filter(m => m.id !== head.id)];
1699
+ }
1700
+ else if (pool.length === 0) {
1701
+ chain = pool;
1702
+ }
1703
+ else {
1704
+ // No pin and no explicit model (stateless / disabled sessions):
1705
+ // the early strategy pick IS this request's leader and already
1706
+ // advanced the cursor once. Keep it when the (possibly widened)
1707
+ // pool still holds it; otherwise draw exactly one replacement
1708
+ // from the pool this chain will actually walk.
1709
+ const early = autoLeader;
1710
+ // The effort-aware pick OUTRANKS the tier leader. `pickModelForEffort`
1711
+ // already resolved (and, in cost mode, ceiling-clamped) the model that
1712
+ // can serve the requested level — it may live in another tier than the
1713
+ // one this chain is built for. Leading with the tier leader would send
1714
+ // the request to a model that cannot serve the level at all and throw
1715
+ // the pick away (the pick is metadata until a candidate actually runs).
1716
+ // A pick that matches the early leader adds nothing, so keep the
1717
+ // early leader then (it already advanced the rotation cursor once).
1718
+ const effortHead = effortPick && effortPick.model.id !== early?.id ? effortPick.model : undefined;
1719
+ const leader = effortHead ??
1720
+ (early && pool.some(m => m.id === early.id)
1721
+ ? early
1722
+ : this.registry.pickLeader(actualTier, pool, costOrder));
1723
+ chain = [leader, ...pool.filter(m => m.id !== leader.id)];
1724
+ }
1497
1725
  // Auto keeps the configured failover budget; an explicit opt-in is
1498
1726
  // bounded by its own chain length (failover.maxAttempts governs
1499
1727
  // auto routing only). Cross-tier escalation is an AUTO-routing
@@ -1503,6 +1731,7 @@ export class PipelineOrchestrator {
1503
1731
  allowEscalate =
1504
1732
  !explicitModel &&
1505
1733
  !normalizedRequest.routerOptions?.forceTier &&
1734
+ (modeTier === undefined || (modeTier === 'lite' && costEscalation !== 'never')) &&
1506
1735
  tierCrossPolicy === 'allow_escalate' &&
1507
1736
  actualTier === 'lite';
1508
1737
  }
@@ -1511,7 +1740,10 @@ export class PipelineOrchestrator {
1511
1740
  chain,
1512
1741
  tier: actualTier,
1513
1742
  accessTierMode,
1743
+ comboEffortMaps: comboId ? this.registry.comboEffortMaps(comboId) : undefined,
1514
1744
  allowEscalate,
1745
+ escalateTier,
1746
+ costOrder,
1515
1747
  attemptCap,
1516
1748
  label: poolLabel,
1517
1749
  modelAccess: context?.modelAccess,
@@ -1588,10 +1820,14 @@ export class PipelineOrchestrator {
1588
1820
  // one `pickModelForEffort` originally picked, with a different effort
1589
1821
  // translation/ceiling. The header / ExecutionResult must reflect reality.
1590
1822
  {
1591
- const r = this.resolveServedEffort(actualModel, requestedEffort, actualTier, budgetTokens);
1823
+ const r = this.resolveServedEffort(actualModel, requestedEffort, actualTier, budgetTokens, execResult.effortMap);
1592
1824
  actualEffort = r.actualEffort;
1593
1825
  reasoningDegraded = r.degraded;
1594
1826
  }
1827
+ // The pool owns the failover verdict: a leader that was attempted and
1828
+ // rejected shifts the served model, and the direct path must report that
1829
+ // exactly like the cascade legs do (gate-skipped candidates are NOT
1830
+ // failovers — they were never attempted).
1595
1831
  failoverOccurred = execResult.failoverOccurred;
1596
1832
  failoverAttempts = execResult.failoverAttempts;
1597
1833
  failoverPath = execResult.failoverPath;
@@ -1700,7 +1936,10 @@ export class PipelineOrchestrator {
1700
1936
  // Cached tokens are included in input; reasoning tokens in output.
1701
1937
  const rlUsage = {
1702
1938
  tokens: usage.inputTokens + usage.outputTokens,
1703
- costUsd: computeRequestCost(usage, actualModel.pricing),
1939
+ // A vendor-reported committed cost (plugin wires whose upstream bills
1940
+ // itself, e.g. qoder credits) is the invoice; the catalog table is only
1941
+ // an estimate and exists as the fallback for wires that report none.
1942
+ costUsd: usage.vendorCostUsd ?? computeRequestCost(usage, actualModel.pricing),
1704
1943
  };
1705
1944
  let usageCredentialPrefix;
1706
1945
  {
@@ -1724,11 +1963,15 @@ export class PipelineOrchestrator {
1724
1963
  // schema-cascade turns where the lite lead owns the tier decision.
1725
1964
  // Directives deliberately write NOTHING back: a manual override is an
1726
1965
  // operator/user decision, not statistical experience to bake into routing.
1966
+ // A NO-OP directive changed nothing, so the ordinary observation stays
1967
+ // learnable; a directive that CHANGED an axis skips the write entirely.
1727
1968
  if (routeEntriesOn && promptHash) {
1728
1969
  const entryStore = getRouteEntryStore();
1729
1970
  if (decision.layerUsed === 'layer2' &&
1730
1971
  (decision.confidence ?? 0) >= L2_CONFIDENT_THRESHOLD &&
1731
- !decision.needsSchemaValidation) {
1972
+ !decision.needsSchemaValidation &&
1973
+ !tierDirectiveChanged &&
1974
+ !effortDirectiveChanged) {
1732
1975
  entryStore.upsert({
1733
1976
  promptHash,
1734
1977
  tier: actualTier,
@@ -1854,6 +2097,39 @@ export class PipelineOrchestrator {
1854
2097
  costUsd: rlUsage.costUsd,
1855
2098
  },
1856
2099
  });
2100
+ // 8B. Snapshot handoff plane (ADR-0038 / ADR-0040). Same seam as the trace,
2101
+ // so the two observation planes name the same turn identically; the canonical
2102
+ // response is only co-scoped with the ids HERE, which is why the store cannot
2103
+ // be fed from the transport's serialized bytes. Fail-open inside `recordTurn`.
2104
+ if (snapshotRequest && !snapshotRecorded) {
2105
+ snapshotRecorded = true;
2106
+ // A COMPLETED upstream request over a client that had already gone away is
2107
+ // NOT a completed conversation record: the response was drained into a dead
2108
+ // socket. Record it as `aborted` so a later reader (or a handoff) never
2109
+ // believes the model's full answer reached anyone (ADR-0040). The STICKY
2110
+ // probe is preferred — by this point `isClientGone` may read "dead" even
2111
+ // for a clean turn (socket torn down after a full send).
2112
+ const clientGoneBeforeWrite = context?.didClientLeave
2113
+ ? context.didClientLeave()
2114
+ : context?.isClientGone?.() === true;
2115
+ this.snapshotStore.recordTurn({
2116
+ sessionId,
2117
+ turnIndex: requestTurn.turnIndex,
2118
+ requestId,
2119
+ ts: startTime,
2120
+ servedModel: actualModel.id,
2121
+ ...(clientGoneBeforeWrite
2122
+ ? { outcome: 'aborted', abortReason: 'client-abort' }
2123
+ : {}),
2124
+ request: snapshotRequest,
2125
+ response: {
2126
+ status: finalResponse.status,
2127
+ ...(finalResponse.reason ? { reason: finalResponse.reason } : {}),
2128
+ output: finalResponse.output ?? [],
2129
+ usage: finalResponse.usage,
2130
+ },
2131
+ });
2132
+ }
1857
2133
  const breakerState = cbManager.getSnapshot(actualModel.id)?.state ?? 'CLOSED';
1858
2134
  // additive keys only — older readers keep reading
1859
2135
  // breakerState alone: when the turn ran in pair mode, expose the serving
@@ -1909,15 +2185,40 @@ export class PipelineOrchestrator {
1909
2185
  wireConsumesBudgetNatively(wire) {
1910
2186
  return wire === 'anthropic-messages' || wire === 'google-gemini' || wire === 'openai-responses';
1911
2187
  }
1912
- resolveServedEffort(model, requestedEffort, servedTier, budgetTokens) {
2188
+ resolveServedEffort(model, requestedEffort, servedTier, budgetTokens,
2189
+ /** Execution-time translation (e.g. a served member's own table) — when the
2190
+ * serving path already resolved one, it MUST be reused rather than
2191
+ * re-derived from the pool, because a directly-addressed combo has no
2192
+ * pool to re-derive from (ADR-0003). */
2193
+ effortMapOverride) {
1913
2194
  const effectiveRequested = requestedEffort ??
1914
2195
  (typeof budgetTokens === 'number' && budgetTokens > 0 && !this.wireConsumesBudgetNatively(model.wire)
1915
2196
  ? effortFromThinkingBudget(budgetTokens)
1916
2197
  : undefined);
1917
2198
  const ask = effectiveRequested ?? 'none';
1918
- const target = applyEffortMap(this.registry.effortMapFor(model, servedTier), ask);
2199
+ const target = applyEffortMap(effortMapOverride ?? this.registry.effortMapFor(model, servedTier), ask);
1919
2200
  const supported = modelSupportsEfforts(model.supportedReasoningEfforts, model.supportsReasoningEffort, model.reasoningDisableable) ?? [];
1920
2201
  const alwaysThink = model.reasoningDisableable === false;
2202
+ // EXPLICITLY declared no level control (`supportedReasoningEfforts: []`) or a
2203
+ // declared table WITHOUT `none`: a level the model cannot honour was never
2204
+ // sent (the wire omits it), so the honest account is "nothing in play", not
2205
+ // a rewritten `none`. Reporting `none` would claim a thinking-off the
2206
+ // gateway never requested — and on a table without `none` that field would
2207
+ // 400 (official: OpenAI `gpt-5`/`gpt-6-astra`, Gemini 3.x). An UNDECLARED
2208
+ // set (`undefined`) keeps the legacy clamp below.
2209
+ if (
2210
+ // A disableable:false model with a declared ladder clamps to its rung
2211
+ // (below) — never an omission. Only the no-rung shapes are handled here.
2212
+ !(alwaysThink && supported.length > 0) &&
2213
+ ((isDeclaredNoControl(model.supportedReasoningEfforts) && target !== 'none') ||
2214
+ (target === 'none' && effectiveRequested !== undefined && declaresLadderWithoutNone(model.supportedReasoningEfforts)))) {
2215
+ // A level the model cannot honour was never sent (the wire omits it), so
2216
+ // the honest account is "nothing in play", not a rewritten `none`.
2217
+ // Reporting `none` would claim a thinking-off the gateway never
2218
+ // requested — and on a table without `none` that field would 400.
2219
+ const explicitlyAsked = effectiveRequested !== undefined;
2220
+ return { actualEffort: undefined, degraded: explicitlyAsked };
2221
+ }
1921
2222
  // ADR-0035 absolute withholding: an always-think model with a declared
1922
2223
  // ladder can NEVER serve `none` — not even for an explicit client none-ask
1923
2224
  // or an effortMap that translates to none. It clamps to its lowest rung.
@@ -1949,9 +2250,9 @@ export class PipelineOrchestrator {
1949
2250
  *
1950
2251
  * Chain contract: chain[0] is the leader (pinned model / explicit model /
1951
2252
  * combo leader), the rest follow failover order. When `allowEscalate` is
1952
- * set (auto lite-tier only), healthy plus-tier models are appended as a
1953
- * cross-tier escalation tail — Strict Anti-Downgrade: plus chains never
1954
- * get lite models appended.
2253
+ * set (auto lite-tier only), the resolved escalation-tier models (see
2254
+ * `escalateTier`) are appended as a cross-tier escalation tail — Strict
2255
+ * Anti-Downgrade: plus chains never get lite models appended.
1955
2256
  *
1956
2257
  * Two-Tier Cost-Aware Resilience Architecture:
1957
2258
  * 1. In-Place Retry (Preserve Upstream KV Prompt Cache, Prevent 10x Cost Invalidation):
@@ -2003,12 +2304,20 @@ export class PipelineOrchestrator {
2003
2304
  let candidateList = opts.chain.map((m) => ({
2004
2305
  model: m,
2005
2306
  accessTier: accessTierOf(m),
2006
- effortMap: this.registry.effortMapFor(m, accessTierOf(m)),
2307
+ // A directly-addressed combo's PER-MEMBER table wins for its own member;
2308
+ // a member with no table (or a non-combo chain) falls back to its home
2309
+ // tier's translation.
2310
+ effortMap: opts.comboEffortMaps?.get(m.id) ?? this.registry.effortMapFor(m, accessTierOf(m)),
2007
2311
  }));
2008
2312
  if (allowEscalate) {
2009
- for (const m of this.registry.getCandidateModelsForTier('plus', true)) {
2313
+ // The escalation target is resolved by the caller (`fallback.escalateTier`
2314
+ // in smart/quality, clamped to COST_MODE_TIER_CEILING in cost mode); the
2315
+ // ceiling is only the default. `accessTier` and the effort translation
2316
+ // follow the tier the model is actually being tried from.
2317
+ const tailTier = opts.escalateTier ?? COST_MODE_TIER_CEILING;
2318
+ for (const m of this.registry.getCandidateModelsForTier(tailTier, true, { costOrder: opts.costOrder === true })) {
2010
2319
  if (!candidateList.some(c => c.model.id === m.id))
2011
- candidateList.push({ model: m, accessTier: 'plus', effortMap: this.registry.effortMapFor(m, 'plus') });
2320
+ candidateList.push({ model: m, accessTier: tailTier, effortMap: this.registry.effortMapFor(m, tailTier) });
2012
2321
  }
2013
2322
  }
2014
2323
  if (opts.modelAccess) {
@@ -2204,7 +2513,23 @@ export class PipelineOrchestrator {
2204
2513
  // `none` — the rewire must run even for an explicit none ask so the
2205
2514
  // upstream payload carries the clamped rung, not the forbidden none.
2206
2515
  const forbidsNone = candidateAlwaysThink && supported.length > 0;
2207
- if (!(target === 'none' && ask === 'none') || forbidsNone) {
2516
+ if (
2517
+ // The always-think clamp (below) owns a disableable:false model whose
2518
+ // ladder has no `none`: its declared rung is the honest floor, never
2519
+ // an omission. Only the NO-RUNG-TO-CLAMP-TO shapes route here.
2520
+ !(candidateAlwaysThink && supported.length > 0) &&
2521
+ ((isDeclaredNoControl(candidate.supportedReasoningEfforts) && target !== 'none') ||
2522
+ (target === 'none' && opts.requestedEffort !== undefined && declaresLadderWithoutNone(candidate.supportedReasoningEfforts)))) {
2523
+ // The level is not one this model can honour — never forward it as a
2524
+ // clamped `none` (a positive "off" on the chat wire, or an HTTP 400 on
2525
+ // a model whose table omits `none`). Send nothing; the vendor's own
2526
+ // default governs. Only rewrite when the request still carries an
2527
+ // effort. An UNDECLARED set (undefined) keeps the legacy clamp below.
2528
+ if (effortOf(request) !== undefined) {
2529
+ candidateReq = { ...request, reasoning: { ...request.reasoning, effort: undefined } };
2530
+ }
2531
+ }
2532
+ else if (!(target === 'none' && ask === 'none') || forbidsNone) {
2208
2533
  let candidateEffort = target === 'none' && !forbidsNone ? 'none' : downgradeReasoning(target, supported, candidateAlwaysThink);
2209
2534
  if (candidateEffort === 'none' && candidateAlwaysThink && supported.length === 0) {
2210
2535
  candidateEffort = ask;
@@ -2342,7 +2667,12 @@ export class PipelineOrchestrator {
2342
2667
  // retry decision below — the committed check at the commit point
2343
2668
  // returns first, so the two can never disagree.
2344
2669
  const willRetryInPlace = diagnosis.isInPlaceRetriable && attempt < maxInplaceAttempts && !opts.relay?.committed;
2345
- if (!willRetryInPlace) {
2670
+ // Operator-state errors are not upstream evidence (ADR-0038 §3): a
2671
+ // local run that is stopped on purpose answers `local_run_inactive`,
2672
+ // and recording it would turn a deliberate action into a breaker
2673
+ // cooldown for a model that never failed.
2674
+ const breakerExempt = err?.breakerExempt === true;
2675
+ if (!willRetryInPlace && !breakerExempt) {
2346
2676
  cbManager.recordFailureScoped(candidate.id, diagnosis, candidate.provider, credentialPrefix, this.registry.getCredentialChain(candidate.provider)?.map((c) => c.keyHashPrefix));
2347
2677
  }
2348
2678
  // Upstream-429 feedback into the local shaping window: the provider
@@ -2453,6 +2783,8 @@ export class PipelineOrchestrator {
2453
2783
  transport: opts.relay ? transport : 'buffered',
2454
2784
  // Served-attempt egress, resolved at the dial by this pool.
2455
2785
  egress: attemptEgress,
2786
+ // The translation that actually applied to the served candidate.
2787
+ effortMap: candidateEffortMap,
2456
2788
  };
2457
2789
  }
2458
2790
  }