opencode-model-router 2.1.0 → 2.3.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (55) hide show
  1. package/CHANGELOG.md +86 -0
  2. package/README.md +44 -5
  3. package/package.json +4 -1
  4. package/src/commands/output.ts +4 -1
  5. package/src/compat/child-session.ts +43 -0
  6. package/src/compat/v2-client.ts +107 -7
  7. package/src/compat/v2-hooks.ts +174 -47
  8. package/src/escalate/attempt-recorder.ts +263 -0
  9. package/src/escalate/ladder.ts +484 -10
  10. package/src/escalate/resume.ts +208 -0
  11. package/src/escalate/variants.ts +391 -0
  12. package/src/index.ts +557 -61
  13. package/src/router/build-info.ts +151 -0
  14. package/src/router/config.ts +1691 -67
  15. package/src/router/protocol.ts +47 -0
  16. package/src/router/sessions.ts +441 -9
  17. package/src/routing/advisor/findings.ts +706 -0
  18. package/src/routing/advisor/index.ts +606 -0
  19. package/src/routing/classify/backends/host.ts +163 -0
  20. package/src/routing/classify/backends/openai-compatible.ts +275 -0
  21. package/src/routing/classify/backends/shared.ts +741 -0
  22. package/src/routing/classify/backends/typesafe.ts +315 -0
  23. package/src/routing/classify/fences.ts +96 -0
  24. package/src/routing/classify/index.ts +576 -0
  25. package/src/routing/classify/route-line.ts +298 -0
  26. package/src/routing/classify/rules.ts +607 -0
  27. package/src/routing/classify/scrub.ts +214 -0
  28. package/src/routing/classify/state.ts +148 -0
  29. package/src/routing/classify/text.ts +20 -0
  30. package/src/routing/classify/types.ts +1280 -0
  31. package/src/routing/commands/annotate-plan.ts +652 -0
  32. package/src/routing/commands/stats.ts +131 -0
  33. package/src/routing/commands/v1-roles.ts +64 -0
  34. package/src/routing/engine/index.ts +32 -0
  35. package/src/routing/engine/kernel.ts +597 -0
  36. package/src/routing/engine/ladders.ts +561 -0
  37. package/src/routing/engine/plan.ts +404 -0
  38. package/src/routing/engine/protocol-line.ts +133 -0
  39. package/src/routing/engine/simulate.ts +167 -0
  40. package/src/routing/engine/types.ts +270 -0
  41. package/src/routing/file-lock.ts +53 -0
  42. package/src/routing/outcomes/beta.ts +141 -0
  43. package/src/routing/outcomes/cost.ts +313 -0
  44. package/src/routing/outcomes/index.ts +172 -0
  45. package/src/routing/outcomes/ingest.ts +812 -0
  46. package/src/routing/outcomes/persist.ts +1058 -0
  47. package/src/routing/outcomes/stats.ts +602 -0
  48. package/src/routing/outcomes/store.ts +653 -0
  49. package/src/routing/outcomes/types.ts +954 -0
  50. package/src/routing/wire/dispatch.ts +799 -0
  51. package/src/routing/wire/hint.ts +208 -0
  52. package/src/routing/wire/host-info.ts +256 -0
  53. package/src/routing/wire/runtime.ts +259 -0
  54. package/src/v2.ts +15 -1
  55. package/tiers.json +43 -0
