opencode-model-router 2.2.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.
- package/CHANGELOG.md +65 -0
- package/README.md +35 -3
- package/package.json +4 -1
- package/src/commands/output.ts +4 -1
- package/src/compat/child-session.ts +43 -0
- package/src/compat/v2-client.ts +107 -7
- package/src/compat/v2-hooks.ts +118 -31
- package/src/escalate/attempt-recorder.ts +263 -0
- package/src/escalate/ladder.ts +484 -10
- package/src/escalate/resume.ts +208 -0
- package/src/escalate/variants.ts +391 -0
- package/src/index.ts +486 -38
- package/src/router/build-info.ts +151 -0
- package/src/router/config.ts +1365 -19
- package/src/router/protocol.ts +47 -0
- package/src/router/sessions.ts +441 -9
- package/src/routing/advisor/findings.ts +706 -0
- package/src/routing/advisor/index.ts +606 -0
- package/src/routing/classify/backends/host.ts +163 -0
- package/src/routing/classify/backends/openai-compatible.ts +275 -0
- package/src/routing/classify/backends/shared.ts +741 -0
- package/src/routing/classify/backends/typesafe.ts +315 -0
- package/src/routing/classify/fences.ts +96 -0
- package/src/routing/classify/index.ts +576 -0
- package/src/routing/classify/route-line.ts +298 -0
- package/src/routing/classify/rules.ts +607 -0
- package/src/routing/classify/scrub.ts +214 -0
- package/src/routing/classify/state.ts +148 -0
- package/src/routing/classify/text.ts +20 -0
- package/src/routing/classify/types.ts +1280 -0
- package/src/routing/commands/annotate-plan.ts +652 -0
- package/src/routing/commands/stats.ts +131 -0
- package/src/routing/commands/v1-roles.ts +64 -0
- package/src/routing/engine/index.ts +32 -0
- package/src/routing/engine/kernel.ts +597 -0
- package/src/routing/engine/ladders.ts +561 -0
- package/src/routing/engine/plan.ts +404 -0
- package/src/routing/engine/protocol-line.ts +133 -0
- package/src/routing/engine/simulate.ts +167 -0
- package/src/routing/engine/types.ts +270 -0
- package/src/routing/file-lock.ts +53 -0
- package/src/routing/outcomes/beta.ts +141 -0
- package/src/routing/outcomes/cost.ts +313 -0
- package/src/routing/outcomes/index.ts +172 -0
- package/src/routing/outcomes/ingest.ts +812 -0
- package/src/routing/outcomes/persist.ts +1058 -0
- package/src/routing/outcomes/stats.ts +602 -0
- package/src/routing/outcomes/store.ts +653 -0
- package/src/routing/outcomes/types.ts +954 -0
- package/src/routing/wire/dispatch.ts +799 -0
- package/src/routing/wire/hint.ts +208 -0
- package/src/routing/wire/host-info.ts +256 -0
- package/src/routing/wire/runtime.ts +259 -0
- package/src/v2.ts +15 -1
package/src/index.ts
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
import type { Plugin } from "@opencode-ai/plugin";
|
|
2
2
|
import type { RouterPluginInput } from "./compat/child-session";
|
|
3
|
-
import { DEPTH_BANNER, TASK_VERIFICATION } from "./compat/child-session";
|
|
3
|
+
import { DEPTH_BANNER, ResumeRejectedError, TASK_VERIFICATION } from "./compat/child-session";
|
|
4
4
|
|
|
5
5
|
// Imports for internal use within this module
|
|
6
6
|
import {
|
|
@@ -14,7 +14,10 @@ import {
|
|
|
14
14
|
findProjectOverride,
|
|
15
15
|
resolveVerifyBudget,
|
|
16
16
|
resolveDepthLimit,
|
|
17
|
-
|
|
17
|
+
resolveRouting,
|
|
18
|
+
resolveVariantSteps,
|
|
19
|
+
routerStatusLines,
|
|
20
|
+
warnConfigIssues,
|
|
18
21
|
} from "./router/config";
|
|
19
22
|
import type { RouterConfig, TierConfig, Preset, ModeConfig, EffortLevel } from "./router/config";
|
|
20
23
|
import { buildAgentOptions, warnAgentOptionsEffortOnce } from "./router/agent-options";
|
|
@@ -57,6 +60,24 @@ import {
|
|
|
57
60
|
} from "./router/protocol";
|
|
58
61
|
import { resolveEnforcementMode } from "./router/enforcement";
|
|
59
62
|
import { createPluginLogger } from "./router/logger";
|
|
63
|
+
import { createCatalogPricing, createIngest, ingestSettings } from "./routing/outcomes/ingest";
|
|
64
|
+
import type { Ingest } from "./routing/outcomes/ingest";
|
|
65
|
+
import { verdictOf } from "./routing/outcomes/types";
|
|
66
|
+
import { checkpointLine, formatStatsReply, runStatsCommand } from "./routing/commands/stats";
|
|
67
|
+
import { buildAnnotateDirectives } from "./routing/commands/annotate-plan";
|
|
68
|
+
import { applyV1Roles, hasExplicitV1Roles, v1AgentInfos } from "./routing/commands/v1-roles";
|
|
69
|
+
import type { HostAgentInfo } from "./routing/engine/types";
|
|
70
|
+
import { createEngineRuntime } from "./routing/wire/runtime";
|
|
71
|
+
import type { EngineRuntime } from "./routing/wire/runtime";
|
|
72
|
+
import {
|
|
73
|
+
advisorSettings,
|
|
74
|
+
catalogFromProviders,
|
|
75
|
+
createAdvisorNotifier,
|
|
76
|
+
formatFindings,
|
|
77
|
+
hostConfigFromAgents,
|
|
78
|
+
runAdvisor,
|
|
79
|
+
} from "./routing/advisor";
|
|
80
|
+
import type { AdvisorCatalogModel, HostConfigView } from "./routing/advisor";
|
|
60
81
|
import {
|
|
61
82
|
findOrphanedStrongPatterns,
|
|
62
83
|
normalizeCatalog,
|
|
@@ -69,6 +90,8 @@ import {
|
|
|
69
90
|
buildCapBanner,
|
|
70
91
|
DEFAULT_TIER_CAPS,
|
|
71
92
|
READ_ONLY_TOOLS,
|
|
93
|
+
awaitExecutionEnd,
|
|
94
|
+
lastStepContext,
|
|
72
95
|
} from "./router/sessions";
|
|
73
96
|
import type { Cap, SubagentState } from "./router/sessions";
|
|
74
97
|
import { createTrajectoryStore } from "./telemetry/trajectory";
|
|
@@ -100,7 +123,11 @@ import {
|
|
|
100
123
|
buildForcingNote,
|
|
101
124
|
buildAcceptedSuffix,
|
|
102
125
|
} from "./verify/dispatch";
|
|
103
|
-
import { newLadderState, recordAttempt, nextAction, advance, buildEscalatePolicy, formatLadderScorecard } from "./escalate/ladder";
|
|
126
|
+
import { newLadderState, recordAttempt, nextAction, advance, buildEscalatePolicy, formatLadderScorecard, startCostRatio } from "./escalate/ladder";
|
|
127
|
+
import { createCatalogLookup, planFirstAttempt, planNextAttempt } from "./escalate/resume";
|
|
128
|
+
import type { AttemptPlan, CatalogLookup } from "./escalate/resume";
|
|
129
|
+
import { classifyDelegation, createAttemptRecorder } from "./escalate/attempt-recorder";
|
|
130
|
+
import type { AttemptRecorder, DelegationFacts } from "./escalate/attempt-recorder";
|
|
104
131
|
import { createDepthTracker, DEPTH_LOOKUP_RETRY_MS } from "./router/depth";
|
|
105
132
|
import { createDepthGuard } from "./router/depth-guard";
|
|
106
133
|
import { applyEffortOverride, createEffortOverrideStore } from "./escalate/effort-override";
|
|
@@ -195,6 +222,8 @@ function buildRouterOutput(cfg: RouterConfig, args: string, projectDir?: string)
|
|
|
195
222
|
|
|
196
223
|
return buildRouterHelp(
|
|
197
224
|
resolveEnforcementMode({ config: cfg, env: process.env }).mode,
|
|
225
|
+
// `/router stats` is listed only for a config that has a `routing` block: without one `/router` is what it was (QA-2.4-3).
|
|
226
|
+
{ stats: cfg.routing !== undefined },
|
|
198
227
|
);
|
|
199
228
|
}
|
|
200
229
|
|
|
@@ -373,6 +402,10 @@ const ModelRouterPlugin: Plugin = async (ctx: RouterPluginInput) => {
|
|
|
373
402
|
() => { sweepVerification(); },
|
|
374
403
|
// 2.4.2b: TTL eviction and reaping of the pending registry (pending.ts R7; no timer of its own).
|
|
375
404
|
() => { pending.sweep(); },
|
|
405
|
+
// 2.1.2: expired dispatch registrations and idle open outcome attempts (v2 only; `ingest` is declared below).
|
|
406
|
+
() => { ingest?.sweep(); },
|
|
407
|
+
// 2.3: release the ladder-attempt recorder's outcomes bundle once the engine is static again.
|
|
408
|
+
() => { attemptRecorder?.sweep(); },
|
|
376
409
|
]);
|
|
377
410
|
|
|
378
411
|
// Layer-2's impure corner: exec, fs, and the opencode client, built once and
|
|
@@ -383,6 +416,27 @@ const ModelRouterPlugin: Plugin = async (ctx: RouterPluginInput) => {
|
|
|
383
416
|
// has no /log endpoint. See src/router/logger.ts.
|
|
384
417
|
const logger = createPluginLogger(ctx.client);
|
|
385
418
|
const routerWarn = { warn: (message: string) => logger.warn(message) };
|
|
419
|
+
// M6 (2.1.3, QA-2.1-7): the one telemetry ingest of this plugin instance. v2 only (D1); every call is a no-op unless
|
|
420
|
+
// routing.engine != static. Verdicts and false refusals come from the hooks below; the v2 adapter receives this same
|
|
421
|
+
// instance through `routerOnIngest` and feeds it the step and session events, so there is a single settings source.
|
|
422
|
+
const ingestAbort = new AbortController();
|
|
423
|
+
const ingest: Ingest | undefined = ctx.routerHost === "v2" ? (() => {
|
|
424
|
+
const core = createIngest({
|
|
425
|
+
settings: () => ingestSettings(cfg, "v2"),
|
|
426
|
+
logger,
|
|
427
|
+
...(ctx.routerCatalog
|
|
428
|
+
? { pricing: createCatalogPricing(ctx.routerCatalog, { logger, cacheKey: ctx.directory, signal: ingestAbort.signal }) }
|
|
429
|
+
: {}),
|
|
430
|
+
});
|
|
431
|
+
// Disposing also releases any lookup still waiting for the catalog (QA-2.1-5): shutdown never waits for it.
|
|
432
|
+
return { ...core, dispose: async () => { ingestAbort.abort(); await core.dispose(); } };
|
|
433
|
+
})() : undefined;
|
|
434
|
+
if (ingest) ctx.routerOnIngest?.(ingest);
|
|
435
|
+
// Phase 2.3: what the delegate ladder tells the telemetry about each attempt (registry entry + decision row). v2 only (D1).
|
|
436
|
+
const attemptRecorder: AttemptRecorder | undefined = ctx.routerHost === "v2"
|
|
437
|
+
? createAttemptRecorder({ host: "v2", config: () => cfg, logger })
|
|
438
|
+
: undefined;
|
|
439
|
+
resolveRouting(cfg, ctx.routerHost === "v2" ? "v2" : "v1", logger); // v1 + engine != static: log the notice once, at startup (QA-1.1-8)
|
|
386
440
|
const depthTracker = createDepthTracker({
|
|
387
441
|
async getParent(id) {
|
|
388
442
|
if (sessionRootMemo.get(id) === true) return null;
|
|
@@ -480,19 +534,124 @@ const ModelRouterPlugin: Plugin = async (ctx: RouterPluginInput) => {
|
|
|
480
534
|
// current plugin lifetime (i.e., until OpenCode is restarted).
|
|
481
535
|
let bypassed = false;
|
|
482
536
|
|
|
483
|
-
|
|
537
|
+
warnConfigIssues(cfg, logger);
|
|
484
538
|
|
|
485
539
|
// Fetch and normalize opencode's live provider/model catalog. Best-effort:
|
|
486
540
|
// returns null when the client call fails, e.g. the server is not ready yet.
|
|
487
541
|
// The pure analysis (validateModels) lives in src/router/catalog.ts.
|
|
488
|
-
const
|
|
542
|
+
const fetchCatalogRaw = async (): Promise<{ catalog: Catalog; raw: unknown } | null> => {
|
|
489
543
|
try {
|
|
490
544
|
const res: any = await ctx.client.config.providers();
|
|
491
|
-
return normalizeCatalog(res?.data);
|
|
545
|
+
return { catalog: normalizeCatalog(res?.data), raw: res?.data };
|
|
492
546
|
} catch {
|
|
493
547
|
return null;
|
|
494
548
|
}
|
|
495
549
|
};
|
|
550
|
+
const fetchCatalog = async (): Promise<Catalog | null> => (await fetchCatalogRaw())?.catalog ?? null;
|
|
551
|
+
|
|
552
|
+
// M8 (Phase 2.4): the cost doctor reads the host's agents and model catalog (v2 only, D1). Each call is bounded and failing
|
|
553
|
+
// one only leaves the checks that need it silent; nothing here ever throws into a session.
|
|
554
|
+
// The orchestrator's model as the last root-session turn reported it: the host's title pick depends on its provider (QA-2.4-1).
|
|
555
|
+
let lastPrimary: { providerID: string; modelID: string | null } | null = null;
|
|
556
|
+
const ADVISOR_HOST_TIMEOUT_MS = 3_000;
|
|
557
|
+
// The catalog comes from `config.providers()` (the call `/router` already makes for the model check, enriched with cost and capabilities
|
|
558
|
+
// by the v2 adapter), so the doctor does not ask the host for the model list a second time (QA-2.4-3). `prefetched` is that call's result
|
|
559
|
+
// when the caller already has it.
|
|
560
|
+
const gatherAdvisorInputs = async (
|
|
561
|
+
prefetched?: { raw: unknown } | null,
|
|
562
|
+
): Promise<{ host: HostConfigView | null; catalog: AdvisorCatalogModel[] | null }> => {
|
|
563
|
+
const attempt = async <T>(label: string, call: (() => Promise<T>) | undefined): Promise<T | null> => {
|
|
564
|
+
if (call === undefined) return null;
|
|
565
|
+
try {
|
|
566
|
+
return await withTimeout(call(), ADVISOR_HOST_TIMEOUT_MS, label);
|
|
567
|
+
} catch (error) {
|
|
568
|
+
logger.warn(`[router] cost doctor: the ${label} is unavailable`, { error: describeError(error) });
|
|
569
|
+
return null;
|
|
570
|
+
}
|
|
571
|
+
};
|
|
572
|
+
const [agents, providers] = await Promise.all([
|
|
573
|
+
attempt("host agent list", ctx.routerAgents),
|
|
574
|
+
prefetched !== undefined ? Promise.resolve(prefetched) : attempt("model catalog", fetchCatalogRaw),
|
|
575
|
+
]);
|
|
576
|
+
return {
|
|
577
|
+
host: agents === null ? null : hostConfigFromAgents(agents, lastPrimary),
|
|
578
|
+
catalog: providers === null ? null : catalogFromProviders(providers.raw),
|
|
579
|
+
};
|
|
580
|
+
};
|
|
581
|
+
const advisorNotifier = ctx.routerHost === "v2"
|
|
582
|
+
? createAdvisorNotifier({ settings: () => advisorSettings(cfg, "v2", { project: projectDir }), config: () => cfg, gather: gatherAdvisorInputs, logger })
|
|
583
|
+
: undefined;
|
|
584
|
+
// `/annotate-plan` (Phase 2.4.4): its own engine runtime (agent list, catalog, classifier backend, outcome store), created on the first use
|
|
585
|
+
// and only on v2; with `routing.engine: static` its `prepare()` answers null before any host call, store or file.
|
|
586
|
+
let annotateRuntime: EngineRuntime | undefined;
|
|
587
|
+
const annotatePlanRuntime = (): EngineRuntime | undefined => {
|
|
588
|
+
if (ctx.routerHost !== "v2" || ctx.routerAgents === undefined || ctx.routerCatalog === undefined) return undefined;
|
|
589
|
+
annotateRuntime ??= createEngineRuntime({
|
|
590
|
+
loadConfig: () => cfg,
|
|
591
|
+
listAgents: ctx.routerAgents,
|
|
592
|
+
listModels: ctx.routerCatalog,
|
|
593
|
+
...(ctx.routerGenerate === undefined ? {} : { generate: ctx.routerGenerate }),
|
|
594
|
+
logger,
|
|
595
|
+
});
|
|
596
|
+
return annotateRuntime;
|
|
597
|
+
};
|
|
598
|
+
// v1 only (A28): the host's agent list for the text-only roles line, read through `client.app.agents()` and never fetched unless
|
|
599
|
+
// `routing.roles` is set explicitly. It is refreshed IN THE BACKGROUND (QA-2.4-13): a turn never waits for it. The first turn after start
|
|
600
|
+
// has no list yet and gets the baseline prompt; later turns use the last list, stale while the next one is fetched (every minute). A
|
|
601
|
+
// failed refresh keeps the last list and is logged; a list that was never fetched leaves the line as it is without roles.
|
|
602
|
+
const V1_AGENTS_TTL_MS = 60_000;
|
|
603
|
+
let v1Agents: { at: number; infos: HostAgentInfo[] | null } | null = null;
|
|
604
|
+
let v1AgentsRefresh: Promise<void> | null = null;
|
|
605
|
+
const refreshV1Agents = (): void => {
|
|
606
|
+
if (v1AgentsRefresh !== null) return;
|
|
607
|
+
const run = (async (): Promise<void> => {
|
|
608
|
+
try {
|
|
609
|
+
const res = await withTimeout(Promise.resolve(ctx.client.app.agents()), 2_000, "v1 agent list");
|
|
610
|
+
const data: unknown = (res as { data?: unknown } | undefined)?.data;
|
|
611
|
+
v1Agents = { at: Date.now(), infos: Array.isArray(data) ? v1AgentInfos(data) : (v1Agents?.infos ?? null) };
|
|
612
|
+
} catch (error) {
|
|
613
|
+
logger.warn("[router] routing.roles: the host's agent list is unavailable; the R: line keeps the last list, or stays without roles", { error: describeError(error) });
|
|
614
|
+
v1Agents = { at: Date.now(), infos: v1Agents?.infos ?? null }; // keep serving the stale list; try again after the interval
|
|
615
|
+
}
|
|
616
|
+
})().finally(() => {
|
|
617
|
+
if (v1AgentsRefresh === run) v1AgentsRefresh = null;
|
|
618
|
+
});
|
|
619
|
+
v1AgentsRefresh = run;
|
|
620
|
+
};
|
|
621
|
+
/** The last known v1 agent list (possibly stale, possibly `null`), starting a background refresh when it is due. Synchronous. */
|
|
622
|
+
const v1AgentsNow = (): HostAgentInfo[] | null => {
|
|
623
|
+
if (v1Agents === null || Date.now() - v1Agents.at >= V1_AGENTS_TTL_MS) refreshV1Agents();
|
|
624
|
+
return v1Agents?.infos ?? null;
|
|
625
|
+
}; /** Hand a notice to the orchestrator as a synthetic transcript entry (v2), or log it where there is no such call. Never throws, never waits. */
|
|
626
|
+
const deliverAdvisorNotice = (sessionID: string, notice: string): void => {
|
|
627
|
+
const synthetic = ctx.routerSynthetic;
|
|
628
|
+
if (synthetic === undefined) {
|
|
629
|
+
logger.warn(notice); // no synthetic-message call on this host: the log line is the whole delivery
|
|
630
|
+
return;
|
|
631
|
+
}
|
|
632
|
+
const text = `Cost doctor notice for the user (say it once, in one short sentence, then carry on with the task):\n${notice}`;
|
|
633
|
+
void Promise.resolve()
|
|
634
|
+
.then(() => synthetic({ sessionID, text, description: "Model router cost doctor" }))
|
|
635
|
+
.catch((error: unknown) => {
|
|
636
|
+
logger.warn("[router] cost doctor: notice not delivered", { error: describeError(error) });
|
|
637
|
+
});
|
|
638
|
+
};
|
|
639
|
+
/** The `/router` section "Cost doctor" (on demand: runs the checks now, writes nothing). */
|
|
640
|
+
const buildCostDoctorLines = async (prefetched?: { raw: unknown } | null): Promise<string[]> => {
|
|
641
|
+
const routing = resolveRouting(cfg, "v2");
|
|
642
|
+
if (!routing.advisor.enabled) return ["Cost doctor: disabled (routing.advisor.enabled is false)."];
|
|
643
|
+
const { host, catalog } = await gatherAdvisorInputs(prefetched);
|
|
644
|
+
const lines = formatFindings(runAdvisor(cfg, host, catalog, logger), {
|
|
645
|
+
hostKnown: host !== null,
|
|
646
|
+
catalogKnown: catalog !== null && catalog.length > 0,
|
|
647
|
+
primaryKnown: lastPrimary !== null,
|
|
648
|
+
});
|
|
649
|
+
// Phase 2.3 handoff (decision 16): a ladder row's confidence is not the evidence share the dispatch rows carry.
|
|
650
|
+
if (routing.engine !== "static") {
|
|
651
|
+
lines.push("Decision log: a ladder-attempt row's confidence is the delegation's class confidence; a dispatch row's is the class confidence scaled by the winner's evidence (n/(n+5)).");
|
|
652
|
+
}
|
|
653
|
+
return lines;
|
|
654
|
+
};
|
|
496
655
|
|
|
497
656
|
// Deferred passive catalog check. The first orchestrator turn only STARTS the
|
|
498
657
|
// fetch (fire-and-forget, never awaited on the chat.message hot path) and
|
|
@@ -562,6 +721,74 @@ const ModelRouterPlugin: Plugin = async (ctx: RouterPluginInput) => {
|
|
|
562
721
|
return (await lookupRootSession(sessionID)) === true;
|
|
563
722
|
};
|
|
564
723
|
|
|
724
|
+
/**
|
|
725
|
+
* Phase 2.3: the host model catalog as the delegate ladder reads it (variants and limits per model). Best effort: a
|
|
726
|
+
* missing, failing or slow catalog is `undefined`, and the ladder then behaves exactly as without variant info
|
|
727
|
+
* (fresh sessions, tier ratios). QA-2.3-3: the answer, positive or negative, is cached for the TTL; delegations that
|
|
728
|
+
* ask while a load is running share it; a call that outlived its timeout is not repeated behind itself (a late answer
|
|
729
|
+
* still fills the cache); and a failure is logged once per streak, until a load succeeds. So with a hung catalog the
|
|
730
|
+
* first delegation waits for the timeout and every later one answers at once.
|
|
731
|
+
*/
|
|
732
|
+
/** How long a failed ladder attempt waits for its child's execution end before it starts fresh (QA-2.3-2). */
|
|
733
|
+
const RESUME_END_WAIT_MS = 1_000;
|
|
734
|
+
const RUNNER_CATALOG_TTL_MS = 15_000;
|
|
735
|
+
const RUNNER_CATALOG_TIMEOUT_MS = 3_000;
|
|
736
|
+
/** A catalog call still pending after this long is abandoned: a new one may start behind it. */
|
|
737
|
+
const RUNNER_CATALOG_ABANDON_MS = 60_000;
|
|
738
|
+
/** The last answer, valid for the TTL; `lookup` undefined = the catalog was unavailable. */
|
|
739
|
+
let runnerCatalog: { at: number; lookup: CatalogLookup | undefined } | undefined;
|
|
740
|
+
/** The load in progress (bounded by the timeout), shared by every delegation that asks meanwhile. */
|
|
741
|
+
let runnerCatalogLoad: Promise<CatalogLookup | undefined> | undefined;
|
|
742
|
+
/** When the outstanding `routerCatalog()` call started; it may outlive its timeout. */
|
|
743
|
+
let runnerCatalogCallAt: number | undefined;
|
|
744
|
+
/** Id of the latest call (QA-2.3-R2-6): an abandoned call that settles late must not clear the state of a newer one. */
|
|
745
|
+
let runnerCatalogCallId = 0;
|
|
746
|
+
let runnerCatalogFailing = false;
|
|
747
|
+
const runnerCatalogFailed = (error: unknown): undefined => {
|
|
748
|
+
runnerCatalog = { at: Date.now(), lookup: undefined };
|
|
749
|
+
if (!runnerCatalogFailing) {
|
|
750
|
+
runnerCatalogFailing = true;
|
|
751
|
+
logger.warn("[router] ladder: the model catalog is unavailable; variant steps and resume are off until it answers", { error: describeError(error) });
|
|
752
|
+
}
|
|
753
|
+
return undefined;
|
|
754
|
+
};
|
|
755
|
+
const loadRunnerCatalog = (): Promise<CatalogLookup | undefined> => {
|
|
756
|
+
const list = ctx.routerCatalog;
|
|
757
|
+
if (!list) return Promise.resolve(undefined);
|
|
758
|
+
const nowMs = Date.now();
|
|
759
|
+
if (runnerCatalog !== undefined && nowMs - runnerCatalog.at < RUNNER_CATALOG_TTL_MS) return Promise.resolve(runnerCatalog.lookup);
|
|
760
|
+
if (runnerCatalogLoad !== undefined) return runnerCatalogLoad;
|
|
761
|
+
if (runnerCatalogCallAt !== undefined && nowMs - runnerCatalogCallAt < RUNNER_CATALOG_ABANDON_MS) {
|
|
762
|
+
// An earlier call timed out and is still outstanding: no second `list()` behind it.
|
|
763
|
+
runnerCatalog = { at: nowMs, lookup: undefined };
|
|
764
|
+
return Promise.resolve(undefined);
|
|
765
|
+
}
|
|
766
|
+
runnerCatalogCallAt = nowMs;
|
|
767
|
+
const callId = ++runnerCatalogCallId;
|
|
768
|
+
const answer = Promise.resolve().then(() => list()).then(
|
|
769
|
+
(models) => {
|
|
770
|
+
// A late answer is still a catalog, whichever call it answers; only the latest call owns the marker.
|
|
771
|
+
if (callId === runnerCatalogCallId) runnerCatalogCallAt = undefined;
|
|
772
|
+
const lookup = createCatalogLookup(models);
|
|
773
|
+
runnerCatalog = { at: Date.now(), lookup };
|
|
774
|
+
runnerCatalogFailing = false;
|
|
775
|
+
return lookup;
|
|
776
|
+
},
|
|
777
|
+
(error: unknown) => {
|
|
778
|
+
// A failure of an abandoned call says nothing about the newer one: leave its marker and the cache alone.
|
|
779
|
+
if (callId !== runnerCatalogCallId) return undefined;
|
|
780
|
+
runnerCatalogCallAt = undefined;
|
|
781
|
+
return runnerCatalogFailed(error);
|
|
782
|
+
},
|
|
783
|
+
);
|
|
784
|
+
const load: Promise<CatalogLookup | undefined> = withTimeout(answer, RUNNER_CATALOG_TIMEOUT_MS, "model catalog")
|
|
785
|
+
.catch((error: unknown) => runnerCatalogFailed(error))
|
|
786
|
+
.finally(() => {
|
|
787
|
+
if (runnerCatalogLoad === load) runnerCatalogLoad = undefined;
|
|
788
|
+
});
|
|
789
|
+
runnerCatalogLoad = load;
|
|
790
|
+
return load;
|
|
791
|
+
};
|
|
565
792
|
return {
|
|
566
793
|
// Warnings post to /log fire-and-forget, which loses the message when the
|
|
567
794
|
// process is about to exit — `opencode run` and `opencode debug` are short
|
|
@@ -569,12 +796,18 @@ const ModelRouterPlugin: Plugin = async (ctx: RouterPluginInput) => {
|
|
|
569
796
|
// that dispose is both called and awaited, so flushing here is enough.
|
|
570
797
|
dispose: async () => {
|
|
571
798
|
stopReferenceGc();
|
|
799
|
+
// Stop new advisor work and finish state/claim writes and lock removal before teardown.
|
|
800
|
+
await advisorNotifier?.dispose();
|
|
572
801
|
// 2.4.5: abort a background run and drop its queue and notices before the registry goes.
|
|
573
802
|
background?.dispose();
|
|
574
803
|
// 2.4.2b: evict every pending delegation; in-flight router_verify runs resolve (pending.ts R5).
|
|
575
804
|
pending.dispose();
|
|
576
805
|
// 2.2.3: settle batched testsPass requests and kill running batches (never rejects).
|
|
577
806
|
await disposeVerification();
|
|
807
|
+
// 2.1.3: flush and release the outcome bundle held by this instance (never rejects).
|
|
808
|
+
await ingest?.dispose();
|
|
809
|
+
await annotateRuntime?.dispose();
|
|
810
|
+
await attemptRecorder?.dispose();
|
|
578
811
|
await logger.flush();
|
|
579
812
|
},
|
|
580
813
|
tool: {
|
|
@@ -608,7 +841,7 @@ const ModelRouterPlugin: Plugin = async (ctx: RouterPluginInput) => {
|
|
|
608
841
|
acceptance?: string;
|
|
609
842
|
cwd?: string;
|
|
610
843
|
},
|
|
611
|
-
toolCtx?: { sessionID?: string },
|
|
844
|
+
toolCtx?: { sessionID?: string; abort?: AbortSignal },
|
|
612
845
|
): Promise<string> {
|
|
613
846
|
// Every ladder iteration creates its own producer session. Tracked out
|
|
614
847
|
// here (not inside the try) so the finally below can dispose any that an
|
|
@@ -644,7 +877,7 @@ const ModelRouterPlugin: Plugin = async (ctx: RouterPluginInput) => {
|
|
|
644
877
|
let activeCfg = cfg;
|
|
645
878
|
try {
|
|
646
879
|
activeCfg = loadConfig(projectDir);
|
|
647
|
-
|
|
880
|
+
warnConfigIssues(activeCfg, logger);
|
|
648
881
|
} catch {
|
|
649
882
|
activeCfg = cfg;
|
|
650
883
|
}
|
|
@@ -658,9 +891,36 @@ const ModelRouterPlugin: Plugin = async (ctx: RouterPluginInput) => {
|
|
|
658
891
|
});
|
|
659
892
|
const effectiveCwd = typeof args.cwd === "string" && args.cwd.trim() ? args.cwd : dod.cwd;
|
|
660
893
|
|
|
661
|
-
|
|
894
|
+
// Phase 2.3 (D10/D11): on v2 with `variantSteps: auto` (A15: only with a `routing` block) and a catalog,
|
|
895
|
+
// the ladder is session-aware: variant steps on the same model first, resume of the child session
|
|
896
|
+
// under the context threshold. Anything else keeps the policy exactly as before (no variants key).
|
|
897
|
+
const host = ctx.routerHost === "v2" ? "v2" : "v1";
|
|
898
|
+
const variantMode = resolveVariantSteps(activeCfg, host);
|
|
899
|
+
const catalog = host === "v2" && ctx.routerChildRunner && variantMode === "auto" ? await loadRunnerCatalog() : undefined;
|
|
900
|
+
const policy = buildEscalatePolicy(
|
|
901
|
+
activeCfg,
|
|
902
|
+
catalog === undefined
|
|
903
|
+
? undefined
|
|
904
|
+
: {
|
|
905
|
+
host,
|
|
906
|
+
variantSteps: variantMode,
|
|
907
|
+
maxContextFraction: resolveRouting(activeCfg, host).sessionReuse.maxContextFraction,
|
|
908
|
+
catalog,
|
|
909
|
+
warn: (message) => logger.warn(message),
|
|
910
|
+
},
|
|
911
|
+
);
|
|
912
|
+
const sessionAware = policy.variants != null;
|
|
662
913
|
let state = newLadderState(initialTier, policy);
|
|
663
914
|
const tiersForCost: any = getActiveTiers(activeCfg);
|
|
915
|
+
// A17 / QA-1.5-20: the first attempt runs the start tier's base rung; every later one charges its action's rung.
|
|
916
|
+
let rungCost: number | undefined = startCostRatio(policy, state);
|
|
917
|
+
let plan: AttemptPlan = planFirstAttempt(activeCfg, state.currentTier);
|
|
918
|
+
// Registry entry + decision row per attempt: for the ladder's own resume decision (the child's last step
|
|
919
|
+
// context) and for the outcome store. Without a routing block both are off and nothing is registered.
|
|
920
|
+
const recording = attemptRecorder !== undefined && (sessionAware || attemptRecorder.engineLive(activeCfg));
|
|
921
|
+
const delegation: DelegationFacts | null = recording
|
|
922
|
+
? await classifyDelegation(activeCfg, host, args.task, args.acceptance, logger)
|
|
923
|
+
: null;
|
|
664
924
|
|
|
665
925
|
// Independent safety net: even a policy bug cannot loop unbounded.
|
|
666
926
|
const safetyMax =
|
|
@@ -672,7 +932,6 @@ const ModelRouterPlugin: Plugin = async (ctx: RouterPluginInput) => {
|
|
|
672
932
|
|
|
673
933
|
let producerText = "";
|
|
674
934
|
let forcing: string | null = null;
|
|
675
|
-
let effort: EffortLevel | undefined;
|
|
676
935
|
|
|
677
936
|
/**
|
|
678
937
|
* One turn of the escalation ladder: create a producer session, run
|
|
@@ -685,31 +944,53 @@ const ModelRouterPlugin: Plugin = async (ctx: RouterPluginInput) => {
|
|
|
685
944
|
* in the middle of it obscured both halves.
|
|
686
945
|
*/
|
|
687
946
|
const runProducerAttempt = async (
|
|
688
|
-
|
|
947
|
+
attemptPlan: AttemptPlan,
|
|
689
948
|
forcingNote: string | null,
|
|
690
|
-
effort?: EffortLevel,
|
|
691
949
|
): Promise<{
|
|
692
950
|
sessionID: string;
|
|
693
951
|
text: string;
|
|
694
952
|
gateRes: Awaited<ReturnType<typeof accept>>;
|
|
953
|
+
/** The producer errored or timed out: its context is not trusted for a resume (D11). */
|
|
954
|
+
producerFailed: boolean;
|
|
955
|
+
confirmProducer?: () => void;
|
|
695
956
|
} | {
|
|
696
957
|
sessionID: string;
|
|
697
958
|
text: string;
|
|
698
959
|
/** 2.4.2c: deferred; the section 1.5-16 footer to append to the result. */
|
|
699
960
|
deferredFooter: string;
|
|
700
961
|
} | null> => {
|
|
962
|
+
const tier = attemptPlan.tier;
|
|
963
|
+
const effort = attemptPlan.effort;
|
|
701
964
|
const taskText = forcingNote
|
|
702
965
|
? `${scrubText(forcingNote)}\n\n${args.task}`
|
|
703
966
|
: args.task;
|
|
704
967
|
|
|
705
968
|
let producerSid: string | undefined;
|
|
969
|
+
/** The child this attempt actually runs on; a resume the host refuses starts a fresh one instead. */
|
|
970
|
+
let resumeTarget: string | undefined = attemptPlan.resumeSessionID;
|
|
971
|
+
let confirmProducer: (() => void) | undefined;
|
|
706
972
|
const registerProducer = async (sid: string) => {
|
|
707
973
|
producerSid = sid;
|
|
708
|
-
producerSessions.push(sid);
|
|
974
|
+
if (!producerSessions.includes(sid)) producerSessions.push(sid);
|
|
709
975
|
depthTracker.recordPluginChild(sid, toolCtx?.sessionID ?? null);
|
|
710
976
|
if (effort !== undefined) {
|
|
711
977
|
const tierCfg = getActiveTiers(activeCfg)[tier];
|
|
712
|
-
|
|
978
|
+
// The D10 fallback (an invalid variant) delivers the step's effort through the override on a bare
|
|
979
|
+
// model, so the override's tier carries that effort and no variant (effortCeilingFor needs both).
|
|
980
|
+
if (tierCfg) effortOverrides.set(sid, tier, attemptPlan.fresh === "invalid-variant" ? { ...tierCfg, variant: undefined, effort } : tierCfg, effort);
|
|
981
|
+
}
|
|
982
|
+
// Phase 2.3: a distinct attempt in the dispatch registry (with its step label) and, when the engine is
|
|
983
|
+
// live, a decision row. Register before the first step; a resume's row waits for host identity confirmation.
|
|
984
|
+
if (recording && delegation !== null) {
|
|
985
|
+
confirmProducer = attemptRecorder?.record({
|
|
986
|
+
childSessionID: sid,
|
|
987
|
+
parentSessionID: toolCtx?.sessionID ?? null,
|
|
988
|
+
plan: attemptPlan,
|
|
989
|
+
config: activeCfg,
|
|
990
|
+
facts: delegation.facts,
|
|
991
|
+
acceptance: delegation.acceptance,
|
|
992
|
+
resumed: sid === resumeTarget,
|
|
993
|
+
}, ctx.routerChildRunner !== undefined && sid === resumeTarget);
|
|
713
994
|
}
|
|
714
995
|
// Keep the ORIGINAL dispatch reference across retries/escalations:
|
|
715
996
|
// recapturing after a failed attempt would excuse its regression.
|
|
@@ -737,6 +1018,26 @@ const ModelRouterPlugin: Plugin = async (ctx: RouterPluginInput) => {
|
|
|
737
1018
|
}
|
|
738
1019
|
|
|
739
1020
|
const model = tierModel(activeCfg, tier) ?? undefined;
|
|
1021
|
+
if (sessionAware && attemptPlan.step !== "dispatch") {
|
|
1022
|
+
// D11: the decision and both numbers are in the decision row (engine != static). The log line is for
|
|
1023
|
+
// anomalies (QA-2.3-4): a fresh start nobody chose (unknown context, no budget, an invalid catalog
|
|
1024
|
+
// variant). The routine ones are only logged with the existing opt-in debug flag: a resume, a start over
|
|
1025
|
+
// the threshold, and the two conservative overrides that the shipped presets hit on every escalation
|
|
1026
|
+
// (`effort-path`, `bare-model-after-variant`; QA-2.3-R2-2).
|
|
1027
|
+
const basis = attemptPlan.resumeBasis;
|
|
1028
|
+
const routine =
|
|
1029
|
+
resumeTarget !== undefined ||
|
|
1030
|
+
basis?.reason === "at-or-over-threshold" ||
|
|
1031
|
+
attemptPlan.fresh === "effort-path" ||
|
|
1032
|
+
attemptPlan.fresh === "bare-model-after-variant";
|
|
1033
|
+
if (!routine || process.env.MODEL_ROUTER_TRAJECTORY_DEBUG === "1") {
|
|
1034
|
+
logger.warn(
|
|
1035
|
+
`[router] ladder ${attemptPlan.step} on ${tier}: ${resumeTarget !== undefined ? "resuming the child session" : "fresh child session"}` +
|
|
1036
|
+
`${basis ? ` (${basis.reason}; tokens=${basis.tokens} budget=${basis.budget} threshold=${basis.threshold})` : ""}` +
|
|
1037
|
+
`${attemptPlan.fresh ? `; runner: ${attemptPlan.fresh}` : ""}`,
|
|
1038
|
+
);
|
|
1039
|
+
}
|
|
1040
|
+
}
|
|
740
1041
|
let producerText = "";
|
|
741
1042
|
// Provider-failover vs quality-escalation precedence (Phase 3.3):
|
|
742
1043
|
// Provider-failover is advisory only — a text chain injected into the orchestrator
|
|
@@ -753,15 +1054,33 @@ const ModelRouterPlugin: Plugin = async (ctx: RouterPluginInput) => {
|
|
|
753
1054
|
let producerError: string | null = null;
|
|
754
1055
|
const childAbort = ctx.routerChildRunner ? new AbortController() : undefined;
|
|
755
1056
|
try {
|
|
1057
|
+
const runChild = (resume: string | undefined) => ctx.routerChildRunner!.run({
|
|
1058
|
+
parentSessionID: toolCtx?.sessionID,
|
|
1059
|
+
agent: attemptPlan.agent,
|
|
1060
|
+
model: attemptPlan.model,
|
|
1061
|
+
prompt: taskText,
|
|
1062
|
+
signal: childAbort!.signal,
|
|
1063
|
+
...(resume === undefined ? {} : { resumeSessionID: resume }),
|
|
1064
|
+
onCreated: registerProducer,
|
|
1065
|
+
...(resume === undefined ? {} : {
|
|
1066
|
+
onConfirmed: async (sid: string) => { if (sid === producerSid) confirmProducer?.(); },
|
|
1067
|
+
}),
|
|
1068
|
+
});
|
|
756
1069
|
const res: any = await withTimeout<unknown>(
|
|
757
|
-
ctx.routerChildRunner ?
|
|
758
|
-
|
|
759
|
-
|
|
760
|
-
|
|
761
|
-
|
|
762
|
-
|
|
763
|
-
|
|
764
|
-
|
|
1070
|
+
ctx.routerChildRunner ? (async () => {
|
|
1071
|
+
try {
|
|
1072
|
+
return await runChild(resumeTarget);
|
|
1073
|
+
} catch (error) {
|
|
1074
|
+
// D11 fallback: a resume the host side refuses before anything ran (the child is gone, or is not
|
|
1075
|
+
// ours) is not a failed attempt: the same attempt starts on a fresh child.
|
|
1076
|
+
if (resumeTarget === undefined || !(error instanceof ResumeRejectedError)) throw error;
|
|
1077
|
+
logger.warn(`[router] ladder ${attemptPlan.step} on ${tier}: ${error.message}; starting a fresh child session`);
|
|
1078
|
+
const refused = resumeTarget;
|
|
1079
|
+
resumeTarget = undefined;
|
|
1080
|
+
await disposeChildSession(refused);
|
|
1081
|
+
return await runChild(undefined);
|
|
1082
|
+
}
|
|
1083
|
+
})() : ctx.client.session.prompt({
|
|
765
1084
|
path: { id: producerSid! },
|
|
766
1085
|
body: {
|
|
767
1086
|
...(model ? { model } : {}),
|
|
@@ -949,9 +1268,12 @@ const ModelRouterPlugin: Plugin = async (ctx: RouterPluginInput) => {
|
|
|
949
1268
|
// Dispose this attempt's backend session before the next iteration
|
|
950
1269
|
// so a long ladder never accumulates live sessions.
|
|
951
1270
|
effortOverrides.clear(producerSid);
|
|
952
|
-
|
|
1271
|
+
// A session-aware ladder (2.3) may resume this child on the next attempt, so its disposal is the loop's
|
|
1272
|
+
// decision, taken once the ladder has said retry/escalate and whether it resumes; every exit path is
|
|
1273
|
+
// still covered by the `finally` below. Without a session-aware policy: as before.
|
|
1274
|
+
if (!sessionAware) await disposeChildSession(producerSid);
|
|
953
1275
|
|
|
954
|
-
return { sessionID: producerSid, text: producerText, gateRes };
|
|
1276
|
+
return { sessionID: producerSid, text: producerText, gateRes, producerFailed: producerError !== null, confirmProducer };
|
|
955
1277
|
};
|
|
956
1278
|
|
|
957
1279
|
while (true) {
|
|
@@ -962,7 +1284,7 @@ const ModelRouterPlugin: Plugin = async (ctx: RouterPluginInput) => {
|
|
|
962
1284
|
);
|
|
963
1285
|
}
|
|
964
1286
|
const tier = state.currentTier;
|
|
965
|
-
const attempt = await runProducerAttempt(
|
|
1287
|
+
const attempt = await runProducerAttempt(plan, forcing);
|
|
966
1288
|
if (!attempt) {
|
|
967
1289
|
return withDepthBanner("[router] delegate failed: could not create a producer session.");
|
|
968
1290
|
}
|
|
@@ -975,16 +1297,49 @@ const ModelRouterPlugin: Plugin = async (ctx: RouterPluginInput) => {
|
|
|
975
1297
|
const producerSid = attempt.sessionID;
|
|
976
1298
|
const gateRes = attempt.gateRes;
|
|
977
1299
|
|
|
1300
|
+
// A17: charge the rung this attempt ran (a candidate's own ratio), the tier's ratio when it has none.
|
|
978
1301
|
const costRatio =
|
|
979
|
-
|
|
1302
|
+
rungCost ??
|
|
1303
|
+
(typeof tiersForCost?.[tier]?.costRatio === "number"
|
|
980
1304
|
? tiersForCost[tier].costRatio
|
|
981
|
-
: 1;
|
|
982
|
-
|
|
1305
|
+
: 1);
|
|
1306
|
+
// D11: the child and its last-step context (from the registry) decide a resume. A producer that errored
|
|
1307
|
+
// or timed out reports no context, so the next attempt starts fresh. The context is read only once the
|
|
1308
|
+
// child's execution end has been seen (QA-2.3-2): that event follows every step event on the stream, so
|
|
1309
|
+
// the number includes the final, largest step. The gate has usually run long enough for it to be there;
|
|
1310
|
+
// when it is not, wait for it, at most RESUME_END_WAIT_MS and no longer than the delegation lives, and
|
|
1311
|
+
// otherwise start fresh (`unknown-tokens`). Nothing is awaited when no retry can follow.
|
|
1312
|
+
let lastStepTokens: number | null = null;
|
|
1313
|
+
if (sessionAware && !attempt.producerFailed) {
|
|
1314
|
+
// No wait when nothing can follow this attempt (QA-2.3-R2-5): accepted, unverifiable, or the ladder's
|
|
1315
|
+
// own limits (checks 3 and 4 of `nextAction`) are reached after it.
|
|
1316
|
+
const firstCost = state.firstAttemptCost ?? costRatio;
|
|
1317
|
+
const limitReached =
|
|
1318
|
+
state.totalAttempts + 1 >= policy.maxTotalAttempts ||
|
|
1319
|
+
(policy.costMultiple != null && state.cumulativeCost + costRatio > firstCost * policy.costMultiple);
|
|
1320
|
+
if (!gateRes.accepted && gateRes.verdict.outcome !== "unverifiable" && !limitReached) {
|
|
1321
|
+
await awaitExecutionEnd(producerSid, RESUME_END_WAIT_MS, toolCtx?.abort);
|
|
1322
|
+
}
|
|
1323
|
+
lastStepTokens = lastStepContext(producerSid);
|
|
1324
|
+
}
|
|
1325
|
+
state = recordAttempt(
|
|
1326
|
+
state,
|
|
1327
|
+
costRatio,
|
|
1328
|
+
sessionAware ? { sessionID: producerSid, lastStepTokens } : undefined,
|
|
1329
|
+
);
|
|
1330
|
+
// The verdict of this attempt, on the attempt's own registration (variant steps feed the store separately).
|
|
1331
|
+
if (recording && !gateRes.verdict.skipped) {
|
|
1332
|
+
// R2-2: a failed/timed-out producer may never deliver host confirmation. The ladder's
|
|
1333
|
+
// verdict still needs its decision row; the same callback is idempotent after host progress/result.
|
|
1334
|
+
attempt.confirmProducer?.();
|
|
1335
|
+
ingest?.onVerdict(producerSid, verdictOf(gateRes.verdict));
|
|
1336
|
+
}
|
|
983
1337
|
|
|
984
1338
|
const action = nextAction(
|
|
985
1339
|
state,
|
|
986
1340
|
{ pass: gateRes.accepted, outcome: gateRes.verdict.outcome, reasons: gateRes.verdict.reasons },
|
|
987
1341
|
policy,
|
|
1342
|
+
sessionAware ? { dispatchPromptChars: args.task.length } : undefined,
|
|
988
1343
|
);
|
|
989
1344
|
|
|
990
1345
|
if (action.action === "accept") {
|
|
@@ -1013,8 +1368,13 @@ const ModelRouterPlugin: Plugin = async (ctx: RouterPluginInput) => {
|
|
|
1013
1368
|
}
|
|
1014
1369
|
// retry or escalate
|
|
1015
1370
|
forcing = action.forcingMessage ?? null;
|
|
1016
|
-
effort = action.effort;
|
|
1017
1371
|
state = advance(state, action);
|
|
1372
|
+
plan = planNextAttempt({ action, state, previous: plan, cfg: activeCfg, policy, catalog });
|
|
1373
|
+
// The rung the plan actually dispatches (QA-2.3-8: not the action's when the plan fell back to the tier's model).
|
|
1374
|
+
rungCost = plan.costRatio;
|
|
1375
|
+
// The child this attempt ran on is kept only when the next attempt resumes it (D11); otherwise it is
|
|
1376
|
+
// discarded now, so a long ladder never accumulates live sessions.
|
|
1377
|
+
if (sessionAware && plan.resumeSessionID !== producerSid) await disposeChildSession(producerSid);
|
|
1018
1378
|
}
|
|
1019
1379
|
} catch {
|
|
1020
1380
|
return withDepthBanner("[router] delegate failed (fail-closed): the delegation or verification could not complete.");
|
|
@@ -1118,10 +1478,26 @@ const ModelRouterPlugin: Plugin = async (ctx: RouterPluginInput) => {
|
|
|
1118
1478
|
|
|
1119
1479
|
"chat.message": async (input: any, output: any) => {
|
|
1120
1480
|
if (bypassed) return;
|
|
1121
|
-
//
|
|
1481
|
+
// 2.4.3 (QA-2.4-R2-1): the cost doctor's notice is NEVER part of the user's message (the prompt text stays byte for byte what the user
|
|
1482
|
+
// typed). It is a synthetic transcript entry, through the same host call the adapter uses for the config-reload and narration notices
|
|
1483
|
+
// (`ctx.session.synthetic({ …, resume: false })`, exposed as `routerSynthetic`): it enters the context of the orchestrator's next
|
|
1484
|
+
// request without resuming or answering anything. Delivery is not awaited (the host may be admitting this very prompt); a failure is
|
|
1485
|
+
// logged. A host without `routerSynthetic` (OpenCode v1 has no such call and no advisor either) gets a log line instead. Only a PROVEN
|
|
1486
|
+
// root session takes it (never a subagent or a grader), and only when one may be waiting.
|
|
1487
|
+
if (advisorNotifier !== undefined && advisorNotifier.maybePending() && typeof input?.sessionID === "string") {
|
|
1488
|
+
const noticeSession: string = input.sessionID;
|
|
1489
|
+
try {
|
|
1490
|
+
if (!graderSessions.has(noticeSession) && !sessionStore.isSubagent(noticeSession) && (await lookupRootSession(noticeSession)) === true) {
|
|
1491
|
+
const notice = await advisorNotifier.take();
|
|
1492
|
+
if (notice !== null) deliverAdvisorNotice(noticeSession, notice);
|
|
1493
|
+
}
|
|
1494
|
+
} catch (error) {
|
|
1495
|
+
logger.warn("[router] cost doctor: notice not delivered", { error: describeError(error) });
|
|
1496
|
+
}
|
|
1497
|
+
} // Re-read cfg so /preset switches take effect without restart
|
|
1122
1498
|
try {
|
|
1123
1499
|
cfg = loadConfig(projectDir);
|
|
1124
|
-
|
|
1500
|
+
warnConfigIssues(cfg, logger);
|
|
1125
1501
|
} catch {}
|
|
1126
1502
|
try {
|
|
1127
1503
|
sweepIdleStores();
|
|
@@ -1383,6 +1759,7 @@ const ModelRouterPlugin: Plugin = async (ctx: RouterPluginInput) => {
|
|
|
1383
1759
|
if (detectFalseRefusal({ toolCalls: calls, resultText: text }).suspected) {
|
|
1384
1760
|
output.output = `[router] FALSE-REFUSAL SUSPECT — this delegate returned a hand-back after 0 tool calls. No tool call was observed for this child, so the capability claim in its answer is untested rather than demonstrated. Re-dispatch the same work with task_id="${childSessionID}" and an instruction to attempt it, or do it yourself; do not escalate a tier on this result.\n\n${output.output}`;
|
|
1385
1761
|
trajectoryStore.recordFalseRefusal(childSessionID);
|
|
1762
|
+
ingest?.onFalseRefusal(childSessionID);
|
|
1386
1763
|
}
|
|
1387
1764
|
}
|
|
1388
1765
|
}
|
|
@@ -1592,6 +1969,8 @@ const ModelRouterPlugin: Plugin = async (ctx: RouterPluginInput) => {
|
|
|
1592
1969
|
});
|
|
1593
1970
|
// QA-3.1-2 / QA-3.1-3: concurrent delegations in this tree; a tool that discarded the baseline.
|
|
1594
1971
|
res = applyDispatchCaveats(res, verification);
|
|
1972
|
+
// M6 (2.1.3): a real verdict of a registered child dispatch feeds the outcome store (v2, engine != static).
|
|
1973
|
+
if (childSessionID && !res.verdict.skipped) ingest?.onVerdict(childSessionID, verdictOf(res.verdict));
|
|
1595
1974
|
if (!res.accepted && !res.verdict.skipped) {
|
|
1596
1975
|
const ladder = cfg.enforcement?.escalate?.ladder ?? ["fast", "medium", "heavy"];
|
|
1597
1976
|
const li = ladder.indexOf(producerTier);
|
|
@@ -1902,7 +2281,7 @@ const ModelRouterPlugin: Plugin = async (ctx: RouterPluginInput) => {
|
|
|
1902
2281
|
if (bypassed) return;
|
|
1903
2282
|
try {
|
|
1904
2283
|
cfg = loadConfig(projectDir); // Returns cache unless invalidated
|
|
1905
|
-
|
|
2284
|
+
warnConfigIssues(cfg, logger);
|
|
1906
2285
|
} catch {
|
|
1907
2286
|
// Use last known config if file read fails
|
|
1908
2287
|
}
|
|
@@ -1955,10 +2334,29 @@ const ModelRouterPlugin: Plugin = async (ctx: RouterPluginInput) => {
|
|
|
1955
2334
|
const providerID = _input?.model?.providerID ?? "";
|
|
1956
2335
|
const modelID = _input?.model?.modelID ?? "";
|
|
1957
2336
|
const orchestratorModel = providerID && modelID ? `${providerID}/${modelID}` : modelID;
|
|
2337
|
+
if (providerID !== "") lastPrimary = { providerID, modelID: modelID === "" ? null : modelID };
|
|
1958
2338
|
|
|
1959
2339
|
let enfOn = false;
|
|
1960
2340
|
try { enfOn = resolveEnforcementMode({ config: cfg, env: process.env }).mode !== "off"; } catch {}
|
|
1961
|
-
|
|
2341
|
+
let systemPrompt = assembleSystemPrompt(cfg, orchestratorModel, enfOn);
|
|
2342
|
+
// A28 (D1): on v1 only, and only with an explicit `routing.roles`, the `R:` line lists those agents as destinations (prose; no model
|
|
2343
|
+
// override). Anything else leaves `systemPrompt` the very string it is: the v1 protocol stays byte-identical.
|
|
2344
|
+
// Any failure leaves the baseline prompt (QA-2.4-13): the line is an extra, never a reason to lose the protocol.
|
|
2345
|
+
if (ctx.routerHost !== "v2") {
|
|
2346
|
+
const baseline = systemPrompt;
|
|
2347
|
+
try {
|
|
2348
|
+
if (hasExplicitV1Roles(cfg, logger)) systemPrompt = applyV1Roles(baseline, cfg, v1AgentsNow(), logger);
|
|
2349
|
+
} catch (error) {
|
|
2350
|
+
systemPrompt = baseline;
|
|
2351
|
+
logger.warn("[router] routing.roles: the R: line could not be extended; the protocol is unchanged", { error: describeError(error) });
|
|
2352
|
+
}
|
|
2353
|
+
}
|
|
2354
|
+
output.system.push(systemPrompt);
|
|
2355
|
+
|
|
2356
|
+
// 2.4.3: the cost doctor's throttled check. `poll` is O(1) when nothing is due and never throws. In static/shadow a notice is logged
|
|
2357
|
+
// from here; in advise/enforce it is delivered with the user's next turn (the `chat.message` hook below), never in the system prompt:
|
|
2358
|
+
// a system part that changes would cost the orchestrator its prompt cache (QA-2.4-9).
|
|
2359
|
+
advisorNotifier?.poll();
|
|
1962
2360
|
|
|
1963
2361
|
// 2.4.4, section 1.5-20: this orchestrator's still-unverified delegations (at most 5 shown,
|
|
1964
2362
|
// newest first), as one short block. Nothing is pushed when the list is empty, so the prompt
|
|
@@ -1992,7 +2390,7 @@ const ModelRouterPlugin: Plugin = async (ctx: RouterPluginInput) => {
|
|
|
1992
2390
|
if (input.command === "tiers") {
|
|
1993
2391
|
try {
|
|
1994
2392
|
cfg = loadConfig(projectDir);
|
|
1995
|
-
|
|
2393
|
+
warnConfigIssues(cfg, logger);
|
|
1996
2394
|
} catch {}
|
|
1997
2395
|
output.parts.push({
|
|
1998
2396
|
type: "text" as const,
|
|
@@ -2000,6 +2398,31 @@ const ModelRouterPlugin: Plugin = async (ctx: RouterPluginInput) => {
|
|
|
2000
2398
|
});
|
|
2001
2399
|
}
|
|
2002
2400
|
|
|
2401
|
+
if (input.command === "annotate-plan") {
|
|
2402
|
+
// 2.4.4: the template (registered in the config hook) is unchanged. With a live engine on v2 this adds ONE message part: the
|
|
2403
|
+
// route lines the router computed for the plan's steps (one batched classification). Everything else is as before.
|
|
2404
|
+
try {
|
|
2405
|
+
cfg = loadConfig(projectDir);
|
|
2406
|
+
warnConfigIssues(cfg, logger);
|
|
2407
|
+
} catch {}
|
|
2408
|
+
try {
|
|
2409
|
+
const runtime = annotatePlanRuntime();
|
|
2410
|
+
if (runtime !== undefined && ctx.routerAgents !== undefined) {
|
|
2411
|
+
const directives = await buildAnnotateDirectives(input.arguments ?? "", {
|
|
2412
|
+
cfg,
|
|
2413
|
+
runtime,
|
|
2414
|
+
listAgents: ctx.routerAgents,
|
|
2415
|
+
dirs: [...new Set([ctx.directory, ctx.worktree].filter((dir): dir is string => typeof dir === "string" && dir !== ""))],
|
|
2416
|
+
logger,
|
|
2417
|
+
});
|
|
2418
|
+
if (directives !== null) output.parts.push({ type: "text" as const, text: directives });
|
|
2419
|
+
}
|
|
2420
|
+
} catch (error) {
|
|
2421
|
+
// No part: the command is then exactly what it was (QA-2.4-15).
|
|
2422
|
+
logger.warn("[router] /annotate-plan: route lines unavailable; the plan is annotated without them", { error: describeError(error) });
|
|
2423
|
+
}
|
|
2424
|
+
}
|
|
2425
|
+
|
|
2003
2426
|
if (input.command === "router-reload") {
|
|
2004
2427
|
invalidateConfigCache();
|
|
2005
2428
|
cfg = loadConfig(projectDir);
|
|
@@ -2035,7 +2458,7 @@ const ModelRouterPlugin: Plugin = async (ctx: RouterPluginInput) => {
|
|
|
2035
2458
|
if (input.command === "preset") {
|
|
2036
2459
|
try {
|
|
2037
2460
|
cfg = loadConfig(projectDir);
|
|
2038
|
-
|
|
2461
|
+
warnConfigIssues(cfg, logger);
|
|
2039
2462
|
} catch {}
|
|
2040
2463
|
output.parts.push({
|
|
2041
2464
|
type: "text" as const,
|
|
@@ -2061,7 +2484,7 @@ const ModelRouterPlugin: Plugin = async (ctx: RouterPluginInput) => {
|
|
|
2061
2484
|
if (input.command === "budget") {
|
|
2062
2485
|
try {
|
|
2063
2486
|
cfg = loadConfig(projectDir);
|
|
2064
|
-
|
|
2487
|
+
warnConfigIssues(cfg, logger);
|
|
2065
2488
|
} catch {}
|
|
2066
2489
|
output.parts.push({
|
|
2067
2490
|
type: "text" as const,
|
|
@@ -2072,7 +2495,7 @@ const ModelRouterPlugin: Plugin = async (ctx: RouterPluginInput) => {
|
|
|
2072
2495
|
if (input.command === "router") {
|
|
2073
2496
|
try {
|
|
2074
2497
|
cfg = loadConfig(projectDir);
|
|
2075
|
-
|
|
2498
|
+
warnConfigIssues(cfg, logger);
|
|
2076
2499
|
} catch {}
|
|
2077
2500
|
const args = (input.arguments ?? "").trim();
|
|
2078
2501
|
const parts = args.split(/\s+/).filter(Boolean);
|
|
@@ -2082,17 +2505,42 @@ const ModelRouterPlugin: Plugin = async (ctx: RouterPluginInput) => {
|
|
|
2082
2505
|
const catalog = await fetchCatalog();
|
|
2083
2506
|
const orphans = catalog ? findOrphanedStrongPatterns(cfg, catalog) : [];
|
|
2084
2507
|
text = buildModelsOutput(catalog, parts.slice(1).join(" "), orphans);
|
|
2508
|
+
} else if (sub === "stats" && cfg.routing !== undefined) {
|
|
2509
|
+
// 2.4.5 (D18): the table of `npm run routing:stats`, run by the very same driver over the configured store.
|
|
2510
|
+
try {
|
|
2511
|
+
text = formatStatsReply(await runStatsCommand(parts.slice(1).join(" "), { cfg, host: ctx.routerHost === "v2" ? "v2" : "v1", logger }));
|
|
2512
|
+
} catch (error) {
|
|
2513
|
+
logger.warn("[router] /router stats failed", { error: describeError(error) });
|
|
2514
|
+
text = `routing-stats: ${describeError(error)}`;
|
|
2515
|
+
}
|
|
2085
2516
|
} else {
|
|
2086
2517
|
text = buildRouterOutput(cfg, args, projectDir);
|
|
2087
2518
|
// On the bare status view, surface stale or missing models inline.
|
|
2088
2519
|
if (sub === "") {
|
|
2089
|
-
|
|
2520
|
+
text += "\n" + routerStatusLines(cfg, ctx.routerHost === "v2" ? "v2" : "v1", logger, projectDir).join("\n");
|
|
2521
|
+
// 2.4.5: the last dogfood checkpoint recorded next to this code (omitted when there is none). Only with a `routing` block:
|
|
2522
|
+
// without one `/router` is exactly what it was (QA-2.4-3, §1.2).
|
|
2523
|
+
const optedIn = cfg.routing !== undefined;
|
|
2524
|
+
const checkpoint = optedIn ? checkpointLine() : null;
|
|
2525
|
+
if (checkpoint !== null) text += "\n" + checkpoint;
|
|
2526
|
+
// One `config.providers()` call serves the model check below and the cost doctor.
|
|
2527
|
+
const fetched = await fetchCatalogRaw();
|
|
2528
|
+
const catalog = fetched?.catalog ?? null;
|
|
2090
2529
|
if (catalog) {
|
|
2091
2530
|
const issues = validateModels(cfg, catalog);
|
|
2092
2531
|
if (issues.length > 0) {
|
|
2093
2532
|
text += "\n\n" + formatModelIssues(issues);
|
|
2094
2533
|
}
|
|
2095
2534
|
}
|
|
2535
|
+
// 2.4.3: the cost doctor (v2 only, and only with a `routing` block; the advisor needs the v2 agent list and catalog).
|
|
2536
|
+
if (ctx.routerHost === "v2" && optedIn) {
|
|
2537
|
+
try {
|
|
2538
|
+
text += "\n\n" + (await buildCostDoctorLines(fetched)).join("\n");
|
|
2539
|
+
} catch (error) {
|
|
2540
|
+
logger.warn("[router] cost doctor failed", { error: describeError(error) });
|
|
2541
|
+
text += `\n\nCost doctor: unavailable (${describeError(error)}).`;
|
|
2542
|
+
}
|
|
2543
|
+
}
|
|
2096
2544
|
}
|
|
2097
2545
|
}
|
|
2098
2546
|
output.parts.push({ type: "text" as const, text });
|