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,348 @@
1
+ /**
2
+ * The engine's per-plugin-instance runtime (M7, Phase 2.2): everything the dispatch path and the context hook share.
3
+ *
4
+ * It owns, lazily and only while `routing.engine != static`:
5
+ * - the process-wide outcomes bundle (A3: one store and one writer per process) used to READ posteriors and to
6
+ * ENQUEUE decision rows (D15: memory only, flushed by the 1.3 flusher off the hot path);
7
+ * - a cached agent list (5 s) and a cached model catalog (`createWireCatalog`);
8
+ * - the classifier backend, built once per distinct classifier settings (the log-once set, the `response_format`
9
+ * memo and the circuit breaker live on the instance, Phase 1.2 handoff).
10
+ *
11
+ * With `routing.engine == static` (the default, and every config without a `routing` block) `prepare()` returns `null`
12
+ * before any host call, any allocation of a bundle or any disk access: the §1.2 guarantee.
13
+ */
14
+
15
+ import type { LadderSessionPolicyInput } from "../../escalate/ladder";
16
+ import {
17
+ resolveClassifierForPreset,
18
+ resolveRolesRouting,
19
+ resolveRouting,
20
+ resolveVariantSteps,
21
+ type ResolvedRouting,
22
+ type RouterConfig,
23
+ } from "../../router/config";
24
+ import { resolveRoles, type RoleSpec } from "../../router/roles";
25
+ import { createClassifierBackend, type ClassifyDeps } from "../classify";
26
+ import type { ClassifierBackend, ClassifierSettings, HostGenerate } from "../classify/types";
27
+ import type { EngineStoreView } from "../engine/types";
28
+ import { acquireOutcomes, type AcquireOutcomesOptions } from "../outcomes";
29
+ import { ingestSettings, type IngestSettings } from "../outcomes/ingest";
30
+ import type { LogRow, OutcomesBundle } from "../outcomes/types";
31
+ import {
32
+ buildAgentView,
33
+ createWireCatalog,
34
+ parseRules,
35
+ type AgentView,
36
+ type PermissionRule,
37
+ type RawCatalogModel,
38
+ type WireCatalog,
39
+ } from "./host-info";
40
+
41
+ export interface WireLogger {
42
+ warn(message: string, extra?: Record<string, unknown>): void;
43
+ /** Optional: lines that only matter when someone is looking (the dispatch router's instance-selection fallback). */
44
+ debug?(message: string, extra?: Record<string, unknown>): void;
45
+ }
46
+
47
+ export interface RuntimeDeps {
48
+ /** The live router config (hot reload re-reads it; the identity changes when the file does). */
49
+ readonly loadConfig: () => RouterConfig;
50
+ /** `ctx.agent.list().data`. */
51
+ readonly listAgents: () => Promise<readonly unknown[]>;
52
+ /** `ctx.model.list({ location }).data`. */
53
+ readonly listModels: () => Promise<readonly RawCatalogModel[]>;
54
+ /** `ctx.generate` for the `host` classifier backend (A4). */
55
+ readonly generate?: HostGenerate;
56
+ readonly logger: WireLogger;
57
+ readonly now?: () => number;
58
+ /** Seam over `acquireOutcomes` (tests inject persistence). */
59
+ readonly acquire?: (options: AcquireOutcomesOptions) => OutcomesBundle;
60
+ /** How long a fetched agent list is reused (default 5 s). */
61
+ readonly agentsTtlMs?: number;
62
+ /** The longest the first dispatch waits for the on-disk store to load (default 500 ms). */
63
+ readonly readyTimeoutMs?: number;
64
+ }
65
+
66
+ /** Everything one decision needs, resolved once per call. */
67
+ export interface Prepared {
68
+ readonly cfg: RouterConfig;
69
+ readonly routing: ResolvedRouting;
70
+ readonly settings: IngestSettings;
71
+ readonly store: EngineStoreView;
72
+ readonly catalog: WireCatalog;
73
+ /** The runner's own policy input (A25, 1.4 handoff): the kernel prices the router block with it. */
74
+ readonly session: LadderSessionPolicyInput;
75
+ /** O(1): the row goes to the flusher's memory queue. */
76
+ readonly enqueue: (row: LogRow) => void;
77
+ }
78
+
79
+ /**
80
+ * Everything one ROLE dispatch needs (#84 P2.1 T2.1.2). Unlike {@link Prepared} it exists in every engine mode, `static`
81
+ * included: a role dispatch always gets a router-set model (I2). Only `routing.delegation: "roles"` on v2 produces one.
82
+ */
83
+ export interface RolePrepared {
84
+ readonly cfg: RouterConfig;
85
+ /** The resolved role table (`resolveRoles(cfg, "v2")`). */
86
+ readonly roles: ReadonlyMap<string, RoleSpec>;
87
+ /** The dispatched role. */
88
+ readonly spec: RoleSpec;
89
+ readonly routing: ResolvedRouting;
90
+ /** `routing.engine`: `static` decides the static default and writes no row. */
91
+ readonly engine: ResolvedRouting["engine"];
92
+ /** `routing.exploration.rate` (0 unless roles mode; the kernel clamps it). */
93
+ readonly exploration: number;
94
+ readonly catalog: WireCatalog;
95
+ readonly session: LadderSessionPolicyInput;
96
+ /** The outcome store (posteriors); `null` when the engine is static. */
97
+ readonly store: EngineStoreView | null;
98
+ /** The decision-log queue; `null` when the engine is static (no rows). */
99
+ readonly enqueue: ((row: LogRow) => void) | null;
100
+ readonly classifyDeps: ClassifyDeps;
101
+ }
102
+
103
+ export interface EngineRuntime {
104
+ /**
105
+ * `null` when the engine is static (or the host is not v2): nothing was touched. Never throws. `cfg` is the config the caller
106
+ * already loaded (one `loadConfig` per hook call); without it the runtime loads its own.
107
+ */
108
+ prepare(cfg?: RouterConfig): Promise<Prepared | null>;
109
+ /**
110
+ * #84 P2.1: `null` unless `agent` is an enabled role agent of `routing.delegation: "roles"` on v2 (tiers mode: `null` before any
111
+ * host call). For a role agent it THROWS when the dispatch cannot be prepared: the caller refuses the role dispatch (fail closed).
112
+ * Optional so that hand-made runtimes keep compiling; `createEngineRuntime` always provides it.
113
+ */
114
+ prepareRoles?(agent: string, cfg?: RouterConfig): Promise<RolePrepared | null>;
115
+ /** The dispatching session's view of the host's agents (evaluated permissions included). */
116
+ agents(parentAgent: string | undefined, sessionRules: readonly PermissionRule[]): Promise<AgentView | null>;
117
+ /** The classifier dependencies for this config (backend memoized). */
118
+ classifyDeps(prepared: Prepared): ClassifyDeps;
119
+ dispose(): Promise<void>;
120
+ }
121
+
122
+ function describeError(error: unknown): string {
123
+ return error instanceof Error ? error.message : String(error);
124
+ }
125
+
126
+ interface Held {
127
+ readonly dir: string;
128
+ readonly bundle: OutcomesBundle;
129
+ ready: "pending" | "done" | "gave-up";
130
+ }
131
+
132
+ export function createEngineRuntime(deps: RuntimeDeps): EngineRuntime {
133
+ const now = deps.now ?? (() => Date.now());
134
+ const acquire = deps.acquire ?? acquireOutcomes;
135
+ const agentsTtlMs = deps.agentsTtlMs ?? 5_000;
136
+ const readyTimeoutMs = deps.readyTimeoutMs ?? 500;
137
+ const catalog = createWireCatalog(deps.listModels, { now, logger: deps.logger });
138
+ let held: Held | null = null;
139
+ let routingMemo: { cfg: RouterConfig; routing: ResolvedRouting } | null = null;
140
+ let agentsMemo: { at: number; data: readonly unknown[] } | null = null;
141
+ let classifierMemo: { key: string; settings: ClassifierSettings; backend: ClassifierBackend | null } | null = null;
142
+ let disposed = false;
143
+
144
+ /**
145
+ * Let go of a store without making the caller wait (a hot reload to static, a moved directory). The release is tracked, so `dispose()`
146
+ * can wait for it: the last holder's release is the final flush of the decision log (QA-2.4-17). Never rejects.
147
+ */
148
+ const releasing = new Set<Promise<void>>();
149
+ const release = (target: Held): Promise<void> => {
150
+ const job: Promise<void> = target.bundle
151
+ .release()
152
+ .catch((error: unknown) => {
153
+ deps.logger.warn("[router] routing: releasing the outcome store failed", { error: describeError(error) });
154
+ })
155
+ .finally(() => {
156
+ releasing.delete(job);
157
+ });
158
+ releasing.add(job);
159
+ return job;
160
+ };
161
+
162
+ const waitReady = async (target: Held): Promise<void> => {
163
+ if (target.ready !== "pending") return;
164
+ let timer: ReturnType<typeof setTimeout> | undefined;
165
+ const outcome = await Promise.race([
166
+ target.bundle.ready.then(() => "done" as const),
167
+ new Promise<"timeout">((resolve) => {
168
+ timer = setTimeout(() => resolve("timeout"), readyTimeoutMs);
169
+ timer.unref();
170
+ }),
171
+ ]);
172
+ if (timer !== undefined) clearTimeout(timer);
173
+ target.ready = outcome === "done" ? "done" : "gave-up"; // a store that is slow to load is not waited for twice
174
+ };
175
+
176
+ const routingOf = (cfg: RouterConfig): ResolvedRouting => {
177
+ if (routingMemo === null || routingMemo.cfg !== cfg) routingMemo = { cfg, routing: resolveRouting(cfg, "v2", deps.logger) };
178
+ return routingMemo.routing;
179
+ };
180
+
181
+ const classifyDepsFor = (cfg: RouterConfig, routing: ResolvedRouting): ClassifyDeps => {
182
+ const settings = resolveClassifierForPreset(routing.classifier, cfg.activePreset);
183
+ const key = JSON.stringify([
184
+ settings.backend, settings.model, settings.baseUrl, settings.apiKeyEnv, settings.timeoutMs, settings.samples, settings.maxStateChars,
185
+ ]);
186
+ if (classifierMemo === null || classifierMemo.key !== key) {
187
+ const memoSettings: ClassifierSettings = {
188
+ backend: settings.backend,
189
+ model: settings.model,
190
+ baseUrl: settings.baseUrl,
191
+ apiKeyEnv: settings.apiKeyEnv,
192
+ timeoutMs: settings.timeoutMs,
193
+ samples: settings.samples,
194
+ maxStateChars: settings.maxStateChars,
195
+ };
196
+ classifierMemo = {
197
+ key,
198
+ settings: memoSettings,
199
+ backend: createClassifierBackend(memoSettings, {
200
+ ...(deps.generate === undefined ? {} : { generate: deps.generate }),
201
+ logger: deps.logger,
202
+ }),
203
+ };
204
+ }
205
+ return {
206
+ cfg,
207
+ settings: classifierMemo.settings,
208
+ minClassConfidence: routing.minClassConfidence,
209
+ backend: classifierMemo.backend,
210
+ logger: deps.logger,
211
+ };
212
+ };
213
+
214
+ const sessionPolicyOf = (cfg: RouterConfig, routing: ResolvedRouting): LadderSessionPolicyInput => ({
215
+ host: "v2",
216
+ variantSteps: resolveVariantSteps(cfg, "v2"),
217
+ maxContextFraction: routing.sessionReuse.maxContextFraction,
218
+ catalog: (model) => catalog.entry(model),
219
+ warn: (message) => deps.logger.warn(message),
220
+ });
221
+
222
+ const self: EngineRuntime = {
223
+ async prepare(given): Promise<Prepared | null> {
224
+ try {
225
+ const cfg = given ?? deps.loadConfig();
226
+ const settings = disposed ? null : ingestSettings(cfg, "v2");
227
+ if (settings === null) {
228
+ if (held !== null) {
229
+ const previous = held;
230
+ held = null;
231
+ release(previous); // hot reload to static: let go of the store (its last release flushes)
232
+ }
233
+ return null;
234
+ }
235
+ if (held === null || held.dir !== settings.outcomesDir) {
236
+ const previous = held;
237
+ held = {
238
+ dir: settings.outcomesDir,
239
+ bundle: acquire({ dir: settings.outcomesDir, tuning: settings.tuning, logger: deps.logger }),
240
+ ready: "pending",
241
+ };
242
+ if (previous !== null) release(previous);
243
+ }
244
+ const current = held;
245
+ await Promise.all([waitReady(current), catalog.ensure()]);
246
+ // QA-2.2-13: the runtime was disposed, or the config went static / moved to another directory, while we waited: the
247
+ // holder we read from is no longer ours, and a decision made on a released store must not be logged.
248
+ if (disposed || held !== current) return null;
249
+ const routing = routingOf(cfg);
250
+ return {
251
+ cfg,
252
+ routing,
253
+ settings,
254
+ store: current.bundle.store,
255
+ catalog,
256
+ session: {
257
+ host: "v2",
258
+ variantSteps: resolveVariantSteps(cfg, "v2"),
259
+ maxContextFraction: routing.sessionReuse.maxContextFraction,
260
+ catalog: (model) => catalog.entry(model),
261
+ warn: (message) => deps.logger.warn(message),
262
+ },
263
+ enqueue: (row) => current.bundle.flusher.enqueue(row),
264
+ };
265
+ } catch (error) {
266
+ deps.logger.warn("[router] routing: engine preparation failed; the dispatch proceeds as the orchestrator chose", { error: describeError(error) });
267
+ return null;
268
+ }
269
+ },
270
+
271
+ async agents(parentAgent, sessionRules): Promise<AgentView | null> {
272
+ try {
273
+ const t = now();
274
+ if (agentsMemo === null || t - agentsMemo.at >= agentsTtlMs) {
275
+ agentsMemo = { at: t, data: await deps.listAgents() };
276
+ }
277
+ return buildAgentView(agentsMemo.data, parentAgent, sessionRules);
278
+ } catch (error) {
279
+ deps.logger.warn("[router] routing: the agent list is unavailable; the dispatch proceeds as the orchestrator chose", { error: describeError(error) });
280
+ return agentsMemo === null ? null : buildAgentView(agentsMemo.data, parentAgent, sessionRules);
281
+ }
282
+ },
283
+
284
+ classifyDeps(prepared): ClassifyDeps {
285
+ return classifyDepsFor(prepared.cfg, prepared.routing);
286
+ },
287
+
288
+ async prepareRoles(agent, given): Promise<RolePrepared | null> {
289
+ if (disposed) return null;
290
+ let cfg: RouterConfig;
291
+ let roles: ReadonlyMap<string, RoleSpec>;
292
+ try {
293
+ cfg = given ?? deps.loadConfig();
294
+ // Tiers mode (and v1, which never reaches this v2 runtime): an empty table before any host call (I1).
295
+ roles = resolveRoles(cfg, "v2");
296
+ } catch (error) {
297
+ // Not known to be a role dispatch: the tier path decides (and fails safe) as before.
298
+ deps.logger.warn("[router] routing: the role table could not be resolved", { error: describeError(error) });
299
+ return null;
300
+ }
301
+ const spec = roles.get(agent);
302
+ if (spec === undefined) return null;
303
+ const routing = routingOf(cfg);
304
+ let store: EngineStoreView | null = null;
305
+ let enqueue: ((row: LogRow) => void) | null = null;
306
+ if (routing.engine !== "static") {
307
+ // The tier engine's own preparation: the same store and decision-log queue (A3: one writer per process).
308
+ const prepared = await self.prepare(cfg);
309
+ if (prepared !== null) {
310
+ store = prepared.store;
311
+ enqueue = prepared.enqueue;
312
+ }
313
+ } else {
314
+ await catalog.ensure(); // static: no store, no rows, but the catalog decides whether a tier variant exists
315
+ }
316
+ if (disposed) return null;
317
+ return {
318
+ cfg,
319
+ roles,
320
+ spec,
321
+ routing,
322
+ engine: routing.engine,
323
+ exploration: resolveRolesRouting(cfg, "v2").exploration.rate,
324
+ catalog,
325
+ session: sessionPolicyOf(cfg, routing),
326
+ store,
327
+ enqueue,
328
+ classifyDeps: classifyDepsFor(cfg, routing),
329
+ };
330
+ },
331
+
332
+ async dispose(): Promise<void> {
333
+ disposed = true;
334
+ const previous = held;
335
+ held = null;
336
+ if (previous !== null) await release(previous);
337
+ // Releases started earlier (hot reload to static, another outcomes directory) may still be flushing: wait for them too, so that
338
+ // when `dispose()` resolves every queued row is on disk and no holder of this runtime is left.
339
+ while (releasing.size > 0) await Promise.allSettled([...releasing]);
340
+ },
341
+ };
342
+ return self;
343
+ }
344
+
345
+ /** The session's own permission rules (`Session.Info.permissions`). */
346
+ export function sessionRulesOf(session: unknown): PermissionRule[] {
347
+ return typeof session === "object" && session !== null ? parseRules((session as { permissions?: unknown }).permissions) : [];
348
+ }
package/src/v2.ts CHANGED
@@ -3,6 +3,8 @@ import type { PluginInput } from "@opencode-ai/plugin";
3
3
  import ModelRouterPlugin from "./index";
