opencode-model-router 2.1.0 → 2.3.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 (55) hide show
  1. package/CHANGELOG.md +86 -0
  2. package/README.md +44 -5
  3. package/package.json +4 -1
  4. package/src/commands/output.ts +4 -1
  5. package/src/compat/child-session.ts +43 -0
  6. package/src/compat/v2-client.ts +107 -7
  7. package/src/compat/v2-hooks.ts +174 -47
  8. package/src/escalate/attempt-recorder.ts +263 -0
  9. package/src/escalate/ladder.ts +484 -10
  10. package/src/escalate/resume.ts +208 -0
  11. package/src/escalate/variants.ts +391 -0
  12. package/src/index.ts +557 -61
  13. package/src/router/build-info.ts +151 -0
  14. package/src/router/config.ts +1691 -67
  15. package/src/router/protocol.ts +47 -0
  16. package/src/router/sessions.ts +441 -9
  17. package/src/routing/advisor/findings.ts +706 -0
  18. package/src/routing/advisor/index.ts +606 -0
  19. package/src/routing/classify/backends/host.ts +163 -0
  20. package/src/routing/classify/backends/openai-compatible.ts +275 -0
  21. package/src/routing/classify/backends/shared.ts +741 -0
  22. package/src/routing/classify/backends/typesafe.ts +315 -0
  23. package/src/routing/classify/fences.ts +96 -0
  24. package/src/routing/classify/index.ts +576 -0
  25. package/src/routing/classify/route-line.ts +298 -0
  26. package/src/routing/classify/rules.ts +607 -0
  27. package/src/routing/classify/scrub.ts +214 -0
  28. package/src/routing/classify/state.ts +148 -0
  29. package/src/routing/classify/text.ts +20 -0
  30. package/src/routing/classify/types.ts +1280 -0
  31. package/src/routing/commands/annotate-plan.ts +652 -0
  32. package/src/routing/commands/stats.ts +131 -0
  33. package/src/routing/commands/v1-roles.ts +64 -0
  34. package/src/routing/engine/index.ts +32 -0
  35. package/src/routing/engine/kernel.ts +597 -0
  36. package/src/routing/engine/ladders.ts +561 -0
  37. package/src/routing/engine/plan.ts +404 -0
  38. package/src/routing/engine/protocol-line.ts +133 -0
  39. package/src/routing/engine/simulate.ts +167 -0
  40. package/src/routing/engine/types.ts +270 -0
  41. package/src/routing/file-lock.ts +53 -0
  42. package/src/routing/outcomes/beta.ts +141 -0
  43. package/src/routing/outcomes/cost.ts +313 -0
  44. package/src/routing/outcomes/index.ts +172 -0
  45. package/src/routing/outcomes/ingest.ts +812 -0
  46. package/src/routing/outcomes/persist.ts +1058 -0
  47. package/src/routing/outcomes/stats.ts +602 -0
  48. package/src/routing/outcomes/store.ts +653 -0
  49. package/src/routing/outcomes/types.ts +954 -0
  50. package/src/routing/wire/dispatch.ts +799 -0
  51. package/src/routing/wire/hint.ts +208 -0
  52. package/src/routing/wire/host-info.ts +256 -0
  53. package/src/routing/wire/runtime.ts +259 -0
  54. package/src/v2.ts +15 -1
  55. package/tiers.json +43 -0
