omnicell-router 0.7.0 → 0.8.2

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 (246) hide show
  1. package/backend/dist/cli/clients/activity.d.ts +35 -0
  2. package/backend/dist/cli/clients/activity.js +67 -0
  3. package/backend/dist/cli/clients/base.d.ts +13 -2
  4. package/backend/dist/cli/clients/claude.d.ts +2 -2
  5. package/backend/dist/cli/clients/codex.d.ts +2 -2
  6. package/backend/dist/cli/clients/core-adapters.d.ts +3 -4
  7. package/backend/dist/cli/clients/core-adapters.js +3 -4
  8. package/backend/dist/cli/clients/cursor-proxy.d.ts +88 -0
  9. package/backend/dist/cli/clients/cursor-proxy.js +421 -0
  10. package/backend/dist/cli/clients/dsh.d.ts +2 -2
  11. package/backend/dist/cli/clients/grok.d.ts +2 -2
  12. package/backend/dist/cli/clients/index.d.ts +8 -1
  13. package/backend/dist/cli/clients/index.js +55 -21
  14. package/backend/dist/cli/clients/kimi.d.ts +2 -2
  15. package/backend/dist/cli/clients/launcher.d.ts +8 -0
  16. package/backend/dist/cli/clients/model-meta.js +1 -1
  17. package/backend/dist/cli/clients/omp.d.ts +2 -2
  18. package/backend/dist/cli/clients/openclaw.d.ts +2 -2
  19. package/backend/dist/cli/clients/opencode-proxy.d.ts +11 -0
  20. package/backend/dist/cli/clients/opencode-proxy.js +351 -0
  21. package/backend/dist/cli/clients/opencode.d.ts +2 -2
  22. package/backend/dist/cli/clients/pi.d.ts +2 -2
  23. package/backend/dist/cli/clients/plugin-adapters.d.ts +3 -1
  24. package/backend/dist/cli/clients/plugin-adapters.js +6 -29
  25. package/backend/dist/cli/clients/qoder-proxy.d.ts +84 -0
  26. package/backend/dist/cli/clients/qoder-proxy.js +497 -0
  27. package/backend/dist/cli/clients/reserved.d.ts +2 -6
  28. package/backend/dist/cli/clients/reserved.js +2 -0
  29. package/backend/dist/cli/clients/workbuddy.d.ts +2 -2
  30. package/backend/dist/cli/index.js +60 -9
  31. package/backend/dist/cli/types.d.ts +29 -8
  32. package/backend/dist/compression/caveman-prompts.d.ts +1 -1
  33. package/backend/dist/config/comments-en.js +6 -12
  34. package/backend/dist/config/comments-zh.js +6 -12
  35. package/backend/dist/config/defaults.d.ts +56 -1
  36. package/backend/dist/config/defaults.js +68 -0
  37. package/backend/dist/config/index.d.ts +9 -2
  38. package/backend/dist/config/index.js +26 -3
  39. package/backend/dist/config/types.d.ts +55 -43
  40. package/backend/dist/forward-proxy/egress.d.ts +10 -2
  41. package/backend/dist/forward-proxy/egress.js +42 -4
  42. package/backend/dist/forward-proxy/ordered-relay.d.ts +29 -0
  43. package/backend/dist/forward-proxy/ordered-relay.js +46 -0
  44. package/backend/dist/forward-proxy/rules.d.ts +66 -19
  45. package/backend/dist/forward-proxy/rules.js +61 -14
  46. package/backend/dist/forward-proxy/server.js +226 -77
  47. package/backend/dist/forward-proxy/system-proxy.d.ts +42 -2
  48. package/backend/dist/forward-proxy/system-proxy.js +199 -22
  49. package/backend/dist/harness/common/market.d.ts +3 -3
  50. package/backend/dist/harness/host/adapters/amp.d.ts +1 -1
  51. package/backend/dist/harness/host/adapters/antigravity.d.ts +1 -1
  52. package/backend/dist/harness/host/adapters/claude.d.ts +1 -1
  53. package/backend/dist/harness/host/adapters/cline.d.ts +1 -1
  54. package/backend/dist/harness/host/adapters/codex.d.ts +1 -1
  55. package/backend/dist/harness/host/adapters/cursor.d.ts +1 -1
  56. package/backend/dist/harness/host/adapters/dsh.d.ts +2 -2
  57. package/backend/dist/harness/host/adapters/factory.d.ts +1 -1
  58. package/backend/dist/harness/host/adapters/gemini-cli.d.ts +1 -1
  59. package/backend/dist/harness/host/adapters/grok.d.ts +1 -1
  60. package/backend/dist/harness/host/adapters/kimi.d.ts +1 -1
  61. package/backend/dist/harness/host/adapters/omp.d.ts +1 -1
  62. package/backend/dist/harness/host/adapters/openclaw.d.ts +1 -1
  63. package/backend/dist/harness/host/adapters/opencode.d.ts +1 -1
  64. package/backend/dist/harness/host/adapters/pi.d.ts +1 -1
  65. package/backend/dist/harness/host/adapters/universal.d.ts +1 -1
  66. package/backend/dist/harness/host/adapters/windsurf.d.ts +1 -1
  67. package/backend/dist/harness/host/adapters/zed.d.ts +1 -1
  68. package/backend/dist/harness/skill/skills-sh.d.ts +1 -1
  69. package/backend/dist/harness/translation.js +64 -21
  70. package/backend/dist/harness/types.d.ts +1 -1
  71. package/backend/dist/harness/types.js +1 -1
  72. package/backend/dist/index.js +31 -18
  73. package/backend/dist/ir/adapters/anthropic-stream.d.ts +18 -0
  74. package/backend/dist/ir/adapters/anthropic-stream.js +247 -0
  75. package/backend/dist/ir/adapters/anthropic.d.ts +29 -0
  76. package/backend/dist/ir/adapters/anthropic.js +788 -0
  77. package/backend/dist/ir/adapters/chat.d.ts +15 -0
  78. package/backend/dist/ir/adapters/chat.js +602 -0
  79. package/backend/dist/ir/adapters/google-stream.d.ts +22 -0
  80. package/backend/dist/ir/adapters/google-stream.js +242 -0
  81. package/backend/dist/ir/adapters/google.d.ts +9 -0
  82. package/backend/dist/ir/adapters/google.js +317 -0
  83. package/backend/dist/ir/adapters/openai-responses-output.js +8 -5
  84. package/backend/dist/ir/adapters/openai-responses.d.ts +15 -0
  85. package/backend/dist/ir/adapters/openai-responses.js +26 -1
  86. package/backend/dist/ir/adapters/responses-output.d.ts +50 -0
  87. package/backend/dist/ir/adapters/responses-output.js +348 -0
  88. package/backend/dist/ir/adapters/responses-stream.d.ts +12 -0
  89. package/backend/dist/ir/adapters/responses-stream.js +178 -0
  90. package/backend/dist/ir/adapters/responses.d.ts +14 -0
  91. package/backend/dist/ir/adapters/responses.js +646 -0
  92. package/backend/dist/ir/errors.d.ts +2 -2
  93. package/backend/dist/ir/types.d.ts +2 -1
  94. package/backend/dist/metrics/request-cost.d.ts +11 -2
  95. package/backend/dist/metrics/request-cost.js +12 -3
  96. package/backend/dist/observability/request-identity.d.ts +1 -1
  97. package/backend/dist/observability/trace-id.d.ts +40 -0
  98. package/backend/dist/observability/trace-id.js +134 -0
  99. package/backend/dist/observability/upstream-events.d.ts +82 -60
  100. package/backend/dist/observability/upstream-events.js +142 -67
  101. package/backend/dist/opencode/catalog/types.d.ts +9 -0
  102. package/backend/dist/opencode/credentials/types.d.ts +2 -2
  103. package/backend/dist/opencode/probe.d.ts +24 -1
  104. package/backend/dist/opencode/probe.js +28 -4
  105. package/backend/dist/opencode/user-config.d.ts +5 -0
  106. package/backend/dist/pipeline/directives.d.ts +6 -2
  107. package/backend/dist/pipeline/directives.js +7 -3
  108. package/backend/dist/pipeline/orchestrator.d.ts +28 -27
  109. package/backend/dist/pipeline/orchestrator.js +220 -194
  110. package/backend/dist/pipeline/unresolved-model.d.ts +33 -0
  111. package/backend/dist/pipeline/unresolved-model.js +43 -0
  112. package/backend/dist/plugins/catalog-def.d.ts +143 -0
  113. package/backend/dist/plugins/catalog-def.js +177 -0
  114. package/backend/dist/plugins/gateways.d.ts +62 -3
  115. package/backend/dist/plugins/gateways.js +139 -2
  116. package/backend/dist/plugins/host.d.ts +42 -5
  117. package/backend/dist/plugins/host.js +454 -38
  118. package/backend/dist/plugins/manifest.d.ts +119 -10
  119. package/backend/dist/plugins/manifest.js +265 -14
  120. package/backend/dist/plugins/pack.js +26 -0
  121. package/backend/dist/plugins/types.d.ts +187 -21
  122. package/backend/dist/protocols/systemone/convert.d.ts +1 -0
  123. package/backend/dist/protocols/systemone/convert.js +6 -1
  124. package/backend/dist/protocols/systemone/decide.js +18 -8
  125. package/backend/dist/providers/anthropic-messages.d.ts +12 -0
  126. package/backend/dist/providers/anthropic-messages.js +53 -0
  127. package/backend/dist/providers/anthropic.d.ts +7 -8
  128. package/backend/dist/providers/anthropic.js +36 -324
  129. package/backend/dist/providers/base.d.ts +14 -2
  130. package/backend/dist/providers/boot-direct.js +68 -38
  131. package/backend/dist/providers/dispatch.d.ts +5 -19
  132. package/backend/dist/providers/dispatch.js +46 -58
  133. package/backend/dist/providers/executors/anthropic-messages.d.ts +1 -0
  134. package/backend/dist/providers/executors/anthropic-messages.js +3 -0
  135. package/backend/dist/providers/executors/dispatch.d.ts +16 -2
  136. package/backend/dist/providers/executors/dispatch.js +39 -9
  137. package/backend/dist/providers/executors/google-gemini.d.ts +1 -0
  138. package/backend/dist/providers/executors/google-gemini.js +3 -0
  139. package/backend/dist/providers/executors/http-stream.js +16 -3
  140. package/backend/dist/providers/executors/openai-chat.d.ts +1 -0
  141. package/backend/dist/providers/executors/openai-chat.js +3 -0
  142. package/backend/dist/providers/executors/openai-responses.d.ts +1 -0
  143. package/backend/dist/providers/executors/openai-responses.js +3 -0
  144. package/backend/dist/providers/executors/plugin-adapter.js +4 -4
  145. package/backend/dist/providers/google-gemini.d.ts +12 -0
  146. package/backend/dist/providers/google-gemini.js +50 -0
  147. package/backend/dist/providers/google.d.ts +7 -8
  148. package/backend/dist/providers/google.js +35 -308
  149. package/backend/dist/providers/http-json.d.ts +19 -0
  150. package/backend/dist/providers/http-json.js +104 -0
  151. package/backend/dist/providers/http-stream.d.ts +52 -0
  152. package/backend/dist/providers/http-stream.js +423 -0
  153. package/backend/dist/providers/member-match.d.ts +4 -5
  154. package/backend/dist/providers/member-match.js +4 -5
  155. package/backend/dist/providers/openai-chat.d.ts +13 -0
  156. package/backend/dist/providers/openai-chat.js +99 -0
  157. package/backend/dist/providers/openai-compatible.d.ts +7 -4
  158. package/backend/dist/providers/openai-compatible.js +71 -368
  159. package/backend/dist/providers/openai-responses.d.ts +12 -0
  160. package/backend/dist/providers/openai-responses.js +68 -0
  161. package/backend/dist/providers/opencode-proxy.d.ts +5 -5
  162. package/backend/dist/providers/opencode-proxy.js +49 -125
  163. package/backend/dist/providers/plugin-adapter.d.ts +9 -0
  164. package/backend/dist/providers/plugin-adapter.js +31 -0
  165. package/backend/dist/providers/registry.d.ts +49 -24
  166. package/backend/dist/providers/registry.js +97 -55
  167. package/backend/dist/providers/responses.d.ts +7 -28
  168. package/backend/dist/providers/responses.js +45 -253
  169. package/backend/dist/providers/tool-markup-leak.d.ts +41 -0
  170. package/backend/dist/providers/tool-markup-leak.js +57 -0
  171. package/backend/dist/providers/tool-markup-recovery.d.ts +27 -0
  172. package/backend/dist/providers/tool-markup-recovery.js +786 -0
  173. package/backend/dist/providers/virtual-meta.d.ts +21 -2
  174. package/backend/dist/providers/virtual-meta.js +49 -9
  175. package/backend/dist/proxy/asset-download.d.ts +54 -0
  176. package/backend/dist/proxy/asset-download.js +420 -0
  177. package/backend/dist/proxy/manual-node-spec.d.ts +16 -16
  178. package/backend/dist/proxy/mihomo-binary.d.ts +17 -2
  179. package/backend/dist/proxy/mihomo-binary.js +62 -51
  180. package/backend/dist/proxy/mihomo-client.js +15 -1
  181. package/backend/dist/proxy/mihomo-config.js +11 -2
  182. package/backend/dist/proxy/mihomo-geo.d.ts +87 -0
  183. package/backend/dist/proxy/mihomo-geo.js +213 -0
  184. package/backend/dist/proxy/mihomo-logs.d.ts +27 -0
  185. package/backend/dist/proxy/mihomo-logs.js +70 -0
  186. package/backend/dist/proxy/mihomo-pac.d.ts +11 -0
  187. package/backend/dist/proxy/mihomo-pac.js +15 -0
  188. package/backend/dist/proxy/mihomo-rules-import.d.ts +1 -1
  189. package/backend/dist/proxy/mihomo-rules-import.js +7 -7
  190. package/backend/dist/proxy/mihomo-sidecar.d.ts +17 -1
  191. package/backend/dist/proxy/mihomo-sidecar.js +148 -26
  192. package/backend/dist/quota/adapters/minimax.js +36 -13
  193. package/backend/dist/quota/cli-login.d.ts +8 -0
  194. package/backend/dist/quota/cli-login.js +18 -0
  195. package/backend/dist/quota/declarations.js +10 -0
  196. package/backend/dist/quota/dsl.js +18 -5
  197. package/backend/dist/quota/engine.d.ts +22 -1
  198. package/backend/dist/quota/engine.js +170 -29
  199. package/backend/dist/quota/prober.d.ts +5 -0
  200. package/backend/dist/quota/prober.js +11 -2
  201. package/backend/dist/quota/types.d.ts +87 -8
  202. package/backend/dist/quota/verdict.d.ts +35 -0
  203. package/backend/dist/quota/verdict.js +135 -0
  204. package/backend/dist/ratelimit/admission.d.ts +131 -0
  205. package/backend/dist/ratelimit/admission.js +233 -0
  206. package/backend/dist/ratelimit/rate-limiter.js +6 -0
  207. package/backend/dist/resilience/types.d.ts +2 -2
  208. package/backend/dist/router/layer2-decision.d.ts +1 -1
  209. package/backend/dist/router/layer2-decision.js +5 -8
  210. package/backend/dist/routes/console.js +248 -52
  211. package/backend/dist/routes/mihomo.d.ts +2 -0
  212. package/backend/dist/routes/mihomo.js +334 -29
  213. package/backend/dist/routes/responses.d.ts +87 -8
  214. package/backend/dist/routes/responses.js +314 -33
  215. package/backend/dist/server.js +34 -6
  216. package/backend/dist/session/session-manager.d.ts +6 -0
  217. package/backend/dist/session/session-manager.js +20 -9
  218. package/backend/dist/surfaces/chat-pipeline.d.ts +2 -2
  219. package/backend/dist/surfaces/chat-pipeline.js +17 -7
  220. package/backend/dist/surfaces/chat.js +15 -0
  221. package/backend/dist/surfaces/decision-pipeline.js +7 -10
  222. package/backend/dist/surfaces/direct-forward.d.ts +3 -0
  223. package/backend/dist/surfaces/direct-forward.js +206 -0
  224. package/backend/dist/surfaces/rate-limit-response.d.ts +17 -0
  225. package/backend/dist/surfaces/rate-limit-response.js +57 -0
  226. package/backend/dist/surfaces/types.d.ts +11 -0
  227. package/backend/dist/trace/tracker.d.ts +32 -1
  228. package/backend/dist/trace/tracker.js +29 -4
  229. package/backend/dist/types/router.d.ts +34 -12
  230. package/backend/dist/types/router.js +35 -6
  231. package/backend/dist/utils/chat-stream.d.ts +21 -8
  232. package/backend/dist/utils/chat-stream.js +46 -9
  233. package/backend/dist/utils/event-ring.d.ts +4 -0
  234. package/backend/dist/utils/event-ring.js +4 -0
  235. package/backend/dist/utils/popularity.js +29 -4
  236. package/backend/dist/utils/proxy.d.ts +7 -0
  237. package/backend/dist/utils/proxy.js +35 -10
  238. package/backend/dist/utils/retry-after.d.ts +21 -0
  239. package/backend/dist/utils/retry-after.js +36 -0
  240. package/bin/ocr.js +2 -2
  241. package/frontend/dist/assets/index-55VVwfFQ.js +1521 -0
  242. package/frontend/dist/assets/{index-CQSLGFTV.css → index-DxZ9MHKB.css} +1 -1
  243. package/frontend/dist/assets/workbuddy.color-DOMpQkxJ.svg +29 -0
  244. package/frontend/dist/index.html +2 -2
  245. package/package.json +1 -1
  246. package/frontend/dist/assets/index-CLvxJjp_.js +0 -1476