@@ -0,0 +1,561 @@
1
+ /**
2
+ * Candidate ladders (M4) — the graph the decision kernel prices.
3
+ *
4
+ * Design: `docs/qa/cost-aware-routing/phase-1.4.md` → "Design (1.4.1)" §3.
5
+ * Plan #74 §1.5: D7 (inherited ranks), D8 (successor `next`), D10/D12 (tier ladders and role agents),
6
+ * A11 (permissions come from the caller), A17a/A20 (variant coverage, effort-configured tiers).
7
+ *
8
+ * Layout of a {@link Ladder}: the router block first (tier order, then rung order), then one chain per
9
+ * role agent (own model, then the owning tier's rungs). `next` pointers are strictly forward inside the
10
+ * router block, and a role chain only points forward inside itself or into the router block, which never
11
+ * points back: the graph is acyclic by construction.
12
+ *
13
+ * Pure: no I/O, no clock, no randomness, no module state. Runtime imports are pure modules only
14
+ * (`router/config` helpers, `escalate/ladder`, `escalate/variants`, `outcomes/types`, `classify/types`).
15
+ */
16
+
17
+ import {
18
+ ROUTING_RESERVED_AGENTS,
19
+ resolveCandidates,
20
+ resolvePresetName,
21
+ type ResolvedRouting,
22
+ type ResolvedCandidate,
23
+ type RouterConfig,
24
+ type TierConfig,
25
+ } from "../../router/config";
26
+ import { buildEscalatePolicy, type EscalatePolicy, type LadderSessionPolicyInput } from "../../escalate/ladder";
27
+ import { variantCovered } from "../../escalate/variants";
28
+ import { CLASS_STATIC_TIER, NEEDS, type Need, type TaskFacts } from "../classify/types";
29
+ import { classifyAgentOrigin, normalizeVariant, splitModelRef } from "../outcomes/types";
30
+ import type { AgentRef, ModelPricing } from "../outcomes/types";
31
+ import { coversNeeds } from "./kernel";
32
+ import { simulateAfter, simulateRunner, type RunnerRung } from "./simulate";
33
+ import type {
34
+ Candidate,
35
+ ChosenDispatch,
36
+ ExcludedCandidate,
37
+ ExclusionReason,
38
+ HostAgentInfo,
39
+ Ladder,
40
+ } from "./types";
41
+
42
+ // ---------------------------------------------------------------------------
43
+ // Escalate ladder and ranks
44
+ // ---------------------------------------------------------------------------
45
+
46
+ /** The active preset's tiers (the same preset name resolution `resolveCandidates` uses), own keys only. */
47
+ function activeTiers(cfg: RouterConfig): Readonly<Record<string, TierConfig>> | undefined {
48
+ const presetName = resolvePresetName(cfg, cfg.activePreset);
49
+ if (presetName === undefined || !Object.hasOwn(cfg.presets, presetName)) return undefined;
50
+ return cfg.presets[presetName];
51
+ }
52
+
53
+ function tierConfigOf(cfg: RouterConfig, tier: string): TierConfig | undefined {
54
+ const tiers = activeTiers(cfg);
55
+ return tiers !== undefined && Object.hasOwn(tiers, tier) ? tiers[tier] : undefined;
56
+ }
57
+
58
+ /** Ids of the router tier agents of the active preset (every tier of the preset, on the ladder or not). */
59
+ export function routerTierIds(cfg: RouterConfig): readonly string[] {
60
+ const tiers = activeTiers(cfg);
61
+ return tiers === undefined ? [] : Object.keys(tiers);
62
+ }
63
+
64
+ /**
65
+ * The runtime escalation ladder (`buildEscalatePolicy(cfg).ladder`, default `fast → medium → heavy`),
66
+ * de-duplicated and restricted to tiers that have at least one rung. One source for the kernel's ranks and
67
+ * for the runtime ladder.
68
+ */
69
+ export function escalateLadder(cfg: RouterConfig): readonly string[] {
70
+ return ladderOf(cfg, buildEscalatePolicy(cfg).ladder);
71
+ }
72
+
73
+ function ladderOf(cfg: RouterConfig, raw: unknown): readonly string[] {
74
+ if (!Array.isArray(raw)) return [];
75
+ const out: string[] = [];
76
+ for (const tier of raw) {
77
+ if (typeof tier !== "string" || tier === "" || out.includes(tier)) continue;
78
+ if (resolveCandidates(tier, cfg).length === 0) continue;
79
+ out.push(tier);
80
+ }
81
+ return out;
82
+ }
83
+
84
+ /** Index of `tier` on the escalate ladder (its capability rank); `null` when absent. */
85
+ export function tierRankOf(cfg: RouterConfig, tier: string | null | undefined): number | null {
86
+ if (typeof tier !== "string" || tier === "") return null;
87
+ const rank = escalateLadder(cfg).indexOf(tier);
88
+ return rank >= 0 ? rank : null;
89
+ }
90
+
91
+ /** Rank of `enforcement.escalate.floorTier`; `null` when unset or off the ladder. */
92
+ export function floorRankOf(cfg: RouterConfig): number | null {
93
+ return tierRankOf(cfg, cfg.enforcement?.escalate?.floorTier);
94
+ }
95
+
96
+ // ---------------------------------------------------------------------------
97
+ // Grants
98
+ // ---------------------------------------------------------------------------
99
+
100
+ const SHELL_TOOLS: readonly string[] = ["shell", "bash"];
101
+ const WEB_TOOLS: readonly string[] = ["webfetch", "websearch"];
102
+ const EDIT_TOOLS: readonly string[] = ["edit", "write", "patch", "apply_patch"];
103
+
104
+ /**
105
+ * Handoff to 2.2 (QA-1.4-14): pass only the tools the agent may use UNCONDITIONALLY, i.e. the evaluated
106
+ * permission is `allow` for the tool (and, for `external_dir`, for every path). A tool that is `ask`,
107
+ * `deny` or allowed only for some patterns must be left out: a need that might block at dispatch time is not
108
+ * a need the agent covers (A11), and an uncovered need only makes a candidate ineligible, never worse.
109
+ *
110
+ * A11: the needs covered by an agent's EVALUATED tool set. `network` means going through a shell command
111
+ * (1.2 `NEEDS`), so it follows `shell`; `external_dir` is the host `external_directory` permission
112
+ * evaluated to allow. Unique, in `NEEDS` order.
113
+ */
114
+ export function grantsFromTools(tools: readonly string[], externalDirectory: boolean): Need[] {
115
+ const have = new Set(tools.map((tool) => tool.toLowerCase()));
116
+ const has = (ids: readonly string[]): boolean => ids.some((id) => have.has(id));
117
+ const granted = new Set<Need>();
118
+ if (has(SHELL_TOOLS)) {
119
+ granted.add("shell");
120
+ granted.add("network");
121
+ }
122
+ if (has(WEB_TOOLS)) granted.add("web");
123
+ if (has(EDIT_TOOLS)) granted.add("edit");
124
+ if (externalDirectory) granted.add("external_dir");
125
+ return NEEDS.filter((need) => granted.has(need));
126
+ }
127
+
128
+ // ---------------------------------------------------------------------------
129
+ // Successor pointers (D8, A17a reduced to a static pointer)
130
+ // ---------------------------------------------------------------------------
131
+
132
+ /** A20 / QA-1.5-18: a tier with `effort`/`thinking`/`reasoning` set is never covered and never a coverage source. */
133
+ function effortConfigured(cfg: RouterConfig, tier: string): boolean {
134
+ const config = tierConfigOf(cfg, tier);
135
+ return config !== undefined && (config.effort !== undefined || config.thinking !== undefined || config.reasoning !== undefined);
136
+ }
137
+
138
+ /** `r` adds nothing after `k` was tried: same model, neither tier effort-configured, variant covered. */
139
+ function skippedAfter(cfg: RouterConfig, k: Candidate, r: Candidate): boolean {
140
+ if (r.model !== k.model) return false;
141
+ if (effortConfigured(cfg, k.tier) || effortConfigured(cfg, r.tier)) return false;
142
+ return variantCovered(r.variant ?? "default", k.variant ?? "default");
143
+ }
144
+
145
+ /**
146
+ * First rung of `following` (already in walk order) that is not covered by `k`, as an index into
147
+ * `all`; `null` when none is left (give up).
148
+ */
149
+ function firstUncovered(
150
+ cfg: RouterConfig,
151
+ k: Candidate,
152
+ following: readonly number[],
153
+ all: readonly Candidate[],
154
+ skipCovered = true,
155
+ ): number | null {
156
+ for (const j of following) {
157
+ if (!skipCovered || !skippedAfter(cfg, k, all[j]!)) return j;
158
+ }
159
+ return null;
160
+ }
161
+
162
+ // ---------------------------------------------------------------------------
163
+ // buildLadder
164
+ // ---------------------------------------------------------------------------
165
+
166
+ export interface LadderBuildInput {
167
+ readonly cfg: RouterConfig;
168
+ readonly routing: Pick<ResolvedRouting, "roles">;
169
+ readonly facts: Pick<TaskFacts, "class" | "needs">;
170
+ /** Router tier agents included. null = unavailable: router grants null, no role candidates. */
171
+ readonly agents: readonly HostAgentInfo[] | null;
172
+ /** Catalog pricing of "provider/model"; a throwing lookup prices as unpriced (QA-1.4-10, A1). */
173
+ readonly pricing?: (model: string) => ModelPricing;
174
+ /** The orchestrator's model: the model of a role agent that has none configured (QA-1.4-4). */
175
+ readonly parentModel?: string | null;
176
+ /** Receives one line per failed pricing lookup; its own failures are swallowed. */
177
+ readonly logger?: { warn(message: string): void };
178
+ /**
179
+ * The input the 1.5 runner's policy is built with (`buildEscalatePolicy(cfg, session)`: host, catalog,
180
+ * `variantSteps`, `maxContextFraction`). Absent = no variant steps, as on v1 or without a catalog (A25).
181
+ */
182
+ readonly session?: LadderSessionPolicyInput;
183
+ }
184
+
185
+ function normalizedVariant(variant: string | null | undefined): string | null {
186
+ return variant === undefined || variant === null || variant === "" ? null : variant;
187
+ }
188
+
189
+ function sameRung(a: { readonly model: string; readonly variant: string | null }, b: { readonly model: string; readonly variant: string | null }): boolean {
190
+ return a.model === b.model && normalizeVariant(a.variant) === normalizeVariant(b.variant);
191
+ }
192
+
193
+ /** Never throws: logging failures are reported through the return value, not raised (QA-1.4-10). */
194
+ function tryWarn(logger: LadderBuildInput["logger"], message: string): boolean {
195
+ if (logger === undefined) return false;
196
+ try {
197
+ logger.warn(message);
198
+ return true;
199
+ } catch {
200
+ return false; // a broken logger must not break the decision
201
+ }
202
+ }
203
+
204
+ /** QA-1.4-10: the catalog lookup is the caller's code; a failure makes the model unpriced (A1), never a throw. */
205
+ function priced(input: LadderBuildInput, model: string): { readonly pricing?: ModelPricing } {
206
+ if (input.pricing === undefined) return {};
207
+ try {
208
+ return { pricing: input.pricing(model) };
209
+ } catch (error) {
210
+ const reason = error instanceof Error ? error.message : String(error);
211
+ tryWarn(input.logger, `[router] ladder: pricing lookup for ${model} failed (${reason}); treating it as unpriced`);
212
+ return {};
213
+ }
214
+ }
215
+
216
+ function ownRoles(roles: Readonly<Record<string, readonly string[]>>, cls: string): readonly string[] {
217
+ const list = Object.hasOwn(roles, cls) ? roles[cls] : undefined;
218
+ return Array.isArray(list) ? [...new Set(list)] : [];
219
+ }
220
+
221
+ /** A host agent unusable as a dispatch target: `mode: primary`, hidden or not permitted for the parent. */
222
+ function agentUnavailable(info: HostAgentInfo): boolean {
223
+ return info.mode === "primary" || info.hidden || !info.permitted;
224
+ }
225
+
226
+ /**
227
+ * Why a `routing.roles` agent cannot be a candidate at the agent level (D12, QA-1.1-18/29): it names a
228
+ * router tier of the active preset (`duplicate`), or it is reserved, absent from the host agent list,
229
+ * `mode: primary`, hidden or not permitted for the parent (`agent-unavailable`). The class-level check
230
+ * (`no-owning-tier`) and the A11 `needs` check are separate; `null` = usable.
231
+ */
232
+ export function roleAgentExclusion(
233
+ id: string,
234
+ info: HostAgentInfo | undefined,
235
+ routerIds: readonly string[],
236
+ ): "duplicate" | "agent-unavailable" | null {
237
+ if (routerIds.includes(id)) return "duplicate";
238
+ if ((ROUTING_RESERVED_AGENTS as readonly string[]).includes(id)) return "agent-unavailable";
239
+ if (info === undefined || agentUnavailable(info)) return "agent-unavailable";
240
+ return null;
241
+ }
242
+
243
+ /** The model a host agent runs on: its configured one, else the parent's (host precedence, QA-1.4-4). */
244
+ function modelOfAgent(info: HostAgentInfo, parentModel: string | null | undefined): string | null {
245
+ return nonEmpty(info.model) ?? nonEmpty(parentModel);
246
+ }
247
+
248
+ /** The base rung of a tier: its own model, variant and ratio (the rung `resolveCandidates` lists for it). */
249
+ function tierBaseRung(cfg: RouterConfig, tier: string): RunnerRung | undefined {
250
+ const config = tierConfigOf(cfg, tier);
251
+ if (config === undefined || typeof config.model !== "string") return undefined;
252
+ const variant = normalizedVariant(config.variant);
253
+ const rungs = resolveCandidates(tier, cfg);
254
+ const own = rungs.find((rung) => sameRung({ model: rung.model, variant: normalizedVariant(rung.variant) }, { model: config.model, variant }));
255
+ const costRatio = (own ?? rungs[0])?.costRatio;
256
+ return costRatio === undefined ? undefined : { tier, model: config.model, variant, costRatio };
257
+ }
258
+
259
+ /**
260
+ * A25: the rungs of a tier the 1.5 runner can walk — the ones on the tier's own model. A `candidates` rung on
261
+ * another model is escalation territory: the runner never runs it, so it is not modelled (`dropped`).
262
+ */
263
+ function modelledRungs(cfg: RouterConfig, tier: string): { readonly kept: readonly ResolvedCandidate[]; readonly dropped: readonly ResolvedCandidate[] } {
264
+ const model = tierConfigOf(cfg, tier)?.model;
265
+ const rungs = resolveCandidates(tier, cfg);
266
+ if (typeof model !== "string") return { kept: rungs, dropped: [] };
267
+ return { kept: rungs.filter((rung) => rung.model === model), dropped: rungs.filter((rung) => rung.model !== model) };
268
+ }
269
+
270
+ /**
271
+ * Build the candidate graph of one decision (§3): the router rungs of the escalate ladder, then the role
272
+ * agents of `facts.class` (D12) with their own-model rung and the owning tier's rungs.
273
+ *
274
+ * Router rungs (A25): every rung on the tier's own model; each carries the attempts the 1.5 runner makes
275
+ * from it — `Ladder.paths`, simulated with `buildEscalatePolicy(cfg, session)` and `nextAction`/`advance` —
276
+ * so the kernel prices retries, `maxTotalAttempts`, the cost ceiling and covered-tier skips as the runner
277
+ * performs them. Rungs only the runner reaches (variant steps) are `Ladder.reachable`, never `best`.
278
+ * `session` is the same input the runner's policy is built with (host, catalog, `variantSteps`); without it
279
+ * the policy has no variant steps, exactly as the runner would behave.
280
+ *
281
+ * Own-model rung of a role agent (D7, A25): when its `(model, variant)` matches a rung of the preset it takes
282
+ * that rung's price AND `min(owningRank, matched.rank)` (an agent on the fast tier's model is a fast-ranked
283
+ * candidate, whatever class it serves); the inherited rank of the owning tier applies only when no rung
284
+ * matches. An agent without a configured model runs on the parent's model and gets its own-model rung there.
285
+ * A role chain is a static successor chain (own model, the owning tier's rungs, then the first router rung of
286
+ * the next tier above, entered as a fresh dispatch).
287
+ *
288
+ * Router rungs of a tier whose agent is `mode: primary`, hidden or not permitted are excluded
289
+ * (`agent-unavailable`): they can never be `best` (a simulated path may still pass through them).
290
+ *
291
+ * Never throws for well-typed input; an unknown preset or a ladder with no resolvable tier yields an empty
292
+ * ladder (the kernel then reports `kept:no-candidates`).
293
+ */
294
+ export function buildLadder(input: LadderBuildInput): Ladder {
295
+ const { cfg, facts, agents } = input;
296
+ const policy: EscalatePolicy = buildEscalatePolicy(cfg, input.session);
297
+ const order = ladderOf(cfg, policy.ladder);
298
+ const rankOf = (tier: string | null | undefined): number | null => {
299
+ const rank = typeof tier === "string" ? order.indexOf(tier) : -1;
300
+ return rank >= 0 ? rank : null;
301
+ };
302
+ const routerIds = routerTierIds(cfg);
303
+ const owningTier = Object.hasOwn(CLASS_STATIC_TIER, facts.class) ? CLASS_STATIC_TIER[facts.class] : null;
304
+ const owningRank = rankOf(owningTier);
305
+ const excluded: ExcludedCandidate[] = [];
306
+ const excludedOf = (id: string, why: ExclusionReason, info: HostAgentInfo | undefined): void => {
307
+ const ref = typeof info?.model === "string" ? splitModelRef(info.model) : null;
308
+ excluded.push({
309
+ agent: { origin: classifyAgentOrigin(id, routerIds), id },
310
+ model: ref === null ? (info?.model ?? "") : `${ref.provider}/${ref.model}`,
311
+ variant: ref?.variant ?? null,
312
+ why,
313
+ });
314
+ };
315
+
316
+ // --- router block --------------------------------------------------------------------------------
317
+ /** Every rung of the preset, modelled or not, available or not: the price/rank table of own-model rungs. */
318
+ const presetRungs: Candidate[] = [];
319
+ const candidates: Candidate[] = [];
320
+ const next: (number | null)[] = [];
321
+ order.forEach((tier, rank) => {
322
+ const info = agents?.find((agent) => agent.id === tier);
323
+ const unavailable = info !== undefined && agentUnavailable(info);
324
+ const grants = info?.grants ?? null;
325
+ const { kept, dropped } = modelledRungs(cfg, tier);
326
+ const routerRung = (rung: ResolvedCandidate): Candidate => ({
327
+ agent: { origin: "router", id: tier },
328
+ model: rung.model,
329
+ variant: normalizedVariant(rung.variant),
330
+ costRatio: rung.costRatio,
331
+ rank,
332
+ tier,
333
+ source: "tier",
334
+ grants,
335
+ ...priced(input, rung.model),
336
+ });
337
+ for (const rung of dropped) {
338
+ const candidate = routerRung(rung);
339
+ presetRungs.push(candidate);
340
+ excluded.push({ agent: candidate.agent, model: candidate.model, variant: candidate.variant, why: "not-modelled" });
341
+ }
342
+ for (const rung of kept) {
343
+ const candidate = routerRung(rung);
344
+ presetRungs.push(candidate);
345
+ if (unavailable) {
346
+ excluded.push({ agent: candidate.agent, model: candidate.model, variant: candidate.variant, why: "agent-unavailable" });
347
+ } else {
348
+ candidates.push(candidate);
349
+ }
350
+ }
351
+ });
352
+ const routerCount = candidates.length;
353
+ for (let k = 0; k < routerCount; k++) next.push(null); // router rungs are priced through `paths` (below)
354
+
355
+ // --- role chains ---------------------------------------------------------------------------------
356
+ const indexes = (from: number, to: number): number[] => {
357
+ const out: number[] = [];
358
+ for (let i = from; i < to; i++) out.push(i);
359
+ return out;
360
+ };
361
+ const roleIds = ownRoles(input.routing.roles, facts.class);
362
+ /** Role chains laid out so far, and the in-chain successor of each of their rungs (QA-1.4-16). */
363
+ const roleChains: { readonly start: number; readonly length: number; readonly tier: string }[] = [];
364
+ const chainNext = new Map<number, number | null>();
365
+ const tierRungs = owningTier !== null && owningRank !== null ? modelledRungs(cfg, owningTier).kept : [];
366
+ const firstTierRung = tierRungs[0];
367
+ for (const id of roleIds) {
368
+ const info = agents?.find((agent) => agent.id === id);
369
+ if (owningTier === null || owningRank === null || firstTierRung === undefined) {
370
+ excludedOf(id, "no-owning-tier", info);
371
+ continue;
372
+ }
373
+ const unusable = roleAgentExclusion(id, info, routerIds);
374
+ if (unusable !== null || info === undefined) {
375
+ excludedOf(id, unusable ?? "agent-unavailable", info);
376
+ continue;
377
+ }
378
+ if (!coversNeeds(info.grants, facts.needs)) {
379
+ excludedOf(id, "needs", info);
380
+ continue;
381
+ }
382
+
383
+ const agent: AgentRef = { origin: "host", id };
384
+ const chainStart = candidates.length;
385
+ const chain: Candidate[] = [];
386
+ let own: Candidate | null = null;
387
+ const modelRef = modelOfAgent(info, input.parentModel);
388
+ const ref = modelRef === null ? null : splitModelRef(modelRef);
389
+ if (ref !== null) {
390
+ const model = `${ref.provider}/${ref.model}`;
391
+ const matched = presetRungs.find((rung) => sameRung(rung, { model, variant: ref.variant }));
392
+ // A25: price and rank come from the matching preset rung; the owning tier's rank only caps it. The cap is for the CANDIDATE
393
+ // only: when this agent is the pick, never-down compares against its capability rank (`kernel.capabilityRank`, A34).
394
+ const lowered = matched !== undefined && matched.rank < owningRank;
395
+ own = {
396
+ agent,
397
+ model,
398
+ variant: ref.variant,
399
+ costRatio: matched?.costRatio ?? firstTierRung.costRatio,
400
+ rank: lowered ? matched.rank : owningRank,
401
+ tier: lowered ? matched.tier : owningTier,
402
+ source: "role-own-model",
403
+ grants: info.grants,
404
+ ...priced(input, model),
405
+ };
406
+ chain.push(own);
407
+ }
408
+ for (const rung of tierRungs) {
409
+ const candidate: Candidate = {
410
+ agent,
411
+ model: rung.model,
412
+ variant: normalizedVariant(rung.variant),
413
+ costRatio: rung.costRatio,
414
+ rank: owningRank,
415
+ tier: owningTier,
416
+ source: "role-tier-rung",
417
+ grants: info.grants,
418
+ ...priced(input, rung.model),
419
+ };
420
+ if (own !== null && sameRung(own, candidate)) {
421
+ excludedOf(id, "duplicate", info);
422
+ continue;
423
+ }
424
+ chain.push(candidate);
425
+ }
426
+
427
+ // After the chain, the cascade continues with the router rungs of the tiers above the owning tier; like
428
+ // the runner, coverage skips apply there only when the policy has variant info.
429
+ const above: number[] = [];
430
+ for (let j = 0; j < routerCount; j++) if (candidates[j]!.rank > owningRank) above.push(j);
431
+ candidates.push(...chain);
432
+ for (let position = 0; position < chain.length; position++) {
433
+ const k = candidates[chainStart + position]!;
434
+ const inChain = firstUncovered(cfg, k, indexes(chainStart + position + 1, chainStart + chain.length), candidates);
435
+ chainNext.set(chainStart + position, inChain);
436
+ next.push(inChain ?? firstUncovered(cfg, k, above, candidates, policy.variants != null));
437
+ }
438
+ roleChains.push({ start: chainStart, length: chain.length, tier: owningTier });
439
+ }
440
+
441
+ // --- simulated runner paths (A25) --------------------------------------------------------------------
442
+ const reachable: Candidate[] = [];
443
+ const paths: (number[] | null)[] = candidates.map(() => null);
444
+ const tierBase = (tier: string): RunnerRung | undefined => tierBaseRung(cfg, tier);
445
+ const indexOfRung = (rung: RunnerRung): number | null => {
446
+ const same = (c: Candidate): boolean => c.tier === rung.tier && c.agent.origin === "router" && sameRung(c, rung);
447
+ for (let j = 0; j < routerCount; j++) if (same(candidates[j]!)) return j;
448
+ const known = reachable.findIndex(same);
449
+ if (known >= 0) return candidates.length + known;
450
+ const rank = rankOf(rung.tier);
451
+ if (rank === null) return null;
452
+ reachable.push({
453
+ agent: { origin: "router", id: rung.tier },
454
+ model: rung.model,
455
+ variant: rung.variant,
456
+ costRatio: rung.costRatio,
457
+ rank,
458
+ tier: rung.tier,
459
+ source: "tier",
460
+ grants: agents?.find((agent) => agent.id === rung.tier)?.grants ?? null,
461
+ ...priced(input, rung.model),
462
+ });
463
+ return candidates.length + reachable.length - 1;
464
+ };
465
+ for (let k = 0; k < routerCount; k++) {
466
+ const start = candidates[k]!;
467
+ const attempts = simulateRunner(policy, tierBase, {
468
+ tier: start.tier,
469
+ model: start.model,
470
+ variant: start.variant,
471
+ costRatio: start.costRatio,
472
+ });
473
+ const path: number[] = [];
474
+ for (const attempt of attempts) {
475
+ const j = indexOfRung(attempt);
476
+ if (j === null) break;
477
+ path.push(j);
478
+ }
479
+ // A router rung is priced through its path; its `next` stays null (a path is not a pointer chain).
480
+ paths[k] = path.length > 0 ? path : null;
481
+ }
482
+ // A role rung's path: the rest of its chain (the same coverage-skipping walk as `next` inside the chain),
483
+ // then the runner continuing the SAME delegation from the tier that owns the class, with the chain's attempts
484
+ // and cost already spent (QA-1.4-16), so a native agent's cascade is not given a fresh budget.
485
+ for (const chain of roleChains) {
486
+ for (let at = chain.start; at < chain.start + chain.length; at++) {
487
+ const members: number[] = [];
488
+ for (let m: number | null = at; m !== null && !members.includes(m); m = chainNext.get(m) ?? null) members.push(m);
489
+ const spent: RunnerRung[] = members.map((m) => {
490
+ const c = candidates[m]!;
491
+ return { tier: chain.tier, model: c.model, variant: c.variant, costRatio: c.costRatio };
492
+ });
493
+ const path = [...members];
494
+ for (const attempt of simulateAfter(policy, tierBase, { tier: chain.tier, attempts: spent })) {
495
+ const j = indexOfRung(attempt);
496
+ if (j === null) break;
497
+ path.push(j);
498
+ }
499
+ paths[at] = path;
500
+ }
501
+ }
502
+
503
+ return {
504
+ candidates,
505
+ next,
506
+ classRank: owningRank,
507
+ excluded,
508
+ ...(reachable.length > 0 ? { reachable } : {}),
509
+ paths,
510
+ // A34 (QA-G-B1): the capability table. A role rung's rank stays capped at the owning tier; the pick's capability is read here.
511
+ presetRungs: presetRungs.map((rung) => ({ model: rung.model, variant: rung.variant, rank: rung.rank })),
512
+ };
513
+ }
514
+ // ---------------------------------------------------------------------------
515
+ // resolveChosen
516
+ // ---------------------------------------------------------------------------
517
+
518
+ export interface ChosenInput {
519
+ readonly cfg: RouterConfig;
520
+ readonly agents: readonly HostAgentInfo[] | null;
521
+ /** `event.input.agent`. */
522
+ readonly agent: string;
523
+ /** `event.input.model`, when the call set one. */
524
+ readonly model?: string | null;
525
+ readonly parentModel?: string | null;
526
+ }
527
+
528
+ function nonEmpty(value: string | null | undefined): string | null {
529
+ return typeof value === "string" && value.trim() !== "" ? value.trim() : null;
530
+ }
531
+
532
+ function splitRef(ref: string): { readonly model: string; readonly variant: string | null } {
533
+ const parts = splitModelRef(ref);
534
+ if (parts !== null) return { model: `${parts.provider}/${parts.model}`, variant: parts.variant };
535
+ const hash = ref.lastIndexOf("#");
536
+ if (hash > 0) return { model: ref.slice(0, hash), variant: normalizedVariant(ref.slice(hash + 1)) };
537
+ return { model: ref, variant: null };
538
+ }
539
+
540
+ /**
541
+ * The orchestrator's pick as the kernel's {@link ChosenDispatch}: a router tier agent resolves to the call's
542
+ * `model` or the tier's own base rung; a host agent to the call's `model`, its configured model or the
543
+ * parent's. `null` when nothing resolves (the caller then logs a kept row without calling `decide`).
544
+ */
545
+ export function resolveChosen(input: ChosenInput): ChosenDispatch | null {
546
+ const { cfg, agent } = input;
547
+ if (typeof agent !== "string" || agent === "") return null;
548
+ const origin = classifyAgentOrigin(agent, routerTierIds(cfg));
549
+ const callModel = nonEmpty(input.model);
550
+ if (origin === "router") {
551
+ const tier = tierConfigOf(cfg, agent);
552
+ if (callModel !== null) return { agent: { origin, id: agent }, ...splitRef(callModel) };
553
+ if (tier === undefined) return null;
554
+ const base = splitRef(tier.model);
555
+ return { agent: { origin, id: agent }, model: base.model, variant: normalizedVariant(tier.variant) ?? base.variant };
556
+ }
557
+ const info = input.agents?.find((candidate) => candidate.id === agent);
558
+ const ref = callModel ?? nonEmpty(info?.model) ?? nonEmpty(input.parentModel);
559
+ if (ref === null) return null;
560
+ return { agent: { origin, id: agent }, ...splitRef(ref) };
561
+ }