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,222 @@
1
+ /**
2
+ * Context-hook side of the engine (M7, Phase 2.2.1): the generated `R:` line and the per-turn hint.
3
+ *
4
+ * `static` and `shadow` leave the system prompt byte-identical (the snapshots pin it). `advise` and `enforce`:
5
+ * - swap the taxonomy line of the delegation protocol for `generateTaxonomy(...)` (a class moves only when the winner
6
+ * has ≥ 5 recorded outcomes, so the line stays the shipped one until evidence exists, D2), and append the route-line
7
+ * paragraph of `protocol.ts`;
8
+ * - in advise only, add one extra system part, the per-turn hint: stable class and destination text, computed from the
9
+ * latest user message with the RULES classifier only (a hint never costs a model call) and cached for the turn, so the
10
+ * system prompt does not change between the steps of one turn.
11
+ *
12
+ * The hint and the generated `R:` line come from the same kernel, but the hint is only emitted when the kernel says
13
+ * `switched` for the class's static tier, i.e. when it agrees with a move the line itself could make (QA focus: a hint
14
+ * must never contradict the `R:` line). Errors are logged and the system prompt stays as the legacy hook built it.
15
+ *
16
+ * Roles mode (`routing.delegation: "roles"`, plan #84 T2.2.1): nothing is added or rewritten — no per-turn hint, no tier
17
+ * `R:` line, no route-line paragraph. The roles protocol carries its own class → role line and route-line keys, and a
18
+ * hint or a tier line would name tiers; a system part that changes per turn would also cost the orchestrator its
19
+ * prompt cache. The check is the roles protocol's heading among the router's own parts, i.e. the text the orchestrator
20
+ * actually carries: a roles config with no enabled role falls back to the tiers protocol, augmented as in tiers mode.
21
+ */
22
+
23
+ import {
24
+ DELEGATION_PROTOCOL_HEADING,
25
+ ROLES_PROTOCOL_HEADING,
26
+ buildRouteLineProtocol,
27
+ swapTaxonomyLine,
28
+ } from "../../router/protocol";
29
+ /** The roles heading only counts at the start of a line (QA-P22-2-4): a part that merely quotes it mid-line is not the roles protocol. */
30
+ const ROLES_HEADING_LINE = /^## Role Delegation Protocol \(MANDATORY\)$/m;
31
+
32
+ import { classify } from "../classify";
33
+ import { CLASS_STATIC_TIER, type TaskFacts } from "../classify/types";
34
+ import { buildLadder, decide, floorRankOf, generateTaxonomy, resolveChosen } from "../engine";
35
+ import { detectionOf, weakerDetection } from "../engine/plan";
36
+ import type { Decision, HostAgentInfo } from "../engine/types";
37
+ import type { AgentView } from "./host-info";
38
+ import { sessionRulesOf, type EngineRuntime, type Prepared, type WireLogger } from "./runtime";
39
+
40
+ /** The generated line is recomputed at most this often (and whenever the config object changes). */
41
+ export const TAXONOMY_TTL_MS = 60_000;
42
+ const TAXONOMY_MEMO_LIMIT = 16;
43
+ /** The user text the hint classifies is cut to this many characters. */
44
+ export const HINT_MAX_USER_CHARS = 4_000;
45
+ const HINT_MEMO_LIMIT = 100;
46
+ const DESCRIPTION_MAX = 60;
47
+
48
+ function oneLine(text: string, max: number): string {
49
+ const collapsed = text.replace(/\s+/g, " ").trim();
50
+ return collapsed.length <= max ? collapsed : `${collapsed.slice(0, max - 1)}…`;
51
+ }
52
+
53
+ /**
54
+ * Stable one-line class/destination text for a decision that wants to leave the orchestrator's usual agent, or `null` when there is
55
+ * nothing to say: no switch, no target, a pinned decision, or a switch inside the same agent (a variant change of the pick
56
+ * says nothing the orchestrator can act on, QA-2.2-6).
57
+ */
58
+ export function buildHint(decision: Decision, facts: Pick<TaskFacts, "class">, descriptions: ReadonlyMap<string, string>): string | null {
59
+ const { target, best, chosen } = decision;
60
+ if (!decision.switched || decision.pinned || target === null || best === null) return null;
61
+ if (target.agent.id === chosen.agent) return null;
62
+ const described = descriptions.get(target.agent.id);
63
+ const destination = `@${target.agent.id}${described === undefined ? "" : ` (${oneLine(described, DESCRIPTION_MAX)})`}`;
64
+ return `Route hint: for ${facts.class} work like this turn, prefer ${destination}.`;
65
+ }
66
+
67
+ /** Text of the latest user message that is the user's own (not a synthetic `Instructions from:` attachment). */
68
+ export function latestUserText(messages: readonly unknown[] | undefined): string | null {
69
+ if (messages === undefined) return null;
70
+ for (let i = messages.length - 1; i >= 0; i--) {
71
+ const message = messages[i];
72
+ if (typeof message !== "object" || message === null || (message as { role?: unknown }).role !== "user") continue;
73
+ const content = (message as { content?: unknown }).content;
74
+ if (!Array.isArray(content)) continue;
75
+ const texts = content
76
+ .filter((part): part is { type: "text"; text: string } =>
77
+ typeof part === "object" && part !== null && (part as { type?: unknown }).type === "text" && typeof (part as { text?: unknown }).text === "string")
78
+ .map((part) => part.text)
79
+ .filter((text) => !/^Instructions from:/m.test(text));
80
+ if (texts.length > 0) return texts.join("\n").slice(0, HINT_MAX_USER_CHARS);
81
+ }
82
+ return null;
83
+ }
84
+
85
+ export interface ContextInput {
86
+ readonly sessionID: string;
87
+ readonly agent: string;
88
+ /** `provider/model` of the model about to answer (the orchestrator's). */
89
+ readonly parentModel: string | null;
90
+ readonly messages?: readonly unknown[];
91
+ /** The router config the hook already loaded. */
92
+ readonly cfg?: Prepared["cfg"];
93
+ }
94
+
95
+ export interface SystemAugmenter {
96
+ /**
97
+ * Called by the context hook after the legacy hook has pushed its text. Rewrites the protocol text in `system` in place
98
+ * and pushes the hint, registering both in `added` (the texts whose vocabulary the adapter translates). Never throws.
99
+ */
100
+ augment(input: ContextInput, system: string[], added: Set<string>): Promise<void>;
101
+ }
102
+
103
+ export interface SystemAugmenterDeps {
104
+ readonly runtime: EngineRuntime;
105
+ readonly getSession: (sessionID: string) => Promise<unknown>;
106
+ readonly logger: WireLogger;
107
+ readonly now?: () => number;
108
+ }
109
+
110
+ function describeError(error: unknown): string {
111
+ return error instanceof Error ? error.message : String(error);
112
+ }
113
+
114
+ export function createSystemAugmenter(deps: SystemAugmenterDeps): SystemAugmenter {
115
+ const now = deps.now ?? (() => Date.now());
116
+ // QA-2.2-9: the line depends on the config, the dispatching agent, its (and its session's) permissions and the orchestrator's model.
117
+ const taxonomyMemo = new Map<string, { cfg: Prepared["cfg"]; at: number; line: string }>();
118
+ const hints = new Map<string, { key: string; hint: string | null }>();
119
+
120
+ const taxonomyLine = (prepared: Prepared, view: AgentView, input: ContextInput): string => {
121
+ const t = now();
122
+ const memoKey = `${input.agent}\u0000${input.parentModel ?? ""}\u0000${JSON.stringify(view.parentRules)}`;
123
+ const memo = taxonomyMemo.get(memoKey);
124
+ if (memo !== undefined && memo.cfg === prepared.cfg && t - memo.at < TAXONOMY_TTL_MS) return memo.line;
125
+ const line = generateTaxonomy({
126
+ cfg: prepared.cfg,
127
+ routing: prepared.routing,
128
+ host: "v2",
129
+ store: prepared.store,
130
+ agents: view.infos,
131
+ pricing: (model) => prepared.catalog.pricing(model),
132
+ session: prepared.session,
133
+ parentModel: input.parentModel,
134
+ logger: deps.logger,
135
+ });
136
+ taxonomyMemo.delete(memoKey);
137
+ taxonomyMemo.set(memoKey, { cfg: prepared.cfg, at: t, line });
138
+ while (taxonomyMemo.size > TAXONOMY_MEMO_LIMIT) taxonomyMemo.delete(taxonomyMemo.keys().next().value as string);
139
+ return line;
140
+ };
141
+
142
+ const hintFor = async (prepared: Prepared, view: AgentView, input: ContextInput): Promise<string | null> => {
143
+ const text = latestUserText(input.messages);
144
+ if (text === null) return null;
145
+ const key = `${text.length}:${text.slice(0, 200)}:${text.slice(-200)}`;
146
+ const memo = hints.get(input.sessionID);
147
+ if (memo !== undefined && memo.key === key) return memo.hint;
148
+ const result = await classify({ prompt: text }, { ...deps.runtime.classifyDeps(prepared), backend: null });
149
+ const staticTier = CLASS_STATIC_TIER[result.facts.class];
150
+ let hint: string | null = null;
151
+ if (staticTier !== null) {
152
+ const infos: readonly HostAgentInfo[] = view.infos;
153
+ const chosen = resolveChosen({ cfg: prepared.cfg, agents: infos, agent: staticTier, parentModel: input.parentModel });
154
+ if (chosen !== null) {
155
+ const ladder = buildLadder({
156
+ cfg: prepared.cfg,
157
+ routing: prepared.routing,
158
+ facts: result.facts,
159
+ agents: infos,
160
+ pricing: (model) => prepared.catalog.pricing(model),
161
+ parentModel: input.parentModel,
162
+ logger: deps.logger,
163
+ session: prepared.session,
164
+ });
165
+ const decision = decide({
166
+ facts: result.facts,
167
+ chosen,
168
+ ladder,
169
+ // A34 (QA-G-B2): a route-line `d=` never raises detection above what the text's own `[acceptance]` block gives.
170
+ detection: weakerDetection(result.detection, detectionOf(text)),
171
+ pin: false,
172
+ routing: prepared.routing,
173
+ store: prepared.store,
174
+ floorRank: floorRankOf(prepared.cfg),
175
+ });
176
+ hint = buildHint(decision, result.facts, view.descriptions);
177
+ }
178
+ }
179
+ hints.delete(input.sessionID);
180
+ hints.set(input.sessionID, { key, hint });
181
+ while (hints.size > HINT_MEMO_LIMIT) hints.delete(hints.keys().next().value as string);
182
+ return hint;
183
+ };
184
+
185
+ return {
186
+ async augment(input, system, added): Promise<void> {
187
+ try {
188
+ // Roles mode: no hint part, and the protocol text stays exactly as the legacy hook built it. Keyed on the roles
189
+ // protocol the orchestrator actually carries (QA-P22-1-5): `delegation: "roles"` with no enabled role keeps the
190
+ // tiers protocol, which is then augmented like tiers mode.
191
+ if (system.some((text) => added.has(text) && ROLES_HEADING_LINE.test(text))) return;
192
+ const protocolAt: number[] = [];
193
+ system.forEach((text, index) => {
194
+ if (added.has(text) && text.includes(DELEGATION_PROTOCOL_HEADING)) protocolAt.push(index);
195
+ });
196
+ if (protocolAt.length === 0) return; // not the orchestrator (the legacy hook pushed no protocol)
197
+ const prepared = await deps.runtime.prepare(input.cfg);
198
+ if (prepared === null) return; // static: byte-identical
199
+ const mode = prepared.settings.engine;
200
+ if (mode !== "advise" && mode !== "enforce") return; // shadow: the text is the shipped one
201
+ const session = await deps.getSession(input.sessionID);
202
+ const view = await deps.runtime.agents(input.agent, sessionRulesOf(session));
203
+ if (view === null) return;
204
+ const line = taxonomyLine(prepared, view, input);
205
+ const paragraph = buildRouteLineProtocol(mode);
206
+ for (const index of protocolAt) {
207
+ const original = system[index] as string;
208
+ const rewritten = `${swapTaxonomyLine(original, prepared.cfg, line)}\n\n${paragraph}`;
209
+ added.add(rewritten);
210
+ system[index] = rewritten;
211
+ }
212
+ const hint = mode === "advise" ? await hintFor(prepared, view, input) : null;
213
+ if (hint !== null) {
214
+ added.add(hint);
215
+ system.push(hint);
216
+ }
217
+ } catch (error) {
218
+ deps.logger.warn("[router] routing: the protocol could not be adapted to the engine; the shipped text stays", { error: describeError(error) });
219
+ }
220
+ },
221
+ };
222
+ }
@@ -0,0 +1,256 @@
1
+ /**
2
+ * What the dispatch wiring (M7, Phase 2.2) knows about the host: agents with their EVALUATED permissions, and a
3
+ * synchronous view of the model catalog.
4
+ *
5
+ * Why this exists. The kernel (`src/routing/engine/*`) is pure and synchronous; it needs, per decision, a
6
+ * `HostAgentInfo[]` (A11: needs come from evaluated permissions, never from agent ids) and a catalog lookup
7
+ * (pricing for D5, variants and limits for the 1.5 runner simulation). The host offers both only through async
8
+ * calls, so this module turns the raw `ctx.agent.list()` / `ctx.model.list()` answers into the kernel's inputs and
9
+ * caches the catalog (stale-while-revalidate, the first load bounded).
10
+ *
11
+ * Permission semantics (verified against OpenCode 2.0.22 in the 0.P spikes, `docs/qa/cost-aware-routing/phase-0P.md`
12
+ * S1-deny): rules are `{ action, resource, effect }`, an agent's rules come before the session's, and the LAST
13
+ * matching rule wins. Anything this module cannot decide with certainty is "not granted": an uncovered need or a
14
+ * missing permission only makes a candidate ineligible, it never makes a dispatch worse.
15
+ */
16
+
17
+ import type { Need } from "../classify/types";
18
+ import { grantsFromTools } from "../engine/ladders";
19
+ import type { HostAgentInfo } from "../engine/types";
20
+ import type { ModelPricing } from "../outcomes/types";
21
+ import type { CatalogModel } from "../../escalate/variants";
22
+
23
+ // ---------------------------------------------------------------------------
24
+ // Permission rules
25
+ // ---------------------------------------------------------------------------
26
+
27
+ export type PermissionEffect = "allow" | "deny" | "ask";
28
+
29
+ export interface PermissionRule {
30
+ readonly action: string;
31
+ readonly resource: string;
32
+ readonly effect: PermissionEffect;
33
+ }
34
+
35
+ function isRecord(value: unknown): value is Record<string, unknown> {
36
+ return typeof value === "object" && value !== null && !Array.isArray(value);
37
+ }
38
+
39
+ /** `*` matches any run of characters (path separators included); everything else is literal and case-sensitive. */
40
+ export function wildcardMatch(pattern: string, value: string): boolean {
41
+ if (pattern === "*" || pattern === "**") return true;
42
+ if (!pattern.includes("*")) return pattern === value;
43
+ const parts = pattern.split("*");
44
+ let position = 0;
45
+ for (let i = 0; i < parts.length; i++) {
46
+ const part = parts[i] as string;
47
+ if (i === 0) {
48
+ if (!value.startsWith(part)) return false;
49
+ position = part.length;
50
+ } else if (i === parts.length - 1) {
51
+ return value.length - part.length >= position && value.endsWith(part);
52
+ } else {
53
+ const found = value.indexOf(part, position);
54
+ if (found < 0) return false;
55
+ position = found + part.length;
56
+ }
57
+ }
58
+ return true;
59
+ }
60
+
61
+ /** Valid rules only (a malformed entry is ignored, so it can never grant anything). A missing `resource` means `*`. */
62
+ export function parseRules(value: unknown): PermissionRule[] {
63
+ if (!Array.isArray(value)) return [];
64
+ const rules: PermissionRule[] = [];
65
+ for (const item of value) {
66
+ if (!isRecord(item) || typeof item.action !== "string") continue;
67
+ const effect = item.effect;
68
+ if (effect !== "allow" && effect !== "deny" && effect !== "ask") continue;
69
+ rules.push({ action: item.action, resource: typeof item.resource === "string" ? item.resource : "*", effect });
70
+ }
71
+ return rules;
72
+ }
73
+
74
+ /** Effect of the last rule matching `(action, resource)`; `null` when none matches. */
75
+ export function evaluateRules(rules: readonly PermissionRule[], action: string, resource: string): PermissionEffect | null {
76
+ let effect: PermissionEffect | null = null;
77
+ for (const rule of rules) {
78
+ if (wildcardMatch(rule.action, action) && wildcardMatch(rule.resource, resource)) effect = rule.effect;
79
+ }
80
+ return effect;
81
+ }
82
+
83
+ /**
84
+ * True only when `action` is allowed for EVERY resource: the last rule that matches the action at all is an `allow`
85
+ * whose resource is `*`. A rule limited to some resources (`bash` for `git *`, `external_directory` for one path)
86
+ * leaves the action conditional, which grants nothing (1.4 handoff, QA-1.4-14).
87
+ */
88
+ export function allowedUnconditionally(rules: readonly PermissionRule[], action: string): boolean {
89
+ let allowed = false;
90
+ for (const rule of rules) {
91
+ if (!wildcardMatch(rule.action, action)) continue;
92
+ allowed = rule.effect === "allow" && (rule.resource === "*" || rule.resource === "**");
93
+ }
94
+ return allowed;
95
+ }
96
+
97
+ const TOOLS_OF_INTEREST: readonly string[] = ["shell", "bash", "webfetch", "websearch", "edit", "write", "patch", "apply_patch"];
98
+
99
+ /** A11: the needs an agent's evaluated rules grant (unconditional allows only). */
100
+ export function grantsOfRules(rules: readonly PermissionRule[]): Need[] {
101
+ const tools = TOOLS_OF_INTEREST.filter((tool) => allowedUnconditionally(rules, tool));
102
+ return grantsFromTools(tools, allowedUnconditionally(rules, "external_directory"));
103
+ }
104
+
105
+ /**
106
+ * May the dispatching session start `agentID` as a subagent? Rules are the parent agent's followed by the session's
107
+ * (last match wins). Only an explicit `allow` counts: `ask` would stop the dispatch on a prompt the engine caused, and
108
+ * the host re-checks after a rewrite (`Subagent denied: explore`, A11).
109
+ */
110
+ export function subagentPermitted(rules: readonly PermissionRule[], agentID: string): boolean {
111
+ return evaluateRules(rules, "subagent", agentID) === "allow";
112
+ }
113
+
114
+ // ---------------------------------------------------------------------------
115
+ // Agents
116
+ // ---------------------------------------------------------------------------
117
+
118
+ /** `provider/model[#variant]` of a host `Agent.Info.model`; `null` when the agent has none. */
119
+ export function agentModelRef(model: unknown): string | null {
120
+ if (!isRecord(model) || typeof model.providerID !== "string" || typeof model.id !== "string") return null;
121
+ if (model.providerID === "" || model.id === "") return null;
122
+ const variant = typeof model.variant === "string" && model.variant !== "" ? `#${model.variant}` : "";
123
+ return `${model.providerID}/${model.id}${variant}`;
124
+ }
125
+
126
+ export interface AgentView {
127
+ readonly infos: readonly HostAgentInfo[];
128
+ /** Agent id → description (hint text). */
129
+ readonly descriptions: ReadonlyMap<string, string>;
130
+ /** Evaluated rules of the dispatching (parent) agent followed by its session's. */
131
+ readonly parentRules: readonly PermissionRule[];
132
+ }
133
+
134
+ /**
135
+ * The kernel's view of `ctx.agent.list().data`. `parentAgent` is the agent that dispatches (the session's agent);
136
+ * `sessionRules` the session's own `permissions`. An unknown parent agent permits nothing: the engine then keeps the
137
+ * orchestrator's pick.
138
+ */
139
+ export function buildAgentView(agents: readonly unknown[], parentAgent: string | undefined, sessionRules: readonly PermissionRule[]): AgentView {
140
+ const records = agents.filter(isRecord);
141
+ const parent = parentAgent === undefined ? undefined : records.find((agent) => agent.id === parentAgent);
142
+ const parentRules: PermissionRule[] = parent === undefined ? [] : [...parseRules(parent.permissions), ...sessionRules];
143
+ const infos: HostAgentInfo[] = [];
144
+ const descriptions = new Map<string, string>();
145
+ for (const agent of records) {
146
+ if (typeof agent.id !== "string" || agent.id === "") continue;
147
+ if (typeof agent.description === "string" && agent.description !== "") descriptions.set(agent.id, agent.description);
148
+ infos.push({
149
+ id: agent.id,
150
+ model: agentModelRef(agent.model),
151
+ mode: typeof agent.mode === "string" ? agent.mode : "primary",
152
+ hidden: agent.hidden === true,
153
+ permitted: parent !== undefined && subagentPermitted(parentRules, agent.id),
154
+ grants: grantsOfRules(parseRules(agent.permissions)),
155
+ });
156
+ }
157
+ return { infos, descriptions, parentRules };
158
+ }
159
+
160
+ // ---------------------------------------------------------------------------
161
+ // Catalog
162
+ // ---------------------------------------------------------------------------
163
+
164
+ /** The part of a host `Model.Info` the wiring reads (variants and limits for the runner, `cost` for D5). */
165
+ export interface RawCatalogModel extends CatalogModel {
166
+ readonly providerID: string;
167
+ readonly id: string;
168
+ readonly cost?: unknown;
169
+ }
170
+
171
+ export interface WireCatalog {
172
+ /**
173
+ * Make a recent catalog available to the synchronous lookups below. The first load waits at most `loadTimeoutMs`
174
+ * (then the lookups answer "unknown"); later calls return at once and refresh in the background. Never rejects.
175
+ */
176
+ ensure(): Promise<void>;
177
+ /** `provider/model` (no `#variant`) → the catalog entry, or `undefined` (unknown model, no catalog yet). */
178
+ entry(model: string): RawCatalogModel | undefined;
179
+ /** Catalog `cost` of the model; `undefined` = unpriced (A1). */
180
+ pricing(model: string): ModelPricing;
181
+ }
182
+
183
+ export interface WireCatalogOptions {
184
+ readonly now?: () => number;
185
+ readonly ttlMs?: number;
186
+ readonly retryMs?: number;
187
+ readonly loadTimeoutMs?: number;
188
+ readonly logger?: { warn(message: string, extra?: Record<string, unknown>): void };
189
+ }
190
+
191
+ function describeError(error: unknown): string {
192
+ return error instanceof Error ? error.message : String(error);
193
+ }
194
+
195
+ export function createWireCatalog(list: () => Promise<readonly RawCatalogModel[]>, options: WireCatalogOptions = {}): WireCatalog {
196
+ const now = options.now ?? (() => Date.now());
197
+ const ttlMs = options.ttlMs ?? 60_000;
198
+ const retryMs = options.retryMs ?? 15_000;
199
+ const loadTimeoutMs = options.loadTimeoutMs ?? 2_000;
200
+ let table = new Map<string, RawCatalogModel>();
201
+ let loadedAt: number | null = null;
202
+ let failedAt: number | null = null;
203
+ let loading: Promise<void> | null = null;
204
+ let gaveUpWaiting = false;
205
+
206
+ const startLoad = (): Promise<void> => {
207
+ const run = async (): Promise<void> => {
208
+ try {
209
+ const models = await list();
210
+ const next = new Map<string, RawCatalogModel>();
211
+ for (const model of models) next.set(`${model.providerID}/${model.id}`, model);
212
+ table = next;
213
+ loadedAt = now();
214
+ failedAt = null;
215
+ gaveUpWaiting = false;
216
+ } catch (error) {
217
+ failedAt = now();
218
+ options.logger?.warn("[router] routing: model catalog unavailable; pricing and variants are unknown", { error: describeError(error) });
219
+ }
220
+ };
221
+ const load: Promise<void> = run().finally(() => {
222
+ if (loading === load) loading = null;
223
+ });
224
+ loading = load;
225
+ return load;
226
+ };
227
+
228
+ return {
229
+ async ensure(): Promise<void> {
230
+ const t = now();
231
+ if (loadedAt !== null && t - loadedAt < ttlMs) return;
232
+ const backingOff = failedAt !== null && t - failedAt < retryMs;
233
+ const load = loading ?? (backingOff ? null : startLoad());
234
+ if (load === null || loadedAt !== null || gaveUpWaiting) return; // stale table served while it reloads
235
+ let timer: ReturnType<typeof setTimeout> | undefined;
236
+ const outcome = await Promise.race([
237
+ load.then(() => "done" as const),
238
+ new Promise<"timeout">((resolve) => {
239
+ timer = setTimeout(() => resolve("timeout"), loadTimeoutMs);
240
+ timer.unref();
241
+ }),
242
+ ]);
243
+ if (timer !== undefined) clearTimeout(timer);
244
+ if (outcome === "timeout" && loadedAt === null) {
245
+ gaveUpWaiting = true; // nobody waits for a catalog that hung once; the load stays pending
246
+ failedAt = now();
247
+ options.logger?.warn("[router] routing: model catalog is slow; pricing and variants are unknown for now", { loadTimeoutMs });
248
+ }
249
+ },
250
+ entry: (model) => table.get(model),
251
+ pricing(model): ModelPricing {
252
+ const cost = table.get(model)?.cost;
253
+ return typeof cost === "object" && cost !== null ? (cost as ModelPricing) : undefined;
254
+ },
255
+ };
256
+ }