4
4
  import { createV2Runtime } from "./compat/v2-client";
5
5
  import { registerV2Hooks } from "./compat/v2-hooks";
6
+ import type { Ingest } from "./routing/outcomes/ingest";
7
+ import type { BudgetSnapshot } from "./guard/enforce";
6
8
 
7
9
  /** Keep the routing engine shared; translate only the host API at this boundary. */
8
10
  export default {
@@ -12,14 +14,51 @@ export default {
12
14
  const runtime = createV2Runtime(ctx);
13
15
  // The engine consumes directory/client only. V2 has no legacy HTTP server
14
16
  // URL or Bun shell context; do not invent either for the adapter.
17
+ let ingest: Ingest | undefined;
18
+ // #84 P2.1: the plugin's `/bypass` state, read by the role dispatch path (the router's own gate will not run while bypassed, S10/P-9).
19
+ let isBypassed: (() => boolean) | undefined;
20
+ let budgetSnapshot: ((childSessionID: string) => BudgetSnapshot) | undefined;
21
+ // #84 P2.1 (handoff 22): the host's own stops of role children (step limit, context overflow), observed by the adapter from the
22
+ // event stream and folded into the plugin's budget signals. The adapter hands its observer back once registered.
23
+ let observeHostBudget: ((childSessionID: string, stepLimit: number | null) => boolean | "unobserved") | undefined;
24
+ let roleLive: ((agent: string) => boolean) | undefined;
25
+ let verifyEnabled: (() => boolean) | undefined;
26
+ // QA-G-A3-2: the plugin's count of a role child's call refused outside its guard (role-authority refusals, permission denials).
27
+ let recordRefusal: ((sessionID: string, agent: string | undefined, tool: string, args: unknown) => string | undefined) | undefined;
15
28
  const input = {
16
29
  directory: ctx.location.directory,
17
30
  worktree: ctx.location.project.directory,
18
31
  client: runtime.client,
19
32
  routerChildRunner: runtime.childRunner,
20
33
  routerHost: "v2" as const,
34
+ // Step pricing reads the catalog the adapter already queries; the plugin's single telemetry ingest comes back
35
+ // here so the event loop feeds the instance that also receives the verdicts (QA-2.1-7).
36
+ routerCatalog: async () => (await ctx.model.list({ location: { directory: ctx.location.directory } })).data,
37
+ // The agents of THIS plugin instance's location (QA-2.4-16): the host lists agents per location.
38
+ routerAgents: async () => (await ctx.agent.list({ location: { directory: ctx.location.directory } })).data,
39
+ ...(ctx.generate === undefined ? {} : { routerGenerate: ctx.generate }),
40
+ // The same host call the adapter uses for the config-reload and narration notices (src/compat/v2-hooks.ts): a transcript entry that
41
+ // does not resume the session (QA-2.4-R2-1).
42
+ routerSynthetic: async (notice: { sessionID: string; text: string; description: string }) => {
43
+ await ctx.session.synthetic({ sessionID: notice.sessionID, text: notice.text, description: notice.description, resume: false });
44
+ },
45
+ routerOnIngest: (created: Ingest) => { ingest = created; },
46
+ routerOnBypassState: (read: () => boolean) => { isBypassed = read; },
47
+ // QA-P21-1-3: the plugin's budget snapshot (guard state + read-only CAP state) for the adapter's budget notice.
48
+ routerOnBudgetSnapshot: (read: (childSessionID: string) => BudgetSnapshot) => { budgetSnapshot = read; },
49
+ routerHostBudget: (childSessionID: string, stepLimit: number | null) => observeHostBudget?.(childSessionID, stepLimit),
50
+ // QA-P21-2-4: the adapter's "this role agent is registered" check; QA-P21-2 nit 3: whether router_verify is registered.
51
+ routerRoleLive: (agent: string) => roleLive?.(agent),
52
+ routerOnVerifyEnabled: (read: () => boolean) => { verifyEnabled = read; },
53
+ routerOnRefusal: (record: NonNullable<typeof recordRefusal>) => { recordRefusal = record; },
21
54
  };
22
55
  const hooks = await ModelRouterPlugin(input as unknown as PluginInput);
23
- return registerV2Hooks(ctx, hooks, runtime);
56
+ return registerV2Hooks(ctx, hooks, runtime, {
57
+ ...(ingest ? { ingest } : {}), ...(isBypassed ? { isBypassed } : {}), ...(budgetSnapshot ? { budgetSnapshot } : {}),
58
+ ...(verifyEnabled ? { routerVerifyEnabled: verifyEnabled } : {}),
59
+ ...(recordRefusal ? { recordRefusal } : {}),
60
+ onHostBudget: (observe) => { observeHostBudget = observe; },
61
+ onRoleLive: (isLive) => { roleLive = isLive; },
62
+ });
24
63
  },
25
64
  } satisfies Plugin.Plugin & { server: typeof ModelRouterPlugin };