opencode-model-router 2.1.0 → 2.3.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (55) hide show
  1. package/CHANGELOG.md +86 -0
  2. package/README.md +44 -5
  3. package/package.json +4 -1
  4. package/src/commands/output.ts +4 -1
  5. package/src/compat/child-session.ts +43 -0
  6. package/src/compat/v2-client.ts +107 -7
  7. package/src/compat/v2-hooks.ts +174 -47
  8. package/src/escalate/attempt-recorder.ts +263 -0
  9. package/src/escalate/ladder.ts +484 -10
  10. package/src/escalate/resume.ts +208 -0
  11. package/src/escalate/variants.ts +391 -0
  12. package/src/index.ts +557 -61
  13. package/src/router/build-info.ts +151 -0
  14. package/src/router/config.ts +1691 -67
  15. package/src/router/protocol.ts +47 -0
  16. package/src/router/sessions.ts +441 -9
  17. package/src/routing/advisor/findings.ts +706 -0
  18. package/src/routing/advisor/index.ts +606 -0
  19. package/src/routing/classify/backends/host.ts +163 -0
  20. package/src/routing/classify/backends/openai-compatible.ts +275 -0
  21. package/src/routing/classify/backends/shared.ts +741 -0
  22. package/src/routing/classify/backends/typesafe.ts +315 -0
  23. package/src/routing/classify/fences.ts +96 -0
  24. package/src/routing/classify/index.ts +576 -0
  25. package/src/routing/classify/route-line.ts +298 -0
  26. package/src/routing/classify/rules.ts +607 -0
  27. package/src/routing/classify/scrub.ts +214 -0
  28. package/src/routing/classify/state.ts +148 -0
  29. package/src/routing/classify/text.ts +20 -0
  30. package/src/routing/classify/types.ts +1280 -0
  31. package/src/routing/commands/annotate-plan.ts +652 -0
  32. package/src/routing/commands/stats.ts +131 -0
  33. package/src/routing/commands/v1-roles.ts +64 -0
  34. package/src/routing/engine/index.ts +32 -0
  35. package/src/routing/engine/kernel.ts +597 -0
  36. package/src/routing/engine/ladders.ts +561 -0
  37. package/src/routing/engine/plan.ts +404 -0
  38. package/src/routing/engine/protocol-line.ts +133 -0
  39. package/src/routing/engine/simulate.ts +167 -0
  40. package/src/routing/engine/types.ts +270 -0
  41. package/src/routing/file-lock.ts +53 -0
  42. package/src/routing/outcomes/beta.ts +141 -0
  43. package/src/routing/outcomes/cost.ts +313 -0
  44. package/src/routing/outcomes/index.ts +172 -0
  45. package/src/routing/outcomes/ingest.ts +812 -0
  46. package/src/routing/outcomes/persist.ts +1058 -0
  47. package/src/routing/outcomes/stats.ts +602 -0
  48. package/src/routing/outcomes/store.ts +653 -0
  49. package/src/routing/outcomes/types.ts +954 -0
  50. package/src/routing/wire/dispatch.ts +799 -0
  51. package/src/routing/wire/hint.ts +208 -0
  52. package/src/routing/wire/host-info.ts +256 -0
  53. package/src/routing/wire/runtime.ts +259 -0
  54. package/src/v2.ts +15 -1
  55. package/tiers.json +43 -0
@@ -11,7 +11,13 @@ import { loadConfig } from "../router/config";
11
11
  import { getActiveTiers } from "../router/protocol";
12
12
  import { resolveSubagentOverrides } from "../router/subagents";
13
13
  import { stripDelegateInstructions } from "../router/instructions";
14
+ import { createPluginLogger } from "../router/logger";
14
15
  import { GRADER_SYSTEM } from "../verify/checker";
16
+ import { EXECUTION_END_TYPES, FLUSH_EVENT_TYPES, NOOP_INGEST } from "../routing/outcomes/ingest";
17
+ import type { Ingest } from "../routing/outcomes/ingest";
18
+ import { createEngineRuntime } from "../routing/wire/runtime";
19
+ import { childSessionOf, createDispatchRouter } from "../routing/wire/dispatch";
20
+ import { createSystemAugmenter } from "../routing/wire/hint";
15
21
 
16
22
  /** Translate the router's own v1 tool vocabulary at the v2 boundary. */
