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
@@ -1,6 +1,30 @@
1
1
  import { effortCeilingFor, effortRank, minEffort, nextEffort } from "../router/agent-options";
2
- import { resolveEffortBump, type EffortLevel, type RouterConfig } from "../router/config";
2
+ import {
3
+ resolveEffortBump,
4
+ type EffortLevel,
5
+ type RouterConfig,
6
+ type TierCandidate,
7
+ type TierConfig,
8
+ } from "../router/config";
3
9
  import { getActiveTiers } from "../router/protocol";
10
+ import {
11
+ DEFAULT_VARIANT,
12
+ buildVariantLadder,
13
+ catalogVariantIds,
14
+ estimateTokensFromChars,
15
+ inputBudget,
16
+ nextVariant,
17
+ resumeDecision,
18
+ variantCovered,
19
+ variantRange,
20
+ type CatalogModel,
21
+ type ResumeDecision,
22
+ type VariantLadder,
23
+ } from "./variants";
24
+
25
+ // The resume decision lives in variants.ts; re-exported so the plan's API
26
+ // location (`ladder.ts`) holds.
27
+ export { resumeDecision, type ResumeDecision } from "./variants";
4
28
 
5
29
  // ---------------------------------------------------------------------------
6
30
  // Types
@@ -10,6 +34,36 @@ export interface EffortBumpPolicy {
10
34
  perTier: Record<string, { base: EffortLevel; bound: EffortLevel }>;
11
35
  }
12
36
 
