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.
- package/CHANGELOG.md +86 -0
- package/README.md +44 -5
- 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 +174 -47
- 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 +557 -61
- package/src/router/build-info.ts +151 -0
- package/src/router/config.ts +1691 -67
- 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/tiers.json +43 -0
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 {
|
|
@@ -8,12 +8,16 @@ import {
|
|
|
8
8
|
resolvePresetName,
|
|
9
9
|
writeState,
|
|
10
10
|
invalidateConfigCache,
|
|
11
|
+
getConfigReloadError,
|
|
11
12
|
overridePath,
|
|
12
13
|
localOverridePath,
|
|
13
14
|
findProjectOverride,
|
|
14
15
|
resolveVerifyBudget,
|
|
15
16
|
resolveDepthLimit,
|
|
16
|
-
|
|
17
|
+
resolveRouting,
|
|
18
|
+
resolveVariantSteps,
|
|
19
|
+
routerStatusLines,
|
|
20
|
+
warnConfigIssues,
|
|
17
21
|
} from "./router/config";
|
|
18
22
|
import type { RouterConfig, TierConfig, Preset, ModeConfig, EffortLevel } from "./router/config";
|
|
19
23
|
import { buildAgentOptions, warnAgentOptionsEffortOnce } from "./router/agent-options";
|
|
@@ -56,6 +60,24 @@ import {
|
|
|
56
60
|
} from "./router/protocol";
|
|
57
61
|
import { resolveEnforcementMode } from "./router/enforcement";
|
|
58
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";
|
|
59
81
|
import {
|
|
60
82
|
findOrphanedStrongPatterns,
|
|
61
83
|
normalizeCatalog,
|
|
@@ -68,6 +90,8 @@ import {
|
|
|
68
90
|
buildCapBanner,
|
|
69
91
|
DEFAULT_TIER_CAPS,
|
|
70
92
|
READ_ONLY_TOOLS,
|
|
93
|
+
awaitExecutionEnd,
|
|
94
|
+
lastStepContext,
|
|
71
95
|
} from "./router/sessions";
|
|
72
96
|
import type { Cap, SubagentState } from "./router/sessions";
|
|
73
97
|
import { createTrajectoryStore } from "./telemetry/trajectory";
|
|
@@ -99,7 +123,11 @@ import {
|
|
|
99
123
|
buildForcingNote,
|
|
100
124
|
buildAcceptedSuffix,
|
|
101
125
|
} from "./verify/dispatch";
|
|
102
|
-
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";
|
|
103
131
|
import { createDepthTracker, DEPTH_LOOKUP_RETRY_MS } from "./router/depth";
|
|
104
132
|
import { createDepthGuard } from "./router/depth-guard";
|
|
105
133
|
import { applyEffortOverride, createEffortOverrideStore } from "./escalate/effort-override";
|
|
@@ -127,8 +155,8 @@ function describeError(error: unknown): string {
|
|
|
127
155
|
}
|
|
128
156
|
}
|
|
129
157
|
|
|
130
|
-
function saveActivePreset(presetName: string): void {
|
|
131
|
-
const cfg = loadConfig();
|
|
158
|
+
function saveActivePreset(presetName: string, projectDir?: string): void {
|
|
159
|
+
const cfg = loadConfig(projectDir);
|
|
132
160
|
const resolved = resolvePresetName(cfg, presetName);
|
|
133
161
|
if (!resolved) {
|
|
134
162
|
return;
|
|
@@ -143,8 +171,8 @@ function saveActivePreset(presetName: string): void {
|
|
|
143
171
|
invalidateConfigCache();
|
|
144
172
|
}
|
|
145
173
|
|
|
146
|
-
function saveActiveMode(modeName: string): void {
|
|
147
|
-
const cfg = loadConfig();
|
|
174
|
+
function saveActiveMode(modeName: string, projectDir?: string): void {
|
|
175
|
+
const cfg = loadConfig(projectDir);
|
|
148
176
|
if (!cfg.modes?.[modeName]) {
|
|
149
177
|
return;
|
|
150
178
|
}
|
|
@@ -163,7 +191,7 @@ function saveEnforcementMode(mode: "off" | "advisory" | "enforced"): void {
|
|
|
163
191
|
* `/router` dispatch. Decides and persists here; rendering lives in
|
|
164
192
|
* src/commands/output.ts.
|
|
165
193
|
*/
|
|
166
|
-
function buildRouterOutput(cfg: RouterConfig, args: string): string {
|
|
194
|
+
function buildRouterOutput(cfg: RouterConfig, args: string, projectDir?: string): string {
|
|
167
195
|
const tokens = (args ?? "").trim().split(/\s+/).filter(Boolean);
|
|
168
196
|
const sub = (tokens[0] ?? "").toLowerCase();
|
|
169
197
|
|
|
@@ -180,8 +208,8 @@ function buildRouterOutput(cfg: RouterConfig, args: string): string {
|
|
|
180
208
|
|
|
181
209
|
if (sub === "overrides") {
|
|
182
210
|
const globalPath = overridePath();
|
|
183
|
-
const foundLocal = findProjectOverride();
|
|
184
|
-
const localPath = foundLocal ?? localOverridePath();
|
|
211
|
+
const foundLocal = findProjectOverride(projectDir);
|
|
212
|
+
const localPath = foundLocal ?? localOverridePath(projectDir);
|
|
185
213
|
return buildOverridesOutput({
|
|
186
214
|
globalPath,
|
|
187
215
|
globalPresent: existsSync(globalPath),
|
|
@@ -194,11 +222,13 @@ function buildRouterOutput(cfg: RouterConfig, args: string): string {
|
|
|
194
222
|
|
|
195
223
|
return buildRouterHelp(
|
|
196
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 },
|
|
197
227
|
);
|
|
198
228
|
}
|
|
199
229
|
|
|
200
230
|
/** `/budget` dispatch. Persists the switch, then renders. */
|
|
201
|
-
function buildBudgetOutput(cfg: RouterConfig, args: string): string {
|
|
231
|
+
function buildBudgetOutput(cfg: RouterConfig, args: string, projectDir?: string): string {
|
|
202
232
|
const modes = cfg.modes;
|
|
203
233
|
if (!modes || Object.keys(modes).length === 0) return buildNoModes();
|
|
204
234
|
|
|
@@ -207,7 +237,7 @@ function buildBudgetOutput(cfg: RouterConfig, args: string): string {
|
|
|
207
237
|
|
|
208
238
|
const mode = modes[requested];
|
|
209
239
|
if (mode) {
|
|
210
|
-
saveActiveMode(requested);
|
|
240
|
+
saveActiveMode(requested, projectDir);
|
|
211
241
|
return buildBudgetSwitched(mode, requested);
|
|
212
242
|
}
|
|
213
243
|
|
|
@@ -215,13 +245,13 @@ function buildBudgetOutput(cfg: RouterConfig, args: string): string {
|
|
|
215
245
|
}
|
|
216
246
|
|
|
217
247
|
/** `/preset` dispatch. Persists the switch, then renders. */
|
|
218
|
-
function buildPresetOutput(cfg: RouterConfig, args: string): string {
|
|
248
|
+
function buildPresetOutput(cfg: RouterConfig, args: string, projectDir?: string): string {
|
|
219
249
|
const requestedPreset = args.trim();
|
|
220
250
|
if (!requestedPreset) return buildPresetList(cfg);
|
|
221
251
|
|
|
222
252
|
const resolvedPreset = resolvePresetName(cfg, requestedPreset);
|
|
223
253
|
if (resolvedPreset) {
|
|
224
|
-
saveActivePreset(resolvedPreset);
|
|
254
|
+
saveActivePreset(resolvedPreset, projectDir);
|
|
225
255
|
cfg.activePreset = resolvedPreset;
|
|
226
256
|
return buildPresetSwitched(cfg, resolvedPreset);
|
|
227
257
|
}
|
|
@@ -254,8 +284,12 @@ const SESSION_ROOT_MEMO_MAX = 500;
|
|
|
254
284
|
const SESSION_LOOKUP_RETRY_MS = DEPTH_LOOKUP_RETRY_MS;
|
|
255
285
|
|
|
256
286
|
const ModelRouterPlugin: Plugin = async (ctx: RouterPluginInput) => {
|
|
257
|
-
|
|
258
|
-
|
|
287
|
+
// Project directory this plugin instance serves. Hosts that run several
|
|
288
|
+
// projects in one process (OpenCode v2) may also move process.cwd() away from
|
|
289
|
+
// it, so config/override lookup must use this and never the working directory.
|
|
290
|
+
const projectDir: string | undefined = ctx.directory || ctx.worktree || undefined;
|
|
291
|
+
let cfg = loadConfig(projectDir);
|
|
292
|
+
let activeTiers = getActiveTiers(cfg);
|
|
259
293
|
|
|
260
294
|
// Per-plugin-instance session store: owns subagentSessionIDs and subagentCapState.
|
|
261
295
|
const sessionStore = createSessionStore();
|
|
@@ -368,6 +402,10 @@ const ModelRouterPlugin: Plugin = async (ctx: RouterPluginInput) => {
|
|
|
368
402
|
() => { sweepVerification(); },
|
|
369
403
|
// 2.4.2b: TTL eviction and reaping of the pending registry (pending.ts R7; no timer of its own).
|
|
370
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(); },
|
|
371
409
|
]);
|
|
372
410
|
|
|
373
411
|
// Layer-2's impure corner: exec, fs, and the opencode client, built once and
|
|
@@ -378,6 +416,27 @@ const ModelRouterPlugin: Plugin = async (ctx: RouterPluginInput) => {
|
|
|
378
416
|
// has no /log endpoint. See src/router/logger.ts.
|
|
379
417
|
const logger = createPluginLogger(ctx.client);
|
|
380
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)
|
|
381
440
|
const depthTracker = createDepthTracker({
|
|
382
441
|
async getParent(id) {
|
|
383
442
|
if (sessionRootMemo.get(id) === true) return null;
|
|
@@ -475,19 +534,124 @@ const ModelRouterPlugin: Plugin = async (ctx: RouterPluginInput) => {
|
|
|
475
534
|
// current plugin lifetime (i.e., until OpenCode is restarted).
|
|
476
535
|
let bypassed = false;
|
|
477
536
|
|
|
478
|
-
|
|
537
|
+
warnConfigIssues(cfg, logger);
|
|
479
538
|
|
|
480
539
|
// Fetch and normalize opencode's live provider/model catalog. Best-effort:
|
|
481
540
|
// returns null when the client call fails, e.g. the server is not ready yet.
|
|
482
541
|
// The pure analysis (validateModels) lives in src/router/catalog.ts.
|
|
483
|
-
const
|
|
542
|
+
const fetchCatalogRaw = async (): Promise<{ catalog: Catalog; raw: unknown } | null> => {
|
|
484
543
|
try {
|
|
485
544
|
const res: any = await ctx.client.config.providers();
|
|
486
|
-
return normalizeCatalog(res?.data);
|
|
545
|
+
return { catalog: normalizeCatalog(res?.data), raw: res?.data };
|
|
487
546
|
} catch {
|
|
488
547
|
return null;
|
|
489
548
|
}
|
|
490
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
|
+
};
|
|
491
655
|
|
|
492
656
|
// Deferred passive catalog check. The first orchestrator turn only STARTS the
|
|
493
657
|
// fetch (fire-and-forget, never awaited on the chat.message hot path) and
|
|
@@ -557,6 +721,74 @@ const ModelRouterPlugin: Plugin = async (ctx: RouterPluginInput) => {
|
|
|
557
721
|
return (await lookupRootSession(sessionID)) === true;
|
|
558
722
|
};
|
|
559
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
|
+
};
|
|
560
792
|
return {
|
|
561
793
|
// Warnings post to /log fire-and-forget, which loses the message when the
|
|
562
794
|
// process is about to exit — `opencode run` and `opencode debug` are short
|
|
@@ -564,12 +796,18 @@ const ModelRouterPlugin: Plugin = async (ctx: RouterPluginInput) => {
|
|
|
564
796
|
// that dispose is both called and awaited, so flushing here is enough.
|
|
565
797
|
dispose: async () => {
|
|
566
798
|
stopReferenceGc();
|
|
799
|
+
// Stop new advisor work and finish state/claim writes and lock removal before teardown.
|
|
800
|
+
await advisorNotifier?.dispose();
|
|
567
801
|
// 2.4.5: abort a background run and drop its queue and notices before the registry goes.
|
|
568
802
|
background?.dispose();
|
|
569
803
|
// 2.4.2b: evict every pending delegation; in-flight router_verify runs resolve (pending.ts R5).
|
|
570
804
|
pending.dispose();
|
|
571
805
|
// 2.2.3: settle batched testsPass requests and kill running batches (never rejects).
|
|
572
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();
|
|
573
811
|
await logger.flush();
|
|
574
812
|
},
|
|
575
813
|
tool: {
|
|
@@ -603,7 +841,7 @@ const ModelRouterPlugin: Plugin = async (ctx: RouterPluginInput) => {
|
|
|
603
841
|
acceptance?: string;
|
|
604
842
|
cwd?: string;
|
|
605
843
|
},
|
|
606
|
-
toolCtx?: { sessionID?: string },
|
|
844
|
+
toolCtx?: { sessionID?: string; abort?: AbortSignal },
|
|
607
845
|
): Promise<string> {
|
|
608
846
|
// Every ladder iteration creates its own producer session. Tracked out
|
|
609
847
|
// here (not inside the try) so the finally below can dispose any that an
|
|
@@ -638,8 +876,8 @@ const ModelRouterPlugin: Plugin = async (ctx: RouterPluginInput) => {
|
|
|
638
876
|
try {
|
|
639
877
|
let activeCfg = cfg;
|
|
640
878
|
try {
|
|
641
|
-
activeCfg = loadConfig();
|
|
642
|
-
|
|
879
|
+
activeCfg = loadConfig(projectDir);
|
|
880
|
+
warnConfigIssues(activeCfg, logger);
|
|
643
881
|
} catch {
|
|
644
882
|
activeCfg = cfg;
|
|
645
883
|
}
|
|
@@ -653,9 +891,36 @@ const ModelRouterPlugin: Plugin = async (ctx: RouterPluginInput) => {
|
|
|
653
891
|
});
|
|
654
892
|
const effectiveCwd = typeof args.cwd === "string" && args.cwd.trim() ? args.cwd : dod.cwd;
|
|
655
893
|
|
|
656
|
-
|
|
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;
|
|
657
913
|
let state = newLadderState(initialTier, policy);
|
|
658
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;
|
|
659
924
|
|
|
660
925
|
// Independent safety net: even a policy bug cannot loop unbounded.
|
|
661
926
|
const safetyMax =
|
|
@@ -667,7 +932,6 @@ const ModelRouterPlugin: Plugin = async (ctx: RouterPluginInput) => {
|
|
|
667
932
|
|
|
668
933
|
let producerText = "";
|
|
669
934
|
let forcing: string | null = null;
|
|
670
|
-
let effort: EffortLevel | undefined;
|
|
671
935
|
|
|
672
936
|
/**
|
|
673
937
|
* One turn of the escalation ladder: create a producer session, run
|
|
@@ -680,31 +944,53 @@ const ModelRouterPlugin: Plugin = async (ctx: RouterPluginInput) => {
|
|
|
680
944
|
* in the middle of it obscured both halves.
|
|
681
945
|
*/
|
|
682
946
|
const runProducerAttempt = async (
|
|
683
|
-
|
|
947
|
+
attemptPlan: AttemptPlan,
|
|
684
948
|
forcingNote: string | null,
|
|
685
|
-
effort?: EffortLevel,
|
|
686
949
|
): Promise<{
|
|
687
950
|
sessionID: string;
|
|
688
951
|
text: string;
|
|
689
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;
|
|
690
956
|
} | {
|
|
691
957
|
sessionID: string;
|
|
692
958
|
text: string;
|
|
693
959
|
/** 2.4.2c: deferred; the section 1.5-16 footer to append to the result. */
|
|
694
960
|
deferredFooter: string;
|
|
695
961
|
} | null> => {
|
|
962
|
+
const tier = attemptPlan.tier;
|
|
963
|
+
const effort = attemptPlan.effort;
|
|
696
964
|
const taskText = forcingNote
|
|
697
965
|
? `${scrubText(forcingNote)}\n\n${args.task}`
|
|
698
966
|
: args.task;
|
|
699
967
|
|
|
700
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;
|
|
701
972
|
const registerProducer = async (sid: string) => {
|
|
702
973
|
producerSid = sid;
|
|
703
|
-
producerSessions.push(sid);
|
|
974
|
+
if (!producerSessions.includes(sid)) producerSessions.push(sid);
|
|
704
975
|
depthTracker.recordPluginChild(sid, toolCtx?.sessionID ?? null);
|
|
705
976
|
if (effort !== undefined) {
|
|
706
977
|
const tierCfg = getActiveTiers(activeCfg)[tier];
|
|
707
|
-
|
|
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);
|
|
708
994
|
}
|
|
709
995
|
// Keep the ORIGINAL dispatch reference across retries/escalations:
|
|
710
996
|
// recapturing after a failed attempt would excuse its regression.
|
|
@@ -732,6 +1018,26 @@ const ModelRouterPlugin: Plugin = async (ctx: RouterPluginInput) => {
|
|
|
732
1018
|
}
|
|
733
1019
|
|
|
734
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
|
+
}
|
|
735
1041
|
let producerText = "";
|
|
736
1042
|
// Provider-failover vs quality-escalation precedence (Phase 3.3):
|
|
737
1043
|
// Provider-failover is advisory only — a text chain injected into the orchestrator
|
|
@@ -748,15 +1054,33 @@ const ModelRouterPlugin: Plugin = async (ctx: RouterPluginInput) => {
|
|
|
748
1054
|
let producerError: string | null = null;
|
|
749
1055
|
const childAbort = ctx.routerChildRunner ? new AbortController() : undefined;
|
|
750
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
|
+
});
|
|
751
1069
|
const res: any = await withTimeout<unknown>(
|
|
752
|
-
ctx.routerChildRunner ?
|
|
753
|
-
|
|
754
|
-
|
|
755
|
-
|
|
756
|
-
|
|
757
|
-
|
|
758
|
-
|
|
759
|
-
|
|
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({
|
|
760
1084
|
path: { id: producerSid! },
|
|
761
1085
|
body: {
|
|
762
1086
|
...(model ? { model } : {}),
|
|
@@ -944,9 +1268,12 @@ const ModelRouterPlugin: Plugin = async (ctx: RouterPluginInput) => {
|
|
|
944
1268
|
// Dispose this attempt's backend session before the next iteration
|
|
945
1269
|
// so a long ladder never accumulates live sessions.
|
|
946
1270
|
effortOverrides.clear(producerSid);
|
|
947
|
-
|
|
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);
|
|
948
1275
|
|
|
949
|
-
return { sessionID: producerSid, text: producerText, gateRes };
|
|
1276
|
+
return { sessionID: producerSid, text: producerText, gateRes, producerFailed: producerError !== null, confirmProducer };
|
|
950
1277
|
};
|
|
951
1278
|
|
|
952
1279
|
while (true) {
|
|
@@ -957,7 +1284,7 @@ const ModelRouterPlugin: Plugin = async (ctx: RouterPluginInput) => {
|
|
|
957
1284
|
);
|
|
958
1285
|
}
|
|
959
1286
|
const tier = state.currentTier;
|
|
960
|
-
const attempt = await runProducerAttempt(
|
|
1287
|
+
const attempt = await runProducerAttempt(plan, forcing);
|
|
961
1288
|
if (!attempt) {
|
|
962
1289
|
return withDepthBanner("[router] delegate failed: could not create a producer session.");
|
|
963
1290
|
}
|
|
@@ -970,16 +1297,49 @@ const ModelRouterPlugin: Plugin = async (ctx: RouterPluginInput) => {
|
|
|
970
1297
|
const producerSid = attempt.sessionID;
|
|
971
1298
|
const gateRes = attempt.gateRes;
|
|
972
1299
|
|
|
1300
|
+
// A17: charge the rung this attempt ran (a candidate's own ratio), the tier's ratio when it has none.
|
|
973
1301
|
const costRatio =
|
|
974
|
-
|
|
1302
|
+
rungCost ??
|
|
1303
|
+
(typeof tiersForCost?.[tier]?.costRatio === "number"
|
|
975
1304
|
? tiersForCost[tier].costRatio
|
|
976
|
-
: 1;
|
|
977
|
-
|
|
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
|
+
}
|
|
978
1337
|
|
|
979
1338
|
const action = nextAction(
|
|
980
1339
|
state,
|
|
981
1340
|
{ pass: gateRes.accepted, outcome: gateRes.verdict.outcome, reasons: gateRes.verdict.reasons },
|
|
982
1341
|
policy,
|
|
1342
|
+
sessionAware ? { dispatchPromptChars: args.task.length } : undefined,
|
|
983
1343
|
);
|
|
984
1344
|
|
|
985
1345
|
if (action.action === "accept") {
|
|
@@ -1008,8 +1368,13 @@ const ModelRouterPlugin: Plugin = async (ctx: RouterPluginInput) => {
|
|
|
1008
1368
|
}
|
|
1009
1369
|
// retry or escalate
|
|
1010
1370
|
forcing = action.forcingMessage ?? null;
|
|
1011
|
-
effort = action.effort;
|
|
1012
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);
|
|
1013
1378
|
}
|
|
1014
1379
|
} catch {
|
|
1015
1380
|
return withDepthBanner("[router] delegate failed (fail-closed): the delegation or verification could not complete.");
|
|
@@ -1113,10 +1478,26 @@ const ModelRouterPlugin: Plugin = async (ctx: RouterPluginInput) => {
|
|
|
1113
1478
|
|
|
1114
1479
|
"chat.message": async (input: any, output: any) => {
|
|
1115
1480
|
if (bypassed) return;
|
|
1116
|
-
//
|
|
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
|
|
1117
1498
|
try {
|
|
1118
|
-
cfg = loadConfig();
|
|
1119
|
-
|
|
1499
|
+
cfg = loadConfig(projectDir);
|
|
1500
|
+
warnConfigIssues(cfg, logger);
|
|
1120
1501
|
} catch {}
|
|
1121
1502
|
try {
|
|
1122
1503
|
sweepIdleStores();
|
|
@@ -1378,6 +1759,7 @@ const ModelRouterPlugin: Plugin = async (ctx: RouterPluginInput) => {
|
|
|
1378
1759
|
if (detectFalseRefusal({ toolCalls: calls, resultText: text }).suspected) {
|
|
1379
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}`;
|
|
1380
1761
|
trajectoryStore.recordFalseRefusal(childSessionID);
|
|
1762
|
+
ingest?.onFalseRefusal(childSessionID);
|
|
1381
1763
|
}
|
|
1382
1764
|
}
|
|
1383
1765
|
}
|
|
@@ -1587,6 +1969,8 @@ const ModelRouterPlugin: Plugin = async (ctx: RouterPluginInput) => {
|
|
|
1587
1969
|
});
|
|
1588
1970
|
// QA-3.1-2 / QA-3.1-3: concurrent delegations in this tree; a tool that discarded the baseline.
|
|
1589
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));
|
|
1590
1974
|
if (!res.accepted && !res.verdict.skipped) {
|
|
1591
1975
|
const ladder = cfg.enforcement?.escalate?.ladder ?? ["fast", "medium", "heavy"];
|
|
1592
1976
|
const li = ladder.indexOf(producerTier);
|
|
@@ -1734,6 +2118,10 @@ const ModelRouterPlugin: Plugin = async (ctx: RouterPluginInput) => {
|
|
|
1734
2118
|
config: async (opencodeConfig: any) => {
|
|
1735
2119
|
opencodeConfig.agent ??= {};
|
|
1736
2120
|
|
|
2121
|
+
// Re-read so re-running this hook (v2 refresh) yields the current preset.
|
|
2122
|
+
cfg = loadConfig(projectDir);
|
|
2123
|
+
activeTiers = getActiveTiers(cfg);
|
|
2124
|
+
|
|
1737
2125
|
for (const [name, tier] of Object.entries(activeTiers)) {
|
|
1738
2126
|
// Resolve prompt: per-tier override wins; otherwise fall back to the
|
|
1739
2127
|
// style-appropriate default (goal-oriented or global tierPrompts[name]).
|
|
@@ -1869,6 +2257,13 @@ const ModelRouterPlugin: Plugin = async (ctx: RouterPluginInput) => {
|
|
|
1869
2257
|
description:
|
|
1870
2258
|
"Annotate a plan with [tier:fast/medium/heavy] delegation tags",
|
|
1871
2259
|
};
|
|
2260
|
+
opencodeConfig.command["router-reload"] = {
|
|
2261
|
+
template: "",
|
|
2262
|
+
description:
|
|
2263
|
+
ctx.routerHost === "v2"
|
|
2264
|
+
? "Reload model-router config (tiers.json, overrides, state) without restarting"
|
|
2265
|
+
: "Reload model-router config (tiers.json, overrides, state); subagent models apply after an opencode restart",
|
|
2266
|
+
};
|
|
1872
2267
|
opencodeConfig.command["router"] = {
|
|
1873
2268
|
template: "$ARGUMENTS",
|
|
1874
2269
|
description:
|
|
@@ -1885,8 +2280,8 @@ const ModelRouterPlugin: Plugin = async (ctx: RouterPluginInput) => {
|
|
|
1885
2280
|
"experimental.chat.system.transform": async (_input: any, output: any) => {
|
|
1886
2281
|
if (bypassed) return;
|
|
1887
2282
|
try {
|
|
1888
|
-
cfg = loadConfig(); // Returns cache unless invalidated
|
|
1889
|
-
|
|
2283
|
+
cfg = loadConfig(projectDir); // Returns cache unless invalidated
|
|
2284
|
+
warnConfigIssues(cfg, logger);
|
|
1890
2285
|
} catch {
|
|
1891
2286
|
// Use last known config if file read fails
|
|
1892
2287
|
}
|
|
@@ -1939,10 +2334,29 @@ const ModelRouterPlugin: Plugin = async (ctx: RouterPluginInput) => {
|
|
|
1939
2334
|
const providerID = _input?.model?.providerID ?? "";
|
|
1940
2335
|
const modelID = _input?.model?.modelID ?? "";
|
|
1941
2336
|
const orchestratorModel = providerID && modelID ? `${providerID}/${modelID}` : modelID;
|
|
2337
|
+
if (providerID !== "") lastPrimary = { providerID, modelID: modelID === "" ? null : modelID };
|
|
1942
2338
|
|
|
1943
2339
|
let enfOn = false;
|
|
1944
2340
|
try { enfOn = resolveEnforcementMode({ config: cfg, env: process.env }).mode !== "off"; } catch {}
|
|
1945
|
-
|
|
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();
|
|
1946
2360
|
|
|
1947
2361
|
// 2.4.4, section 1.5-20: this orchestrator's still-unverified delegations (at most 5 shown,
|
|
1948
2362
|
// newest first), as one short block. Nothing is pushed when the list is empty, so the prompt
|
|
@@ -1975,8 +2389,8 @@ const ModelRouterPlugin: Plugin = async (ctx: RouterPluginInput) => {
|
|
|
1975
2389
|
"command.execute.before": async (input: any, output: any) => {
|
|
1976
2390
|
if (input.command === "tiers") {
|
|
1977
2391
|
try {
|
|
1978
|
-
cfg = loadConfig();
|
|
1979
|
-
|
|
2392
|
+
cfg = loadConfig(projectDir);
|
|
2393
|
+
warnConfigIssues(cfg, logger);
|
|
1980
2394
|
} catch {}
|
|
1981
2395
|
output.parts.push({
|
|
1982
2396
|
type: "text" as const,
|
|
@@ -1984,14 +2398,71 @@ const ModelRouterPlugin: Plugin = async (ctx: RouterPluginInput) => {
|
|
|
1984
2398
|
});
|
|
1985
2399
|
}
|
|
1986
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
|
+
|
|
2426
|
+
if (input.command === "router-reload") {
|
|
2427
|
+
invalidateConfigCache();
|
|
2428
|
+
cfg = loadConfig(projectDir);
|
|
2429
|
+
activeTiers = getActiveTiers(cfg);
|
|
2430
|
+
const mapping = Object.entries(activeTiers)
|
|
2431
|
+
.map(([name, tier]) => ` ${name} -> ${tier.model}`)
|
|
2432
|
+
.join("\n");
|
|
2433
|
+
const reloadError = getConfigReloadError(projectDir);
|
|
2434
|
+
output.parts.push({
|
|
2435
|
+
type: "text" as const,
|
|
2436
|
+
text: [
|
|
2437
|
+
...(reloadError
|
|
2438
|
+
? [
|
|
2439
|
+
`Config reload FAILED — keeping last valid config:\n${reloadError}`,
|
|
2440
|
+
"Model router is still using the last valid config.",
|
|
2441
|
+
]
|
|
2442
|
+
: ["Model router config reloaded."]),
|
|
2443
|
+
`Preset: ${cfg.activePreset}`,
|
|
2444
|
+
`Mode: ${cfg.activeMode ?? "normal"}`,
|
|
2445
|
+
"Tiers:",
|
|
2446
|
+
mapping,
|
|
2447
|
+
// opencode v1 builds its agent registry once at startup; only the v2
|
|
2448
|
+
// adapter re-runs the config hook + agent reload after /router-reload.
|
|
2449
|
+
...(ctx.routerHost === "v2"
|
|
2450
|
+
? []
|
|
2451
|
+
: [
|
|
2452
|
+
"Note: opencode v1 keeps subagent (task) models from startup; restart opencode to apply tier model changes to subagents. Routing and protocol already use the new config.",
|
|
2453
|
+
]),
|
|
2454
|
+
].join("\n"),
|
|
2455
|
+
});
|
|
2456
|
+
}
|
|
2457
|
+
|
|
1987
2458
|
if (input.command === "preset") {
|
|
1988
2459
|
try {
|
|
1989
|
-
cfg = loadConfig();
|
|
1990
|
-
|
|
2460
|
+
cfg = loadConfig(projectDir);
|
|
2461
|
+
warnConfigIssues(cfg, logger);
|
|
1991
2462
|
} catch {}
|
|
1992
2463
|
output.parts.push({
|
|
1993
2464
|
type: "text" as const,
|
|
1994
|
-
text: buildPresetOutput(cfg, input.arguments ?? ""),
|
|
2465
|
+
text: buildPresetOutput(cfg, input.arguments ?? "", projectDir),
|
|
1995
2466
|
});
|
|
1996
2467
|
}
|
|
1997
2468
|
|
|
@@ -2012,19 +2483,19 @@ const ModelRouterPlugin: Plugin = async (ctx: RouterPluginInput) => {
|
|
|
2012
2483
|
|
|
2013
2484
|
if (input.command === "budget") {
|
|
2014
2485
|
try {
|
|
2015
|
-
cfg = loadConfig();
|
|
2016
|
-
|
|
2486
|
+
cfg = loadConfig(projectDir);
|
|
2487
|
+
warnConfigIssues(cfg, logger);
|
|
2017
2488
|
} catch {}
|
|
2018
2489
|
output.parts.push({
|
|
2019
2490
|
type: "text" as const,
|
|
2020
|
-
text: buildBudgetOutput(cfg, input.arguments ?? ""),
|
|
2491
|
+
text: buildBudgetOutput(cfg, input.arguments ?? "", projectDir),
|
|
2021
2492
|
});
|
|
2022
2493
|
}
|
|
2023
2494
|
|
|
2024
2495
|
if (input.command === "router") {
|
|
2025
2496
|
try {
|
|
2026
|
-
cfg = loadConfig();
|
|
2027
|
-
|
|
2497
|
+
cfg = loadConfig(projectDir);
|
|
2498
|
+
warnConfigIssues(cfg, logger);
|
|
2028
2499
|
} catch {}
|
|
2029
2500
|
const args = (input.arguments ?? "").trim();
|
|
2030
2501
|
const parts = args.split(/\s+/).filter(Boolean);
|
|
@@ -2034,17 +2505,42 @@ const ModelRouterPlugin: Plugin = async (ctx: RouterPluginInput) => {
|
|
|
2034
2505
|
const catalog = await fetchCatalog();
|
|
2035
2506
|
const orphans = catalog ? findOrphanedStrongPatterns(cfg, catalog) : [];
|
|
2036
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
|
+
}
|
|
2037
2516
|
} else {
|
|
2038
|
-
text = buildRouterOutput(cfg, args);
|
|
2517
|
+
text = buildRouterOutput(cfg, args, projectDir);
|
|
2039
2518
|
// On the bare status view, surface stale or missing models inline.
|
|
2040
2519
|
if (sub === "") {
|
|
2041
|
-
|
|
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;
|
|
2042
2529
|
if (catalog) {
|
|
2043
2530
|
const issues = validateModels(cfg, catalog);
|
|
2044
2531
|
if (issues.length > 0) {
|
|
2045
2532
|
text += "\n\n" + formatModelIssues(issues);
|
|
2046
2533
|
}
|
|
2047
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
|
+
}
|
|
2048
2544
|
}
|
|
2049
2545
|
}
|
|
2050
2546
|
output.parts.push({ type: "text" as const, text });
|