@@ -1,5 +1,5 @@
1
1
  import path from 'node:path';
2
- import { EFFORT_LADDER, TIER_RANK, downgradeReasoning, effortFromThinkingBudget } from '../types/router.js';
2
+ import { EFFORT_LADDER, TIER_RANK, 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';
@@ -25,6 +25,7 @@ import { SessionManager } from '../session/session-manager.js';
25
25
  import { getEnvPaths } from '../config/env.js';
26
26
  import { TraceTracker } from '../trace/tracker.js';
27
27
  import { CaptureRecorder } from '../capture/recorder.js';
28
+ import { UpstreamEventContext } from '../observability/upstream-events.js';
28
29
  import { emitClientRequest, captureKeyIdentity, setClientExchangeContext } from '../observability/http-exchange.js';
29
30
  import { resolveClientRequestId, mintRequestId } from '../observability/request-identity.js';
30
31
  import { getWarnThrottle } from '../observability/warn-throttle.js';
@@ -277,6 +278,17 @@ export class PipelineOrchestrator {
277
278
  getCircuitBreakerManager() {
278
279
  return this.registry.getCircuitBreakerManager();
279
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
+ }
280
292
  /**
281
293
  * Auto-request routing with the experience table in front of the decision layer
282
294
  * (ADR-0011): an entry hit short-circuits L2 entirely — the table IS a
@@ -313,10 +325,9 @@ export class PipelineOrchestrator {
313
325
  }
314
326
  }
315
327
  return RouterEngine.routeAsync(request, this.config.classifier, this.registry, this.config.systemone?.defaultModel,
316
- // Decision-call capture identity: the outer turn's requestId/sessionId (only
317
- // exists while the capture master is on). The LAYER 2 DECISION applies
318
- // the recorder master gate (requestCapture.enabled) — when off it
319
- // 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.
320
331
  decisionCapture,
321
332
  // Failure attribution: decision layer wire failures land in the failure_events
322
333
  // ledger tagged with THIS conversation, whatever the capture switch.
@@ -334,25 +345,6 @@ export class PipelineOrchestrator {
334
345
  getProberIntervalMs() {
335
346
  return this.healthProber?.getIntervalMs() ?? 0;
336
347
  }
337
- /**
338
- * Public entry point — thin capture wrapper around processInternal.
339
- *
340
- * Records the full request/response into the opt-in CaptureRecorder audit
341
- * log on BOTH the success and the failure path (debugging failed requests
342
- * is the primary use case). Implemented as a wrapper instead of an inline
343
- * hook so processInternal stays untouched: the session-id resolution and
344
- * the PRE-compression message snapshot are rebuilt here with the same pure
345
- * functions (PromptOptimizer.normalizeMessages / scanDirectives /
346
- * resolveSessionId) — all deterministic and run in the same synchronous
347
- * segment, so the wrapper snapshot is byte-identical to the scrubbed chain
348
- * processInternal routes on before applyCompression mutates the request
349
- * (ADR-0011 §4: the scrubbed chain feeds hashing, snippets, traces AND
350
- * capture — reserved tokens never reach the archive, and session /
351
- * conversation anchor resolution sees the same bytes the router sees).
352
- * Request headers are captured in
353
- * SANITIZED form (credential values masked per the deny-list in
354
- * observability/http-exchange.ts), never raw.
355
- */
356
348
  /** One-shot allocation of the write-time turn identity (ADR-0024). */
357
349
  allocateTurn(sessionId, input) {
358
350
  // Retained traces seed the counter for sessions that predate the v3
@@ -367,6 +359,14 @@ export class PipelineOrchestrator {
367
359
  turnDecision: a.turnDecision,
368
360
  };
369
361
  }
362
+ /**
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).
369
+ */
370
370
  async process(request, context,
371
371
  /**
372
372
  * Progressive-output relay (see utils/stream-relay). Offered by a transport
@@ -385,52 +385,47 @@ export class PipelineOrchestrator {
385
385
  // Headers come from the transport that owns the leg: the Fastify leg
386
386
  // reads its own request, the MITM leg the original clientRequest headers,
387
387
  // then plain `headers` (in-process/test callers).
388
- const traceHeaders = context?.fastifyRequest?.headers ?? context?.clientRequest?.headers ?? context?.headers;
389
- const clientRequest = traceHeaders ? resolveClientRequestId({ headers: traceHeaders }) : {};
388
+ const admissionHeaders = context?.headers ?? context?.clientRequest?.headers ?? context?.fastifyRequest?.headers;
389
+ const clientRequest = admissionHeaders ? resolveClientRequestId({ headers: admissionHeaders }) : {};
390
390
  const turnIdentity = {
391
391
  requestId: mintRequestId(),
392
392
  ...(clientRequest.clientRequestId ? { clientRequestId: clientRequest.clientRequestId } : {}),
393
393
  turn: NO_TURN,
394
- allocated: false,
395
394
  };
396
- let captureSessionId = '';
397
- let preResolvedSession;
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);
398
426
  let upstreamEventContext;
399
427
  if (captureEnabled) {
400
- // ADR-0011 §4: reserved tokens never reach the archive. Session and
401
- // conversation identity use the scrubbed IR chain; the client event uses
402
- // a separately scrubbed projection of the original protocol envelope.
403
- // scanDirectives is idempotent; processInternal scrubs the live request
404
- // again on its own path.
405
- const normalizedMessages = PromptOptimizer.normalizeMessages(request);
406
- // Scrub with the LIVE gate (enabled flag + configured prefix), matching
407
- // processInternal — a relocated prefix or a disabled gate must not
408
- // desync capture/anchor bytes from what the router actually serves.
409
- const gate = directivesGate();
410
- const snapshotScan = scanDirectives(normalizedMessages, gate.enabled ? gate.prefix : null, request.instructions);
411
- const snapshotRequest = {
412
- ...request,
413
- input: snapshotScan.input,
414
- ...(request.instructions !== undefined ? { instructions: snapshotScan.instructions } : {}),
415
- };
416
- const keyIdentity = keyIdentityOf(context);
417
- // Resolve ONCE here and hand the result to processInternal: cold-start
418
- // IDs carry fresh random entropy, so a second resolve of the same
419
- // request would mint a different ID and split capture from routing.
420
- preResolvedSession = this.sessionManager.resolveSessionId(snapshotRequest, {
421
- keyId: keyIdentity?.id,
422
- headers: context?.headers,
423
- });
424
- captureSessionId = preResolvedSession.sessionId;
425
- // ADR-0024: allocate the turn boundary ONCE — after the final session
426
- // binding, before the first event. Re-entries, retries, failover hops
427
- // and the L2 decision leg copy it; none of them re-allocate.
428
- turnIdentity.turn = this.allocateTurn(captureSessionId, snapshotRequest.input);
429
- turnIdentity.allocated = true;
430
- // Deterministic conversation key stamped onto EVERY event of the request:
431
- // the capture archive can regroup turns even when the volatile session
432
- // id shifts (content-addressed, never a credential, mirrors the
433
- // session-manager resolution input exactly).
428
+ // Content-addressed regroup key for the archive only. Not a session id.
434
429
  const conversationKey = SessionManager.conversationKey(snapshotRequest.input || [], keyIdentity?.id) ?? undefined;
435
430
  // CLIENT REQUEST event fires synchronously here — independent of any
436
431
  // response. Even if the upstream call hangs / times out / the handler
@@ -444,7 +439,7 @@ export class PipelineOrchestrator {
444
439
  req: context?.fastifyRequest ?? context?.clientRequest,
445
440
  apiKey: keyIdentity,
446
441
  body: scrubWireDirectives(context?.clientBody ?? snapshotRequest, gate.enabled ? gate.prefix : null),
447
- sessionId: captureSessionId,
442
+ sessionId: admissionSessionId,
448
443
  clientRequestId: turnIdentity.clientRequestId,
449
444
  requestId: turnIdentity.requestId,
450
445
  model: request.model || 'auto',
@@ -457,9 +452,9 @@ export class PipelineOrchestrator {
457
452
  else if (context?.onClientExchange) {
458
453
  context.onClientExchange(clientExchangeCtx);
459
454
  }
460
- upstreamEventContext = {
455
+ upstreamEventContext = new UpstreamEventContext({
461
456
  recorder: this.captureRecorder,
462
- sessionId: captureSessionId,
457
+ sessionId: admissionSessionId,
463
458
  clientRequestId: turnIdentity.clientRequestId,
464
459
  requestId: turnIdentity.requestId,
465
460
  model: request.model || 'auto',
@@ -469,7 +464,7 @@ export class PipelineOrchestrator {
469
464
  apiKey: keyIdentity,
470
465
  conversationKey,
471
466
  turn: turnIdentity.turn,
472
- };
467
+ });
473
468
  }
474
469
  // Provider-leg transport (streaming.upstream.mode — ADR-0008 §1):
475
470
  // buffered → never hand a relay to the executor pool (the historical
@@ -479,7 +474,7 @@ export class PipelineOrchestrator {
479
474
  // response. The sink never writes a byte, so `committed` stays
480
475
  // false and retries/failover remain legal;
481
476
  // follow → the client's own relay (or none) — historical behavior.
482
- return await this.processInternal(request, context, preResolvedSession, upstreamEventContext, turnIdentity, this.resolveUpstreamRelay(relay));
477
+ return await this.processInternal(snapshotRequest, snapshotScan, addressed, context, preResolvedSession, upstreamEventContext, turnIdentity, this.resolveUpstreamRelay(relay));
483
478
  }
484
479
  /**
485
480
  * Apply `streaming.upstream.mode` to the surface-supplied relay. The sink
@@ -496,42 +491,13 @@ export class PipelineOrchestrator {
496
491
  return mode === 'stream' ? UPSTREAM_SINK_RELAY : undefined;
497
492
  }
498
493
  /**
499
- * Complete orchestration workflow:
500
- * 1. Prompt normalization (canonical order)
501
- * 2. Zero-header session identification & prefix fingerprinting
502
- * 3. Multi-Layer hierarchical routing (Layer 0 -> Layer 2)
503
- * 4. Monotonic Ratchet session state enforcement + Session-Pin Eviction
504
- * 5. Execution with Circuit Breaker, Transparent Failover & Schema Assertion
505
- * 6. FinOps accounting
506
- * 7. Post-turn prefix fingerprint registration
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.
507
499
  */
508
- async processInternal(request, context, preResolvedSession, upstreamEventContext, turnIdentity, relay) {
509
- const clientRequestId = turnIdentity?.clientRequestId;
510
- const requestId = turnIdentity?.requestId ?? mintRequestId();
511
- const startTime = Date.now();
512
- // 1. Optimize message prefix order & resolve virtual routing models
513
- const normalizedMessages = PromptOptimizer.normalizeMessages(request);
514
- // 1.0 Control directives (ADR-0011 rewrite): SCRUB first, before anything
515
- // reads or forwards the chain. Every reserved token is removed from every
516
- // role and text part, and directive-only messages are dropped, so the
517
- // upstream payload is byte-equivalent to one that never carried a directive
518
- // (stable prefix cache, no reserved word at any vendor). Only the LAST user
519
- // message's tokens are actionable — and only for this turn. The namespace
520
- // comes from the hot-applied gate (`directives.prefix`); `enabled: false`
521
- // disables the scan entirely, so tokens travel as ordinary text.
522
- const directiveGate = directivesGate();
523
- const directivePrefix = directiveGate.prefix;
524
- const directiveScan = scanDirectives(normalizedMessages, directiveGate.enabled ? directivePrefix : null, request.instructions);
525
- if (directiveScan.droppedMessages > 0 &&
526
- !directiveScan.input.some((item) => item.type === 'message' && item.role === 'user')) {
527
- // A directive-only prompt with no history: nothing left to send.
528
- throw Object.assign(new Error(`Empty prompt — ${directivePrefix}* directives were the only content in the request`), { statusCode: 400 });
529
- }
530
- const normalizedRequest = {
531
- ...request,
532
- input: directiveScan.input,
533
- ...(request.instructions !== undefined ? { instructions: directiveScan.instructions } : {}),
534
- };
500
+ resolveAddressedModel(request, context) {
535
501
  let explicitModel;
536
502
  let variantUsed;
537
503
  // Routing-name matching trims once. `request.model` itself stays verbatim
@@ -542,7 +508,7 @@ export class PipelineOrchestrator {
542
508
  const modelName = (request.model ?? '').trim();
543
509
  const bareTier = tierFromVirtualEntry(modelName);
544
510
  if (bareTier) {
545
- normalizedRequest.routerOptions = { ...normalizedRequest.routerOptions, forceTier: bareTier };
511
+ request.routerOptions = { ...request.routerOptions, forceTier: bareTier };
546
512
  }
547
513
  else if (modelName && modelName !== 'auto') {
548
514
  const specific = this.registry.getModel(modelName);
@@ -553,7 +519,7 @@ export class PipelineOrchestrator {
553
519
  // same-model retry and credential re-spread still apply; the model
554
520
  // itself is never substituted (ADR-0014).
555
521
  explicitModel = specific;
556
- normalizedRequest.routerOptions = { ...normalizedRequest.routerOptions, forceTier: specific.tier };
522
+ request.routerOptions = { ...request.routerOptions, forceTier: specific.tier };
557
523
  }
558
524
  else {
559
525
  const variantRef = this.registry.resolveVariantRef(modelName);
@@ -566,9 +532,9 @@ export class PipelineOrchestrator {
566
532
  // applies its downgrade/honesty contract.
567
533
  explicitModel = variantRef.base;
568
534
  variantUsed = variantRef.variant.id;
569
- setEffort(normalizedRequest, variantRef.variant.reasoningEffort);
570
- normalizedRequest.model = variantRef.base.id;
571
- normalizedRequest.routerOptions = { ...normalizedRequest.routerOptions, forceTier: variantRef.base.tier };
535
+ setEffort(request, variantRef.variant.reasoningEffort);
536
+ request.model = variantRef.base.id;
537
+ request.routerOptions = { ...request.routerOptions, forceTier: variantRef.base.tier };
572
538
  }
573
539
  else if (modelName.includes('#')) {
574
540
  // `#variant` is explicit syntax — a typo must fail loud instead of
@@ -603,8 +569,8 @@ export class PipelineOrchestrator {
603
569
  // models stay addressable by their full provider-prefixed id.
604
570
  if (bareHits.length > 0 && !this.registry.isCombo(modelName)) {
605
571
  explicitModel = bareHits[0];
606
- normalizedRequest.routerOptions = {
607
- ...normalizedRequest.routerOptions,
572
+ request.routerOptions = {
573
+ ...request.routerOptions,
608
574
  forceTier: explicitModel.tier,
609
575
  };
610
576
  }
@@ -617,69 +583,54 @@ export class PipelineOrchestrator {
617
583
  }
618
584
  }
619
585
  }
620
- // 1A. Custom model combo: the client named a configured combo id — the
621
- // 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,
622
588
  // session ratchet and schema-assertion escalation are all bypassed
623
589
  // (explicit user composition wins, mirroring the exact-model
624
590
  // pass-through above).
625
591
  const comboByName = !explicitModel && modelName && this.registry.isCombo(modelName) ? modelName : undefined;
626
592
  if (comboByName && this.registry.isComboDisabled(comboByName)) {
627
- // Fail fast like the empty-member case below: the combo is hidden from
628
- // /v1/models, so an in-flight client naming it must get a loud 404 —
629
- // routing it as `auto` would be invisible billing/model drift.
630
593
  throw Object.assign(new Error(`Combo '${comboByName}' is disabled — re-enable it in the console or choose another model.`), { statusCode: 404 });
631
594
  }
632
595
  if (comboByName && this.registry.resolveCombo(comboByName).length === 0) {
633
- // Fail fast instead of silently degrading to classifier routing: the
634
- // combo is still advertised via /v1/models, so routing it as `auto`
635
- // would be invisible billing/model drift.
636
- // 404 like the disabled branch above: the combo is not currently
637
- // routable (no member registered) — an operator-config gap must not
638
- // read as an upstream 502.
639
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 });
640
597
  }
641
598
  const comboId = comboByName ?? undefined;
642
- // Defense in depth: an explicitly named model outside the key's model
643
- // policy fails loud here (HTTP routes entry-check this too; direct
644
- // orchestrator callers might not). The model's FULL membership set is
645
- // passed so TIER-level entries (lite/plus/pro/ultra) match exactly
646
- // as they do in the execution pool filter (executeCandidatePool) — a
647
- // tier-denied explicit model must not slip through the bare-name/variant
648
- // resolution paths, and a multi-pool model is admitted when any of its
649
- // 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.
650
603
  if (explicitModel &&
651
604
  context?.modelAccess &&
652
605
  !isModelAllowedInTiers(explicitModel.id, context.modelAccess, this.registry.tiersOf(explicitModel))) {
653
606
  throw Object.assign(new Error(`API key model policy denies model '${explicitModel.id}'`), { statusCode: 403 });
654
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;
655
623
  // 1B. Global routing mode (config.routing.mode) — cost/quality force the tier
656
624
  // for auto/tier-alias requests; explicit client choices always win.
657
625
  const modeTier = routingModeForceTier(normalizedRequest.model, normalizedRequest.routerOptions, this.config.routing?.mode);
658
626
  if (modeTier) {
659
627
  normalizedRequest.routerOptions = { ...normalizedRequest.routerOptions, forceTier: modeTier };
660
628
  }
661
- // 2. Identify / track conversation session (zero-header layered resolution).
662
- // Reuse the capture-time resolve when present: both call sites normalize
663
- // identically, and one request must yield exactly one session ID. The
664
- // client conversation ref is resolved ONCE here and handed to both the
665
- // resolver and the trace, so the console's "both ids" view and the session
666
- // it names can never disagree.
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.
667
631
  const clientRef = SessionManager.clientRefOf(normalizedRequest);
668
- const sessionResolve = preResolvedSession ??
669
- this.sessionManager.resolveSessionId(normalizedRequest, {
670
- keyId: keyIdentityOf(context)?.id,
671
- headers: context?.headers,
672
- clientRef: clientRef ?? undefined,
673
- });
674
- const sessionId = sessionResolve.sessionId;
675
- // Capture-disabled requests reach the admission gate only here; allocate
676
- // exactly once so the trace plane carries the same identity regardless of
677
- // the capture switch. `allocated` makes the two gates mutually exclusive.
678
- if (turnIdentity && !turnIdentity.allocated) {
679
- turnIdentity.turn = this.allocateTurn(sessionId, normalizedRequest.input);
680
- turnIdentity.allocated = true;
681
- }
682
- const requestTurn = turnIdentity?.turn ?? NO_TURN;
632
+ const sessionId = preResolvedSession.sessionId;
633
+ const requestTurn = turnIdentity.turn;
683
634
  // 2B. Snapshot canonical strings before pairing/compression. Session
684
635
  // anchors must describe the bytes the client sent, not a compressed or
685
636
  // repaired upstream projection. Serialization avoids a deep content clone.
@@ -753,7 +704,7 @@ export class PipelineOrchestrator {
753
704
  if (explicitModel && initialDecision.reasonCode === 'forced') {
754
705
  initialDecision.reasonCode = 'explicit.model';
755
706
  initialDecision.reason = `Explicit model '${explicitModel.id}' — routed to the named model, no tier judgment`;
756
- initialDecision.reasonParams = { model: explicitModel.id, tier: explicitModel.tier };
707
+ initialDecision.reasonParams = { model: explicitModel.id, ...(explicitModel.tier ? { tier: explicitModel.tier } : {}) };
757
708
  }
758
709
  // ADR-0012 §1 + ADR-0011 floor: L2-decided effort joins the request
759
710
  // exactly like a route-entry hit — only into an omitted field (the
@@ -824,7 +775,7 @@ export class PipelineOrchestrator {
824
775
  let ratchetApplied = false;
825
776
  let sessionRequestCount;
826
777
  if (sessionMode === 'bypass') {
827
- decision = { ...initialDecision, sessionId, sessionRatchetApplied: false, sessionLookupType: sessionResolve.lookupType };
778
+ decision = { ...initialDecision, sessionId, sessionRatchetApplied: false, sessionLookupType: preResolvedSession.lookupType };
828
779
  // Bypass never mints a session entity, so getSession reads undefined
829
780
  // every turn and stamped every combo request #1 in the console's
830
781
  // request-detail table. Dedicated counter instead — display-only
@@ -836,7 +787,7 @@ export class PipelineOrchestrator {
836
787
  // Tier representative for session bookkeeping (pin birth). An
837
788
  // explicitly named model IS the representative of its own turn —
838
789
  // consulting the pool for it would hard-throw in a pool-less
839
- // deployment where every registered model is unclassified, even
790
+ // deployment where no member list claims any registered model, even
840
791
  // though the request itself is directly callable by design. Bare
841
792
  // `auto` keeps resolving through the pool (its empty-pool throw is
842
793
  // the honest "add tier members" answer).
@@ -844,7 +795,7 @@ export class PipelineOrchestrator {
844
795
  decision = ratchetResult.finalDecision;
845
796
  decision.sessionId = sessionId;
846
797
  decision.sessionRatchetApplied = ratchetResult.ratchetApplied;
847
- decision.sessionLookupType = sessionResolve.lookupType;
798
+ decision.sessionLookupType = preResolvedSession.lookupType;
848
799
  ratchetApplied = ratchetResult.ratchetApplied;
849
800
  sessionRequestCount = ratchetResult.session.requestCount;
850
801
  }
@@ -904,7 +855,7 @@ export class PipelineOrchestrator {
904
855
  // the client ip and the first-message snippet for UI identification.
905
856
  const bornSession = this.sessionManager.getSession(sessionId);
906
857
  if (bornSession && bornSession.requestCount === 1) {
907
- this.sessionManager.attachOrigin(sessionId, { wire: context?.wire, lookupType: sessionResolve.lookupType }, context?.clientIp, firstUserSummary);
858
+ this.sessionManager.attachOrigin(sessionId, { wire: context?.wire, lookupType: preResolvedSession.lookupType }, context?.clientIp, firstUserSummary);
908
859
  }
909
860
  // 4A. Directives (`<prefix>tier-up` / `<prefix>tier-down`, ADR-0011
910
861
  // rewrite) — TIER axis. Deliberately
@@ -1007,13 +958,13 @@ export class PipelineOrchestrator {
1007
958
  // (removed from config.models; the unresolvable-pin / zombie case,
1008
959
  // which pre-fix silently re-fell back through the getModelForTier
1009
960
  // head below every turn without ever writing the pin back), it reads
1010
- // `unclassified` (removed from every tier member list / no glob
1011
- // claims it any more), or the global denylist (tiers.exclude) vetoes
1012
- // it. A model MOVED to another tier is NOT evicted: the new tier's
1013
- // member list claims it, so it still joins that pool (multi-membership
1014
- // included — eviction fires only when NO pool claims the id).
1015
- // Hand-configured models (no tierMatch) are reclassification-immune —
1016
- // 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
1017
968
  // removal can. Checked with healthyOnly=false so health never
1018
969
  // masquerades as config intent (and vice versa below).
1019
970
  // HEALTH (runtime reality, model CAPABILITY view —
@@ -1035,7 +986,7 @@ export class PipelineOrchestrator {
1035
986
  // session on a model that cannot serve now.
1036
987
  const configEvicted = pinnedId !== undefined &&
1037
988
  (preferredModel === null ||
1038
- !this.registry.getCandidateModelsForTier(preferredModel.tier, false).some((m) => m.id === pinnedId));
989
+ !this.poolOfHomedModel(preferredModel).some((m) => m.id === pinnedId));
1039
990
  const healthEvicted = preferredModel !== null && this.registry.modelHealthView(preferredModel) === 'unavailable';
1040
991
  if (pinnedId && (configEvicted || healthEvicted)) {
1041
992
  const healthyReplacement = this.registry.getModelForTier(actualTier, true);
@@ -1083,18 +1034,25 @@ export class PipelineOrchestrator {
1083
1034
  const pinnedId = this.sessionManager.getSession(sessionId)?.pinnedModel;
1084
1035
  preferredModel = pinnedId ? this.registry.getModel(pinnedId) ?? null : null;
1085
1036
  // Follow gates: a same-tier pin (pure KV affinity — serving it cannot
1086
- // cross the contract), the EMPTY-tier degraded landing (the pin IS the
1087
- // model getModelForTier degrades to), or a zombie id (repair to the
1088
- // 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
1089
1042
  // while the forced pool has members — is neither followed nor
1090
1043
  // rewritten (ADR-0014).
1091
1044
  const tierPool = this.registry.getCandidateModelsForTier(actualTier, false);
1092
1045
  const degradeLanding = preferredModel !== null &&
1093
1046
  tierPool.length === 0 &&
1094
1047
  this.registry.getModelForTier(actualTier).id === preferredModel.id;
1095
- 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)) {
1096
1054
  const configEvicted = preferredModel === null ||
1097
- !this.registry.getCandidateModelsForTier(preferredModel.tier, false).some((m) => m.id === pinnedId);
1055
+ !this.poolOfHomedModel(preferredModel).some((m) => m.id === pinnedId);
1098
1056
  const healthEvicted = preferredModel !== null && this.registry.modelHealthView(preferredModel) === 'unavailable';
1099
1057
  if (configEvicted || healthEvicted) {
1100
1058
  const healthyReplacement = this.registry.getModelForTier(actualTier, true);
@@ -1121,7 +1079,7 @@ export class PipelineOrchestrator {
1121
1079
  // resolution must not consult the tier pool when the request already
1122
1080
  // carries its own model: a combo is the sanctioned way to address
1123
1081
  // pool-less models, and an explicitly named model stays directly
1124
- // callable by design — when every registered model is unclassified the
1082
+ // callable by design — when no member list claims any registered model the
1125
1083
  // tier lookup hard-throws and would kill both (and the placeholder is
1126
1084
  // overwritten by the executed member after the pool run regardless).
1127
1085
  // The combo's first resolved member is the honestest combo placeholder;
@@ -1178,10 +1136,18 @@ export class PipelineOrchestrator {
1178
1136
  // model pick can honour a raised level. Per-turn: it writes the request
1179
1137
  // for this call only and never records session state.
1180
1138
  if (directivesApplicable) {
1181
- const supportedEfforts = actualModel.supportedReasoningEfforts
1182
- ?? (actualModel.supportsReasoningEffort ? EFFORT_LADDER : undefined);
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);
1183
1149
  const before = effortOf(normalizedRequest);
1184
- const effortDirective = applyEffortDirectives(directiveActions, before, supportedEfforts);
1150
+ const effortDirective = applyEffortDirectives(directiveActions, before, supportedEfforts, actualModel.reasoningDisableable === false);
1185
1151
  if (effortDirective.applied) {
1186
1152
  const suffix = effortDirective.suffix ?? (effortDirective.delta > 0 ? 'effort-up' : 'effort-down');
1187
1153
  const token = `${directivePrefix}${suffix}`;
@@ -1271,16 +1237,21 @@ export class PipelineOrchestrator {
1271
1237
  // Explicit model choice / session pin: never re-route, but translate by
1272
1238
  // the model's pool effortMap first (none included), then clamp to what
1273
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;
1274
1245
  const target = applyEffortMap(this.registry.effortMapFor(preferredModel, actualTier), requestedEffort ?? 'none');
1275
- if (target === 'none') {
1246
+ if (target === 'none' && !forbidsNone) {
1276
1247
  actualEffort = requestedEffort; // nothing in play — mirror exactly
1277
1248
  }
1278
1249
  else {
1279
- const supported = preferredModel.supportedReasoningEfforts
1280
- ?? (preferredModel.supportsReasoningEffort
1281
- ? EFFORT_LADDER
1282
- : []);
1283
- 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;
1284
1255
  actualEffort = recomputed;
1285
1256
  reasoningDegraded =
1286
1257
  EFFORT_LADDER.indexOf(recomputed) < EFFORT_LADDER.indexOf(requestedEffort ?? 'none');
@@ -1314,6 +1285,11 @@ export class PipelineOrchestrator {
1314
1285
  // §1). Buffered by construction on the cascade's lite lead (it is never
1315
1286
  // given a relay) and whenever `streaming.upstream.mode` is `buffered`.
1316
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;
1317
1293
  // 5. Execution with Cascading Fallback & Schema Assertion
1318
1294
  // (lite-lead cascade is skipped for explicit model choices, combos AND
1319
1295
  // forced tiers — the client named exactly what to run. A forced tier is
@@ -1367,6 +1343,7 @@ export class PipelineOrchestrator {
1367
1343
  inplaceRetries += liteResult.inplaceRetries;
1368
1344
  servedCredentialPrefix = liteResult.servedCredentialPrefix;
1369
1345
  upstreamStream = liteResult.transport;
1346
+ servedEgress = liteResult.egress;
1370
1347
  }
1371
1348
  else {
1372
1349
  assertionError = validation.error || 'Schema validation assertion failed';
@@ -1397,7 +1374,7 @@ export class PipelineOrchestrator {
1397
1374
  layerUsed: decision.layerUsed || 'layer0',
1398
1375
  sessionId,
1399
1376
  sessionRatchetApplied: ratchetApplied,
1400
- sessionLookupType: sessionResolve.lookupType,
1377
+ sessionLookupType: preResolvedSession.lookupType,
1401
1378
  requestId,
1402
1379
  requestedEffort,
1403
1380
  variantUsed,
@@ -1434,6 +1411,7 @@ export class PipelineOrchestrator {
1434
1411
  servedCredentialPrefix = plusResult.servedCredentialPrefix;
1435
1412
  poolTiming = plusResult.timing;
1436
1413
  upstreamStream = plusResult.transport;
1414
+ servedEgress = plusResult.egress;
1437
1415
  }
1438
1416
  }
1439
1417
  else {
@@ -1495,14 +1473,18 @@ export class PipelineOrchestrator {
1495
1473
  const isBareAuto = !normalizedRequest.model || normalizedRequest.model === 'auto';
1496
1474
  if (accessPolicy && isBareAuto && !explicitModel && !comboId) {
1497
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;
1498
1480
  // Multi-membership admit: allowed when the id or ANY membership
1499
1481
  // tier passes (allow mode); denied when the id or ANY membership
1500
1482
  // tier is denied (deny mode).
1501
1483
  const widened = this.registry
1502
1484
  .getAllModels()
1503
1485
  .filter((m) => isModelAllowedInTiers(m.id, accessPolicy, this.registry.tiersOf(m)))
1504
- .sort((a, b) => Math.abs((rank[a.tier] ?? 9) - (rank[actualTier] ?? 9)) - Math.abs((rank[b.tier] ?? 9) - (rank[actualTier] ?? 9)) ||
1505
- (rank[a.tier] ?? 9) - (rank[b.tier] ?? 9));
1486
+ .sort((a, b) => Math.abs(rankOf(a) - (rank[actualTier] ?? 9)) - Math.abs(rankOf(b) - (rank[actualTier] ?? 9)) ||
1487
+ rankOf(a) - rankOf(b));
1506
1488
  if (widened.length > 0)
1507
1489
  pool = widened;
1508
1490
  }
@@ -1540,7 +1522,7 @@ export class PipelineOrchestrator {
1540
1522
  layerUsed: decision.layerUsed || 'layer0',
1541
1523
  sessionId,
1542
1524
  sessionRatchetApplied: ratchetApplied,
1543
- sessionLookupType: sessionResolve.lookupType,
1525
+ sessionLookupType: preResolvedSession.lookupType,
1544
1526
  requestId,
1545
1527
  requestedEffort,
1546
1528
  variantUsed,
@@ -1594,6 +1576,7 @@ export class PipelineOrchestrator {
1594
1576
  actualTier = execResult.tierUsed;
1595
1577
  poolTiming = execResult.timing;
1596
1578
  upstreamStream = execResult.transport;
1579
+ servedEgress = execResult.egress;
1597
1580
  // Recompute `actualEffort` against the model that ACTUALLY served the
1598
1581
  // request — failover may have shifted to a different model than the
1599
1582
  // one `pickModelForEffort` originally picked, with a different effort
@@ -1666,8 +1649,7 @@ export class PipelineOrchestrator {
1666
1649
  const wantsThinking = (servedEffort != null && servedEffort !== 'none') ||
1667
1650
  (typeof budgetTokens === 'number' && budgetTokens > 0);
1668
1651
  // 5-level default: `none` is a client toggle, not a capability.
1669
- const modelEfforts = actualModel.supportedReasoningEfforts
1670
- ?? (actualModel.supportsReasoningEffort ? EFFORT_LADDER : []);
1652
+ const modelEfforts = modelSupportsEfforts(actualModel.supportedReasoningEfforts, actualModel.supportsReasoningEffort, actualModel.reasoningDisableable) ?? [];
1671
1653
  const supportsAnyThinking = modelEfforts.some((e) => e !== 'none');
1672
1654
  // Both warn paths go through the dedup + rate-limit warn throttle: at
1673
1655
  // QPS a misconfigured pool would otherwise print one warn per request.
@@ -1817,7 +1799,7 @@ export class PipelineOrchestrator {
1817
1799
  reasonCode: decision.reasonCode,
1818
1800
  reasonParams: decision.reasonParams,
1819
1801
  sessionRatchetApplied: ratchetApplied,
1820
- sessionLookupType: sessionResolve.lookupType,
1802
+ sessionLookupType: preResolvedSession.lookupType,
1821
1803
  },
1822
1804
  execution: {
1823
1805
  modelUsed: actualModel.id,
@@ -1836,6 +1818,15 @@ export class PipelineOrchestrator {
1836
1818
  // tag (ADR-0008 §1). 'sse' with clientStream:false is the accumulate
1837
1819
  // mode: the gateway read a stream and answered in JSON.
1838
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
+ : {}),
1839
1830
  fallbackReason,
1840
1831
  failoverOccurred,
1841
1832
  failoverAttempts,
@@ -1881,7 +1872,7 @@ export class PipelineOrchestrator {
1881
1872
  modelAvailability,
1882
1873
  sessionId,
1883
1874
  sessionRatchetApplied: ratchetApplied,
1884
- sessionLookupType: sessionResolve.lookupType,
1875
+ sessionLookupType: preResolvedSession.lookupType,
1885
1876
  requestId,
1886
1877
  latencyMs,
1887
1878
  ttftMs,
@@ -1919,10 +1910,26 @@ export class PipelineOrchestrator {
1919
1910
  : undefined);
1920
1911
  const ask = effectiveRequested ?? 'none';
1921
1912
  const target = applyEffortMap(this.registry.effortMapFor(model, servedTier), ask);
1922
- if (target === 'none' && ask === 'none')
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)
1923
1920
  return { actualEffort: effectiveRequested, degraded: false };
1924
- const supported = model.supportedReasoningEfforts ?? (model.supportsReasoningEffort ? EFFORT_LADDER : []);
1925
- const actual = target === 'none' ? 'none' : downgradeReasoning(target, supported);
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
+ }
1926
1933
  return {
1927
1934
  actualEffort: actual,
1928
1935
  degraded: EFFORT_LADDER.indexOf(actual) < EFFORT_LADDER.indexOf(ask),
@@ -1982,7 +1989,11 @@ export class PipelineOrchestrator {
1982
1989
  // Each entry carries its ACCESS tier (pool tier vs member home tier, see
1983
1990
  // accessTierMode) and the effort translation that applies to it — a model
1984
1991
  // holding membership in several tiers translates per serving pool.
1985
- 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;
1986
1997
  let candidateList = opts.chain.map((m) => ({
1987
1998
  model: m,
1988
1999
  accessTier: accessTierOf(m),
@@ -2177,9 +2188,17 @@ export class PipelineOrchestrator {
2177
2188
  : undefined;
2178
2189
  const ask = opts.requestedEffort ?? budgetAsk ?? 'none';
2179
2190
  const target = applyEffortMap(candidateEffortMap, ask);
2180
- if (!(target === 'none' && ask === 'none')) {
2181
- const supported = candidate.supportedReasoningEfforts ?? (candidate.supportsReasoningEffort ? EFFORT_LADDER : []);
2182
- const candidateEffort = target === 'none' ? 'none' : downgradeReasoning(target, supported);
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
+ }
2183
2202
  if (candidateEffort !== effortOf(request)) {
2184
2203
  candidateReq = {
2185
2204
  ...request,
@@ -2243,6 +2262,8 @@ export class PipelineOrchestrator {
2243
2262
  // Transport the served attempt actually used (registry-reported, once
2244
2263
  // per attempt). Reset per attempt: a retry re-issues with a fresh tag.
2245
2264
  let transport;
2265
+ // Outbound egress resolved at THIS attempt's dial (AttemptEgress).
2266
+ let attemptEgress;
2246
2267
  const timingRelay = opts.relay
2247
2268
  ? {
2248
2269
  stageRouting: (facts) => opts.relay.stageRouting(facts),
@@ -2274,7 +2295,10 @@ export class PipelineOrchestrator {
2274
2295
  : undefined;
2275
2296
  for (let attempt = 0; attempt <= maxInplaceAttempts; attempt++) {
2276
2297
  try {
2277
- 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);
2278
2302
  if (firstChunkAt !== undefined)
2279
2303
  streamEndAt = Date.now();
2280
2304
  // Scope-aware success: undefined prefix degenerates to the exact
@@ -2417,6 +2441,8 @@ export class PipelineOrchestrator {
2417
2441
  // Served-attempt transport tag. `opts.relay` absent = the executor
2418
2442
  // was never given a relay, so the buffered call is certain.
2419
2443
  transport: opts.relay ? transport : 'buffered',
2444
+ // Served-attempt egress, resolved at the dial by this pool.
2445
+ egress: attemptEgress,
2420
2446
  };
2421
2447
  }
2422
2448
  }