@@ -0,0 +1,597 @@
1
+ /**
2
+ * Decision kernel (M4) — expected cost of the whole cascade per candidate and the margin rule.
3
+ *
4
+ * Design: `docs/qa/cost-aware-routing/phase-1.4.md` → "Design (1.4.1)" §2.
5
+ * Plan #74 §1.5: D5 (unit rule), D7 (rank priors), D8 (cascade cost), D9 (margin rule, amended by
6
+ * A16: strict `<`, boundary kept, `best == chosen` never a switch), D13 (`pin`); amendments A1 (every
7
+ * live candidate compares in `costRatio` units today) and A11 (permissions come from the caller).
8
+ *
9
+ * D8, for candidate k with successor next(k) on its ladder (terminal successor = give up at cost U):
10
+ *
11
+ * C(k) = c_k + tax_k + (1 − p_k) · [ d · C(next(k)) + (1 − d) · U ]
12
+ *
13
+ * - c_k attempt cost in the decision unit: `costRatio` (ratio) or `expectedAttemptUSD` (usd);
14
+ * - tax_k orchestrator re-read cost of k's final message (`taxUSD`); 0 until measured, always 0 in
15
+ * ratio units (there is no USD→ratio exchange rate, so it is never invented);
16
+ * - p_k Beta posterior mean of the key, prior `priorForRankOffset(rank(k) − rank(static tier))`;
17
+ * - d `routing.detection[detection]`;
18
+ * - U `GIVE_UP_COST[profile][risk]` (fast = 1), times the USD value of one ratio unit in usd.
19
+ *
20
+ * What "k fails and the failure is detected" leads to (A25): for a rung with a simulated runner path
21
+ * (`Ladder.paths`, built by `ladders.ts` from `nextAction`/`advance` of the 1.5 runner) the same recurrence
22
+ * runs over the attempts the runner really makes — retries, variant steps, covered-tier skips, the
23
+ * `maxTotalAttempts` and the cost ceiling included — and ends in `U`. Rungs without a path (role chains,
24
+ * hand-built ladders) use the static `next` pointer; a chain that reaches a router rung continues with that
25
+ * rung's path as if it were a fresh dispatch (the runner state of the chain is not carried over).
26
+ *
27
+ * Caveat of the USD unit (QA-1.4-14): `U` is a ratio-unit constant, converted to USD with the price of ONE
28
+ * ratio unit measured on the cheapest-ratio candidate (D8 "fast = 1"). That candidate's USD estimate is the
29
+ * only anchor, so a noisy or stale estimate for it rescales `U` for the whole decision; when it cannot be
30
+ * derived the decision falls back to ratio units for every candidate instead of mixing units (D5).
31
+ *
32
+ * Pure: no I/O, no clock, no module state. The only reads are the injected store view's
33
+ * `posterior`/`cost`/`classTokenProfile`. Memoisation lives in arrays local to one `decide` call.
34
+ * Every runtime import is a pure module (`outcomes/beta`, `outcomes/cost`, `outcomes/types`, `escalate/variants`).
35
+ */
36
+
37
+ import type { RoutingProfile } from "../../router/config";
38
+ import { variantPosition } from "../../escalate/variants";
39
+ import type { Need, Risk } from "../classify/types";
40
+ import { PRIOR_STRENGTH, priorForRankOffset } from "../outcomes/beta";
41
+ import { compareUnit, expectedAttemptUSD, isUnpriced, taxUSD } from "../outcomes/cost";
42
+ import type {
43
+ AgentRef,
44
+ CostStats,
45
+ CostUnit,
46
+ MeanStat,
47
+ OutcomeKey,
48
+ RouteChoice,
49
+ TokenMeans,
50
+ UnitCandidate,
51
+ } from "../outcomes/types";
52
+ import { makeKey, normalizeVariant, splitModelRef } from "../outcomes/types";
53
+ import type {
54
+ Candidate,
55
+ Decision,
56
+ DecisionInput,
57
+ DecisionReasonCode,
58
+ IneligibleReason,
59
+ Ladder,
60
+ } from "./types";
61
+
62
+ // ---------------------------------------------------------------------------
63
+ // Constants
64
+ // ---------------------------------------------------------------------------
65
+
66
+ /** D8 give-up cost `U = profile[risk]`, in cost units where fast = 1. */
67
+ export const GIVE_UP_COST: Readonly<Record<RoutingProfile, Readonly<Record<Risk, number>>>> = Object.freeze({
68
+ frugal: Object.freeze({ low: 3, medium: 8, high: 20 }),
69
+ balanced: Object.freeze({ low: 5, medium: 15, high: 40 }),
70
+ safe: Object.freeze({ low: 10, medium: 30, high: 100 }),
71
+ });
72
+
73
+ /** D8 `remainingTurnsEstimate`. */
74
+ export const DEFAULT_REMAINING_TURNS = 4;
75
+
76
+ /**
77
+ * A24 (QA-1.4-6, amended by QA-1.4-15): only a switch to a STRICTLY HIGHER rank is ungated. Every other
78
+ * switch — down, sideways at an equal rank (a role agent on a rung of the pick's own tier, a lower variant of
79
+ * the same model) — needs at least this much recorded evidence on the candidate's own key: the strength of a
80
+ * D7 prior, so priors alone never move a dispatch down or sideways. (The name predates the amendment.)
81
+ */
82
+ export const MIN_EVIDENCE_TO_SWITCH_DOWN: number = PRIOR_STRENGTH;
83
+
84
+ /** Decay and floating point make "five outcomes recorded a moment ago" 4.9999999…; this absorbs only that. */
85
+ const EVIDENCE_EPSILON = 1e-6;
86
+
87
+ /** Whether `n` effective outcomes (a posterior's `n`) reach {@link MIN_EVIDENCE_TO_SWITCH_DOWN}. */
88
+ export function hasMinEvidence(n: number): boolean {
89
+ return Number.isFinite(n) && n + EVIDENCE_EPSILON >= MIN_EVIDENCE_TO_SWITCH_DOWN;
90
+ }
91
+
92
+ const EMPTY_MEAN: MeanStat = Object.freeze({ mean: 0, n: 0 });
93
+
94
+ // ---------------------------------------------------------------------------
95
+ // Small pure helpers
96
+ // ---------------------------------------------------------------------------
97
+
98
+ function isFiniteNumber(x: unknown): x is number {
99
+ return typeof x === "number" && Number.isFinite(x);
100
+ }
101
+
102
+ function clamp01(x: unknown): number {
103
+ return isFiniteNumber(x) ? Math.min(1, Math.max(0, x)) : 0;
104
+ }
105
+
106
+ function round2(x: number): number {
107
+ return Math.round(x * 100) / 100;
108
+ }
109
+
110
+ /** Compact number for reason texts (≤ 4 decimals, no trailing zeros). */
111
+ function fmt(x: number): string {
112
+ return Number.isFinite(x) ? String(Number(x.toFixed(4))) : String(x);
113
+ }
114
+
115
+ function ownValue<T>(record: Readonly<Record<string, T>>, key: string): T | undefined {
116
+ return Object.prototype.hasOwnProperty.call(record, key) ? record[key] : undefined;
117
+ }
118
+
119
+ /** D8 `U` for a profile and a risk (balanced/medium semantics for an unknown value). */
120
+ export function giveUpCost(profile: RoutingProfile, risk: Risk): number {
121
+ const table = ownValue(GIVE_UP_COST, profile) ?? GIVE_UP_COST.balanced;
122
+ return ownValue(table, risk) ?? table.medium;
123
+ }
124
+
125
+ interface ModelParts {
126
+ /** "" when the ref has no `provider/` prefix (makeKey stores `unknown`). */
127
+ readonly provider: string;
128
+ readonly model: string;
129
+ readonly variant: string | null;
130
+ }
131
+
132
+ function modelParts(model: string, variant: string | null): ModelParts {
133
+ const ref = splitModelRef(model);
134
+ if (ref === null) return { provider: "", model, variant };
135
+ return { provider: ref.provider, model: ref.model, variant: variant ?? ref.variant };
136
+ }
137
+
138
+ function keyOf(cls: string, agent: AgentRef, parts: ModelParts): OutcomeKey {
139
+ return makeKey(cls, agent, parts.provider, parts.model, parts.variant);
140
+ }
141
+
142
+ function routeChoice(key: OutcomeKey, agent: AgentRef, parts: ModelParts): RouteChoice {
143
+ return Object.freeze({
144
+ key,
145
+ agent: agent.id,
146
+ origin: agent.origin,
147
+ model: parts.provider === "" ? parts.model : `${parts.provider}/${parts.model}`,
148
+ variant: normalizeVariant(parts.variant),
149
+ });
150
+ }
151
+
152
+ /**
153
+ * Outcome key of a candidate (or the chosen dispatch) for class `cls` — the one key format the
154
+ * kernel, the store and the decision log share (`class|origin:agent|provider/model#variant`).
155
+ */
156
+ export function candidateKey(
157
+ cls: string,
158
+ candidate: { readonly agent: AgentRef; readonly model: string; readonly variant: string | null },
159
+ ): OutcomeKey {
160
+ return keyOf(cls, candidate.agent, modelParts(candidate.model, candidate.variant));
161
+ }
162
+
163
+ /** A11: the evaluated permissions cover every need; unknown permissions (`null`) cover none. */
164
+ export function coversNeeds(grants: readonly Need[] | null, needs: readonly Need[]): boolean {
165
+ return needs.every((need) => grants !== null && grants.includes(need));
166
+ }
167
+
168
+ /** `provider/model` of a dispatch (a `#variant` suffix split off) and its normalized variant (`default` when none). */
169
+ function canonicalRung(dispatch: { readonly model: string; readonly variant: string | null }): { readonly model: string; readonly variant: string } {
170
+ const parts = modelParts(dispatch.model, dispatch.variant);
171
+ return { model: (parts.provider === "" ? parts.model : `${parts.provider}/${parts.model}`).toLowerCase(), variant: normalizeVariant(parts.variant) };
172
+ }
173
+
174
+ /**
175
+ * A34 (QA-G-B1): the CAPABILITY rank of a dispatch — what the model it runs on is worth on the escalate ladder, whatever agent
176
+ * runs it. The highest rank of a preset rung with its exact `model#variant`; when no rung has that variant, the highest rank of
177
+ * any preset rung on its model; never less than `candidateRank` (its rank as a candidate, when it is one). `null` when no preset
178
+ * rung is on its model and it has no candidate rank.
179
+ *
180
+ * Why: a role agent's candidate rank is capped at the class's owning tier (A25). That cap is right for a CANDIDATE (an agent on
181
+ * the heavy model serving a medium class is priced as a medium option), but the pick is the status quo that D9 "never down"
182
+ * protects: `@general` on the parent's `opus#xhigh` is heavy-capable, and moving it to the medium tier on high-risk work without
183
+ * detection is a move down. The table is `ladder.presetRungs`; a hand-built ladder without one uses its router rungs.
184
+ */
185
+ export function capabilityRank(
186
+ ladder: Pick<Ladder, "presetRungs" | "candidates" | "reachable">,
187
+ dispatch: { readonly model: string; readonly variant: string | null },
188
+ candidateRank: number | null,
189
+ ): number | null {
190
+ return capabilityRankLookup(ladder)(dispatch, candidateRank);
191
+ }
192
+
193
+ /** Index once per decision: evidence checks must stay linear on long ladders. */
194
+ function capabilityRankLookup(ladder: Pick<Ladder, "presetRungs" | "candidates" | "reachable">) {
195
+ const table = ladder.presetRungs
196
+ ?? [...ladder.candidates, ...(ladder.reachable ?? [])].filter((rung) => rung.agent.origin === "router");
197
+ const models = new Map<string, number>();
198
+ const exact = new Map<string, Map<string, number>>();
199
+ for (const rung of table) {
200
+ if (!isFiniteNumber(rung.rank)) continue;
201
+ const own = canonicalRung(rung);
202
+ models.set(own.model, Math.max(models.get(own.model) ?? -Infinity, rung.rank));
203
+ let variants = exact.get(own.model);
204
+ if (variants === undefined) { variants = new Map(); exact.set(own.model, variants); }
205
+ variants.set(own.variant, Math.max(variants.get(own.variant) ?? -Infinity, rung.rank));
206
+ }
207
+ return (dispatch: { readonly model: string; readonly variant: string | null }, candidateRank: number | null): number | null => {
208
+ const target = canonicalRung(dispatch);
209
+ const preset = exact.get(target.model)?.get(target.variant) ?? models.get(target.model) ?? null;
210
+ const floor = isFiniteNumber(candidateRank) ? candidateRank : null;
211
+ if (preset === null) return floor;
212
+ return floor === null ? preset : Math.max(preset, floor);
213
+ };
214
+ }
215
+
216
+ /**
217
+ * A34 (QA-G-B6): `candidate` runs the pick's own model on a variant that is NOT placed at or above the pick's on the effort scale
218
+ * every variant ladder follows (`escalate/variants`: ladders rise strictly in effort, `default` sits just below `high`) — a lower
219
+ * effort at an equal rank. A variant that cannot be placed (an unranked id) is not known to be at or above, so it counts as lower:
220
+ * under D9 "never down" the unknown side is the conservative one. The same model#variant is never lower.
221
+ */
222
+ export function lowerEffortOnSameModel(
223
+ candidate: { readonly model: string; readonly variant: string | null },
224
+ pick: { readonly model: string; readonly variant: string | null },
225
+ ): boolean {
226
+ const c = canonicalRung(candidate);
227
+ const p = canonicalRung(pick);
228
+ if (c.model !== p.model || c.variant === p.variant) return false;
229
+ const cPos = variantPosition(c.variant);
230
+ const pPos = variantPosition(p.variant);
231
+ return cPos === null || pPos === null || cPos < pPos;
232
+ }
233
+
234
+ /** D5 `tokenSamples`: the key's own token samples, else the class-pooled profile's (1.3, C1). */
235
+ function tokenSamples(stats: CostStats | null, profile: TokenMeans | null): number {
236
+ if (stats !== null && stats.tokens.n >= 1) return stats.tokens.n;
237
+ return profile?.n ?? 0;
238
+ }
239
+
240
+ // ---------------------------------------------------------------------------
241
+ // The kernel
242
+ // ---------------------------------------------------------------------------
243
+
244
+ /**
245
+ * Decide one dispatch: `C(k)` for every candidate, `best` = argmin over the orchestrator's pick and
246
+ * the eligible candidates, and whether `enforce` would switch (D9 as amended by A16).
247
+ *
248
+ * Switch iff ALL hold: not pinned; the pick is a priced candidate; `best` is another candidate;
249
+ * `facts.confidence ≥ minClassConfidence`; `C(best) < (1 − margin) · C(chosen)` (strict).
250
+ * Eligibility of a candidate as `best` (the pick itself is always eligible — it is the status quo):
251
+ * its permissions cover `facts.needs` (A11), it is not below `floorRank`, and when `risk == high &&
252
+ * detection == none` (D9 "never down", A34) it is neither below the pick's CAPABILITY rank
253
+ * ({@link capabilityRank}, not the pick's capped candidate rank) nor the pick's own model on a lower-effort
254
+ * variant ({@link lowerEffortOnSameModel}). The A24/A27 "strictly higher rank" exemption from the evidence
255
+ * gate is measured against the same capability rank.
256
+ *
257
+ * Class trust (1.2 → 1.4 handoff): below `minClassConfidence` the store is not read at all — no
258
+ * posterior or cost is taken under an untrusted class; priors are then centred on the pick's rank.
259
+ *
260
+ * Never throws for well-typed input; non-finite numbers degrade to the conservative side
261
+ * (an unusable successor is a give-up, an unusable candidate is ineligible, a bad margin never switches).
262
+ */
263
+ export function decide(input: DecisionInput): Decision {
264
+ const { facts, ladder, routing } = input;
265
+ const cls = facts.class;
266
+ const cands = ladder.candidates;
267
+ const n = cands.length;
268
+ const pinned = input.pin === true;
269
+
270
+ const chosenParts = modelParts(input.chosen.model, input.chosen.variant);
271
+ const chosenKey = keyOf(cls, input.chosen.agent, chosenParts);
272
+ const chosen = routeChoice(chosenKey, input.chosen.agent, chosenParts);
273
+
274
+ const classConfidence = clamp01(facts.confidence);
275
+ const minConfidence = routing.minClassConfidence;
276
+ const margin = routing.margin;
277
+ const trusted = isFiniteNumber(minConfidence) && classConfidence >= minConfidence;
278
+ const store = trusted ? input.store : null;
279
+
280
+ if (n === 0) {
281
+ return freezeDecision({
282
+ chosen,
283
+ best: null,
284
+ argmin: null,
285
+ switched: false,
286
+ pinned,
287
+ confidence: 0,
288
+ reasonCode: "kept:no-candidates",
289
+ reason: "kept: no candidate survived the ladder filters",
290
+ costs: {},
291
+ unit: "ratio",
292
+ ineligible: {},
293
+ target: null,
294
+ pickRank: null,
295
+ });
296
+ }
297
+
298
+ // `all` = the dispatchable candidates, then the rungs only the 1.5 runner reaches (A25): the second kind is
299
+ // priced like the first (it can sit on a simulated path) but is never `best`.
300
+ const all: readonly Candidate[] = ladder.reachable === undefined || ladder.reachable.length === 0
301
+ ? cands
302
+ : [...cands, ...ladder.reachable];
303
+ const total = all.length;
304
+ const parts = all.map((c) => modelParts(c.model, c.variant));
305
+ const keys = all.map((c, k) => keyOf(cls, c.agent, parts[k]!));
306
+ let chosenIndex = -1;
307
+ for (let k = 0; k < n; k++) {
308
+ if (keys[k] === chosenKey) {
309
+ chosenIndex = k;
310
+ break;
311
+ }
312
+ }
313
+ const chosenRank = chosenIndex >= 0 ? cands[chosenIndex]!.rank : null;
314
+ // A34 (QA-G-B1): what the pick is worth, not its capped candidate rank: never-down and the A24/A27 test compare against this.
315
+ const rankOf = capabilityRankLookup(ladder);
316
+ const pickRank = chosenRank === null ? null : rankOf(input.chosen, chosenRank);
317
+
318
+ // --- p_k: D7 prior by rank offset + evidence (store reads only for a trusted class) ------------
319
+ const referenceRank = trusted
320
+ ? (ladder.classRank ?? chosenRank ?? 0)
321
+ : (chosenRank ?? ladder.classRank ?? 0);
322
+ const p = new Float64Array(total);
323
+ const evidence = new Float64Array(total);
324
+ for (let k = 0; k < total; k++) {
325
+ const prior = priorForRankOffset(all[k]!.rank - referenceRank);
326
+ const priorMean = prior.alpha / (prior.alpha + prior.beta);
327
+ if (store === null) {
328
+ p[k] = priorMean;
329
+ continue;
330
+ }
331
+ const post = store.posterior(keys[k]!, prior);
332
+ p[k] = isFiniteNumber(post.mean) ? clamp01(post.mean) : priorMean;
333
+ evidence[k] = isFiniteNumber(post.n) && post.n > 0 ? post.n : 0;
334
+ }
335
+
336
+ // --- unit (D5) and c_k ------------------------------------------------------------------------
337
+ const stats: (CostStats | null)[] = all.map((_, k) => (store === null ? null : store.cost(keys[k]!)));
338
+ const classProfile = store === null ? null : store.classTokenProfile(cls);
339
+ let unit: CostUnit = "ratio";
340
+ let usd: readonly number[] | null = null;
341
+ let usdPerRatioUnit = 1;
342
+ if (store !== null) {
343
+ const unitCandidates: UnitCandidate[] = all.map((c, k) => ({
344
+ key: keys[k]!,
345
+ priced: !isUnpriced(c.pricing),
346
+ measuredUSD: stats[k]?.measuredUSD ?? EMPTY_MEAN,
347
+ tokenSamples: tokenSamples(stats[k] ?? null, classProfile),
348
+ }));
349
+ if (compareUnit(unitCandidates) === "usd") {
350
+ const estimates = all.map((c, k) => expectedAttemptUSD(stats[k]!, c.pricing, classProfile));
351
+ const scale = usdScale(all, estimates);
352
+ if (scale !== null && estimates.every((v) => isFiniteNumber(v) && v >= 0)) {
353
+ unit = "usd";
354
+ usd = estimates as number[];
355
+ usdPerRatioUnit = scale;
356
+ }
357
+ }
358
+ }
359
+
360
+ const c = new Float64Array(total);
361
+ const usable = new Uint8Array(total);
362
+ for (let k = 0; k < total; k++) {
363
+ const value = usd !== null ? usd[k]! : all[k]!.costRatio;
364
+ const ok = usd !== null ? isFiniteNumber(value) && value >= 0 : isFiniteNumber(value) && value > 0;
365
+ c[k] = ok ? value : 0;
366
+ usable[k] = ok ? 1 : 0;
367
+ }
368
+
369
+ // --- tax_k (D8): measured USD only; 0 in ratio units and until measured ------------------------
370
+ const tax = new Float64Array(total);
371
+ const orchestrator = input.orchestrator ?? null;
372
+ if (unit === "usd" && orchestrator !== null) {
373
+ const turns = isFiniteNumber(input.remainingTurns) && input.remainingTurns >= 0
374
+ ? input.remainingTurns
375
+ : DEFAULT_REMAINING_TURNS;
376
+ for (let k = 0; k < total; k++) {
377
+ const s = stats[k];
378
+ if (s === null || s === undefined) continue;
379
+ const t = taxUSD(s.finalMessageTokens, turns, orchestrator.pricing, orchestrator.contextTokens);
380
+ tax[k] = isFiniteNumber(t) && t > 0 ? t : 0;
381
+ }
382
+ }
383
+
384
+ // --- d and U ----------------------------------------------------------------------------------
385
+ const d = clamp01(ownValue(routing.detection as Readonly<Record<string, number>>, input.detection));
386
+ const U = giveUpCost(routing.profile, facts.risk) * usdPerRatioUnit;
387
+
388
+ // --- simulated runner paths (A25): the usable prefix of each candidate's attempt list --------------
389
+ const pathCache: (readonly number[] | null)[] = new Array<readonly number[] | null>(n).fill(null);
390
+ for (let k = 0; k < n; k++) {
391
+ const raw = ladder.paths?.[k];
392
+ if (!Array.isArray(raw)) continue;
393
+ const prefix: number[] = [];
394
+ for (const a of raw as readonly unknown[]) {
395
+ if (typeof a !== "number" || !Number.isInteger(a) || a < 0 || a >= total || usable[a] !== 1) break;
396
+ prefix.push(a);
397
+ }
398
+ if (prefix.length > 0) pathCache[k] = prefix;
399
+ else usable[k] = 0; // its first attempt cannot be priced
400
+ }
401
+
402
+ // --- C(k): D8 recursion, evaluated iteratively and memoised per call --------------------------------
403
+ // C(k) = c_k + tax_k + (1 − p_k)·[d·C(next(k)) + (1 − d)·U] (static `next` chain)
404
+ // A candidate with a simulated path a_1…a_m (a_1 = k) is the same recurrence over the attempts the runner
405
+ // makes (retries and variant steps included), ending in `U` after a_m. Iteration, not recursion: a chain of
406
+ // thousands of rungs must not be able to exhaust the stack (QA-1.4-12).
407
+ const memo = new Float64Array(n);
408
+ const visit = new Uint8Array(n); // 0 = new, 1 = on the current chain, 2 = done
409
+ const next = ladder.next;
410
+ const attemptValue = (a: number, after: number): number =>
411
+ c[a]! + tax[a]! + (1 - p[a]!) * (d * after + (1 - d) * U);
412
+ const cascade = (start: number): number => {
413
+ if (visit[start] === 2) return memo[start]!;
414
+ const stack: number[] = [];
415
+ let tail = U;
416
+ let k = start;
417
+ for (;;) {
418
+ if (visit[k] === 2) {
419
+ tail = memo[k]!;
420
+ break;
421
+ }
422
+ if (visit[k] === 1) {
423
+ tail = U; // defensive: a cycle is a give-up, never an infinite escalation
424
+ break;
425
+ }
426
+ const path = pathCache[k];
427
+ if (path !== null && path !== undefined) {
428
+ let value = U;
429
+ for (let i = path.length - 1; i >= 0; i--) value = attemptValue(path[i]!, value);
430
+ memo[k] = value;
431
+ visit[k] = 2;
432
+ tail = value;
433
+ break;
434
+ }
435
+ visit[k] = 1;
436
+ stack.push(k);
437
+ const j = next[k];
438
+ if (typeof j === "number" && Number.isInteger(j) && j >= 0 && j < n && usable[j] === 1) {
439
+ k = j;
440
+ continue;
441
+ }
442
+ tail = U; // no, out-of-range or unusable successor: give up
443
+ break;
444
+ }
445
+ for (let i = stack.length - 1; i >= 0; i--) {
446
+ const node = stack[i]!;
447
+ tail = attemptValue(node, tail);
448
+ memo[node] = tail;
449
+ visit[node] = 2;
450
+ }
451
+ return memo[start]!;
452
+ };
453
+
454
+ const C = new Float64Array(n).fill(Number.NaN);
455
+ const costs: Record<string, number> = {};
456
+ for (let k = 0; k < n; k++) {
457
+ if (usable[k] !== 1) continue;
458
+ const value = cascade(k);
459
+ C[k] = value;
460
+ if (isFiniteNumber(value) && !Object.prototype.hasOwnProperty.call(costs, keys[k]!)) costs[keys[k]!] = value;
461
+ }
462
+ // --- best: argmin over the pick and the eligible candidates ------------------------------------
463
+ const chosenPriced = chosenIndex >= 0 && usable[chosenIndex] === 1 && isFiniteNumber(C[chosenIndex]);
464
+ const floorRank = isFiniteNumber(input.floorRank) ? input.floorRank : null;
465
+ const neverDown = facts.risk === "high" && input.detection === "none";
466
+ const ineligible: Record<string, IneligibleReason> = {};
467
+ let best = chosenPriced ? chosenIndex : -1;
468
+ // A27: `argmin` is what the old single-argmin-then-gate rule would have picked; `best` is drawn only from the candidates
469
+ // that survive the evidence filter as well (evidence, or a strictly higher rank than the pick).
470
+ let argmin = best;
471
+ for (let k = 0; k < n; k++) {
472
+ if (k === chosenIndex || keys[k] === chosenKey) continue;
473
+ const cand = cands[k]!;
474
+ let why: IneligibleReason | null = null;
475
+ if (usable[k] !== 1 || !isFiniteNumber(C[k])) why = "invalid-cost";
476
+ else if (!coversNeeds(cand.grants, facts.needs)) why = "needs";
477
+ else if (floorRank !== null && cand.rank < floorRank) why = "floor";
478
+ else if (neverDown && pickRank !== null && (cand.rank < pickRank || (cand.rank === pickRank && lowerEffortOnSameModel(cand, input.chosen)))) {
479
+ why = "never-down"; // A34: below the pick's capability rank, or the pick's model on a lower variant at its rank (QA-G-B1/B6)
480
+ }
481
+ if (why !== null) {
482
+ if (!Object.prototype.hasOwnProperty.call(ineligible, keys[k]!)) ineligible[keys[k]!] = why;
483
+ continue;
484
+ }
485
+ // Strict: ties keep the pick (considered first), then the earlier rung.
486
+ if (argmin < 0 || C[k]! < C[argmin]!) argmin = k;
487
+ const presetRank = rankOf(cand, null);
488
+ if (!(pickRank !== null && cand.rank > pickRank && presetRank !== null && presetRank > pickRank) && !hasMinEvidence(evidence[k]!)) {
489
+ if (!Object.prototype.hasOwnProperty.call(ineligible, keys[k]!)) ineligible[keys[k]!] = "evidence";
490
+ continue;
491
+ }
492
+ if (best < 0 || C[k]! < C[best]!) best = k;
493
+ }
494
+
495
+ const bestIndex = best >= 0 ? best : null;
496
+ const argminIndex = argmin >= 0 ? argmin : null;
497
+ const argminChoice = argminIndex === null ? null : routeChoice(keys[argminIndex]!, cands[argminIndex]!.agent, parts[argminIndex]!);
498
+ const bestChoice = bestIndex === null ? null : routeChoice(keys[bestIndex]!, cands[bestIndex]!.agent, parts[bestIndex]!);
499
+ const bestCost = bestIndex === null ? Number.NaN : C[bestIndex]!;
500
+ const chosenCost = chosenPriced ? C[chosenIndex]! : Number.NaN;
501
+
502
+ // --- D9 (A16), A27 ------------------------------------------------------------------------------
503
+ // `gated`: the evidence filter removed a cheaper candidate, so `best` fell back to the pick. The margin, class-confidence
504
+ // and config checks then judge that cheaper candidate (the one the old argmin-then-gate rule would have judged), so the
505
+ // reason codes keep their precedence; only the last step differs (`kept:evidence` instead of a switch).
506
+ const gated = bestIndex !== null && bestIndex === chosenIndex && argminIndex !== null && argminIndex !== chosenIndex;
507
+ const decidingIndex = gated ? argminIndex : bestIndex;
508
+ const decidingCost = decidingIndex === null ? Number.NaN : C[decidingIndex]!;
509
+ const marginValid = isFiniteNumber(margin) && margin >= 0 && margin < 1;
510
+ const threshold = marginValid ? (1 - margin) * chosenCost : Number.NaN;
511
+ let reasonCode: DecisionReasonCode;
512
+ let reason: string;
513
+ if (bestIndex === null) {
514
+ reasonCode = "kept:no-candidates";
515
+ reason = "kept: no candidate could be priced";
516
+ } else if (pinned) {
517
+ reasonCode = "kept:pinned";
518
+ reason = `kept: pinned dispatch (best ${bestChoice!.key} at ${fmt(bestCost)} ${unit})`;
519
+ } else if (!chosenPriced) {
520
+ reasonCode = "kept:chosen-not-candidate";
521
+ reason = `kept: the chosen ${chosenKey} is not a priced candidate`;
522
+ } else if (bestIndex === chosenIndex && !gated) {
523
+ reasonCode = "kept:best-is-chosen";
524
+ reason = `kept: the chosen dispatch is the cheapest (${fmt(chosenCost)} ${unit})`;
525
+ } else if (!marginValid || !isFiniteNumber(minConfidence)) {
526
+ reasonCode = "kept:invalid-config";
527
+ reason = "kept: routing.margin or routing.minClassConfidence is not a usable number";
528
+ } else if (classConfidence < minConfidence) {
529
+ reasonCode = "kept:class-confidence";
530
+ reason = `kept: class confidence ${fmt(classConfidence)} < minClassConfidence ${fmt(minConfidence)}`;
531
+ } else if (!(decidingCost < threshold)) {
532
+ reasonCode = "kept:margin";
533
+ // R2-4: when the evidence filter left `best` at the pick, the cost compared is the cheapest option's (the gated one), and the reason says so.
534
+ reason = gated
535
+ ? `kept: C(cheapest)=${fmt(decidingCost)} (${argminChoice!.key}, gated by evidence) is not < (1 − ${fmt(margin)})·C(chosen)=${fmt(threshold)} ${unit}`
536
+ : `kept: C(best)=${fmt(decidingCost)} is not < (1 − ${fmt(margin)})·C(chosen)=${fmt(threshold)} ${unit}`;
537
+ } else if (gated) {
538
+ reasonCode = "kept:evidence";
539
+ reason = `kept: the cheapest option ${argminChoice!.key} (${fmt(decidingCost)} ${unit}, rank ${cands[argminIndex!]!.rank}, the pick is rank ${pickRank ?? cands[chosenIndex]!.rank}) needs ≥ ${MIN_EVIDENCE_TO_SWITCH_DOWN} recorded outcomes, it has ${fmt(evidence[argminIndex!]!)}; the chosen dispatch is the cheapest eligible (${fmt(chosenCost)} ${unit})`;
540
+ } else {
541
+ reasonCode = "switched";
542
+ reason = `switched: C(best)=${fmt(bestCost)} < (1 − ${fmt(margin)})·C(chosen)=${fmt(threshold)} ${unit}`;
543
+ }
544
+ // QA-1.4-17: a pick below `floorTier` is not what the runner would start on; say so, and say what was priced.
545
+ if (floorRank !== null && chosenRank !== null && chosenRank < floorRank) {
546
+ const lifted = chosenIndex >= 0 && pathCache[chosenIndex] !== null && pathCache[chosenIndex]![0] !== chosenIndex;
547
+ reason += ` [the pick is below floorTier (rank ${chosenRank} < ${floorRank}); ${lifted
548
+ ? "its cost is that of the floor path the runner starts on"
549
+ : "it is priced as dispatched"}]`;
550
+ }
551
+
552
+ const bestEvidence = bestIndex === null ? 0 : evidence[bestIndex]!;
553
+ const confidence = bestIndex === null
554
+ ? 0
555
+ : round2(classConfidence * (bestEvidence / (bestEvidence + PRIOR_STRENGTH)));
556
+
557
+ return freezeDecision({
558
+ chosen,
559
+ best: bestChoice,
560
+ argmin: argminChoice,
561
+ switched: reasonCode === "switched",
562
+ pinned,
563
+ confidence,
564
+ reasonCode,
565
+ reason,
566
+ costs,
567
+ unit,
568
+ ineligible,
569
+ target: bestIndex === null ? null : cands[bestIndex]!,
570
+ pickRank,
571
+ });
572
+ }
573
+
574
+ /**
575
+ * USD value of one `costRatio` unit (D8 "U in cost units where fast = 1", expressed in USD): the
576
+ * USD estimate of the cheapest-ratio candidate divided by its ratio. `null` when it cannot be
577
+ * derived (the decision then falls back to ratio units for every candidate — never mixed).
578
+ */
579
+ function usdScale(cands: readonly Candidate[], estimates: readonly (number | null)[]): number | null {
580
+ let ref = -1;
581
+ for (let k = 0; k < cands.length; k++) {
582
+ const r = cands[k]!.costRatio;
583
+ if (!isFiniteNumber(r) || r <= 0) continue;
584
+ if (ref < 0 || r < cands[ref]!.costRatio) ref = k;
585
+ }
586
+ if (ref < 0) return null;
587
+ const e = estimates[ref];
588
+ if (!isFiniteNumber(e) || e <= 0) return null;
589
+ const scale = e / cands[ref]!.costRatio;
590
+ return isFiniteNumber(scale) && scale > 0 ? scale : null;
591
+ }
592
+
593
+ function freezeDecision(d: Decision): Decision {
594
+ Object.freeze(d.costs);
595
+ Object.freeze(d.ineligible);
596
+ return Object.freeze(d);
597
+ }