37
+ /** Per-tier variant data; built only on v2 with variantSteps "auto" and a catalog entry. */
38
+ export interface TierVariantInfo {
39
+ /** "provider/model" of the tier. */
40
+ model: string;
41
+ /** tier.variant (a catalog member) or DEFAULT_VARIANT. */
42
+ base: string;
43
+ /** buildVariantLadder(...) for that model. */
44
+ ladder: VariantLadder;
45
+ /** inputBudget(catalogEntry.limit) (A5/A10). */
46
+ inputBudget: number | null;
47
+ /**
48
+ * Rung -> costRatio (A17): the matching candidate's own `costRatio` when the tier configures one,
49
+ * else the tier's `costRatio`. Keyed by variant id; `default` for the bare model. A missing key
50
+ * means the ratio is unknown and the runner charges the tier's `costRatio`.
51
+ */
52
+ costRatios: Record<string, number>;
53
+ /**
54
+ * Set when the tier configures `effort`/`thinking`/`reasoning` (A20, QA-1.5-18): its effort travels
55
+ * on the effort path only, so it has an empty variant ladder, is never treated as covered by another
56
+ * tier and never counts as a coverage source in `triedByModel`.
57
+ */
58
+ effortConfigured?: true;
59
+ }
60
+
61
+ export interface VariantPolicy {
62
+ /** routing.sessionReuse.maxContextFraction (default 0.6). */
63
+ maxContextFraction: number;
64
+ perTier: Record<string, TierVariantInfo>;
65
+ }
66
+
13
67
  export interface EscalatePolicy {
14
68
  ladder: string[];
15
69
  floorTier?: string | null;
@@ -17,6 +71,7 @@ export interface EscalatePolicy {
17
71
  maxTotalAttempts: number;
18
72
  costMultiple?: number | null;
19
73
  effortBump?: EffortBumpPolicy | null;
74
+ variants?: VariantPolicy | null;
20
75
  }
21
76
 
22
77
  export interface LadderState {
@@ -27,6 +82,27 @@ export interface LadderState {
27
82
  firstAttemptCost: number | null;
28
83
  cumulativeCost: number;
29
84
  currentEffort?: EffortLevel | null;
85
+ /** Variant reached by variant steps on the current tier; null = the tier's base. */
86
+ currentVariant?: string | null;
87
+ /** Variant steps taken in this delegation (never reset). */
88
+ variantSteps?: number;
89
+ /** Child of the latest attempt; null = none, or a fresh start is pending. */
90
+ childSessionID?: string | null;
91
+ /** stepContextTokens() of that child's last step; null = unknown. */
92
+ lastStepTokens?: number | null;
93
+ /**
94
+ * inputBudget of the model the next attempt runs on. Telemetry only (QA-1.5-14): `advance` and
95
+ * `newLadderState` store it so a log or scorecard can show it, but `nextAction` never reads it. The
96
+ * decision uses the budget of the target tier, which `sessionFields` puts into a probe state.
97
+ */
98
+ nextModelContext?: number | null;
99
+ /**
100
+ * A17a (QA-1.5-17): the highest rung run per model in this delegation, `model -> variant`
101
+ * (`default` for the bare model). Session-aware states only. Variant steps and escalations raise it
102
+ * (plain retries repeat a rung and do not); an escalation into a tier whose base it covers enters
103
+ * above it or skips the tier, so the ladder never re-runs a `(model, variant)` that already failed.
104
+ */
105
+ triedByModel?: Record<string, string>;
30
106
  }
31
107
 
32
108
  export type LadderActionKind = "accept" | "retry" | "escalate" | "give_up";
@@ -37,6 +113,57 @@ export interface LadderAction {
37
113
  forcingMessage?: string;
38
114
  reason?: string;
39
115
  effort?: EffortLevel;
116
+ /** Present only on a D10 variant step (action is "retry"). */
117
+ variantStep?: true;
118
+ /** Escalate only: target agent id (= tier name for router tiers). */
119
+ agent?: string;
120
+ /** "provider/model" of the target, when it has TierVariantInfo. */
121
+ model?: string;
122
+ /** Catalog-validated target variant; absent = default / leave unchanged. */
123
+ variant?: string;
124
+ /**
125
+ * Escalate only: the target tier is covered by a rung already tried on its model (A17a), so it is
126
+ * entered at `variant`, the first rung above that one, instead of at its base; advance seeds currentVariant.
127
+ */
128
+ carryVariant?: true;
129
+ /**
130
+ * The `(model, variant)` rung this action starts, recorded by `advance` into `triedByModel`
131
+ * (`default` for the bare model). On variant steps and escalations only, never on plain retries.
132
+ */
133
+ rung?: { model: string; variant: string };
134
+ /**
135
+ * A17: costRatio of the rung this action runs (`model` + `variant`), on variant steps, plain
136
+ * retries and escalations when it is known. The runner charges `action.costRatio ?? tier.costRatio`.
137
+ */
138
+ costRatio?: number;
139
+ /** Present on every retry/escalate when policy.variants is set. */
140
+ resume?: boolean;
141
+ /** D11 "decision and both numbers are logged"; present iff resume is. */
142
+ resumeBasis?: ResumeDecision;
143
+ }
144
+
145
+ /** Fourth, optional argument of nextAction. */
146
+ export interface LadderSessionInput {
147
+ dispatchPromptChars: number;
148
+ }
149
+
150
+ /** Child observation passed to recordAttempt after an attempt on a session-aware policy. */
151
+ export interface LadderChildObservation {
152
+ sessionID: string;
153
+ lastStepTokens: number | null;
154
+ }
155
+
156
+ /** Second, optional argument of buildEscalatePolicy (filled by Phase 2.3 from 1.1's resolved config). */
157
+ export interface LadderSessionPolicyInput {
158
+ host: "v1" | "v2";
159
+ /** Default "auto" (D10). */
160
+ variantSteps?: "auto" | "none";
161
+ /** Default 0.6 (§1.4). */
162
+ maxContextFraction?: number;
163
+ /** Catalog lookup for a "provider/model" id. A throwing lookup is treated as no catalog entry (QA-1.5-15). */
164
+ catalog: (model: string) => CatalogModel | null | undefined;
165
+ /** Receives one line per failed catalog lookup; its own failures are swallowed. */
166
+ warn?: (message: string) => void;
40
167
  }
41
168
 
42
169
  export interface LadderVerdict {
@@ -77,20 +204,44 @@ export function newLadderState(
77
204
  cumulativeCost: 0,
78
205
  };
79
206
  if (policy.effortBump) state.currentEffort = null;
207
+ if (policy.variants) {
208
+ state.currentVariant = null;
209
+ state.variantSteps = 0;
210
+ state.childSessionID = null;
211
+ state.lastStepTokens = null;
212
+ // Budget of the start tier (after floorTier).
213
+ const start = ownTierInfo(policy, state.currentTier);
214
+ state.nextModelContext = start?.inputBudget ?? null; // telemetry only
215
+ // The first attempt runs the start tier's base, unless the tier is effort-configured (QA-1.5-18).
216
+ state.triedByModel = start && !start.effortConfigured ? { [start.model]: start.base } : {};
217
+ }
80
218
  return state;
81
219
  }
82
220
 
83
221
  export function recordAttempt(
84
222
  state: LadderState,
85
223
  costUnits = 0,
224
+ child?: LadderChildObservation,
86
225
  ): LadderState {
87
- return {
226
+ const next: LadderState = {
88
227
  ...state,
89
228
  totalAttempts: state.totalAttempts + 1,
90
229
  cumulativeCost: state.cumulativeCost + costUnits,
91
230
  firstAttemptCost:
92
231
  state.firstAttemptCost == null ? costUnits : state.firstAttemptCost,
93
232
  };
233
+ // Only a session-aware state records its child; otherwise the shape is unchanged.
234
+ if (child && state.childSessionID !== undefined) {
235
+ next.childSessionID = child.sessionID;
236
+ next.lastStepTokens = child.lastStepTokens;
237
+ }
238
+ return next;
239
+ }
240
+
241
+ /** Own-property lookup, like the effort bump's, so a tier named `__proto__` cannot reach Object.prototype. */
242
+ function ownTierInfo(policy: EscalatePolicy, tier: string): TierVariantInfo | undefined {
243
+ const perTier = policy.variants?.perTier;
244
+ return perTier && Object.prototype.hasOwnProperty.call(perTier, tier) ? perTier[tier] : undefined;
94
245
  }
95
246
 
96
247
  export function nextTierAfter(
@@ -116,10 +267,124 @@ export function buildLadderForcingMessage(reasons: string[]): string {
116
267
  );
117
268
  }
118
269
 
270
+ /**
271
+ * Record a rung in `triedByModel`, keeping the entry with the higher guaranteed effort (the lowest
272
+ * effort the rung can have, so a `default` rung never outranks a ranked one). Pure: never mutates.
273
+ */
274
+ function raiseTried(tried: Record<string, string> | undefined, model: string, variant: string): Record<string, string> {
275
+ const current = tried ?? {};
276
+ if (Object.prototype.hasOwnProperty.call(current, model)) {
277
+ const known = variantRange(current[model]);
278
+ const next = variantRange(variant);
279
+ if (next === null || (known !== null && next.low <= known.low)) return current;
280
+ }
281
+ return { ...current, [model]: variant };
282
+ }
283
+
284
+ /** A variant may be emitted only when it is the tier's validated base or a ladder member, never default. */
285
+ function emittable(info: TierVariantInfo, v: string): string | undefined {
286
+ return v !== DEFAULT_VARIANT && (v === info.base || info.ladder.variants.includes(v)) ? v : undefined;
287
+ }
288
+
289
+ /** A17: costRatio of the rung `variant` (default when absent) of a tier; `undefined` when unknown. */
290
+ function costFields(info: TierVariantInfo, variant: string | undefined): Pick<LadderAction, "costRatio"> {
291
+ const costRatio = costRatioOf(info, variant);
292
+ return costRatio === undefined ? {} : { costRatio };
293
+ }
294
+
295
+ function costRatioOf(info: TierVariantInfo, variant: string | undefined): number | undefined {
296
+ const ratios = info.costRatios;
297
+ const key = variant ?? DEFAULT_VARIANT;
298
+ return ratios && Object.prototype.hasOwnProperty.call(ratios, key) ? ratios[key] : undefined;
299
+ }
300
+
301
+ /**
302
+ * QA-1.5-20: the costRatio of the rung the attempt about to run uses, from the state alone. For the
303
+ * first attempt (a state from `newLadderState`) that is the start tier's base rung, which no action
304
+ * carries; the runner charges `startCostRatio(policy, state) ?? tier.costRatio` for it, and
305
+ * `action.costRatio ?? tier.costRatio` for every later attempt. `undefined` without `policy.variants`,
306
+ * for a tier without variant info, or when the rung has no known ratio.
307
+ */
308
+ export function startCostRatio(policy: EscalatePolicy, state: LadderState): number | undefined {
309
+ const info = ownTierInfo(policy, state.currentTier);
310
+ return info ? costRatioOf(info, state.currentVariant ?? info.base) : undefined;
311
+ }
312
+
313
+ /** D11: the resume decision and both numbers for the attempt this action leads to. */
314
+ function sessionFields(
315
+ state: LadderState,
316
+ variants: VariantPolicy,
317
+ target: TierVariantInfo | undefined,
318
+ forcingMessage: string,
319
+ session?: LadderSessionInput,
320
+ ): Pick<LadderAction, "resume" | "resumeBasis"> {
321
+ const resumeBasis = resumeDecision(
322
+ {
323
+ childSessionID: state.childSessionID,
324
+ lastStepTokens: state.lastStepTokens,
325
+ nextModelContext: target?.inputBudget ?? null, // the NEXT model's budget (A5)
326
+ },
327
+ {
328
+ maxContextFraction: variants.maxContextFraction,
329
+ nextPromptTokens: estimateTokensFromChars(forcingMessage.length + (session?.dispatchPromptChars ?? 0)),
330
+ },
331
+ );
332
+ return { resume: resumeBasis.resume, resumeBasis };
333
+ }
334
+
335
+ /** Ladder tiers above `tier` (A17's H); 0 when the tier is not on the ladder. */
336
+ function tiersAbove(policy: EscalatePolicy, tier: string): number {
337
+ const index = tierRank(tier, policy.ladder);
338
+ return index < 0 ? 0 : policy.ladder.length - 1 - index;
339
+ }
340
+
341
+ /** A17: `maxTotalAttempts − totalAttempts − 1 ≥ H`, so every ladder tier above keeps at least one attempt. */
342
+ function reserveAllows(policy: EscalatePolicy, state: LadderState): boolean {
343
+ return policy.maxTotalAttempts - state.totalAttempts - 1 >= tiersAbove(policy, state.currentTier);
344
+ }
345
+
346
+ /** Where an escalation lands. `variant` is set when the target tier is covered but has rungs above (A17a). */
347
+ interface EscalationTarget {
348
+ tier: string | null;
349
+ variant?: string;
350
+ }
351
+
352
+ /**
353
+ * A17a (QA-1.5-17, QA-1.5-4): the ladder never re-runs a `(model, variant)` that already failed. For each
354
+ * next tier, `reached` is the highest rung tried on THAT tier's model (`triedByModel`, plus the rung the
355
+ * failed attempt just ran), whichever tier ran it. If the tier's base is not covered by `reached` (QA-1.5-3:
356
+ * `default` is a range, see `variantCovered`), it is entered at its base. If it is covered, it is entered at
357
+ * `nextVariant(to.ladder, reached)`, the first rung above `reached`, or skipped when there is none.
358
+ */
359
+ function skipCoveredTiers(
360
+ next: string | null,
361
+ state: LadderState,
362
+ policy: EscalatePolicy,
363
+ from: TierVariantInfo,
364
+ ): EscalationTarget {
365
+ // An effort-configured tier is never a coverage source (QA-1.5-18): its own rung is not recorded.
366
+ const tried = from.effortConfigured
367
+ ? (state.triedByModel ?? {})
368
+ : raiseTried(state.triedByModel, from.model, state.currentVariant ?? from.base);
369
+ let hops = 0;
370
+ while (next != null) {
371
+ const to = ownTierInfo(policy, next);
372
+ // ...and never covered: its effort delivery differs from any variant rung, so it always runs.
373
+ if (!to || to.effortConfigured) return { tier: next };
374
+ const reached = Object.prototype.hasOwnProperty.call(tried, to.model) ? tried[to.model] : undefined;
375
+ if (reached === undefined || !variantCovered(to.base, reached)) return { tier: next };
376
+ const entry = nextVariant(to.ladder, reached);
377
+ if (entry !== null) return { tier: next, variant: entry };
378
+ if (++hops >= policy.ladder.length) return { tier: null }; // guard: duplicate ladder entries cannot spin
379
+ next = nextTierAfter(next, policy);
380
+ }
381
+ return { tier: null };
382
+ }
119
383
  export function nextAction(
120
384
  state: LadderState,
121
385
  verdict: LadderVerdict | null | undefined,
122
386
  policy: EscalatePolicy,
387
+ session?: LadderSessionInput,
123
388
  ): LadderAction {
124
389
  // (1) pass
125
390
  if (verdict?.pass === true) {
@@ -150,8 +415,37 @@ export function nextAction(
150
415
  return { action: "give_up", reason: "cost ceiling exceeded" };
151
416
  }
152
417
 
418
+ const variants = policy.variants ?? null;
419
+ const info = variants ? ownTierInfo(policy, state.currentTier) : undefined;
420
+ // A17/A17a budget reserve: whenever variant steps are enabled for the session (`policy.variants`),
421
+ // spending another attempt on any tier (variant step or plain retry, cataloged or not) must leave
422
+ // one attempt for each ladder tier above; otherwise escalate now (QA-1.5-21). Without
423
+ // `policy.variants` the ladder is exactly the 2.2.0 one.
424
+ const mayStay = !variants || reserveAllows(policy, state);
425
+
426
+ // (5V) variant step (D10): not gated by attemptsThisTier; steps 3 and 4 above already bound it by
427
+ // maxTotalAttempts and the cost ceiling.
428
+ const variantStep = (): LadderAction | null => {
429
+ if (!variants || !info) return null;
430
+ const variant = nextVariant(info.ladder, state.currentVariant ?? info.base);
431
+ if (variant === null) return null;
432
+ const forcingMessage = buildLadderForcingMessage(verdict?.reasons ?? []);
433
+ return {
434
+ action: "retry",
435
+ tier: state.currentTier,
436
+ forcingMessage,
437
+ variantStep: true,
438
+ model: info.model,
439
+ variant,
440
+ ...costFields(info, variant),
441
+ ...(info.effortConfigured ? {} : { rung: { model: info.model, variant } }),
442
+ ...sessionFields(state, variants, info, forcingMessage, session),
443
+ };
444
+ };
445
+
153
446
  // (5) retry within tier
154
- if (state.attemptsThisTier < policy.maxAttemptsPerTier) {
447
+ const plainRetry = (): LadderAction | null => {
448
+ if (state.attemptsThisTier >= policy.maxAttemptsPerTier) return null;
155
449
  const action: LadderAction = {
156
450
  action: "retry",
157
451
  tier: state.currentTier,
@@ -170,45 +464,116 @@ export function nextAction(
170
464
  ?? (state.currentEffort == null ? undefined : startingEffort);
171
465
  if (effort !== undefined) action.effort = effort;
172
466
  }
467
+ if (variants) {
468
+ if (info) {
469
+ action.model = info.model;
470
+ const v = emittable(info, state.currentVariant ?? info.base);
471
+ if (v !== undefined) action.variant = v; // keeps the reached variant on a fresh retry
472
+ Object.assign(action, costFields(info, action.variant));
473
+ }
474
+ Object.assign(action, sessionFields(state, variants, info, action.forcingMessage!, session));
475
+ }
173
476
  return action;
477
+ };
478
+
479
+ if (mayStay) {
480
+ const stay = variantStep() ?? plainRetry();
481
+ if (stay) return stay;
174
482
  }
175
483
 
176
484
  // (6) escalate or give_up
177
- const next = nextTierAfter(state.currentTier, policy);
485
+ let next = nextTierAfter(state.currentTier, policy);
486
+ const tierAbove = next != null;
487
+ let entry: string | undefined;
488
+ if (variants && info) ({ tier: next, variant: entry } = skipCoveredTiers(next, state, policy, info));
178
489
  if (next == null) {
490
+ // QA-1.5-19: the reserve withheld these attempts for tiers above, but none is left to run (every
491
+ // one only repeats a rung already tried), so spend them here instead of giving up with budget left.
492
+ if (!mayStay) {
493
+ const spend = variantStep() ?? plainRetry();
494
+ if (spend) return spend;
495
+ }
179
496
  return {
180
497
  action: "give_up",
181
- reason: "no higher tier (already at top of ladder)",
498
+ reason: tierAbove
499
+ ? "no higher tier left to try (the remaining tiers only repeat rungs already tried)"
500
+ : "no higher tier (already at top of ladder)",
182
501
  };
183
502
  }
184
- return {
503
+ const action: LadderAction = {
185
504
  action: "escalate",
186
505
  tier: next,
187
506
  forcingMessage: buildLadderForcingMessage(verdict?.reasons ?? []),
188
507
  };
508
+ if (variants) {
509
+ const target = ownTierInfo(policy, next);
510
+ action.agent = next; // D11: the role changes on escalation
511
+ if (target) {
512
+ action.model = target.model;
513
+ // A covered tier is entered above the rung already tried on its model (A17a), always a member of
514
+ // its own ladder; any other tier at its base.
515
+ const v = entry ?? emittable(target, target.base);
516
+ if (v !== undefined) {
517
+ action.variant = v;
518
+ if (entry !== undefined) action.carryVariant = true;
519
+ }
520
+ Object.assign(action, costFields(target, action.variant));
521
+ if (!target.effortConfigured) action.rung = { model: target.model, variant: action.variant ?? DEFAULT_VARIANT };
522
+ }
523
+ Object.assign(action, sessionFields(state, variants, target, action.forcingMessage!, session));
524
+ }
525
+ return action;
526
+ }
527
+ /** Records the rung an action starts into `triedByModel`; a no-op on states without it. */
528
+ function applyRung(next: LadderState, action: LadderAction): void {
529
+ if (next.triedByModel === undefined || action.rung === undefined) return;
530
+ next.triedByModel = raiseTried(next.triedByModel, action.rung.model, action.rung.variant);
531
+ }
532
+
533
+ /** Session bookkeeping of an advance; a no-op on states that are not session-aware. */
534
+ function applySession(next: LadderState, action: LadderAction): void {
535
+ if (next.childSessionID === undefined) return; // not session-aware: shape unchanged
536
+ if (action.resume !== true) next.childSessionID = null; // fresh start: clear the stale child
537
+ next.lastStepTokens = null; // must be re-observed after the next attempt
538
+ next.nextModelContext = action.resumeBasis?.budget ?? null; // telemetry only: nextAction never reads it
189
539
  }
190
540
 
191
541
  export function advance(state: LadderState, action: LadderAction): LadderState {
192
542
  if (action.action === "retry") {
193
- const next = { ...state, attemptsThisTier: state.attemptsThisTier + 1 };
543
+ const next: LadderState = { ...state };
544
+ if (action.variantStep === true) {
545
+ next.currentVariant = action.variant ?? null;
546
+ next.variantSteps = (state.variantSteps ?? 0) + 1; // does NOT touch attemptsThisTier
547
+ } else {
548
+ next.attemptsThisTier = state.attemptsThisTier + 1;
549
+ }
194
550
  if (action.effort !== undefined) next.currentEffort = action.effort;
551
+ applyRung(next, action);
552
+ applySession(next, action);
195
553
  return next;
196
554
  }
197
555
  if (action.action === "escalate") {
198
- const next = {
556
+ const next: LadderState = {
199
557
  ...state,
200
558
  currentTier: action.tier!,
201
559
  attemptsThisTier: 0,
202
560
  escalations: state.escalations + 1,
203
561
  };
204
562
  if (next.currentEffort !== undefined) next.currentEffort = null;
563
+ // A new tier starts at its base, unless it is entered above a rung already tried on its model (A17a).
564
+ if (next.currentVariant !== undefined) next.currentVariant = action.carryVariant === true ? (action.variant ?? null) : null;
565
+ applyRung(next, action);
566
+ applySession(next, action);
205
567
  return next;
206
568
  }
207
569
  // accept / give_up — terminal, return unchanged
208
570
  return state;
209
571
  }
210
572
 
211
- export function buildEscalatePolicy(cfg: RouterConfig): EscalatePolicy {
573
+ export function buildEscalatePolicy(
574
+ cfg: RouterConfig,
575
+ session?: LadderSessionPolicyInput,
576
+ ): EscalatePolicy {
212
577
  const esc = cfg.enforcement?.escalate;
213
578
  const policy: EscalatePolicy = {
214
579
  ladder: esc?.ladder ?? ["fast", "medium", "heavy"],
@@ -220,9 +585,118 @@ export function buildEscalatePolicy(cfg: RouterConfig): EscalatePolicy {
220
585
  const effortBump = buildEffortBump(cfg);
221
586
  // Keep bump-off policies byte-identical to the original golden fixture.
222
587
  if (effortBump) policy.effortBump = effortBump;
588
+ const variants = buildVariantPolicy(cfg, session);
589
+ // Absent key when off, so policies without session input stay byte-identical.
590
+ if (variants) policy.variants = variants;
223
591
  return policy;
224
592
  }
225
593
 
594
+ /** costRatio as 1.1 validates it: a finite number above 0. */
595
+ function validCostRatio(value: unknown): number | undefined {
596
+ return typeof value === "number" && Number.isFinite(value) && value > 0 ? value : undefined;
597
+ }
598
+
599
+ /**
600
+ * A17: the costRatio of every rung a tier can run (its base and its ladder): a candidate of the same
601
+ * model naming that variant (no variant = `default`) with its own `costRatio`, else the tier's.
602
+ * Catalog steps that reach another preset tier's rung on the same model cost at least that rung.
603
+ * Rungs without any ratio are omitted, so the runner falls back to the tier's `costRatio`.
604
+ */
605
+ function rungCostRatios(
606
+ tier: TierConfig,
607
+ rawCandidates: readonly TierCandidate[] | undefined,
608
+ base: string,
609
+ ladder: VariantLadder,
610
+ presetTiers: readonly TierConfig[],
611
+ ): Record<string, number> {
612
+ const tierRatio = validCostRatio(tier.costRatio);
613
+ const own = new Map<string, number>();
614
+ if (Array.isArray(rawCandidates)) {
615
+ for (const candidate of rawCandidates) {
616
+ if (candidate === null || typeof candidate !== "object") continue;
617
+ const model = typeof candidate.model === "string" && candidate.model.length > 0 ? candidate.model : tier.model;
618
+ const ratio = validCostRatio(candidate.costRatio);
619
+ if (model !== tier.model || ratio === undefined) continue;
620
+ const rung = typeof candidate.variant === "string" && candidate.variant.length > 0 ? candidate.variant : DEFAULT_VARIANT;
621
+ if (!own.has(rung)) own.set(rung, ratio);
622
+ }
623
+ }
624
+ const entries: Array<[string, number]> = [];
625
+ for (const rung of new Set([base, ...ladder.variants])) {
626
+ let ratio = own.get(rung) ?? tierRatio;
627
+ if (ladder.source === "catalog" && rung !== base) {
628
+ for (const other of presetTiers) {
629
+ if (other === tier || other.model !== tier.model || (other.variant ?? other.effort ?? DEFAULT_VARIANT) !== rung) continue;
630
+ const otherRatio = validCostRatio(other.costRatio);
631
+ if (otherRatio !== undefined) ratio = Math.max(ratio ?? 0, otherRatio);
632
+ }
633
+ }
634
+ if (ratio !== undefined) entries.push([rung, ratio]);
635
+ }
636
+ return Object.fromEntries(entries);
637
+ }
638
+
639
+ /** QA-1.5-15: a throwing catalog is "no catalog" for that model, logged once per lookup and never raised. */
640
+ function lookupCatalog(session: LadderSessionPolicyInput, model: string): CatalogModel | null | undefined {
641
+ try {
642
+ return session.catalog(model);
643
+ } catch (error) {
644
+ try {
645
+ const reason = error instanceof Error ? error.message : String(error);
646
+ session.warn?.(`[router] ladder: catalog lookup for ${model} failed (${reason}); treating it as no catalog entry`);
647
+ } catch {
648
+ // logging must never break policy construction
649
+ }
650
+ return undefined;
651
+ }
652
+ }
653
+
654
+ function buildVariantPolicy(
655
+ cfg: RouterConfig,
656
+ session?: LadderSessionPolicyInput,
657
+ ): VariantPolicy | null {
658
+ if (!session || session.host !== "v2" || (session.variantSteps ?? "auto") === "none") return null; // D1, D10
659
+ const { max } = resolveEffortBump(cfg); // cap for catalog ladders (F2)
660
+ const entries: Array<[string, TierVariantInfo]> = [];
661
+ const tiers = getActiveTiers(cfg) ?? {};
662
+ const presetTiers = Object.values(tiers).filter((tier) => tier !== null && typeof tier === "object");
663
+ for (const [name, tier] of Object.entries(tiers)) {
664
+ if (tier === null || typeof tier !== "object" || typeof tier.model !== "string" || tier.model.length === 0) continue;
665
+ // QA-1.5-6: every tier with a catalog entry gets variant info (and its input budget), whether or
666
+ // not it can step; a tier without an entry keeps today's behaviour (no info, fresh start).
667
+ const entry = lookupCatalog(session, tier.model);
668
+ if (entry === null || entry === undefined || typeof entry !== "object") continue;
669
+ const ids = catalogVariantIds(entry);
670
+ const configured = typeof tier.variant === "string" && tier.variant.length > 0 ? tier.variant : null;
671
+ if (configured !== null && !(ids ?? []).includes(configured)) continue; // invalid configured variant: never resume-switch it
672
+ // One effort delivery per tier (F3, A20): a tier that configures effort/thinking/reasoning stays on
673
+ // the effort path only, with or without a `variant`, and gets an empty variant ladder; it still
674
+ // carries its model, base and budget.
675
+ const effortConfigured = tier.effort !== undefined || tier.thinking !== undefined || tier.reasoning !== undefined;
676
+ // Membership comes from the tier's own typed list (F11); ignored lists are already deleted at load
677
+ // (QA-1.1-30). The Array.isArray guard stays for configs built without going through load.
678
+ const raw: readonly TierCandidate[] | undefined = Array.isArray(tier.candidates) ? tier.candidates : undefined;
679
+ const base = configured ?? DEFAULT_VARIANT;
680
+ const ladder = effortConfigured
681
+ ? buildVariantLadder({ model: tier.model, catalog: null })
682
+ : buildVariantLadder({
683
+ model: tier.model,
684
+ catalog: entry,
685
+ candidates: raw,
686
+ maxEffort: max,
687
+ });
688
+ entries.push([name, {
689
+ model: tier.model,
690
+ base,
691
+ ladder,
692
+ inputBudget: inputBudget(entry.limit),
693
+ costRatios: rungCostRatios(tier, raw, base, ladder, presetTiers),
694
+ ...(effortConfigured ? { effortConfigured: true as const } : {}),
695
+ }]);
696
+ }
697
+ if (entries.length === 0) return null;
698
+ return { maxContextFraction: session.maxContextFraction ?? 0.6, perTier: Object.fromEntries(entries) };
699
+ }
226
700
  function buildEffortBump(cfg: RouterConfig): EffortBumpPolicy | null {
227
701
  const { enabled, max } = resolveEffortBump(cfg);
228
702
  if (!enabled) return null;
@@ -249,7 +723,7 @@ export function formatLadderScorecard(
249
723
  method: string,
250
724
  ): string {
251
725
  return (
252
- `[router delegate scorecard | final_tier=${state.currentTier}${state.currentEffort ? `@${state.currentEffort}` : ""} | ` +
726
+ `[router delegate scorecard | final_tier=${state.currentTier}${state.currentEffort ? `@${state.currentEffort}` : state.currentVariant ? `#${state.currentVariant}` : ""} | ` +
253
727
  `attempts=${state.totalAttempts} | escalations=${state.escalations} | ` +
254
728
  `cost=${state.cumulativeCost} | verdict=${accepted ? "PASS" : "UNMET"} | ` +
255
729
  `method=${method}]`