17
23
  export function v2Instructions(text: string): string {
@@ -80,6 +86,8 @@ export async function registerV2Hooks(
80
86
  ctx: Context,
81
87
  hooks: Hooks,
82
88
  runtime?: Pick<V2Runtime, "withToolContext" | "applyChildSystem"> & Partial<Pick<V2Runtime, "dispose" | "forgetSession">>,
89
+ /** `ingest`: the plugin instance's telemetry ingest (M6, QA-2.1-7); without one the adapter ingests nothing. */
90
+ options: { ingest?: Ingest } = {},
83
91
  ): Promise<() => Promise<void>> {
84
92
  // The old plugin surface uses separate mutable input/output bags. Keep those
85
93
  // casts confined to this adapter, rather than weakening the v2 event types.
@@ -88,6 +96,33 @@ export async function registerV2Hooks(
88
96
  const abort = new AbortController();
89
97
  const verifyingCalls = new Set<string>();
90
98
  const depthBanners = new Map<string, string>();
99
+ // M6 (2.1.3): child-session outcomes and costs reach the outcome store through the plugin instance's ingest, which
100
+ // does nothing unless routing.engine != static (its settings are null otherwise: no bundle, no files).
101
+ const ingestLogger = createPluginLogger();
102
+ const ingest: Ingest = options.ingest ?? NOOP_INGEST;
103
+ // An ingestion error is logged and the loop carries on: it must never cost the router an event.
104
+ const ingesting = async (what: string, run: () => void | Promise<void>): Promise<void> => {
105
+ try {
106
+ await run();
107
+ } catch (error) {
108
+ if (!abort.signal.aborted) ingestLogger.warn(`[router] telemetry ingestion: ${what} failed`, { error: error instanceof Error ? error.message : String(error) });
109
+ }
110
+ };
111
+ // M7 (2.2): dispatch routing and the protocol/hint adaptation share one runtime; it touches nothing (no host call, no
112
+ // store, no disk) while routing.engine is static, which is the default and what every config without a `routing` block is.
113
+ const sessionOf = (sessionID: string): Promise<unknown> => ctx.session.get({ sessionID } as Parameters<typeof ctx.session.get>[0]);
114
+ const engine = createEngineRuntime({
115
+ loadConfig: () => loadConfig(ctx.location.directory),
116
+ listAgents: async () => (await ctx.agent.list()).data,
117
+ listModels: async () => (await ctx.model.list({ location: { directory: ctx.location.directory } })).data,
118
+ ...(ctx.generate === undefined ? {} : { generate: ctx.generate }),
119
+ logger: ingestLogger,
120
+ });
121
+ const dispatchRouter = createDispatchRouter({
122
+ runtime: engine, getSession: sessionOf, graderAgent: V2_GRADER_AGENT, directory: ctx.location.directory,
123
+ logger: { warn: (message, extra) => ingestLogger.warn(message, extra), debug: (message, extra) => console.debug(message, extra ?? "") },
124
+ });
125
+ const systemAugmenter = createSystemAugmenter({ runtime: engine, getSession: sessionOf, logger: ingestLogger });
91
126
  let eventTask: Promise<void> | undefined;
92
127
  let disposed = false;
93
128
  const within = <T>(context: ToolContext, operation: () => Promise<T>): Promise<T> =>
@@ -108,31 +143,65 @@ export async function registerV2Hooks(
108
143
  disposed = true;
109
144
  abort.abort();
110
145
  await runtime?.dispose?.();
146
+ // Before the event task: disposing releases a step handler that waits for the model catalog (QA-2.1-5).
147
+ await ingest.dispose();
148
+ dispatchRouter.dispose(); // this location no longer owns its sessions
149
+ await engine.dispose();
111
150
  await eventTask;
112
151
  await Promise.allSettled(registrations.map((registration) => registration.dispose()));
113
152
  await hooks.dispose?.();
114
153
  };
115
154
 
116
155
  try {
156
+ // Captured once: after our own transform, ctx.agent.list() returns
157
+ // router-modified agents, which would defeat the originals diff on refresh.
117
158
  const agents = await ctx.agent.list();
118
- const config: LegacyConfig = { agent: {}, command: {} };
119
- for (const agent of agents.data) config.agent[agent.id] = {
159
+ const baseSeed: Record<string, LegacyAgent> = {};
160
+ for (const agent of agents.data) baseSeed[agent.id] = {
120
161
  mode: agent.mode,
121
162
  model: agent.model && `${agent.model.providerID}/${agent.model.id}`,
122
163
  variant: agent.model?.variant,
123
164
  };
124
- const originals = new Map(Object.entries(config.agent).map(([id, agent]) => [id, JSON.stringify(agent)]));
125
- await hooks.config?.(config);
126
- const agentOptions = new Map<string, Record<string, unknown>>();
127
- for (const [name, definition] of Object.entries(config.agent)) {
128
- if (originals.get(name) === JSON.stringify(definition) || !definition.options) continue;
129
- const { reasoning_effort, reasoning_summary, budget_tokens, ...options } = definition.options;
130
- const normalized = { ...options };
131
- if (reasoning_effort !== undefined && normalized.reasoningEffort === undefined) normalized.reasoningEffort = reasoning_effort;
132
- if (reasoning_summary !== undefined && normalized.reasoningSummary === undefined) normalized.reasoningSummary = reasoning_summary;
133
- if (budget_tokens !== undefined && normalized.thinking === undefined) normalized.thinking = { type: "enabled", budgetTokens: budget_tokens };
134
- agentOptions.set(name, normalized);
135
- }
165
+ let config: LegacyConfig = { agent: {}, command: {} };
166
+ let originals = new Map<string, string>();
167
+ let agentOptions = new Map<string, Record<string, unknown>>();
168
+ let lastConfig: unknown;
169
+ // Returns the router config the registry state was built from; the caller
170
+ // advances `lastConfig` only once the host registries have reloaded from it.
171
+ const buildConfig = async (): Promise<unknown> => {
172
+ const next: LegacyConfig = { agent: JSON.parse(JSON.stringify(baseSeed)), command: {} };
173
+ const nextOriginals = new Map(Object.entries(next.agent).map(([id, agent]) => [id, JSON.stringify(agent)]));
174
+ await hooks.config?.(next);
175
+ const nextOptions = new Map<string, Record<string, unknown>>();
176
+ for (const [name, definition] of Object.entries(next.agent)) {
177
+ if (nextOriginals.get(name) === JSON.stringify(definition) || !definition.options) continue;
178
+ const { reasoning_effort, reasoning_summary, budget_tokens, ...options } = definition.options;
179
+ const normalized = { ...options };
180
+ if (reasoning_effort !== undefined && normalized.reasoningEffort === undefined) normalized.reasoningEffort = reasoning_effort;
181
+ if (reasoning_summary !== undefined && normalized.reasoningSummary === undefined) normalized.reasoningSummary = reasoning_summary;
182
+ if (budget_tokens !== undefined && normalized.thinking === undefined) normalized.thinking = { type: "enabled", budgetTokens: budget_tokens };
183
+ nextOptions.set(name, normalized);
184
+ }
185
+ config = next;
186
+ originals = nextOriginals;
187
+ agentOptions = nextOptions;
188
+ return loadConfig(ctx.location.directory);
189
+ };
190
+ lastConfig = await buildConfig();
191
+ let refreshChain: Promise<void> = Promise.resolve();
192
+ const refresh = (): Promise<void> => {
193
+ const run = refreshChain.then(async () => {
194
+ if (disposed) return;
195
+ const built = await buildConfig();
196
+ await ctx.agent.reload();
197
+ await ctx.command.reload();
198
+ // Only after both registries reloaded: a rejected reload leaves
199
+ // `lastConfig` stale so the next prompt retries the refresh.
200
+ lastConfig = built;
201
+ });
202
+ refreshChain = run.catch(() => {});
203
+ return run;
204
+ };
136
205
  registrations.push(await ctx.agent.transform((editor) => {
137
206
  if (runtime) editor.update(V2_GRADER_AGENT, (agent) => {
138
207
  agent.mode = "subagent";
@@ -163,6 +232,15 @@ export async function registerV2Hooks(
163
232
  await legacy["command.execute.before"]?.({
164
233
  command: name, arguments: invocation.prompt.text, sessionID: invocation.sessionID,
165
234
  }, output);
235
+ if (name === "router-reload") {
236
+ const reloadText = output.parts.map((part) => v2Instructions(part.text)).join("\n\n");
237
+ await refresh();
238
+ await ctx.session.synthetic({
239
+ sessionID: invocation.sessionID, text: reloadText, description: "Model router config reload", resume: false,
240
+ });
241
+ return;
242
+ }
243
+ if (name === "preset") await refresh();
166
244
  await ctx.session.prompt({
167
245
  ...invocation.prompt,
168
246
  sessionID: invocation.sessionID,
@@ -207,6 +285,7 @@ export async function registerV2Hooks(
207
285
  const output = { message: { agent: session.agent }, parts: [{ type: "text", text: event.prompt.text }] };
208
286
  await legacy["chat.message"]?.({ sessionID: event.sessionID, agent: session.agent }, output);
209
287
  event.prompt.text = output.parts.map((part) => part.text).join("\n\n");
288
+ if (loadConfig(ctx.location.directory) !== lastConfig) await refresh();
210
289
  }));
211
290
  registrations.push(await ctx.session.hook("context", async (event) => {
212
291
  const input = { sessionID: event.sessionID, agent: event.agent, model: { ...event.model, modelID: event.model.id } };
@@ -215,7 +294,8 @@ export async function registerV2Hooks(
215
294
  if (!(key in event.options)) event.options[key] = value;
216
295
  }
217
296
  await legacy["chat.params"]?.(input, event.options);
218
- const verify = loadConfig().enforcement?.verify;
297
+ const routerConfig = loadConfig(ctx.location.directory);
298
+ const verify = routerConfig.enforcement?.verify;
219
299
  if (event.agent === V2_GRADER_AGENT
220
300
  && (verify?.graderTemperature === null
221
301
  || !(verify?.graderTemperatureModels ?? []).includes(`${event.model.providerID}/${event.model.id}`))) {
@@ -236,6 +316,11 @@ export async function registerV2Hooks(
236
316
  return Array.prototype.push.apply(output.system, texts);
237
317
  } });
238
318
  await legacy["experimental.chat.system.transform"]?.(input, output);
319
+ // M7 (2.2): advise/enforce swap the R: line, append the route-line paragraph and add the per-turn hint.
320
+ // static/shadow (and every config without a routing block) leave `output.system` exactly as the legacy hook built it.
321
+ await systemAugmenter.augment({
322
+ sessionID: event.sessionID, agent: event.agent, parentModel: `${event.model.providerID}/${event.model.id}`, messages: event.messages, cfg: routerConfig,
323
+ }, output.system, added);
239
324
  event.system = output.system.map((text): SystemPart =>
240
325
  original.get(text)?.shift() ?? { type: "text", text: added.has(text) ? v2Instructions(text) : text });
241
326
  runtime?.applyChildSystem(event.sessionID, event.system);
@@ -256,7 +341,7 @@ export async function registerV2Hooks(
256
341
  const source = message.id ? attributed.get(message.id) : undefined;
257
342
  if (!source || source.type !== "synthetic") continue;
258
343
  const filtered = { system: [source.text] };
259
- stripDelegateInstructions(filtered, loadConfig(), session.location?.directory ?? ctx.location.directory);
344
+ stripDelegateInstructions(filtered, loadConfig(ctx.location.directory), session.location?.directory ?? ctx.location.directory);
260
345
  const retained = filtered.system.join("");
261
346
  if (retained === source.text) continue;
262
347
  const index = event.messages.indexOf(message);
@@ -271,41 +356,65 @@ export async function registerV2Hooks(
271
356
 
272
357
  registrations.push(await ctx.tool.hook("execute.before", async (event) => {
273
358
  const args = await scopedArgs(event);
274
- const original = args && typeof args === "object" ? { ...args } : args;
275
- const output = { args };
276
- if (event.tool === "subagent" && args && typeof args.agent === "string" && args.model === undefined) {
277
- const cfg = loadConfig();
278
- if (cfg.subagentTiers?.[args.agent]) {
279
- const actual = await ctx.agent.list();
280
- const overrides = actual.data.some((agent) => agent.id === args.agent) ? resolveSubagentOverrides({
281
- subagentTiers: cfg.subagentTiers, tiers: getActiveTiers(cfg),
282
- existingAgents: Object.fromEntries(actual.data.map((agent) => [agent.id, { mode: agent.mode }])),
283
- }) : {};
284
- const override = overrides[args.agent];
285
- if (override) args.model = `${override.model}${override.variant ? `#${override.variant}` : ""}`;
359
+ if (event.tool === "subagent" && args && typeof args.agent === "string") {
360
+ // The model `subagentTiers` would fill in when the call names none (unchanged behaviour: only then, only for a mapped agent).
361
+ const cfg = loadConfig(ctx.location.directory);
362
+ let tierModel: string | undefined;
363
+ if (args.model === undefined) {
364
+ if (cfg.subagentTiers?.[args.agent]) {
365
+ const actual = await ctx.agent.list();
366
+ const overrides = actual.data.some((agent) => agent.id === args.agent) ? resolveSubagentOverrides({
367
+ subagentTiers: cfg.subagentTiers, tiers: getActiveTiers(cfg),
368
+ existingAgents: Object.fromEntries(actual.data.map((agent) => [agent.id, { mode: agent.mode }])),
369
+ }) : {};
370
+ const override = overrides[args.agent];
371
+ if (override) tierModel = `${override.model}${override.variant ? `#${override.variant}` : ""}`;
372
+ }
286
373
  }
374
+ // M7 (2.2): the engine goes first. Static (the default) returns untouched without any host call; shadow/advise only
375
+ // log and strip `[route …]`; enforce may also replace agent and model. `subagentTiers` then only fills a missing model.
376
+ const routed = await dispatchRouter.route({
377
+ callID: event.id, sessionID: event.sessionID, agent: event.agent, args, tierModel, cfg,
378
+ });
379
+ if (routed.prompt !== undefined) args.prompt = routed.prompt;
380
+ if (routed.agent !== undefined) { args.agent = routed.agent; args.subagent_type = routed.agent; }
381
+ if (routed.model !== undefined) args.model = routed.model;
382
+ if (args.model === undefined && tierModel !== undefined) args.model = tierModel;
287
383
  }
288
- await within(hookContext(event), async () => {
289
- await legacy["tool.execute.before"]?.({ ...event, tool: legacyToolName(event.tool), callID: event.id }, output);
290
- });
291
- const verifying = (output as Record<PropertyKey, unknown>)[TASK_VERIFICATION] === true;
292
- const banner = (output as Record<PropertyKey, unknown>)[DEPTH_BANNER];
293
- if (typeof banner === "string") {
294
- depthBanners.delete(event.id);
295
- depthBanners.set(event.id, banner);
296
- while (depthBanners.size > 1000) depthBanners.delete(depthBanners.keys().next().value!);
297
- }
298
- if (verifying) {
299
- verifyingCalls.add(event.id);
300
- while (verifyingCalls.size > 1000) verifyingCalls.delete(verifyingCalls.values().next().value!);
301
- }
302
- if (event.tool === "subagent" && typeof output.args?.prompt === "string") {
303
- const prompt = typeof original?.prompt === "string" ? original.prompt : typeof original?.description === "string" ? original.description : "";
304
- output.args.prompt = translateAdded(prompt, output.args.prompt);
384
+ // After routing: the prompt the legacy hook starts from is the one the engine left (a stripped route line is not "added" text).
385
+ try {
386
+ const original = args && typeof args === "object" ? { ...args } : args;
387
+ const output = { args };
388
+ await within(hookContext(event), async () => {
389
+ await legacy["tool.execute.before"]?.({ ...event, tool: legacyToolName(event.tool), callID: event.id }, output);
390
+ });
391
+ const verifying = (output as Record<PropertyKey, unknown>)[TASK_VERIFICATION] === true;
392
+ const banner = (output as Record<PropertyKey, unknown>)[DEPTH_BANNER];
393
+ if (typeof banner === "string") {
394
+ depthBanners.delete(event.id);
395
+ depthBanners.set(event.id, banner);
396
+ while (depthBanners.size > 1000) depthBanners.delete(depthBanners.keys().next().value!);
397
+ }
398
+ if (verifying) {
399
+ verifyingCalls.add(event.id);
400
+ while (verifyingCalls.size > 1000) verifyingCalls.delete(verifyingCalls.values().next().value!);
401
+ }
402
+ if (event.tool === "subagent" && typeof output.args?.prompt === "string") {
403
+ const prompt = typeof original?.prompt === "string" ? original.prompt : typeof original?.description === "string" ? original.description : "";
404
+ output.args.prompt = translateAdded(prompt, output.args.prompt);
405
+ }
406
+ event.input = nativeArgs(event.tool, output.args, original, verifying);
407
+ } catch (error) {
408
+ dispatchRouter.onCallFinished(event.id); // the hook chain rejected the call: it will never reach execute.after (2.2)
409
+ throw error;
305
410
  }
306
- event.input = nativeArgs(event.tool, output.args, original, verifying);
411
+ // The input the host will execute (after the legacy hook): the dispatch is registered for ingestion from it, not from what the engine decided (2.2).
412
+ dispatchRouter.commit(event.id, event.input);
307
413
  }));
308
414
  registrations.push(await ctx.tool.hook("execute.after", async (event) => {
415
+ // 2.2: the result names the child. A dispatch still waiting for it is registered under it, and a heuristic claim that picked
416
+ // the wrong child is corrected here, before the legacy hook below records the verdict. A call without a result is just dropped.
417
+ dispatchRouter.onCallResult(event.id, event.status === "completed" ? childSessionOf(event.result) : null);
309
418
  const banner = depthBanners.get(event.id);
310
419
  depthBanners.delete(event.id);
311
420
  const verifying = verifyingCalls.delete(event.id);
@@ -378,7 +487,25 @@ export async function registerV2Hooks(
378
487
  if (abort.signal.aborted) break;
379
488
  try {
380
489
  const data = event.data as Record<string, any>;
381
- if (event.type === "session.deleted") runtime?.forgetSession?.(data.sessionID);
490
+ if (event.type === "session.step.ended" || event.type === "session.step.failed") {
491
+ // Cost and tokens of a registered child dispatch (ingest ignores every other session).
492
+ await ingesting(event.type, () => ingest.onStepEnded(event));
493
+ continue;
494
+ }
495
+ // A new child session: the dispatch the engine routed for it is registered with the 2.1 registry (2.2).
496
+ if (event.type === "session.created") dispatchRouter.onSessionCreated({ sessionID: data.sessionID, parentID: data.parentID, agent: data.agent, title: data.title });
497
+ if (event.type === "session.deleted") {
498
+ runtime?.forgetSession?.(data.sessionID);
499
+ await ingesting("session.deleted", () => ingest.onSessionGone(data.sessionID));
500
+ } else if (FLUSH_EVENT_TYPES.has(event.type)) {
501
+ // The v2 equivalents of session.idle: coalesced, throttled flush (D15); never awaited.
502
+ await ingesting(event.type, () => {
503
+ // The child's attempt is over: fold it before the flush that persists it.
504
+ if (EXECUTION_END_TYPES.has(event.type)) ingest.onExecutionEnded(data.sessionID, event.id);
505
+ ingest.sweep();
506
+ ingest.requestFlush();
507
+ });
508
+ }
382
509
  if (event.type === "session.text.ended") {
383
510
  const output = { text: data.text };
384
511
  await legacy["experimental.text.complete"]?.({ sessionID: data.sessionID, messageID: data.assistantMessageID }, output);
@@ -0,0 +1,263 @@
1
+ /**
2
+ * Phase 2.3: what the delegate runner tells the telemetry about each ladder attempt.
3
+ *
4
+ * Every attempt of a `delegate` ladder (the first dispatch, a variant step, a plain retry, an escalation) is
5
+ * its own attempt in the 2.1 dispatch-facts registry, under the attempt's step label, so that
6
+ *
7
+ * - `session.step.ended` events, verdicts and false refusals land on the right `(class x agent x model#variant)`
8
+ * key (a resumed child that moved to a higher variant is a different key from the attempt before it);
9
+ * - the variant-refusal rule (QA-2.1-R2-3: a refusal that is a variant attempt's first terminal signal is a
10
+ * variant failure) and the ladder's `triedByModel` (A17a) name the same rungs;
11
+ * - the delegate ladder's last-step context (`lastStepContext`, D11) is tracked for the child.
12
+ *
13
+ * and, when `routing.engine` is not `static`, enqueues one `DecisionRow` per attempt (1.3 handoff to 2.3):
14
+ * `step` in `dispatch | variant | retry | escalate`, `resume` per D11/A5, `chosen` = the ladder's pick,
15
+ * `best` null, `switched` false. Rows go through the process-wide outcomes bundle (A3), never on a hot path:
16
+ * `enqueue` is an O(1) push and the flusher writes at idle/deleted or every 30 s (D15).
17
+ *
18
+ * Everything here is best effort: a failure is logged and never reaches the delegation.
19
+ */
20
+
21
+ import { randomBytes } from "node:crypto";
22
+ import type { RouterConfig, RouterHost } from "../router/config";
23
+ import { resolveRouting } from "../router/config";
24
+ import { rememberDispatch, type DetectionDepth } from "../router/sessions";
25
+ import { classify, type TaskFacts } from "../routing/classify";
26
+ import { acquireOutcomes } from "../routing/outcomes";
27
+ import { ingestSettings, type IngestSettings } from "../routing/outcomes/ingest";
28
+ import type { AcquireOutcomesOptions } from "../routing/outcomes";
29
+ import {
30
+ LOG_ROW_VERSION,
31
+ classifyAgentOrigin,
32
+ makeKey,
33
+ normalizeVariant,
34
+ safeNow,
35
+ type Clock,
36
+ type DecisionFacts,
37
+ type DecisionRow,
38
+ type OutcomeLogger,
39
+ type OutcomesBundle,
40
+ } from "../routing/outcomes/types";
41
+ import type { AttemptPlan } from "./resume";
42
+
43
+ /** What one ladder attempt registers. */
44
+ export interface AttemptRecord {
45
+ /** The child the attempt runs on (created, or the resumed one). */
46
+ readonly childSessionID: string;
47
+ /** The orchestrator session that called `delegate`. */
48
+ readonly parentSessionID: string | null;
49
+ readonly plan: AttemptPlan;
50
+ /** The configuration this delegation runs under (the runner's hot-reloaded `activeCfg`); default: the recorder's own. */
51
+ readonly config?: RouterConfig;
52
+ /** Typed facts of the delegated task (rules classifier). */
53
+ readonly facts: DecisionFacts;
54
+ /** The delegation's verification depth, from its `[acceptance]` block. */
55
+ readonly acceptance: DetectionDepth | null;
56
+ /** True when the attempt runs on a child that already existed. */
57
+ readonly resumed: boolean;
58
+ }
59
+
60
+ export interface AttemptRecorder {
61
+ /** True when attempts are worth registering for the engine alone (any mode but `static`, on v2). */
62
+ engineLive(config?: RouterConfig): boolean;
63
+ /** Register now; optionally defer the row until the returned idempotent confirmation is called. Never throws. */
64
+ record(attempt: AttemptRecord, deferRow?: boolean): () => void;
65
+ /** Opportunistic maintenance: releases the outcomes bundle when the engine went back to `static`. */
66
+ sweep(): void;
67
+ /** Releases this recorder's reference to the outcomes bundle. Never rejects. */
68
+ dispose(): Promise<void>;
69
+ }
70
+
71
+ export interface AttemptRecorderDeps {
72
+ readonly host: RouterHost;
73
+ /** The live configuration (hot reload swaps the object). */
74
+ readonly config: () => RouterConfig;
75
+ readonly logger: OutcomeLogger;
76
+ readonly now?: Clock;
77
+ /** Seam over `acquireOutcomes` (tests). */
78
+ readonly acquire?: (options: AcquireOutcomesOptions) => OutcomesBundle;
79
+ }
80
+
81
+ const NONCE = randomBytes(4).toString("hex");
82
+ let decisionSeq = 0;
83
+
84
+ function describe(error: unknown): string {
85
+ return error instanceof Error ? error.message : String(error);
86
+ }
87
+
88
+ /** `provider/model` of a plan, or null when the tier's model did not resolve. */
89
+ function modelOf(plan: AttemptPlan): string | null {
90
+ return plan.model === undefined ? null : `${plan.model.providerID}/${plan.model.modelID}`;
91
+ }
92
+
93
+ /** The decision row's `reason`: the ladder's step, the D11 verdict with both numbers, and any runner override. */
94
+ export function describeAttempt(attempt: AttemptRecord): string {
95
+ const { plan } = attempt;
96
+ const parts = [`ladder ${plan.step} on ${plan.tier}`, attempt.resumed ? "resumed child" : "fresh child"];
97
+ const basis = plan.resumeBasis;
98
+ if (basis !== undefined) {
99
+ const numbers = [
100
+ basis.tokens === null ? null : `tokens=${basis.tokens}`,
101
+ basis.budget === null ? null : `budget=${basis.budget}`,
102
+ basis.threshold === null ? null : `threshold=${basis.threshold}`,
103
+ ].filter((part): part is string => part !== null);
104
+ parts.push(`D11 ${basis.reason}${numbers.length === 0 ? "" : ` (${numbers.join(" ")})`}`);
105
+ }
106
+ if (plan.fresh !== undefined) parts.push(`runner: fresh (${plan.fresh})`);
107
+ if (plan.costRatio !== undefined) parts.push(`rung costRatio ${plan.costRatio}`);
108
+ return parts.join("; ");
109
+ }
110
+
111
+ export function createAttemptRecorder(deps: AttemptRecorderDeps): AttemptRecorder {
112
+ const now: Clock = deps.now ?? Date.now;
113
+ const acquire = deps.acquire ?? acquireOutcomes;
114
+ let held: { readonly dir: string; readonly bundle: OutcomesBundle } | null = null;
115
+ let disposed = false;
116
+
117
+ const settingsNow = (config?: RouterConfig): IngestSettings | null => ingestSettings(config ?? deps.config(), deps.host);
118
+
119
+ const release = (): void => {
120
+ const current = held;
121
+ held = null;
122
+ if (current !== null) void current.bundle.release().catch((error: unknown) => deps.logger.warn("[router] ladder attempts: releasing the outcomes bundle failed", { error: describe(error) }));
123
+ };
124
+
125
+ const bundleFor = (settings: IngestSettings): OutcomesBundle | null => {
126
+ if (disposed) return null;
127
+ if (held !== null && held.dir === settings.outcomesDir) return held.bundle;
128
+ release();
129
+ const bundle = acquire({ dir: settings.outcomesDir, tuning: settings.tuning, logger: deps.logger });
130
+ held = { dir: settings.outcomesDir, bundle };
131
+ return bundle;
132
+ };
133
+
134
+ return {
135
+ engineLive: (config) => {
136
+ try {
137
+ return settingsNow(config) !== null;
138
+ } catch (error) {
139
+ deps.logger.warn("[router] ladder attempts: reading the routing settings failed", { error: describe(error) });
140
+ return false;
141
+ }
142
+ },
143
+
144
+ record(attempt, deferRow = false) {
145
+ try {
146
+ const { plan } = attempt;
147
+ const settings = settingsNow(attempt.config);
148
+ const model = modelOf(plan);
149
+ const decisionID = settings === null || model === null ? null : `ladder-${NONCE}-${++decisionSeq}`;
150
+ rememberDispatch(attempt.childSessionID, {
151
+ facts: attempt.facts,
152
+ agent: plan.agent,
153
+ model,
154
+ variant: plan.model?.variant ?? null,
155
+ tier: plan.tier,
156
+ acceptance: attempt.acceptance,
157
+ parentSessionID: attempt.parentSessionID,
158
+ decisionID,
159
+ step: plan.step,
160
+ // Registered with ingestion off (engine static): no instance may score it (QA-2.3-6).
161
+ outcomes: settings !== null,
162
+ }, safeNow(now));
163
+ if (settings === null || decisionID === null || plan.model === undefined) return () => undefined;
164
+ const bundle = bundleFor(settings);
165
+ if (bundle === null) return () => undefined;
166
+ const variant = normalizeVariant(plan.model.variant);
167
+ const origin = classifyAgentOrigin(plan.agent, settings.routerAgentIds);
168
+ const key = makeKey(attempt.facts.class, { origin, id: plan.agent }, plan.model.providerID, plan.model.modelID, variant);
169
+ const chosen = { key, agent: plan.agent, origin, model: `${plan.model.providerID}/${plan.model.modelID}`, variant };
170
+ const row: DecisionRow = {
171
+ v: LOG_ROW_VERSION,
172
+ ts: new Date(safeNow(now)).toISOString(),
173
+ sessionID: attempt.parentSessionID ?? "",
174
+ kind: "decision",
175
+ decisionID,
176
+ mode: settings.engine,
177
+ childSessionID: attempt.childSessionID,
178
+ facts: attempt.facts,
179
+ chosen,
180
+ best: null,
181
+ switched: false,
182
+ pinned: false,
183
+ unit: "ratio",
184
+ costs: {},
185
+ confidence: attempt.facts.confidence,
186
+ reason: describeAttempt(attempt),
187
+ step: plan.step,
188
+ resume: attempt.resumed,
189
+ };
190
+ let confirmed = false;
191
+ const confirm = (): void => {
192
+ if (confirmed) return;
193
+ confirmed = true;
194
+ try {
195
+ bundle.flusher.enqueue(row);
196
+ } catch (error) {
197
+ deps.logger.warn("[router] ladder attempts: enqueueing an attempt failed", { error: describe(error), child: attempt.childSessionID });
198
+ }
199
+ };
200
+ if (!deferRow) confirm();
201
+ return confirm;
202
+ } catch (error) {
203
+ deps.logger.warn("[router] ladder attempts: registering an attempt failed", { error: describe(error), child: attempt.childSessionID });
204
+ return () => undefined;
205
+ }
206
+ },
207
+
208
+ sweep() {
209
+ try {
210
+ if (held !== null && settingsNow() === null) release();
211
+ } catch (error) {
212
+ deps.logger.warn("[router] ladder attempts: sweep failed", { error: describe(error) });
213
+ }
214
+ },
215
+
216
+ async dispose() {
217
+ disposed = true;
218
+ const current = held;
219
+ held = null;
220
+ if (current === null) return;
221
+ try {
222
+ await current.bundle.release();
223
+ } catch (error) {
224
+ deps.logger.warn("[router] ladder attempts: releasing the outcomes bundle failed", { error: describe(error) });
225
+ }
226
+ },
227
+ };
228
+ }
229
+
230
+ /** What the rules classifier says about a delegated task, for the registry and the decision rows. */
231
+ export interface DelegationFacts {
232
+ readonly facts: TaskFacts;
233
+ readonly acceptance: DetectionDepth | null;
234
+ }
235
+
236
+ /**
237
+ * Rules-only facts of a delegation (D3: no backend call, nothing leaves the machine, never throws). The
238
+ * delegate tool has no orchestrator-chosen class, so the class comes from the same rules `/annotate-plan` and
239
+ * the dispatch hook start from; a class below `routing.minClassConfidence` is simply not recorded by the ingest.
240
+ */
241
+ export async function classifyDelegation(
242
+ cfg: RouterConfig,
243
+ host: RouterHost,
244
+ task: string,
245
+ acceptance: string | undefined,
246
+ logger: OutcomeLogger,
247
+ ): Promise<DelegationFacts | null> {
248
+ try {
249
+ const routing = resolveRouting(cfg, host);
250
+ const prompt = acceptance === undefined || acceptance.trim() === "" ? task : `${task}\n\n${acceptance}`;
251
+ const result = await classify({ prompt }, {
252
+ cfg,
253
+ settings: { ...routing.classifier, backend: "rules" },
254
+ minClassConfidence: routing.minClassConfidence,
255
+ backend: null,
256
+ logger: { warn: (message: string) => logger.warn(message) },
257
+ });
258
+ return { facts: result.facts, acceptance: result.detection };
259
+ } catch (error) {
260
+ logger.warn("[router] ladder attempts: classifying the delegation failed", { error: describe(error) });
261
+ return null;
262
+ }
263
+ }