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