opencode-model-router 2.2.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 (54) hide show
  1. package/CHANGELOG.md +65 -0
  2. package/README.md +35 -3
  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 +118 -31
  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 +486 -38
  13. package/src/router/build-info.ts +151 -0
  14. package/src/router/config.ts +1365 -19
  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
@@ -0,0 +1,208 @@
1
+ /**
2
+ * Phase 2.3 (M5 in `delegate`): turns a ladder action into the attempt the runner executes.
3
+ *
4
+ * The ladder algebra (`ladder.ts`) decides WHAT the next attempt is (a variant step, a plain retry, an
5
+ * escalation, with the D11 resume verdict). This module decides HOW the runner carries it out, in one pure
6
+ * place the runner and the tests share:
7
+ *
8
+ * - which agent and `provider/model#variant` the attempt dispatches;
9
+ * - whether it resumes the previous child session (`sessionID`) or starts a fresh one, and why;
10
+ * - the catalog validation of the target variant before the call (D10: an invalid variant never reaches the
11
+ * host; the attempt starts fresh on the tier's configured model, and its effort travels as an effort
12
+ * override when the variant is an effort level);
13
+ * - the two host behaviours that are unverified on 2.0.22 and therefore start fresh (see `FreshReason`).
14
+ *
15
+ * Nothing here does I/O. The v1 path never reaches the session-aware branches: they need
16
+ * `action.model`, which only a session-aware policy (v2, `variantSteps: "auto"`, a catalog) sets, so with
17
+ * no `routing` block (A15) the plan is exactly what the runner always dispatched.
18
+ */
19
+
20
+ import { EFFORT_LEVELS, type EffortLevel, type RouterConfig } from "../router/config";
21
+ import { getActiveTiers } from "../router/protocol";
22
+ import type { LadderStepKind } from "../routing/outcomes/types";
23
+ import type { EscalatePolicy, LadderAction, LadderState } from "./ladder";
24
+ import { DEFAULT_VARIANT, catalogVariantIds, type CatalogModel, type ResumeDecision } from "./variants";
25
+
26
+ /** A catalog entry as the runner needs it: the variants and limits of `variants.ts` plus the model identity. */
27
+ export interface RunnerCatalogModel extends CatalogModel {
28
+ readonly providerID: string;
29
+ readonly id: string;
30
+ }
31
+
32
+ /** Non-throwing lookup of a `provider/model` id in the host catalog. */
33
+ export type CatalogLookup = (model: string) => CatalogModel | null | undefined;
34
+
35
+ /** Builds the lookup from a host model list, keyed `providerID/id`. A malformed entry is skipped, a repeat keeps the first. */
36
+ export function createCatalogLookup(models: readonly RunnerCatalogModel[]): CatalogLookup {
37
+ const byRef = new Map<string, CatalogModel>();
38
+ for (const entry of models) {
39
+ if (entry === null || typeof entry !== "object") continue;
40
+ if (typeof entry.providerID !== "string" || entry.providerID === "" || typeof entry.id !== "string" || entry.id === "") continue;
41
+ const ref = `${entry.providerID}/${entry.id}`;
42
+ if (!byRef.has(ref)) byRef.set(ref, entry);
43
+ }
44
+ return (model) => byRef.get(model);
45
+ }
46
+
47
+ export interface AttemptModel {
48
+ readonly providerID: string;
49
+ readonly modelID: string;
50
+ readonly variant?: string;
51
+ }
52
+
53
+ /**
54
+ * Why an attempt that the ladder marked `resume` (or could have resumed) starts a fresh child instead.
55
+ *
56
+ * - `invalid-variant`: the target variant is not in the live catalog (D10 fallback, logged).
57
+ * - `bare-model-after-variant` (1.5 R1): the escalation sends a bare `provider/model` to a child whose stored
58
+ * variant was set by an earlier step. MEASURED on 2.0.22 in Phase 3.2 (H7 and scenario 7): the host does not keep the old
59
+ * variant, it stores `default` and sends the model's default effort (Anthropic sonnet-5-5: in-band `high`; opus-5-5: none; OpenAI
60
+ * luna: in-band `medium`), which is what a fresh bare-model child would run with. The guard stays all the same: that was seen at the
61
+ * host-to-provider boundary only, and PROVIDER ACCEPTANCE of in-band effort is unverified. Re-decide after a real-provider check.
62
+ * - `effort-path` (1.5 QA-1.5-22): an escalation (agent switch) across a tier that configures
63
+ * `effort`/`thinking`/`reasoning`. MEASURED on 2.0.22 in Phase 3.2 (H7, H7b): after an agent switch on resume the request carries the
64
+ * TARGET agent's effort option once (effort options never accumulate), delivered as follows: on a model change at the top level; on a same-model
65
+ * switch the previous agent's effort stays at the top level and the target's goes in-band, taking effect only if the provider honours
66
+ * in-band effort. The agent's `effort` option wins over the stored variant. The guard stays: provider
67
+ * acceptance of in-band effort is unverified, so the least trusted path still starts fresh. Re-decide after a real-provider check.
68
+ */
69
+ export type FreshReason = "invalid-variant" | "bare-model-after-variant" | "effort-path";
70
+
71
+ /** What the runner executes for one ladder attempt. */
72
+ export interface AttemptPlan {
73
+ /** Kind of attempt (the registry's `step`): `dispatch` for the first one. */
74
+ readonly step: LadderStepKind;
75
+ /** Ladder tier the attempt runs for (configuration, guards, cost). */
76
+ readonly tier: string;
77
+ /** Agent id to dispatch (the tier name for a router tier). */
78
+ readonly agent: string;
79
+ /** Model and variant to dispatch; undefined when the tier's model does not resolve (as today). */
80
+ readonly model?: AttemptModel;
81
+ /** Resume this child instead of creating one. */
82
+ readonly resumeSessionID?: string;
83
+ /** The ladder's D11 verdict with both numbers, when the policy is session-aware. */
84
+ readonly resumeBasis?: ResumeDecision;
85
+ /** Set when the ladder said `resume` but the runner starts fresh anyway, or the variant was invalid. */
86
+ readonly fresh?: FreshReason;
87
+ /** Effort-bump override for the attempt's session (the ladder's, or the invalid-variant fallback). */
88
+ readonly effort?: EffortLevel;
89
+ /** costRatio of the rung the attempt runs (A17); undefined = the tier's ratio (also for the `invalid-variant` fallback). */
90
+ readonly costRatio?: number;
91
+ /** The variant the dispatch asks for, for the next plan's R1 check (undefined = the model's default). */
92
+ readonly variant?: string;
93
+ }
94
+
95
+ function splitModel(ref: string | undefined): { providerID: string; modelID: string } | null {
96
+ if (typeof ref !== "string") return null;
97
+ const slash = ref.indexOf("/");
98
+ if (slash <= 0 || slash >= ref.length - 1) return null;
99
+ return { providerID: ref.slice(0, slash), modelID: ref.slice(slash + 1) };
100
+ }
101
+
102
+ function isEffortLevel(value: string): value is EffortLevel {
103
+ return (EFFORT_LEVELS as readonly string[]).includes(value);
104
+ }
105
+
106
+ /** Today's dispatch of a tier: its configured model and variant. */
107
+ function configuredModel(cfg: RouterConfig, tier: string): AttemptModel | undefined {
108
+ const tierCfg = getActiveTiers(cfg)[tier];
109
+ const parsed = splitModel(typeof tierCfg?.model === "string" ? tierCfg.model : undefined);
110
+ if (parsed === null) return undefined;
111
+ return { ...parsed, variant: tierCfg?.variant };
112
+ }
113
+
114
+ /** The first attempt of a delegation: the start tier exactly as the runner always dispatched it. */
115
+ export function planFirstAttempt(cfg: RouterConfig, tier: string): AttemptPlan {
116
+ const model = configuredModel(cfg, tier);
117
+ return {
118
+ step: "dispatch",
119
+ tier,
120
+ agent: tier,
121
+ ...(model === undefined ? {} : { model }),
122
+ ...(model?.variant === undefined ? {} : { variant: model.variant }),
123
+ };
124
+ }
125
+
126
+ export interface NextAttemptInput {
127
+ /** The retry/escalate action `nextAction` returned. */
128
+ readonly action: LadderAction;
129
+ /** State after `advance(state, action)`: `currentTier` is the target tier; `childSessionID` survives only on resume. */
130
+ readonly state: LadderState;
131
+ /** The plan of the attempt that just ran (its variant is what the child's stored variant is). */
132
+ readonly previous: AttemptPlan;
133
+ readonly cfg: RouterConfig;
134
+ readonly policy: EscalatePolicy;
135
+ readonly catalog: CatalogLookup | undefined;
136
+ }
137
+
138
+ /** The attempt that follows a retry or escalate action. */
139
+ export function planNextAttempt(input: NextAttemptInput): AttemptPlan {
140
+ const { action, state, previous, cfg, policy, catalog } = input;
141
+ const tier = state.currentTier;
142
+ const step: LadderStepKind = action.action === "escalate" ? "escalate" : action.variantStep === true ? "variant" : "retry";
143
+ const agent = action.agent ?? tier;
144
+ const costRatio = action.costRatio;
145
+ const sessionAware = action.model !== undefined;
146
+
147
+ let model: AttemptModel | undefined;
148
+ let fresh: FreshReason | undefined;
149
+ let effort: EffortLevel | undefined = action.effort;
150
+ if (!sessionAware) {
151
+ // No variant info for the target (v1, `variantSteps: none`, no catalog entry, an effort-configured tier):
152
+ // exactly what the runner dispatched before this phase.
153
+ model = configuredModel(cfg, tier);
154
+ } else {
155
+ const parsed = splitModel(action.model);
156
+ const ids = catalogVariantIds(catalog?.(action.model!));
157
+ const invalid =
158
+ parsed === null || (action.variant !== undefined && (ids === null || !ids.includes(action.variant)));
159
+ if (invalid) {
160
+ // D10 fallback: a fresh session on the tier's model. When the variant names an effort level, the effort travels
161
+ // as the producer-side effort override (the v1 path) and the model goes bare, so the effort is delivered once
162
+ // and never next to a variant (A7/F3: which one wins on the wire is unverified). Otherwise the tier's own
163
+ // model and variant, with no effort.
164
+ fresh = "invalid-variant";
165
+ const configured = configuredModel(cfg, tier);
166
+ if (configured !== undefined && action.variant !== undefined && isEffortLevel(action.variant)) {
167
+ model = { providerID: configured.providerID, modelID: configured.modelID };
168
+ effort = effort ?? action.variant;
169
+ } else {
170
+ model = configured;
171
+ }
172
+ } else {
173
+ model = { ...parsed, ...(action.variant === undefined ? {} : { variant: action.variant }) };
174
+ }
175
+ }
176
+
177
+ let resumeSessionID: string | undefined;
178
+ if (action.resume === true && typeof state.childSessionID === "string" && state.childSessionID !== "") {
179
+ if (fresh === undefined) {
180
+ const stored = previous.variant;
181
+ const storedVariant = stored !== undefined && stored !== "" && stored !== DEFAULT_VARIANT;
182
+ const perTier = policy.variants?.perTier;
183
+ const own = (name: string) => (perTier !== undefined && Object.prototype.hasOwnProperty.call(perTier, name) ? perTier[name] : undefined);
184
+ // Both guards are kept on purpose (Phase 3.2 measured the host side; provider acceptance of in-band effort is unverified).
185
+ if (model !== undefined && model.variant === undefined && storedVariant) {
186
+ fresh = "bare-model-after-variant";
187
+ } else if (action.action === "escalate" && (own(previous.tier)?.effortConfigured === true || own(tier)?.effortConfigured === true)) {
188
+ fresh = "effort-path";
189
+ }
190
+ }
191
+ if (fresh === undefined) resumeSessionID = state.childSessionID;
192
+ }
193
+
194
+ return {
195
+ step,
196
+ tier,
197
+ agent,
198
+ ...(model === undefined ? {} : { model }),
199
+ ...(resumeSessionID === undefined ? {} : { resumeSessionID }),
200
+ ...(action.resumeBasis === undefined ? {} : { resumeBasis: action.resumeBasis }),
201
+ ...(fresh === undefined ? {} : { fresh }),
202
+ ...(effort === undefined ? {} : { effort }),
203
+ // The rung's ratio is the one the action priced for its own model#variant; the invalid-variant fallback runs the
204
+ // tier's configured model instead, so the runner charges the tier's ratio (QA-2.3-8).
205
+ ...(costRatio === undefined || fresh === "invalid-variant" ? {} : { costRatio }),
206
+ ...(model?.variant === undefined ? {} : { variant: model.variant }),
207
+ };
208
+ }
@@ -0,0 +1,391 @@
1
+ /**
2
+ * Session-aware ladder algebra, catalog half (M5; plan #74 §1.5 D10/D11,
3
+ * amendments A5, A7, A9, A10).
4
+ *
5
+ * Pure helpers over structural slices of the host's `Model.Info`: the variant
6
+ * ladder of one model, the next variant step, the position of the stored
7
+ * `default` variant, a model's input budget and the resume-vs-fresh decision.
8
+ * No I/O, no clock, no host types. `ladder.ts` composes these into
9
+ * `nextAction`; nothing here knows about tiers or attempts.
10
+ *
11
+ * Invariant: every id this module returns as a step target comes from the
12
+ * catalog's `variants[]` of that model. `default` (A9) is never returned.
13
+ */
14
+
15
+ /** The host's effort order (@opencode/ai ReasoningEfforts); 0.P S4 found every live variant list in this order. */
16
+ export const HOST_EFFORT_ORDER = ["none", "minimal", "low", "medium", "high", "xhigh", "max"] as const;
17
+
18
+ /** Variant the host stores for a child created without one (A9). It is not a member of `variants[]` and sends no effort. */
19
+ export const DEFAULT_VARIANT = "default";
20
+
21
+ /**
22
+ * Position of {@link DEFAULT_VARIANT} on the host effort scale: strictly
23
+ * between `medium` and `high`.
24
+ *
25
+ * A child without a variant sends no effort (0.P S2b), so its effective effort
26
+ * is the provider's own default: no thinking on `claude-haiku-4-5`, `high` on
27
+ * the Anthropic Messages API, at most `medium` on OpenAI reasoning models
28
+ * (documented provider defaults; 0.P observed only that nothing is sent).
29
+ * Placing `default` just below `high` makes the first step from it the lowest
30
+ * ladder variant ranked `high` or above: never below any of those defaults,
31
+ * and never a `none`/`low` step that would reduce reasoning.
32
+ */
33
+ export const DEFAULT_VARIANT_POSITION = HOST_EFFORT_ORDER.indexOf("high") - 0.5;
34
+
35
+ /** Structural slice of the host's `Model.Info` that this module reads. */
36
+ export interface CatalogModel {
37
+ readonly variants?: ReadonlyArray<{ readonly id?: unknown } | null | undefined> | null;
38
+ readonly limit?: {
39
+ readonly context?: unknown;
40
+ readonly input?: unknown;
41
+ readonly output?: unknown;
42
+ } | null;
43
+ }
44
+
45
+ /** Structural slice of a configured `tiers.<t>.candidates[]` entry. */
46
+ export interface VariantCandidate {
47
+ /** Inherits the ladder's model when omitted (§1.1.2). */
48
+ readonly model?: string | null;
49
+ readonly variant?: string | null;
50
+ }
51
+
52
+ /** A configured candidate rung on another model: variant steps never walk it (escalation territory). */
53
+ export interface ForeignRung {
54
+ readonly model: string;
55
+ readonly variant: string | null;
56
+ }
57
+
58
+ export interface VariantLadder {
59
+ /** `provider/model`, as configured. */
60
+ readonly model: string;
61
+ /** Step targets in step order, strictly rising in rank; always a subset of the catalog's `variants[].id`. */
62
+ readonly variants: readonly string[];
63
+ /**
64
+ * `candidates` whenever the tier configured a non-empty `candidates` array (even if no rung of this
65
+ * model survived, QA-1.5-5), `catalog` for the catalog order, `none` without a catalog `variants` array.
66
+ */
67
+ readonly source: "catalog" | "candidates" | "none";
68
+ /**
69
+ * Candidate variants of this model dropped: absent from the catalog, unranked, or not ranked above
70
+ * every variant kept before them (for the advisor and logs).
71
+ */
72
+ readonly rejected: readonly string[];
73
+ /** Candidate rungs naming another model (for the 2.4 advisor); never part of `variants`. */
74
+ readonly foreign: readonly ForeignRung[];
75
+ }
76
+
77
+ export interface VariantLadderInput {
78
+ /** `provider/model` the ladder is for. */
79
+ model: string;
80
+ /** Catalog entry of `model`; absent or without a `variants` array means no variant steps. */
81
+ catalog: CatalogModel | null | undefined;
82
+ /**
83
+ * The tier's configured `candidates` exactly as written — never the
84
+ * defaulted single-entry list of `resolveCandidates`, which would pin the
85
+ * ladder to the tier's own variant.
86
+ */
87
+ candidates?: readonly (VariantCandidate | null | undefined)[] | null;
88
+ /**
89
+ * Highest ranked variant a catalog ladder may reach (the resolved
90
+ * `effortBumpMax`). `null`/omitted: no cap. An id outside
91
+ * {@link HOST_EFFORT_ORDER} admits nothing. Explicit candidates are not capped.
92
+ */
93
+ maxEffort?: string | null;
94
+ }
95
+
96
+ /** Index of `id` in {@link HOST_EFFORT_ORDER}, or -1 for an unranked id. */
97
+ export function variantRank(id: string): number {
98
+ return (HOST_EFFORT_ORDER as readonly string[]).indexOf(id);
99
+ }
100
+
101
+ /** Position on the effort scale: rank, {@link DEFAULT_VARIANT_POSITION} for `default`, `null` when unranked. */
102
+ export function variantPosition(id: string | null | undefined): number | null {
103
+ if (id == null || id === "" || id === DEFAULT_VARIANT) return DEFAULT_VARIANT_POSITION;
104
+ const rank = variantRank(id);
105
+ return rank >= 0 ? rank : null;
106
+ }
107
+
108
+ /** Interval a variant occupies on the effort scale. */
109
+ export interface VariantRange {
110
+ readonly low: number;
111
+ readonly high: number;
112
+ }
113
+
114
+ /**
115
+ * The effort interval of a variant (QA-1.5-3). A ranked id is a point. `default` is a range, because
116
+ * the provider's own default effort is unobserved (F9): from "below everything" (-1) up to `high`.
117
+ * `null` for an unranked id.
118
+ */
119
+ export function variantRange(id: string | null | undefined): VariantRange | null {
120
+ if (id == null || id === "" || id === DEFAULT_VARIANT) return { low: -1, high: variantRank("high") };
121
+ const rank = variantRank(id);
122
+ return rank >= 0 ? { low: rank, high: rank } : null;
123
+ }
124
+
125
+ /**
126
+ * Whether a tier whose base is `base` adds nothing once `reached` has been tried on the same model:
127
+ * the very same variant, or a base whose highest possible effort is at most the lowest possible
128
+ * effort of `reached`. `default` as a base is only covered by `high` or above; `default` as the
129
+ * reached variant covers nothing but `default` itself.
130
+ */
131
+ export function variantCovered(base: string | null | undefined, reached: string | null | undefined): boolean {
132
+ const normalized = (id: string | null | undefined): string => (id == null || id === "" ? DEFAULT_VARIANT : id);
133
+ if (normalized(base) === normalized(reached)) return true;
134
+ const b = variantRange(base);
135
+ const r = variantRange(reached);
136
+ return b !== null && r !== null && b.high <= r.low;
137
+ }
138
+
139
+ /** Catalog variant ids in catalog order, deduplicated; `null` when the entry has no `variants` array. */
140
+ export function catalogVariantIds(catalog: CatalogModel | null | undefined): readonly string[] | null {
141
+ const variants = catalog?.variants;
142
+ if (!Array.isArray(variants)) return null;
143
+ const ids: string[] = [];
144
+ for (const entry of variants) {
145
+ const id: unknown = entry?.id;
146
+ if (typeof id !== "string" || id.length === 0 || id === DEFAULT_VARIANT || ids.includes(id)) continue;
147
+ ids.push(id);
148
+ }
149
+ return ids;
150
+ }
151
+
152
+ interface CandidateScan {
153
+ /** Variants this model's candidates name, in candidate order, deduplicated. */
154
+ named: string[];
155
+ /** Rungs that name another model, deduplicated. */
156
+ foreign: ForeignRung[];
157
+ /** The tier configured a non-empty `candidates` array. */
158
+ explicit: boolean;
159
+ }
160
+
161
+ function scanCandidates(model: string, candidates: VariantLadderInput["candidates"]): CandidateScan {
162
+ const scan: CandidateScan = { named: [], foreign: [], explicit: false };
163
+ if (!Array.isArray(candidates) || candidates.length === 0) return scan;
164
+ scan.explicit = true;
165
+ for (const candidate of candidates) {
166
+ if (candidate === null || typeof candidate !== "object") continue;
167
+ const candidateModel = candidate.model ?? model;
168
+ if (typeof candidateModel !== "string") continue;
169
+ const variant = typeof candidate.variant === "string" && candidate.variant.length > 0 ? candidate.variant : null;
170
+ if (candidateModel !== model) {
171
+ if (!scan.foreign.some((rung) => rung.model === candidateModel && rung.variant === variant)) {
172
+ scan.foreign.push(Object.freeze({ model: candidateModel, variant }));
173
+ }
174
+ continue;
175
+ }
176
+ if (variant !== null && !scan.named.includes(variant)) scan.named.push(variant);
177
+ }
178
+ return scan;
179
+ }
180
+ function freezeLadder(
181
+ model: string,
182
+ variants: string[],
183
+ source: VariantLadder["source"],
184
+ rejected: string[],
185
+ foreign: ForeignRung[],
186
+ ): VariantLadder {
187
+ return Object.freeze({
188
+ model,
189
+ variants: Object.freeze(variants),
190
+ source,
191
+ rejected: Object.freeze(rejected),
192
+ foreign: Object.freeze(foreign),
193
+ });
194
+ }
195
+
196
+ /**
197
+ * The variant ladder of one model (D10).
198
+ *
199
+ * - A non-empty `candidates` array makes the ladder exactly the variants its entries name for `model`,
200
+ * in their own order, keeping only ids the catalog offers that are ranked strictly above everything
201
+ * kept before them (the rest go to `rejected`), so a candidate ladder never steps down either. The
202
+ * source is `candidates` even when nothing survives; entries naming another model are reported in
203
+ * `foreign`. No `maxEffort` cap applies: the user listed them.
204
+ * - Otherwise the catalog's `variants[].id` in catalog order, keeping only ranked ids at or below
205
+ * `maxEffort` that strictly raise the rank, so a catalog ladder never steps down even if a catalog
206
+ * is out of order.
207
+ * - Without a catalog `variants` array there is no ladder.
208
+ */
209
+ export function buildVariantLadder(input: VariantLadderInput): VariantLadder {
210
+ const { model } = input;
211
+ const catalogIds = catalogVariantIds(input.catalog);
212
+ const scan = scanCandidates(model, input.candidates);
213
+ if (catalogIds === null) return freezeLadder(model, [], "none", scan.named, scan.foreign);
214
+ if (scan.explicit) {
215
+ const variants: string[] = [];
216
+ const rejected: string[] = [];
217
+ let last = -1;
218
+ for (const id of scan.named) {
219
+ const rank = variantRank(id);
220
+ if (!catalogIds.includes(id) || rank < 0 || rank <= last) {
221
+ rejected.push(id);
222
+ continue;
223
+ }
224
+ variants.push(id);
225
+ last = rank;
226
+ }
227
+ return freezeLadder(model, variants, "candidates", rejected, scan.foreign);
228
+ }
229
+ const cap = input.maxEffort == null ? Number.POSITIVE_INFINITY : variantRank(input.maxEffort);
230
+ const variants: string[] = [];
231
+ let last = -1;
232
+ for (const id of catalogIds) {
233
+ const rank = variantRank(id);
234
+ if (rank < 0 || rank > cap || rank <= last) continue;
235
+ variants.push(id);
236
+ last = rank;
237
+ }
238
+ return freezeLadder(model, variants, "catalog", [], []);
239
+ }
240
+ /**
241
+ * The next variant step from `current` on `ladder`, or `null` when none.
242
+ *
243
+ * - `current` on the ladder: the following entry.
244
+ * - `current` absent, `null`, empty or `default` (A9): the first ladder entry
245
+ * positioned above {@link DEFAULT_VARIANT_POSITION}, i.e. ranked `high` or above.
246
+ * - Any other ranked `current` off the ladder (a configured base the ladder
247
+ * skips): the first ladder entry ranked above it.
248
+ * - An unranked `current` off the ladder: `null` (it cannot be placed).
249
+ *
250
+ * Every non-null result is a ladder member, so repeated stepping terminates
251
+ * within `ladder.variants.length` steps.
252
+ */
253
+ export function nextVariant(ladder: VariantLadder, current: string | null | undefined): string | null {
254
+ const ids = ladder.variants;
255
+ if (ids.length === 0) return null;
256
+ const effective = current == null || current === "" ? DEFAULT_VARIANT : current;
257
+ const at = ids.indexOf(effective);
258
+ if (at >= 0) return ids[at + 1] ?? null;
259
+ const position = variantPosition(effective);
260
+ if (position === null) return null;
261
+ for (const id of ids) {
262
+ const rank = variantRank(id);
263
+ if (rank >= 0 && rank > position) return id;
264
+ }
265
+ return null;
266
+ }
267
+
268
+ /** `provider/model#variant` for the host's `subagent` `model` field; bare model for `default`/none. */
269
+ export function modelRef(model: string, variant: string | null | undefined): string {
270
+ return variant == null || variant === "" || variant === DEFAULT_VARIANT ? model : `${model}#${variant}`;
271
+ }
272
+
273
+ function finiteAtLeast(value: unknown, min: number, inclusive: boolean): number | null {
274
+ if (typeof value !== "number" || !Number.isFinite(value)) return null;
275
+ return value > min || (inclusive && value === min) ? value : null;
276
+ }
277
+
278
+ /**
279
+ * Input budget of a model (A5, A10): `limit.input ?? (limit.context − limit.output)`.
280
+ * `null` when unknown or not positive — callers treat that as "do not resume".
281
+ */
282
+ export function inputBudget(limit: CatalogModel["limit"]): number | null {
283
+ if (limit === null || typeof limit !== "object") return null;
284
+ if (limit.input !== undefined && limit.input !== null) return finiteAtLeast(limit.input, 0, false);
285
+ const context = finiteAtLeast(limit.context, 0, false);
286
+ const output = finiteAtLeast(limit.output, 0, true);
287
+ if (context === null || output === null) return null;
288
+ return context > output ? context - output : null;
289
+ }
290
+
291
+ /** Structural slice of the host's `TokenUsage.Info` of one finished step. */
292
+ export interface StepTokens {
293
+ readonly input?: unknown;
294
+ readonly output?: unknown;
295
+ readonly reasoning?: unknown;
296
+ readonly cache?: { readonly read?: unknown; readonly write?: unknown } | null;
297
+ }
298
+
299
+ /**
300
+ * Context a resumed child carries (D11): `input + cache.read + cache.write + output`
301
+ * of its last step. Reasoning tokens are not counted (D11 lists four fields).
302
+ * Missing cache counts as 0; any other missing or invalid field gives `null`.
303
+ */
304
+ export function stepContextTokens(tokens: StepTokens | null | undefined): number | null {
305
+ if (tokens === null || typeof tokens !== "object") return null;
306
+ const input = finiteAtLeast(tokens.input, 0, true);
307
+ const output = finiteAtLeast(tokens.output, 0, true);
308
+ const cache = tokens.cache ?? {};
309
+ if (typeof cache !== "object") return null;
310
+ const read = cache.read === undefined ? 0 : finiteAtLeast(cache.read, 0, true);
311
+ const write = cache.write === undefined ? 0 : finiteAtLeast(cache.write, 0, true);
312
+ if (input === null || output === null || read === null || write === null) return null;
313
+ return input + read + write + output;
314
+ }
315
+
316
+ /** Token estimate of a prompt (A5: characters / 4, rounded up); `null` for an invalid count. */
317
+ export function estimateTokensFromChars(chars: number): number | null {
318
+ const valid = finiteAtLeast(chars, 0, true);
319
+ return valid === null ? null : Math.ceil(valid / 4);
320
+ }
321
+
322
+ /** Ladder-state fields the resume decision reads (a structural slice of `LadderState`). */
323
+ export interface ResumeState {
324
+ readonly childSessionID?: string | null;
325
+ readonly lastStepTokens?: number | null;
326
+ /** Input budget of the model the next attempt runs on. */
327
+ readonly nextModelContext?: number | null;
328
+ }
329
+
330
+ export interface ResumeConfig {
331
+ /** `routing.sessionReuse.maxContextFraction`. */
332
+ readonly maxContextFraction: number;
333
+ /** Estimate of forcing message + dispatch prompt ({@link estimateTokensFromChars}). */
334
+ readonly nextPromptTokens: number | null;
335
+ }
336
+
337
+ export type ResumeReason =
338
+ | "no-child"
339
+ | "unknown-tokens"
340
+ | "unknown-budget"
341
+ | "unknown-estimate"
342
+ | "invalid-fraction"
343
+ | "under-threshold"
344
+ | "at-or-over-threshold";
345
+
346
+ /** The decision and the numbers D11 requires to be logged. */
347
+ export interface ResumeDecision {
348
+ resume: boolean;
349
+ reason: ResumeReason;
350
+ /** `lastStepTokens + nextPromptTokens`, when both are known. */
351
+ tokens: number | null;
352
+ /** Input budget of the next model. */
353
+ budget: number | null;
354
+ /**
355
+ * `maxContextFraction × budget`, when both are valid. For logging only: the decision compares
356
+ * `tokens / budget < maxContextFraction`, which is exact where the product is not (QA-1.5-7).
357
+ */
358
+ threshold: number | null;
359
+ }
360
+
361
+ /**
362
+ * Resume vs fresh (D11 as amended by A5): resume only when
363
+ * `lastStepTokens + nextPromptTokens < maxContextFraction × nextModelContext`, decided as
364
+ * `tokens / budget < maxContextFraction`: a division is correctly rounded, so tokens exactly at the
365
+ * fraction compare equal, whereas the product `0.55 × 200000` is 110000.00000000001 and would resume
366
+ * at exactly 110000 tokens (QA-1.5-7). Exactly at the threshold, and whenever any input is unknown,
367
+ * start fresh.
368
+ */
369
+ export function resumeDecision(state: ResumeState, cfg: ResumeConfig): ResumeDecision {
370
+ const child = state.childSessionID;
371
+ const last = finiteAtLeast(state.lastStepTokens, 0, true);
372
+ const budget = finiteAtLeast(state.nextModelContext, 0, false);
373
+ const estimate = finiteAtLeast(cfg.nextPromptTokens, 0, true);
374
+ const fraction = finiteAtLeast(cfg.maxContextFraction, 0, false);
375
+ const validFraction = fraction !== null && fraction <= 1 ? fraction : null;
376
+ const tokens = last !== null && estimate !== null ? last + estimate : null;
377
+ const threshold = budget !== null && validFraction !== null ? validFraction * budget : null;
378
+ const decide = (reason: ResumeReason): ResumeDecision => ({
379
+ resume: reason === "under-threshold",
380
+ reason,
381
+ tokens,
382
+ budget,
383
+ threshold,
384
+ });
385
+ if (typeof child !== "string" || child.length === 0) return decide("no-child");
386
+ if (last === null) return decide("unknown-tokens");
387
+ if (budget === null) return decide("unknown-budget");
388
+ if (estimate === null) return decide("unknown-estimate");
389
+ if (validFraction === null) return decide("invalid-fraction");
390
+ return decide(tokens! / budget! < validFraction! ? "under-threshold" : "at-or-over-threshold");
391
+ }