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
@@ -0,0 +1,802 @@
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
+ resolveActiveTiers,
21
+ resolvePresetName,
22
+ type ResolvedRouting,
23
+ type ResolvedCandidate,
24
+ type RouterConfig,
25
+ type TierConfig,
26
+ } from "../../router/config";
27
+ import { presetTierOrder } from "../../router/roles";
28
+ import { buildEscalatePolicy, type EscalatePolicy, type LadderSessionPolicyInput } from "../../escalate/ladder";
29
+ import { variantCovered } from "../../escalate/variants";
30
+ import { CLASS_STATIC_TIER, NEEDS, type Need, type TaskFacts } from "../classify/types";
31
+ import { classifyAgentOrigin, normalizeVariant, splitModelRef } from "../outcomes/types";
32
+ import type { AgentRef, ModelPricing } from "../outcomes/types";
33
+ import { coversNeeds } from "./kernel";
34
+ import { simulateAfter, simulateRunner, type RunnerRung } from "./simulate";
35
+ import type {
36
+ Candidate,
37
+ ChosenDispatch,
38
+ ExcludedCandidate,
39
+ ExclusionReason,
40
+ HostAgentInfo,
41
+ Ladder,
42
+ PresetRung,
43
+ RoleLadder,
44
+ RoleLadderTier,
45
+ RoleWindow,
46
+ } from "./types";
47
+
48
+ // ---------------------------------------------------------------------------
49
+ // Escalate ladder and ranks
50
+ // ---------------------------------------------------------------------------
51
+
52
+ /** The active preset's tiers (the same preset name resolution `resolveCandidates` uses), own keys only. */
53
+ function activeTiers(cfg: RouterConfig): Readonly<Record<string, TierConfig>> | undefined {
54
+ const presetName = resolvePresetName(cfg, cfg.activePreset);
55
+ if (presetName === undefined || !Object.hasOwn(cfg.presets, presetName)) return undefined;
56
+ return cfg.presets[presetName];
57
+ }
58
+
59
+ function tierConfigOf(cfg: RouterConfig, tier: string): TierConfig | undefined {
60
+ const tiers = activeTiers(cfg);
61
+ return tiers !== undefined && Object.hasOwn(tiers, tier) ? tiers[tier] : undefined;
62
+ }
63
+
64
+ /** Ids of the router tier agents of the active preset (every tier of the preset, on the ladder or not). */
65
+ export function routerTierIds(cfg: RouterConfig): readonly string[] {
66
+ const tiers = activeTiers(cfg);
67
+ return tiers === undefined ? [] : Object.keys(tiers);
68
+ }
69
+
70
+ /**
71
+ * The runtime escalation ladder (`buildEscalatePolicy(cfg).ladder`, default `fast → medium → heavy`),
72
+ * de-duplicated and restricted to tiers that have at least one rung. One source for the kernel's ranks and
73
+ * for the runtime ladder.
74
+ */
75
+ export function escalateLadder(cfg: RouterConfig): readonly string[] {
76
+ return ladderOf(cfg, buildEscalatePolicy(cfg).ladder);
77
+ }
78
+
79
+ function ladderOf(cfg: RouterConfig, raw: unknown): readonly string[] {
80
+ if (!Array.isArray(raw)) return [];
81
+ const out: string[] = [];
82
+ for (const tier of raw) {
83
+ if (typeof tier !== "string" || tier === "" || out.includes(tier)) continue;
84
+ if (resolveCandidates(tier, cfg).length === 0) continue;
85
+ out.push(tier);
86
+ }
87
+ return out;
88
+ }
89
+
90
+ /** Index of `tier` on the escalate ladder (its capability rank); `null` when absent. */
91
+ export function tierRankOf(cfg: RouterConfig, tier: string | null | undefined): number | null {
92
+ if (typeof tier !== "string" || tier === "") return null;
93
+ const rank = escalateLadder(cfg).indexOf(tier);
94
+ return rank >= 0 ? rank : null;
95
+ }
96
+
97
+ /** Rank of `enforcement.escalate.floorTier`; `null` when unset or off the ladder. */
98
+ export function floorRankOf(cfg: RouterConfig): number | null {
99
+ return tierRankOf(cfg, cfg.enforcement?.escalate?.floorTier);
100
+ }
101
+
102
+ // ---------------------------------------------------------------------------
103
+ // Grants
104
+ // ---------------------------------------------------------------------------
105
+
106
+ const SHELL_TOOLS: readonly string[] = ["shell", "bash"];
107
+ const WEB_TOOLS: readonly string[] = ["webfetch", "websearch"];
108
+ const EDIT_TOOLS: readonly string[] = ["edit", "write", "patch", "apply_patch"];
109
+
110
+ /**
111
+ * Handoff to 2.2 (QA-1.4-14): pass only the tools the agent may use UNCONDITIONALLY, i.e. the evaluated
112
+ * permission is `allow` for the tool (and, for `external_dir`, for every path). A tool that is `ask`,
113
+ * `deny` or allowed only for some patterns must be left out: a need that might block at dispatch time is not
114
+ * a need the agent covers (A11), and an uncovered need only makes a candidate ineligible, never worse.
115
+ *
116
+ * A11: the needs covered by an agent's EVALUATED tool set. `network` means going through a shell command
117
+ * (1.2 `NEEDS`), so it follows `shell`; `external_dir` is the host `external_directory` permission
118
+ * evaluated to allow. Unique, in `NEEDS` order.
119
+ */
120
+ export function grantsFromTools(tools: readonly string[], externalDirectory: boolean): Need[] {
121
+ const have = new Set(tools.map((tool) => tool.toLowerCase()));
122
+ const has = (ids: readonly string[]): boolean => ids.some((id) => have.has(id));
123
+ const granted = new Set<Need>();
124
+ if (has(SHELL_TOOLS)) {
125
+ granted.add("shell");
126
+ granted.add("network");
127
+ }
128
+ if (has(WEB_TOOLS)) granted.add("web");
129
+ if (has(EDIT_TOOLS)) granted.add("edit");
130
+ if (externalDirectory) granted.add("external_dir");
131
+ return NEEDS.filter((need) => granted.has(need));
132
+ }
133
+
134
+ // ---------------------------------------------------------------------------
135
+ // Successor pointers (D8, A17a reduced to a static pointer)
136
+ // ---------------------------------------------------------------------------
137
+
138
+ /** A20 / QA-1.5-18: a tier with `effort`/`thinking`/`reasoning` set is never covered and never a coverage source. */
139
+ function effortConfigured(cfg: RouterConfig, tier: string): boolean {
140
+ const config = tierConfigOf(cfg, tier);
141
+ return config !== undefined && (config.effort !== undefined || config.thinking !== undefined || config.reasoning !== undefined);
142
+ }
143
+
144
+ /** `r` adds nothing after `k` was tried: same model, neither tier effort-configured, variant covered. */
145
+ function skippedAfter(cfg: RouterConfig, k: Candidate, r: Candidate): boolean {
146
+ if (r.model !== k.model) return false;
147
+ if (effortConfigured(cfg, k.tier) || effortConfigured(cfg, r.tier)) return false;
148
+ return variantCovered(r.variant ?? "default", k.variant ?? "default");
149
+ }
150
+
151
+ /**
152
+ * First rung of `following` (already in walk order) that is not covered by `k`, as an index into
153
+ * `all`; `null` when none is left (give up).
154
+ */
155
+ function firstUncovered(
156
+ cfg: RouterConfig,
157
+ k: Candidate,
158
+ following: readonly number[],
159
+ all: readonly Candidate[],
160
+ skipCovered = true,
161
+ ): number | null {
162
+ for (const j of following) {
163
+ if (!skipCovered || !skippedAfter(cfg, k, all[j]!)) return j;
164
+ }
165
+ return null;
166
+ }
167
+
168
+ // ---------------------------------------------------------------------------
169
+ // buildLadder
170
+ // ---------------------------------------------------------------------------
171
+
172
+ export interface LadderBuildInput {
173
+ readonly cfg: RouterConfig;
174
+ readonly routing: Pick<ResolvedRouting, "roles">;
175
+ readonly facts: Pick<TaskFacts, "class" | "needs">;
176
+ /** Router tier agents included. null = unavailable: router grants null, no role candidates. */
177
+ readonly agents: readonly HostAgentInfo[] | null;
178
+ /** Catalog pricing of "provider/model"; a throwing lookup prices as unpriced (QA-1.4-10, A1). */
179
+ readonly pricing?: (model: string) => ModelPricing;
180
+ /** The orchestrator's model: the model of a role agent that has none configured (QA-1.4-4). */
181
+ readonly parentModel?: string | null;
182
+ /** Receives one line per failed pricing lookup; its own failures are swallowed. */
183
+ readonly logger?: { warn(message: string): void };
184
+ /**
185
+ * The input the 1.5 runner's policy is built with (`buildEscalatePolicy(cfg, session)`: host, catalog,
186
+ * `variantSteps`, `maxContextFraction`). Absent = no variant steps, as on v1 or without a catalog (A25).
187
+ */
188
+ readonly session?: LadderSessionPolicyInput;
189
+ }
190
+
191
+ function normalizedVariant(variant: string | null | undefined): string | null {
192
+ return variant === undefined || variant === null || variant === "" ? null : variant;
193
+ }
194
+
195
+ function sameRung(a: { readonly model: string; readonly variant: string | null }, b: { readonly model: string; readonly variant: string | null }): boolean {
196
+ return a.model === b.model && normalizeVariant(a.variant) === normalizeVariant(b.variant);
197
+ }
198
+
199
+ /** Never throws: logging failures are reported through the return value, not raised (QA-1.4-10). */
200
+ function tryWarn(logger: LadderBuildInput["logger"], message: string): boolean {
201
+ if (logger === undefined) return false;
202
+ try {
203
+ logger.warn(message);
204
+ return true;
205
+ } catch {
206
+ return false; // a broken logger must not break the decision
207
+ }
208
+ }
209
+
210
+ /** QA-1.4-10: the catalog lookup is the caller's code; a failure makes the model unpriced (A1), never a throw. */
211
+ function priced(input: Pick<LadderBuildInput, "pricing" | "logger">, model: string): { readonly pricing?: ModelPricing } {
212
+ if (input.pricing === undefined) return {};
213
+ try {
214
+ return { pricing: input.pricing(model) };
215
+ } catch (error) {
216
+ const reason = error instanceof Error ? error.message : String(error);
217
+ tryWarn(input.logger, `[router] ladder: pricing lookup for ${model} failed (${reason}); treating it as unpriced`);
218
+ return {};
219
+ }
220
+ }
221
+
222
+ function ownRoles(roles: Readonly<Record<string, readonly string[]>>, cls: string): readonly string[] {
223
+ const list = Object.hasOwn(roles, cls) ? roles[cls] : undefined;
224
+ return Array.isArray(list) ? [...new Set(list)] : [];
225
+ }
226
+
227
+ /** A host agent unusable as a dispatch target: `mode: primary`, hidden or not permitted for the parent. */
228
+ function agentUnavailable(info: HostAgentInfo): boolean {
229
+ return info.mode === "primary" || info.hidden || !info.permitted;
230
+ }
231
+
232
+ /**
233
+ * Why a `routing.roles` agent cannot be a candidate at the agent level (D12, QA-1.1-18/29): it names a
234
+ * router tier of the active preset (`duplicate`), or it is reserved, absent from the host agent list,
235
+ * `mode: primary`, hidden or not permitted for the parent (`agent-unavailable`). The class-level check
236
+ * (`no-owning-tier`) and the A11 `needs` check are separate; `null` = usable.
237
+ */
238
+ export function roleAgentExclusion(
239
+ id: string,
240
+ info: HostAgentInfo | undefined,
241
+ routerIds: readonly string[],
242
+ ): "duplicate" | "agent-unavailable" | null {
243
+ if (routerIds.includes(id)) return "duplicate";
244
+ if ((ROUTING_RESERVED_AGENTS as readonly string[]).includes(id)) return "agent-unavailable";
245
+ if (info === undefined || agentUnavailable(info)) return "agent-unavailable";
246
+ return null;
247
+ }
248
+
249
+ /** The model a host agent runs on: its configured one, else the parent's (host precedence, QA-1.4-4). */
250
+ function modelOfAgent(info: HostAgentInfo, parentModel: string | null | undefined): string | null {
251
+ return nonEmpty(info.model) ?? nonEmpty(parentModel);
252
+ }
253
+
254
+ /** The base rung of a tier: its own model, variant and ratio (the rung `resolveCandidates` lists for it). */
255
+ function tierBaseRung(cfg: RouterConfig, tier: string): RunnerRung | undefined {
256
+ const config = tierConfigOf(cfg, tier);
257
+ if (config === undefined || typeof config.model !== "string") return undefined;
258
+ const variant = normalizedVariant(config.variant);
259
+ const rungs = resolveCandidates(tier, cfg);
260
+ const own = rungs.find((rung) => sameRung({ model: rung.model, variant: normalizedVariant(rung.variant) }, { model: config.model, variant }));
261
+ const costRatio = (own ?? rungs[0])?.costRatio;
262
+ return costRatio === undefined ? undefined : { tier, model: config.model, variant, costRatio };
263
+ }
264
+
265
+ /**
266
+ * A25: the rungs of a tier the 1.5 runner can walk — the ones on the tier's own model. A `candidates` rung on
267
+ * another model is escalation territory: the runner never runs it, so it is not modelled (`dropped`).
268
+ */
269
+ function modelledRungs(cfg: RouterConfig, tier: string): { readonly kept: readonly ResolvedCandidate[]; readonly dropped: readonly ResolvedCandidate[] } {
270
+ const model = tierConfigOf(cfg, tier)?.model;
271
+ const rungs = resolveCandidates(tier, cfg);
272
+ if (typeof model !== "string") return { kept: rungs, dropped: [] };
273
+ return { kept: rungs.filter((rung) => rung.model === model), dropped: rungs.filter((rung) => rung.model !== model) };
274
+ }
275
+
276
+ /**
277
+ * Build the candidate graph of one decision (§3): the router rungs of the escalate ladder, then the role
278
+ * agents of `facts.class` (D12) with their own-model rung and the owning tier's rungs.
279
+ *
280
+ * Router rungs (A25): every rung on the tier's own model; each carries the attempts the 1.5 runner makes
281
+ * from it — `Ladder.paths`, simulated with `buildEscalatePolicy(cfg, session)` and `nextAction`/`advance` —
282
+ * so the kernel prices retries, `maxTotalAttempts`, the cost ceiling and covered-tier skips as the runner
283
+ * performs them. Rungs only the runner reaches (variant steps) are `Ladder.reachable`, never `best`.
284
+ * `session` is the same input the runner's policy is built with (host, catalog, `variantSteps`); without it
285
+ * the policy has no variant steps, exactly as the runner would behave.
286
+ *
287
+ * Own-model rung of a role agent (D7, A25): when its `(model, variant)` matches a rung of the preset it takes
288
+ * that rung's price AND `min(owningRank, matched.rank)` (an agent on the fast tier's model is a fast-ranked
289
+ * candidate, whatever class it serves); the inherited rank of the owning tier applies only when no rung
290
+ * matches. An agent without a configured model runs on the parent's model and gets its own-model rung there.
291
+ * A role chain is a static successor chain (own model, the owning tier's rungs, then the first router rung of
292
+ * the next tier above, entered as a fresh dispatch).
293
+ *
294
+ * Router rungs of a tier whose agent is `mode: primary`, hidden or not permitted are excluded
295
+ * (`agent-unavailable`): they can never be `best` (a simulated path may still pass through them).
296
+ *
297
+ * Never throws for well-typed input; an unknown preset or a ladder with no resolvable tier yields an empty
298
+ * ladder (the kernel then reports `kept:no-candidates`).
299
+ */
300
+ export function buildLadder(input: LadderBuildInput): Ladder {
301
+ const { cfg, facts, agents } = input;
302
+ const policy: EscalatePolicy = buildEscalatePolicy(cfg, input.session);
303
+ const order = ladderOf(cfg, policy.ladder);
304
+ const rankOf = (tier: string | null | undefined): number | null => {
305
+ const rank = typeof tier === "string" ? order.indexOf(tier) : -1;
306
+ return rank >= 0 ? rank : null;
307
+ };
308
+ const routerIds = routerTierIds(cfg);
309
+ const owningTier = Object.hasOwn(CLASS_STATIC_TIER, facts.class) ? CLASS_STATIC_TIER[facts.class] : null;
310
+ const owningRank = rankOf(owningTier);
311
+ const excluded: ExcludedCandidate[] = [];
312
+ const excludedOf = (id: string, why: ExclusionReason, info: HostAgentInfo | undefined): void => {
313
+ const ref = typeof info?.model === "string" ? splitModelRef(info.model) : null;
314
+ excluded.push({
315
+ agent: { origin: classifyAgentOrigin(id, routerIds), id },
316
+ model: ref === null ? (info?.model ?? "") : `${ref.provider}/${ref.model}`,
317
+ variant: ref?.variant ?? null,
318
+ why,
319
+ });
320
+ };
321
+
322
+ // --- router block --------------------------------------------------------------------------------
323
+ /** Every rung of the preset, modelled or not, available or not: the price/rank table of own-model rungs. */
324
+ const presetRungs: Candidate[] = [];
325
+ const candidates: Candidate[] = [];
326
+ const next: (number | null)[] = [];
327
+ order.forEach((tier, rank) => {
328
+ const info = agents?.find((agent) => agent.id === tier);
329
+ const unavailable = info !== undefined && agentUnavailable(info);
330
+ const grants = info?.grants ?? null;
331
+ const { kept, dropped } = modelledRungs(cfg, tier);
332
+ const routerRung = (rung: ResolvedCandidate): Candidate => ({
333
+ agent: { origin: "router", id: tier },
334
+ model: rung.model,
335
+ variant: normalizedVariant(rung.variant),
336
+ costRatio: rung.costRatio,
337
+ rank,
338
+ tier,
339
+ source: "tier",
340
+ grants,
341
+ ...priced(input, rung.model),
342
+ });
343
+ for (const rung of dropped) {
344
+ const candidate = routerRung(rung);
345
+ presetRungs.push(candidate);
346
+ excluded.push({ agent: candidate.agent, model: candidate.model, variant: candidate.variant, why: "not-modelled" });
347
+ }
348
+ for (const rung of kept) {
349
+ const candidate = routerRung(rung);
350
+ presetRungs.push(candidate);
351
+ if (unavailable) {
352
+ excluded.push({ agent: candidate.agent, model: candidate.model, variant: candidate.variant, why: "agent-unavailable" });
353
+ } else {
354
+ candidates.push(candidate);
355
+ }
356
+ }
357
+ });
358
+ const routerCount = candidates.length;
359
+ for (let k = 0; k < routerCount; k++) next.push(null); // router rungs are priced through `paths` (below)
360
+
361
+ // --- role chains ---------------------------------------------------------------------------------
362
+ const indexes = (from: number, to: number): number[] => {
363
+ const out: number[] = [];
364
+ for (let i = from; i < to; i++) out.push(i);
365
+ return out;
366
+ };
367
+ const roleIds = ownRoles(input.routing.roles, facts.class);
368
+ /** Role chains laid out so far, and the in-chain successor of each of their rungs (QA-1.4-16). */
369
+ const roleChains: { readonly start: number; readonly length: number; readonly tier: string }[] = [];
370
+ const chainNext = new Map<number, number | null>();
371
+ const tierRungs = owningTier !== null && owningRank !== null ? modelledRungs(cfg, owningTier).kept : [];
372
+ const firstTierRung = tierRungs[0];
373
+ for (const id of roleIds) {
374
+ const info = agents?.find((agent) => agent.id === id);
375
+ if (owningTier === null || owningRank === null || firstTierRung === undefined) {
376
+ excludedOf(id, "no-owning-tier", info);
377
+ continue;
378
+ }
379
+ const unusable = roleAgentExclusion(id, info, routerIds);
380
+ if (unusable !== null || info === undefined) {
381
+ excludedOf(id, unusable ?? "agent-unavailable", info);
382
+ continue;
383
+ }
384
+ if (!coversNeeds(info.grants, facts.needs)) {
385
+ excludedOf(id, "needs", info);
386
+ continue;
387
+ }
388
+
389
+ const agent: AgentRef = { origin: "host", id };
390
+ const chainStart = candidates.length;
391
+ const chain: Candidate[] = [];
392
+ let own: Candidate | null = null;
393
+ const modelRef = modelOfAgent(info, input.parentModel);
394
+ const ref = modelRef === null ? null : splitModelRef(modelRef);
395
+ if (ref !== null) {
396
+ const model = `${ref.provider}/${ref.model}`;
397
+ const matched = presetRungs.find((rung) => sameRung(rung, { model, variant: ref.variant }));
398
+ // A25: price and rank come from the matching preset rung; the owning tier's rank only caps it. The cap is for the CANDIDATE
399
+ // only: when this agent is the pick, never-down compares against its capability rank (`kernel.capabilityRank`, A34).
400
+ const lowered = matched !== undefined && matched.rank < owningRank;
401
+ own = {
402
+ agent,
403
+ model,
404
+ variant: ref.variant,
405
+ costRatio: matched?.costRatio ?? firstTierRung.costRatio,
406
+ rank: lowered ? matched.rank : owningRank,
407
+ tier: lowered ? matched.tier : owningTier,
408
+ source: "role-own-model",
409
+ grants: info.grants,
410
+ ...priced(input, model),
411
+ };
412
+ chain.push(own);
413
+ }
414
+ for (const rung of tierRungs) {
415
+ const candidate: Candidate = {
416
+ agent,
417
+ model: rung.model,
418
+ variant: normalizedVariant(rung.variant),
419
+ costRatio: rung.costRatio,
420
+ rank: owningRank,
421
+ tier: owningTier,
422
+ source: "role-tier-rung",
423
+ grants: info.grants,
424
+ ...priced(input, rung.model),
425
+ };
426
+ if (own !== null && sameRung(own, candidate)) {
427
+ excludedOf(id, "duplicate", info);
428
+ continue;
429
+ }
430
+ chain.push(candidate);
431
+ }
432
+
433
+ // After the chain, the cascade continues with the router rungs of the tiers above the owning tier; like
434
+ // the runner, coverage skips apply there only when the policy has variant info.
435
+ const above: number[] = [];
436
+ for (let j = 0; j < routerCount; j++) if (candidates[j]!.rank > owningRank) above.push(j);
437
+ candidates.push(...chain);
438
+ for (let position = 0; position < chain.length; position++) {
439
+ const k = candidates[chainStart + position]!;
440
+ const inChain = firstUncovered(cfg, k, indexes(chainStart + position + 1, chainStart + chain.length), candidates);
441
+ chainNext.set(chainStart + position, inChain);
442
+ next.push(inChain ?? firstUncovered(cfg, k, above, candidates, policy.variants != null));
443
+ }
444
+ roleChains.push({ start: chainStart, length: chain.length, tier: owningTier });
445
+ }
446
+
447
+ // --- simulated runner paths (A25) --------------------------------------------------------------------
448
+ const reachable: Candidate[] = [];
449
+ const paths: (number[] | null)[] = candidates.map(() => null);
450
+ const tierBase = (tier: string): RunnerRung | undefined => tierBaseRung(cfg, tier);
451
+ const indexOfRung = (rung: RunnerRung): number | null => {
452
+ const same = (c: Candidate): boolean => c.tier === rung.tier && c.agent.origin === "router" && sameRung(c, rung);
453
+ for (let j = 0; j < routerCount; j++) if (same(candidates[j]!)) return j;
454
+ const known = reachable.findIndex(same);
455
+ if (known >= 0) return candidates.length + known;
456
+ const rank = rankOf(rung.tier);
457
+ if (rank === null) return null;
458
+ reachable.push({
459
+ agent: { origin: "router", id: rung.tier },
460
+ model: rung.model,
461
+ variant: rung.variant,
462
+ costRatio: rung.costRatio,
463
+ rank,
464
+ tier: rung.tier,
465
+ source: "tier",
466
+ grants: agents?.find((agent) => agent.id === rung.tier)?.grants ?? null,
467
+ ...priced(input, rung.model),
468
+ });
469
+ return candidates.length + reachable.length - 1;
470
+ };
471
+ for (let k = 0; k < routerCount; k++) {
472
+ const start = candidates[k]!;
473
+ const attempts = simulateRunner(policy, tierBase, {
474
+ tier: start.tier,
475
+ model: start.model,
476
+ variant: start.variant,
477
+ costRatio: start.costRatio,
478
+ });
479
+ const path: number[] = [];
480
+ for (const attempt of attempts) {
481
+ const j = indexOfRung(attempt);
482
+ if (j === null) break;
483
+ path.push(j);
484
+ }
485
+ // A router rung is priced through its path; its `next` stays null (a path is not a pointer chain).
486
+ paths[k] = path.length > 0 ? path : null;
487
+ }
488
+ // A role rung's path: the rest of its chain (the same coverage-skipping walk as `next` inside the chain),
489
+ // then the runner continuing the SAME delegation from the tier that owns the class, with the chain's attempts
490
+ // and cost already spent (QA-1.4-16), so a native agent's cascade is not given a fresh budget.
491
+ for (const chain of roleChains) {
492
+ for (let at = chain.start; at < chain.start + chain.length; at++) {
493
+ const members: number[] = [];
494
+ for (let m: number | null = at; m !== null && !members.includes(m); m = chainNext.get(m) ?? null) members.push(m);
495
+ const spent: RunnerRung[] = members.map((m) => {
496
+ const c = candidates[m]!;
497
+ return { tier: chain.tier, model: c.model, variant: c.variant, costRatio: c.costRatio };
498
+ });
499
+ const path = [...members];
500
+ for (const attempt of simulateAfter(policy, tierBase, { tier: chain.tier, attempts: spent })) {
501
+ const j = indexOfRung(attempt);
502
+ if (j === null) break;
503
+ path.push(j);
504
+ }
505
+ paths[at] = path;
506
+ }
507
+ }
508
+
509
+ return {
510
+ candidates,
511
+ next,
512
+ classRank: owningRank,
513
+ excluded,
514
+ ...(reachable.length > 0 ? { reachable } : {}),
515
+ paths,
516
+ // 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.
517
+ presetRungs: presetRungs.map((rung) => ({ model: rung.model, variant: rung.variant, rank: rung.rank })),
518
+ };
519
+ }
520
+
521
+ // ---------------------------------------------------------------------------
522
+ // Role ladders (role-tier-assurance plan §2.1, §2.3, P1.2 T1.2.3)
523
+ // ---------------------------------------------------------------------------
524
+
525
+ export interface RoleLadderInput {
526
+ readonly cfg: RouterConfig;
527
+ readonly facts: Pick<TaskFacts, "class" | "needs">;
528
+ /** The role agent (outcome-key origin `role`). */
529
+ readonly role: string;
530
+ /** `roles/policy.tierBounds(...)` computed with `tiers: escalateLadder(cfg)`. */
531
+ readonly window: RoleWindow;
532
+ /** The class's taxonomy tier; absent = `CLASS_STATIC_TIER[facts.class]` (`null` → the window floor). */
533
+ readonly classTier?: string | null;
534
+ readonly pricing?: (model: string) => ModelPricing;
535
+ readonly logger?: { warn(message: string): void };
536
+ /** The input the runner's policy is built with (same meaning as {@link LadderBuildInput.session}). */
537
+ readonly session?: LadderSessionPolicyInput;
538
+ }
539
+
540
+ interface WindowSpan {
541
+ readonly floor: number;
542
+ readonly ceiling: number;
543
+ readonly reasons: readonly string[];
544
+ }
545
+
546
+ /**
547
+ * The window on the escalate ladder `order`. Fail closed: a floor off the ladder places nothing (`null`, no candidate);
548
+ * a ceiling off the ladder or below the floor collapses to the floor (the narrowest window that keeps the floor).
549
+ */
550
+ function windowSpan(order: readonly string[], window: Pick<RoleWindow, "floor" | "ceiling">): WindowSpan | null {
551
+ const floor = order.indexOf(window.floor);
552
+ if (floor < 0) return null;
553
+ const ceiling = order.indexOf(window.ceiling);
554
+ if (ceiling < 0) return { floor, ceiling: floor, reasons: [`window:ceiling-off-ladder:${window.ceiling}`] };
555
+ if (ceiling < floor) return { floor, ceiling: floor, reasons: ["window:ceiling-below-floor"] };
556
+ return { floor, ceiling, reasons: [] };
557
+ }
558
+
559
+ /**
560
+ * The tier order of every role dispatch (QA-P12-1-5, plan R7): `presetTierOrder` of the active preset (cheapest to
561
+ * dearest by `costRatio`, else listing order — the order role tier ranges are placed on), restricted to tiers with at
562
+ * least one rung. Pass it as `tierBounds(..., { tiers })` AND build the
563
+ * ladder with the same `cfg`/`session` ({@link buildRoleLadder}, {@link roleEscalatePolicy} use it), so the window and
564
+ * the ladder can never disagree on tier names.
565
+ */
566
+ export function roleTierOrder(cfg: RouterConfig, _session?: LadderSessionPolicyInput): readonly string[] {
567
+ // One tier order for role ranges (`router/roles.ts`) and role ladders: the active preset's cost order. The only
568
+ // narrowing is the one every ladder applies: tiers without a rung are left out. The session never changes tiers.
569
+ return ladderOf(cfg, presetTierOrder(resolveActiveTiers(cfg)));
570
+ }
571
+
572
+ /**
573
+ * The escalation policy of a role dispatch, as the runtime escalates one (QA-G-B-6): after a verification FAIL the router raises
574
+ * the child to the NEXT tier of the role's range on its next resume (`roleEscalationAfterFail` / `nextRoleTier`, dispatch.ts) —
575
+ * one tier per FAIL, never a retry on the same tier, no variant step, no effort bump, no attempt or cost ceiling — and nothing
576
+ * above the ceiling. So: the ladder = the tiers of `[floor, ceiling]` on {@link roleTierOrder}, `floorTier` = the window floor
577
+ * (the runner never starts below the floor nor escalates above the ceiling, I2), `maxAttemptsPerTier` 0, `maxTotalAttempts` =
578
+ * one attempt per tier of the window, no `costMultiple`, `effortBump` or `variants`. {@link buildRoleLadder}'s simulated paths
579
+ * price role candidates with this one policy, so they price exactly the raise path the runtime takes (one attempt on each tier
580
+ * from the start tier up to the ceiling, each on the tier's base rung). `null` when the floor is not on the order: P2.1 then
581
+ * refuses the role dispatch — it never falls back to the unrestricted `buildEscalatePolicy`. (`session` only names the tier
582
+ * order's input; the session's variant steps never apply to a role dispatch.)
583
+ */
584
+ export function roleEscalatePolicy(
585
+ cfg: RouterConfig,
586
+ window: Pick<RoleWindow, "floor" | "ceiling">,
587
+ session?: LadderSessionPolicyInput,
588
+ ): EscalatePolicy | null {
589
+ const order = roleTierOrder(cfg, session);
590
+ const span = windowSpan(order, window);
591
+ if (span === null) return null;
592
+ const ladder = order.slice(span.floor, span.ceiling + 1);
593
+ return { ladder, floorTier: order[span.floor]!, maxAttemptsPerTier: 0, maxTotalAttempts: ladder.length, costMultiple: null };
594
+ }
595
+
596
+ /**
597
+ * Build the candidate graph of a role dispatch (T1.2.3).
598
+ *
599
+ * - Candidates: for every tier of the escalate ladder in `[floor, ceiling]` (tier order, then rung order), the rungs on
600
+ * the tier's own model (A25; other-model rungs are `not-modelled`), each run by the role agent (`origin: "role"`) at
601
+ * the tier's rank. A `model#variant` already listed on a lower tier is the same outcome key: kept once (`duplicate`).
602
+ * - Grants: every rung runs the same agent under the same dispatch grant, so `grants` = `facts.needs` (needs a grant
603
+ * cannot cover are reported by `grantFor` notes, not by the kernel's per-rung `needs` filter).
604
+ * - Paths: the attempts the runner makes under {@link roleEscalatePolicy} (`simulateRunner`), as indices into
605
+ * `[...candidates, ...reachable]`.
606
+ * - Static default: the class's taxonomy tier clamped into the window (`default:clamp:floor|ceiling`); no class tier or
607
+ * one off the ladder → the floor. Pin: `window.pinned` (re-clamped defensively, `pin:clamp`), reason `pinned:<tier>`.
608
+ *
609
+ * Never throws for well-typed input; a window that cannot be placed yields an empty ladder (`window:floor-off-ladder`).
610
+ */
611
+ export function buildRoleLadder(input: RoleLadderInput): RoleLadder {
612
+ const { cfg, facts, role } = input;
613
+ const order = roleTierOrder(cfg, input.session);
614
+ const agent: AgentRef = { origin: "role", id: role };
615
+ const grants: readonly Need[] = [...facts.needs];
616
+ const classTier = input.classTier !== undefined
617
+ ? input.classTier
618
+ : (Object.hasOwn(CLASS_STATIC_TIER, facts.class) ? CLASS_STATIC_TIER[facts.class] : null);
619
+ const classAt = typeof classTier === "string" ? order.indexOf(classTier) : -1;
620
+ const classRank = classAt >= 0 ? classAt : null;
621
+ const presetRungs: PresetRung[] = [];
622
+ order.forEach((tier, rank) => {
623
+ for (const rung of resolveCandidates(tier, cfg)) presetRungs.push({ model: rung.model, variant: normalizedVariant(rung.variant), rank });
624
+ });
625
+
626
+ const span = windowSpan(order, input.window);
627
+ // QA-P12-1-7: the one source of the window's policy (the same call the role runner makes).
628
+ const rolePolicy = roleEscalatePolicy(cfg, input.window, input.session);
629
+ if (span === null || rolePolicy === null) {
630
+ return {
631
+ role,
632
+ candidates: [],
633
+ next: [],
634
+ classRank,
635
+ excluded: [],
636
+ paths: [],
637
+ presetRungs,
638
+ floorRank: null,
639
+ ceilingRank: null,
640
+ tiers: [],
641
+ staticDefault: null,
642
+ pinnedIndex: null,
643
+ reasons: [`window:floor-off-ladder:${input.window.floor}`, "window:no-candidates"],
644
+ };
645
+ }
646
+
647
+ // --- candidates: the window's tiers, cheapest first --------------------------------------------------
648
+ const candidates: Candidate[] = [];
649
+ const excluded: ExcludedCandidate[] = [];
650
+ const tiers: RoleLadderTier[] = [];
651
+ const roleRung = (rung: { readonly model: string; readonly variant: string | null; readonly costRatio: number }, tier: string, rank: number): Candidate => ({
652
+ agent,
653
+ model: rung.model,
654
+ variant: normalizedVariant(rung.variant),
655
+ costRatio: rung.costRatio,
656
+ rank,
657
+ tier,
658
+ source: "role-range",
659
+ grants,
660
+ ...priced(input, rung.model),
661
+ });
662
+ for (let rank = span.floor; rank <= span.ceiling; rank++) {
663
+ const tier = order[rank]!;
664
+ const { kept, dropped } = modelledRungs(cfg, tier);
665
+ for (const rung of dropped) excluded.push({ agent, model: rung.model, variant: normalizedVariant(rung.variant), why: "not-modelled" });
666
+ let first: number | null = null;
667
+ for (const rung of kept) {
668
+ const candidate = roleRung({ model: rung.model, variant: normalizedVariant(rung.variant), costRatio: rung.costRatio }, tier, rank);
669
+ if (candidates.some((c) => sameRung(c, candidate))) {
670
+ excluded.push({ agent, model: candidate.model, variant: candidate.variant, why: "duplicate" });
671
+ continue;
672
+ }
673
+ first ??= candidates.length;
674
+ candidates.push(candidate);
675
+ }
676
+ tiers.push({ tier, rank, first });
677
+ }
678
+
679
+ // --- simulated runner paths under the window's policy ----------------------------------------------------
680
+ const reachable: Candidate[] = [];
681
+ const indexOfRung = (rung: RunnerRung): number | null => {
682
+ const same = (c: Candidate): boolean => c.tier === rung.tier && sameRung(c, rung);
683
+ const at = candidates.findIndex(same);
684
+ if (at >= 0) return at;
685
+ const known = reachable.findIndex(same);
686
+ if (known >= 0) return candidates.length + known;
687
+ const rank = order.indexOf(rung.tier);
688
+ if (rank < span.floor || rank > span.ceiling) return null; // unreachable under the window policy; defensive
689
+ reachable.push(roleRung(rung, rung.tier, rank));
690
+ return candidates.length + reachable.length - 1;
691
+ };
692
+ const paths = candidates.map((start) => {
693
+ const path: number[] = [];
694
+ for (const attempt of simulateRunner(rolePolicy, (tier) => tierBaseRung(cfg, tier), start)) {
695
+ const j = indexOfRung(attempt);
696
+ if (j === null) break;
697
+ path.push(j);
698
+ }
699
+ return path.length > 0 ? path : null;
700
+ });
701
+
702
+ // --- static default and pin --------------------------------------------------------------------------------
703
+ const reasons: string[] = [...span.reasons];
704
+ if (candidates.length === 0) reasons.push("window:no-candidates");
705
+ /** First candidate of the first tier at or above `rank` that has one, else of the highest tier below it. */
706
+ const candidateAt = (rank: number): number | null => {
707
+ for (const t of tiers) if (t.rank >= rank && t.first !== null) return t.first;
708
+ for (let i = tiers.length - 1; i >= 0; i--) if (tiers[i]!.first !== null) return tiers[i]!.first;
709
+ return null;
710
+ };
711
+ let target = span.floor;
712
+ if (classRank === null) reasons.push(typeof classTier === "string" ? `default:off-ladder:${classTier}` : "default:no-class-tier");
713
+ else if (classRank < span.floor) reasons.push("default:clamp:floor");
714
+ else if (classRank > span.ceiling) {
715
+ target = span.ceiling;
716
+ reasons.push("default:clamp:ceiling");
717
+ } else target = classRank;
718
+ const staticDefault = candidateAt(target);
719
+
720
+ let pinnedIndex: number | null = null;
721
+ const pin = input.window.pinned;
722
+ if (pin !== null) {
723
+ const at = order.indexOf(pin);
724
+ if (at < 0) reasons.push(`pin:off-ladder:${pin}`);
725
+ else {
726
+ const clamped = Math.min(Math.max(at, span.floor), span.ceiling);
727
+ if (clamped !== at) reasons.push("pin:clamp");
728
+ pinnedIndex = candidateAt(clamped);
729
+ if (pinnedIndex !== null) {
730
+ // QA-P12-1-8: say so when the dispatched rung is not on the requested tier (clamped, or a duplicate rung).
731
+ const got = candidates[pinnedIndex]!.tier;
732
+ reasons.push(got === pin ? `pinned:${pin}` : `pinned:${pin}->${got}`);
733
+ }
734
+ }
735
+ }
736
+
737
+ return {
738
+ role,
739
+ candidates,
740
+ next: candidates.map(() => null),
741
+ classRank,
742
+ excluded,
743
+ ...(reachable.length > 0 ? { reachable } : {}),
744
+ paths,
745
+ presetRungs,
746
+ floorRank: span.floor,
747
+ ceilingRank: span.ceiling,
748
+ tiers,
749
+ staticDefault,
750
+ pinnedIndex,
751
+ reasons,
752
+ };
753
+ }
754
+
755
+ // ---------------------------------------------------------------------------
756
+ // resolveChosen
757
+ // ---------------------------------------------------------------------------
758
+
759
+ export interface ChosenInput {
760
+ readonly cfg: RouterConfig;
761
+ readonly agents: readonly HostAgentInfo[] | null;
762
+ /** `event.input.agent`. */
763
+ readonly agent: string;
764
+ /** `event.input.model`, when the call set one. */
765
+ readonly model?: string | null;
766
+ readonly parentModel?: string | null;
767
+ }
768
+
769
+ function nonEmpty(value: string | null | undefined): string | null {
770
+ return typeof value === "string" && value.trim() !== "" ? value.trim() : null;
771
+ }
772
+
773
+ function splitRef(ref: string): { readonly model: string; readonly variant: string | null } {
774
+ const parts = splitModelRef(ref);
775
+ if (parts !== null) return { model: `${parts.provider}/${parts.model}`, variant: parts.variant };
776
+ const hash = ref.lastIndexOf("#");
777
+ if (hash > 0) return { model: ref.slice(0, hash), variant: normalizedVariant(ref.slice(hash + 1)) };
778
+ return { model: ref, variant: null };
779
+ }
780
+
781
+ /**
782
+ * The orchestrator's pick as the kernel's {@link ChosenDispatch}: a router tier agent resolves to the call's
783
+ * `model` or the tier's own base rung; a host agent to the call's `model`, its configured model or the
784
+ * parent's. `null` when nothing resolves (the caller then logs a kept row without calling `decide`).
785
+ */
786
+ export function resolveChosen(input: ChosenInput): ChosenDispatch | null {
787
+ const { cfg, agent } = input;
788
+ if (typeof agent !== "string" || agent === "") return null;
789
+ const origin = classifyAgentOrigin(agent, routerTierIds(cfg));
790
+ const callModel = nonEmpty(input.model);
791
+ if (origin === "router") {
792
+ const tier = tierConfigOf(cfg, agent);
793
+ if (callModel !== null) return { agent: { origin, id: agent }, ...splitRef(callModel) };
794
+ if (tier === undefined) return null;
795
+ const base = splitRef(tier.model);
796
+ return { agent: { origin, id: agent }, model: base.model, variant: normalizedVariant(tier.variant) ?? base.variant };
797
+ }
798
+ const info = input.agents?.find((candidate) => candidate.id === agent);
799
+ const ref = callModel ?? nonEmpty(info?.model) ?? nonEmpty(input.parentModel);
800
+ if (ref === null) return null;
801
+ return { agent: { origin, id: agent }, ...splitRef(ref) };
802
+ }