opencode-model-router 2.2.0 → 2.4.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +214 -0
- package/README.md +90 -12
- package/package.json +4 -1
- package/src/commands/output.ts +24 -1
- package/src/compat/child-session.ts +43 -0
- package/src/compat/v2-client.ts +107 -7
- package/src/compat/v2-hooks.ts +1435 -44
- package/src/escalate/attempt-recorder.ts +263 -0
- package/src/escalate/ladder.ts +496 -10
- package/src/escalate/resume.ts +208 -0
- package/src/escalate/variants.ts +391 -0
- package/src/guard/enforce.ts +186 -22
- package/src/guard/guards.ts +132 -6
- package/src/guard/store.ts +5 -0
- package/src/index.ts +1193 -56
- package/src/router/build-info.ts +151 -0
- package/src/router/config.ts +1611 -19
- package/src/router/dispatch-header.ts +46 -4
- package/src/router/git-tools.ts +1152 -0
- package/src/router/guard-profile.ts +100 -0
- package/src/router/plugin-agents.ts +433 -0
- package/src/router/prompts.ts +26 -1
- package/src/router/protocol.ts +180 -0
- package/src/router/read-only.ts +149 -0
- package/src/router/role-agents.ts +409 -0
- package/src/router/roles-config.ts +429 -0
- package/src/router/roles.ts +600 -0
- package/src/router/run-tools.ts +913 -0
- package/src/router/sensitive-paths.ts +101 -0
- package/src/router/sessions.ts +533 -9
- package/src/router/subagents.ts +28 -1
- package/src/routing/advisor/findings.ts +898 -0
- package/src/routing/advisor/index.ts +614 -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 +594 -0
- package/src/routing/classify/route-line.ts +362 -0
- package/src/routing/classify/rules.ts +667 -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 +1310 -0
- package/src/routing/commands/annotate-plan.ts +652 -0
- package/src/routing/commands/stats.ts +134 -0
- package/src/routing/commands/v1-roles.ts +64 -0
- package/src/routing/engine/index.ts +32 -0
- package/src/routing/engine/kernel.ts +760 -0
- package/src/routing/engine/ladders.ts +802 -0
- package/src/routing/engine/plan.ts +404 -0
- package/src/routing/engine/protocol-line.ts +150 -0
- package/src/routing/engine/roles-taxonomy.ts +52 -0
- package/src/routing/engine/simulate.ts +167 -0
- package/src/routing/engine/types.ts +368 -0
- package/src/routing/file-lock.ts +53 -0
- package/src/routing/outcomes/beta.ts +147 -0
- package/src/routing/outcomes/cost.ts +313 -0
- package/src/routing/outcomes/index.ts +215 -0
- package/src/routing/outcomes/ingest.ts +960 -0
- package/src/routing/outcomes/persist.ts +1080 -0
- package/src/routing/outcomes/signals.ts +650 -0
- package/src/routing/outcomes/stats.ts +873 -0
- package/src/routing/outcomes/store.ts +673 -0
- package/src/routing/outcomes/types.ts +1093 -0
- package/src/routing/roles/authority.ts +495 -0
- package/src/routing/roles/binding.ts +543 -0
- package/src/routing/roles/policy.ts +416 -0
- package/src/routing/roles/work-root.ts +132 -0
- package/src/routing/wire/dispatch.ts +2088 -0
- package/src/routing/wire/hint.ts +222 -0
- package/src/routing/wire/host-info.ts +256 -0
- package/src/routing/wire/runtime.ts +348 -0
- package/src/v2.ts +40 -1
- package/src/verify/checker.ts +249 -7
- package/src/verify/deterministic.ts +10 -1
- package/src/verify/dispatch.ts +63 -6
- package/src/verify/dod.ts +127 -10
- package/src/verify/gate.ts +75 -7
- package/src/verify/types.ts +12 -0
- package/src/verify/wiring.ts +55 -10
- package/tiers.json +13 -5
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,13 +14,22 @@ import {
|
|
|
14
14
|
findProjectOverride,
|
|
15
15
|
resolveVerifyBudget,
|
|
16
16
|
resolveDepthLimit,
|
|
17
|
-
|
|
17
|
+
resolveRouting,
|
|
18
|
+
resolveRolesRouting,
|
|
19
|
+
resolveVariantSteps,
|
|
20
|
+
routerStatusLines,
|
|
21
|
+
warnConfigIssues,
|
|
22
|
+
resolveActiveTiers,
|
|
18
23
|
} from "./router/config";
|
|
19
24
|
import type { RouterConfig, TierConfig, Preset, ModeConfig, EffortLevel } from "./router/config";
|
|
20
25
|
import { buildAgentOptions, warnAgentOptionsEffortOnce } from "./router/agent-options";
|
|
26
|
+
import { gitTools } from "./router/git-tools";
|
|
27
|
+
import { isReadOnlyTier, legacyReadOnlyTools, mergePermissions, readOnlyPermissions } from "./router/read-only";
|
|
28
|
+
import { buildPluginAgentDefinition, mergeHostAgentEntry, pluginAgentMarker } from "./router/plugin-agents";
|
|
29
|
+
import { filterSensitiveGrep } from "./router/sensitive-paths";
|
|
21
30
|
import { selectTierPrompt, TOOL_AUTHORITY_CLAUSE } from "./router/prompts";
|
|
22
31
|
import { stripDelegateInstructions } from "./router/instructions";
|
|
23
|
-
import { buildDispatchHeader } from "./router/dispatch-header";
|
|
32
|
+
import { buildDispatchHeader, DISPATCH_HEADER_PREFIX, DISPATCH_HEADER_SEPARATOR, routeLineRoot } from "./router/dispatch-header";
|
|
24
33
|
import { detectFalseRefusal, parseTaskResult as parseRefusalTaskResult } from "./router/false-refusal";
|
|
25
34
|
import {
|
|
26
35
|
buildTiersOutput,
|
|
@@ -41,6 +50,8 @@ import {
|
|
|
41
50
|
} from "./commands/output";
|
|
42
51
|
import {
|
|
43
52
|
resolveSubagentOverrides,
|
|
53
|
+
DEFER_MISSING_SUBAGENT_NOTICE,
|
|
54
|
+
HOST_SEED_AGENTS,
|
|
44
55
|
mergeSubagentOverride,
|
|
45
56
|
} from "./router/subagents";
|
|
46
57
|
import { fingerprintToolCall } from "./guard/fingerprint";
|
|
@@ -53,10 +64,47 @@ import {
|
|
|
53
64
|
CLAUDE_ORCHESTRATOR_PREFIX,
|
|
54
65
|
CLAUDE_ANTI_NARRATION,
|
|
55
66
|
assembleSystemPrompt,
|
|
67
|
+
assembleRolesSystemPrompt,
|
|
56
68
|
DELEGATE_TOOL_DESCRIPTION,
|
|
57
69
|
} from "./router/protocol";
|
|
70
|
+
import { resolveRoles, type RoleSpec } from "./router/roles";
|
|
71
|
+
import { routerRunTool, type RunRecord } from "./router/run-tools";
|
|
72
|
+
import type { WorkRootAnswer } from "./router/git-tools";
|
|
73
|
+
import { GUARD_CUMULATIVE_MULTIPLIER, roleGuardProfile, type GuardProfile } from "./router/guard-profile";
|
|
74
|
+
import { currentBinding } from "./routing/roles/binding";
|
|
75
|
+
import { authorityTool, requestedAuthority } from "./routing/roles/authority";
|
|
76
|
+
import {
|
|
77
|
+
CARRIED_NO_PROCESS_REASON, roleAttemptVerification, roleEscalationAfterFail, roleMaxActions, routedRoleOf, strippedRouteRoot,
|
|
78
|
+
} from "./routing/wire/dispatch";
|
|
79
|
+
import { roleTierOrder } from "./routing/engine/ladders";
|
|
80
|
+
import { detectRedispatch, returnSignal, runSignal, parseReturnPrefix, type DispatchText } from "./routing/outcomes/signals";
|
|
81
|
+
import type { IngestSettings } from "./routing/outcomes/ingest";
|
|
82
|
+
import { captureBudget } from "./guard/enforce";
|
|
83
|
+
import { budgetClaimObserved, isIncompleteVerdict } from "./verify/checker";
|
|
84
|
+
import { lookupDispatch } from "./router/sessions";
|
|
58
85
|
import { resolveEnforcementMode } from "./router/enforcement";
|
|
59
86
|
import { createPluginLogger } from "./router/logger";
|
|
87
|
+
import { createCatalogPricing, createIngest, ingestSettings } from "./routing/outcomes/ingest";
|
|
88
|
+
import type { Ingest } from "./routing/outcomes/ingest";
|
|
89
|
+
import { isAnnotationRow, verdictGraderOf, verdictOf, type LogRow } from "./routing/outcomes/types";
|
|
90
|
+
import { createPersister, nodePersistDeps, summarizeRoles } from "./routing/outcomes";
|
|
91
|
+
import { roleAgentSteps } from "./router/role-agents";
|
|
92
|
+
import type { HostBudgetObservation } from "./compat/v2-hooks";
|
|
93
|
+
import { checkpointLine, formatStatsReply, runStatsCommand } from "./routing/commands/stats";
|
|
94
|
+
import { buildAnnotateDirectives } from "./routing/commands/annotate-plan";
|
|
95
|
+
import { applyV1Roles, hasExplicitV1Roles, v1AgentInfos } from "./routing/commands/v1-roles";
|
|
96
|
+
import type { HostAgentInfo } from "./routing/engine/types";
|
|
97
|
+
import { createEngineRuntime } from "./routing/wire/runtime";
|
|
98
|
+
import type { EngineRuntime } from "./routing/wire/runtime";
|
|
99
|
+
import {
|
|
100
|
+
advisorSettings,
|
|
101
|
+
catalogFromProviders,
|
|
102
|
+
createAdvisorNotifier,
|
|
103
|
+
formatFindings,
|
|
104
|
+
hostConfigFromAgents,
|
|
105
|
+
runAdvisor,
|
|
106
|
+
} from "./routing/advisor";
|
|
107
|
+
import type { AdvisorCatalogModel, AdvisorExtras, HostConfigView } from "./routing/advisor";
|
|
60
108
|
import {
|
|
61
109
|
findOrphanedStrongPatterns,
|
|
62
110
|
normalizeCatalog,
|
|
@@ -69,12 +117,14 @@ import {
|
|
|
69
117
|
buildCapBanner,
|
|
70
118
|
DEFAULT_TIER_CAPS,
|
|
71
119
|
READ_ONLY_TOOLS,
|
|
120
|
+
awaitExecutionEnd,
|
|
121
|
+
lastStepContext,
|
|
72
122
|
} from "./router/sessions";
|
|
73
123
|
import type { Cap, SubagentState } from "./router/sessions";
|
|
74
124
|
import { createTrajectoryStore } from "./telemetry/trajectory";
|
|
75
125
|
import { createGuardStore } from "./guard/store";
|
|
76
126
|
import { createIdleTtlSweeper } from "./router/idle-sweep";
|
|
77
|
-
import { guardBeforeCall, guardAfterCall, formatScorecard } from "./guard/enforce";
|
|
127
|
+
import { guardBeforeCall, guardAfterCall, guardRefusedCall, formatScorecard } from "./guard/enforce";
|
|
78
128
|
import { mkdirSync, writeFileSync, existsSync } from "node:fs";
|
|
79
129
|
import { tmpdir } from "node:os";
|
|
80
130
|
import { join, isAbsolute } from "node:path";
|
|
@@ -100,7 +150,12 @@ import {
|
|
|
100
150
|
buildForcingNote,
|
|
101
151
|
buildAcceptedSuffix,
|
|
102
152
|
} from "./verify/dispatch";
|
|
103
|
-
import {
|
|
153
|
+
import { requestedVerificationCwd, requestedVerificationCwdSource, verificationScope, type VerificationScope } from "./routing/roles/work-root";
|
|
154
|
+
import { newLadderState, recordAttempt, nextAction, advance, buildEscalatePolicy, formatLadderScorecard, startCostRatio } from "./escalate/ladder";
|
|
155
|
+
import { createCatalogLookup, planFirstAttempt, planNextAttempt } from "./escalate/resume";
|
|
156
|
+
import type { AttemptPlan, CatalogLookup } from "./escalate/resume";
|
|
157
|
+
import { classifyDelegation, createAttemptRecorder } from "./escalate/attempt-recorder";
|
|
158
|
+
import type { AttemptRecorder, DelegationFacts } from "./escalate/attempt-recorder";
|
|
104
159
|
import { createDepthTracker, DEPTH_LOOKUP_RETRY_MS } from "./router/depth";
|
|
105
160
|
import { createDepthGuard } from "./router/depth-guard";
|
|
106
161
|
import { applyEffortOverride, createEffortOverrideStore } from "./escalate/effort-override";
|
|
@@ -128,6 +183,34 @@ function describeError(error: unknown): string {
|
|
|
128
183
|
}
|
|
129
184
|
}
|
|
130
185
|
|
|
186
|
+
/**
|
|
187
|
+
* #84 P2.2 (advisor `tierDispatches`): dispatch rows WITHOUT a role at or after `since` — non-annotation `dispatch` decision rows,
|
|
188
|
+
* the first row per decision id (as `summarizeRoles` keeps them), whose row names no role and whose chosen key is not a role's.
|
|
189
|
+
*/
|
|
190
|
+
function tierDispatchCount(rows: readonly LogRow[], since: number): number {
|
|
191
|
+
const seen = new Set<string>();
|
|
192
|
+
let count = 0;
|
|
193
|
+
for (const row of rows) {
|
|
194
|
+
if (row.kind !== "decision" || isAnnotationRow(row) || row.step !== "dispatch" || seen.has(row.decisionID)) continue;
|
|
195
|
+
seen.add(row.decisionID);
|
|
196
|
+
const t = Date.parse(row.ts);
|
|
197
|
+
if (!Number.isFinite(t) || t < since) continue;
|
|
198
|
+
if (typeof row.role === "string" || row.chosen?.origin === "role") continue;
|
|
199
|
+
count += 1;
|
|
200
|
+
}
|
|
201
|
+
return count;
|
|
202
|
+
}
|
|
203
|
+
|
|
204
|
+
/**
|
|
205
|
+
* #84 P2.1 (handoffs 22, 23): one budget observation from the guard's and the host's. A stop seen by either is a stop; without a
|
|
206
|
+
* host observer (v1, or a host that does not hand one) the guard's alone; otherwise anything unobserved leaves it unobserved.
|
|
207
|
+
*/
|
|
208
|
+
function foldBudgetObservation(guard: HostBudgetObservation, host: HostBudgetObservation | undefined): HostBudgetObservation {
|
|
209
|
+
if (guard === true || host === true) return true;
|
|
210
|
+
if (host === undefined) return guard;
|
|
211
|
+
return guard === "unobserved" || host === "unobserved" ? "unobserved" : false;
|
|
212
|
+
}
|
|
213
|
+
|
|
131
214
|
function saveActivePreset(presetName: string, projectDir?: string): void {
|
|
132
215
|
const cfg = loadConfig(projectDir);
|
|
133
216
|
const resolved = resolvePresetName(cfg, presetName);
|
|
@@ -164,7 +247,7 @@ function saveEnforcementMode(mode: "off" | "advisory" | "enforced"): void {
|
|
|
164
247
|
* `/router` dispatch. Decides and persists here; rendering lives in
|
|
165
248
|
* src/commands/output.ts.
|
|
166
249
|
*/
|
|
167
|
-
function buildRouterOutput(cfg: RouterConfig, args: string, projectDir?: string): string {
|
|
250
|
+
function buildRouterOutput(cfg: RouterConfig, args: string, projectDir?: string, roles?: Iterable<RoleSpec>): string {
|
|
168
251
|
const tokens = (args ?? "").trim().split(/\s+/).filter(Boolean);
|
|
169
252
|
const sub = (tokens[0] ?? "").toLowerCase();
|
|
170
253
|
|
|
@@ -195,6 +278,9 @@ function buildRouterOutput(cfg: RouterConfig, args: string, projectDir?: string)
|
|
|
195
278
|
|
|
196
279
|
return buildRouterHelp(
|
|
197
280
|
resolveEnforcementMode({ config: cfg, env: process.env }).mode,
|
|
281
|
+
// `/router stats` is listed only for a config that has a `routing` block: without one `/router` is what it was (QA-2.4-3).
|
|
282
|
+
// #84 P2.2: the role lines, only when the caller hands roles (roles mode on v2); otherwise the help is what it was.
|
|
283
|
+
{ stats: cfg.routing !== undefined, ...(roles === undefined ? {} : { roles }) },
|
|
198
284
|
);
|
|
199
285
|
}
|
|
200
286
|
|
|
@@ -251,6 +337,20 @@ function warnSessionLookupFailedOnce(): void {
|
|
|
251
337
|
);
|
|
252
338
|
}
|
|
253
339
|
|
|
340
|
+
/**
|
|
341
|
+
* Agents the v1 host defines itself (opencode v1.18.34 agent.ts). They are absent from the `opencodeConfig.agent`
|
|
342
|
+
* record the config hook receives, so `subagentTiers` needs them listed to avoid a false `missing` skip (QA-81-4).
|
|
343
|
+
*/
|
|
344
|
+
const V1_HOST_BUILTIN_AGENTS: Record<string, { mode: string }> = {
|
|
345
|
+
general: { mode: "subagent" },
|
|
346
|
+
explore: { mode: "subagent" },
|
|
347
|
+
build: { mode: "primary" },
|
|
348
|
+
plan: { mode: "primary" },
|
|
349
|
+
title: { mode: "primary" },
|
|
350
|
+
summary: { mode: "primary" },
|
|
351
|
+
compaction: { mode: "primary" },
|
|
352
|
+
};
|
|
353
|
+
|
|
254
354
|
const SESSION_ROOT_MEMO_MAX = 500;
|
|
255
355
|
const SESSION_LOOKUP_RETRY_MS = DEPTH_LOOKUP_RETRY_MS;
|
|
256
356
|
|
|
@@ -264,6 +364,20 @@ const ModelRouterPlugin: Plugin = async (ctx: RouterPluginInput) => {
|
|
|
264
364
|
|
|
265
365
|
// Per-plugin-instance session store: owns subagentSessionIDs and subagentCapState.
|
|
266
366
|
const sessionStore = createSessionStore();
|
|
367
|
+
/** v1 sessionID -> plugin agent name, from chat.message (tool.execute.after has no `agent` on v1). */
|
|
368
|
+
const pluginAgentSessions = new Map<string, string>();
|
|
369
|
+
/** Records a plugin-agent session, bounded like the session-root memo (oldest entry evicted first). */
|
|
370
|
+
const rememberPluginAgentSession = (sessionID: string, agent: string): void => {
|
|
371
|
+
pluginAgentSessions.delete(sessionID);
|
|
372
|
+
pluginAgentSessions.set(sessionID, agent);
|
|
373
|
+
while (pluginAgentSessions.size > SESSION_ROOT_MEMO_MAX) {
|
|
374
|
+
const oldest = pluginAgentSessions.keys().next().value;
|
|
375
|
+
if (oldest === undefined) break;
|
|
376
|
+
pluginAgentSessions.delete(oldest);
|
|
377
|
+
}
|
|
378
|
+
};
|
|
379
|
+
/** Plugin agents the v1 config hook built on its previous run -> the host entry it merged (QA-81-8). */
|
|
380
|
+
let builtPluginAgents = new Map<string, Record<string, unknown> | undefined>();
|
|
267
381
|
let systemDebugLogged = false;
|
|
268
382
|
let dispatchDebugLogged = false;
|
|
269
383
|
|
|
@@ -373,6 +487,10 @@ const ModelRouterPlugin: Plugin = async (ctx: RouterPluginInput) => {
|
|
|
373
487
|
() => { sweepVerification(); },
|
|
374
488
|
// 2.4.2b: TTL eviction and reaping of the pending registry (pending.ts R7; no timer of its own).
|
|
375
489
|
() => { pending.sweep(); },
|
|
490
|
+
// 2.1.2: expired dispatch registrations and idle open outcome attempts (v2 only; `ingest` is declared below).
|
|
491
|
+
() => { ingest?.sweep(); },
|
|
492
|
+
// 2.3: release the ladder-attempt recorder's outcomes bundle once the engine is static again.
|
|
493
|
+
() => { attemptRecorder?.sweep(); },
|
|
376
494
|
]);
|
|
377
495
|
|
|
378
496
|
// Layer-2's impure corner: exec, fs, and the opencode client, built once and
|
|
@@ -383,6 +501,186 @@ const ModelRouterPlugin: Plugin = async (ctx: RouterPluginInput) => {
|
|
|
383
501
|
// has no /log endpoint. See src/router/logger.ts.
|
|
384
502
|
const logger = createPluginLogger(ctx.client);
|
|
385
503
|
const routerWarn = { warn: (message: string) => logger.warn(message) };
|
|
504
|
+
|
|
505
|
+
// -------------------------------------------------------------------------
|
|
506
|
+
// #84 P2.1 (T2.1.3): the role runtime of roles mode on OpenCode v2. `rolesNow()` is empty on v1 and in tiers mode, so
|
|
507
|
+
// every role branch below is skipped there and both stay byte-identical (§2.7, I1, I8).
|
|
508
|
+
// -------------------------------------------------------------------------
|
|
509
|
+
const isV2Host = ctx.routerHost === "v2";
|
|
510
|
+
/**
|
|
511
|
+
* QA-P21-1-8 (plan R8): the role runtime exists only when the plugin STARTED in roles mode — its role tools are registered at
|
|
512
|
+
* start and its role agents only then (the v2 adapter logs "restart OpenCode" when the config switches to roles at runtime).
|
|
513
|
+
*/
|
|
514
|
+
const startedInRoles = isV2Host && cfg.routing?.delegation === "roles";
|
|
515
|
+
/** QA-P21-2-4: the v2 adapter's "this role agent is registered" check (absent on v1 and before the adapter is set up). */
|
|
516
|
+
const roleLiveOf = (ctx as RouterPluginInput & { routerRoleLive?: (agent: string) => boolean | undefined }).routerRoleLive;
|
|
517
|
+
const NO_ROLES: ReadonlyMap<string, RoleSpec> = new Map();
|
|
518
|
+
const roleTables = new WeakMap<RouterConfig, ReadonlyMap<string, RoleSpec>>();
|
|
519
|
+
/** The role agents of the current config, cached per config object (hot reload builds a new one). */
|
|
520
|
+
const rolesNow = (): ReadonlyMap<string, RoleSpec> => {
|
|
521
|
+
if (!startedInRoles) return NO_ROLES;
|
|
522
|
+
const current = cfg;
|
|
523
|
+
let roles = roleTables.get(current);
|
|
524
|
+
if (roles === undefined) {
|
|
525
|
+
try {
|
|
526
|
+
roles = resolveRoles(current, "v2");
|
|
527
|
+
} catch (error) {
|
|
528
|
+
roles = NO_ROLES;
|
|
529
|
+
logger.warn("[router] roles: the role table could not be resolved; no role runtime for this config", { error: describeError(error) });
|
|
530
|
+
}
|
|
531
|
+
roleTables.set(current, roles);
|
|
532
|
+
}
|
|
533
|
+
// QA-P21-2-4: a role whose agent registration failed is not live (the v2 adapter's check; undefined = not known yet).
|
|
534
|
+
const live = roleLiveOf === undefined ? [...roles] : [...roles].filter(([name]) => roleLiveOf(name) !== false);
|
|
535
|
+
return live.length === roles.size ? roles : new Map(live);
|
|
536
|
+
};
|
|
537
|
+
const roleSpecOf = (agent: unknown): RoleSpec | undefined => (typeof agent === "string" ? rolesNow().get(agent) : undefined);
|
|
538
|
+
/** `maxOf` of every `currentBinding` call (handoff 33). */
|
|
539
|
+
const roleMaxOf = (agent: string) => roleMaxActions(rolesNow().get(agent));
|
|
540
|
+
/** Role child sessions → their role agent: from the tool hooks' calling agent and `session.created` (bounded, oldest out). */
|
|
541
|
+
const roleSessions = new Map<string, string>();
|
|
542
|
+
const ROLE_STATE_MAX = 1000;
|
|
543
|
+
const rememberRoleSession = (sessionID: unknown, agent: unknown): boolean => {
|
|
544
|
+
if (typeof sessionID !== "string" || sessionID === "" || typeof agent !== "string" || roleSpecOf(agent) === undefined) return false;
|
|
545
|
+
roleSessions.delete(sessionID);
|
|
546
|
+
roleSessions.set(sessionID, agent);
|
|
547
|
+
while (roleSessions.size > ROLE_STATE_MAX) roleSessions.delete(roleSessions.keys().next().value!);
|
|
548
|
+
return true;
|
|
549
|
+
};
|
|
550
|
+
/** The role of a session: what its tool hooks named, else what the dispatch registry recorded for it. */
|
|
551
|
+
const roleOfSession = (sessionID: unknown): RoleSpec | undefined => typeof sessionID !== "string" || sessionID === ""
|
|
552
|
+
? undefined : roleSpecOf(roleSessions.get(sessionID) ?? lookupDispatch(sessionID)?.agent);
|
|
553
|
+
/**
|
|
554
|
+
* Handoff 11 (P-10, P-18): the ONE work-root resolver of `router_run` and `router_git_*`, from the child's binding (bound by the
|
|
555
|
+
* adapter's `execute.before` before any tool of the child runs). Not a role session → `{ role: false }` (git keeps today's
|
|
556
|
+
* directory; `router_run` refuses); a role session without a binding or a work root → `{ role: true, root: null }` (I9).
|
|
557
|
+
*/
|
|
558
|
+
const resolveWorkRoot = (sessionID: string): WorkRootAnswer => {
|
|
559
|
+
if (roleOfSession(sessionID) === undefined) return { role: false };
|
|
560
|
+
return { role: true, root: currentBinding(sessionID, { maxOf: roleMaxOf })?.grant.workRoot ?? null };
|
|
561
|
+
};
|
|
562
|
+
/**
|
|
563
|
+
* #84 P2.3 (P-12, S11, I3): no `evaluate` fires for a plugin tool, so each tool's own resolver also refuses a role session whose
|
|
564
|
+
* dispatch grant lacks the tool's action (`router_run`: exec; `router_git_*`: local): the answer is then "no bound work root"
|
|
565
|
+
* and the tool refuses (I9). The context hook's catalog filter is the primary control; this one holds when a call gets through.
|
|
566
|
+
*/
|
|
567
|
+
const resolveWorkRootFor = (action: "router_run" | "router_git") => (sessionID: string): WorkRootAnswer => {
|
|
568
|
+
const answer = resolveWorkRoot(sessionID);
|
|
569
|
+
if (!answer.role) return answer;
|
|
570
|
+
const grant = currentBinding(sessionID, { maxOf: roleMaxOf })?.grant;
|
|
571
|
+
return grant !== undefined && grant.actions.has(action) ? answer : { role: true, root: null };
|
|
572
|
+
};
|
|
573
|
+
/** What a routed role dispatch decided for its child's guard (QA-G-A3-3): the dispatched tier and the route line's `budget=`. */
|
|
574
|
+
interface RoutedGuardInput { readonly agent: string; readonly tier: string; readonly routeBudget: number | null }
|
|
575
|
+
/**
|
|
576
|
+
* QA-G-B-5 / QA-G-A3-3: each routed role dispatch this instance noted, by the parent's call — when it was dispatched (the
|
|
577
|
+
* attempt's start, for the `run` signal) and its routed guard input. Bounded, oldest out.
|
|
578
|
+
*/
|
|
579
|
+
const roleAttempts = new Map<string, RoutedGuardInput & { readonly at: number }>();
|
|
580
|
+
/** QA-G-A3-3: the routed guard input of each role child — its latest routed dispatch or resume (a resume replaces it). */
|
|
581
|
+
const roleChildGuards = new Map<string, RoutedGuardInput>();
|
|
582
|
+
/** QA-G-A3-2-2: the largest round budget each role child's guard profile had (its cumulative limit follows it). */
|
|
583
|
+
const roleBudgetPeaks = new Map<string, number>();
|
|
584
|
+
const setBounded = <T>(map: Map<string, T>, key: string, value: T): void => {
|
|
585
|
+
map.delete(key);
|
|
586
|
+
map.set(key, value);
|
|
587
|
+
while (map.size > ROLE_STATE_MAX) map.delete(map.keys().next().value!);
|
|
588
|
+
};
|
|
589
|
+
/**
|
|
590
|
+
* QA-G-A3-3: the routed guard input of a role child. A resume set it in `noteRoleDispatch`; a fresh child takes its dispatch's
|
|
591
|
+
* once it is bound EXACTLY (its binding names the parent's call). Undefined when no routed decision is known for it.
|
|
592
|
+
*/
|
|
593
|
+
const routedGuardOf = (sessionID: string): RoutedGuardInput | undefined => {
|
|
594
|
+
const known = roleChildGuards.get(sessionID);
|
|
595
|
+
if (known !== undefined) return known;
|
|
596
|
+
const binding = currentBinding(sessionID, { maxOf: roleMaxOf });
|
|
597
|
+
const callID = binding?.kind === "exact" ? binding.candidates[0] : undefined;
|
|
598
|
+
const attempt = callID === undefined ? undefined : roleAttempts.get(callID);
|
|
599
|
+
if (attempt === undefined) return undefined;
|
|
600
|
+
const routed: RoutedGuardInput = { agent: attempt.agent, tier: attempt.tier, routeBudget: attempt.routeBudget };
|
|
601
|
+
setBounded(roleChildGuards, sessionID, routed);
|
|
602
|
+
return routed;
|
|
603
|
+
};
|
|
604
|
+
/**
|
|
605
|
+
* Handoff 27: the guard profile of a role child — the role's budget for the tier it runs on, raised by the dispatch's `budget=`.
|
|
606
|
+
* QA-G-A3-3: both come from the ROUTED decision of the child's current dispatch (a resume's own tier and `budget=`); only a child
|
|
607
|
+
* without one (a delegate's unbound child, another instance's) falls back to the dispatch registry's tier (else the role's floor,
|
|
608
|
+
* its registered fallback model, P-1) and the bound dispatch budget.
|
|
609
|
+
*/
|
|
610
|
+
const roleGuardProfileOf = (sessionID: unknown, agent: unknown): GuardProfile | undefined => {
|
|
611
|
+
const spec = roleSpecOf(agent) ?? roleOfSession(sessionID);
|
|
612
|
+
if (spec === undefined || typeof sessionID !== "string") return undefined;
|
|
613
|
+
const routed = routedGuardOf(sessionID);
|
|
614
|
+
let profile: GuardProfile;
|
|
615
|
+
if (routed !== undefined && routed.agent === spec.agent) {
|
|
616
|
+
profile = roleGuardProfile(spec, routed.tier, routed.routeBudget);
|
|
617
|
+
} else {
|
|
618
|
+
const record = lookupDispatch(sessionID);
|
|
619
|
+
const tier = record?.agent === spec.agent && typeof record.tier === "string" && record.tier !== "" ? record.tier : spec.tierRange.floor;
|
|
620
|
+
profile = roleGuardProfile(spec, tier, currentBinding(sessionID, { maxOf: roleMaxOf })?.budget ?? null);
|
|
621
|
+
}
|
|
622
|
+
// QA-G-A3-2-2 (§2.6): the cumulative limit spans the child's rounds, so it follows the LARGEST round budget the child had
|
|
623
|
+
// (a later round with a smaller budget never shrinks it below what earlier rounds were allowed).
|
|
624
|
+
const peak = Math.max(roleBudgetPeaks.get(sessionID) ?? 0, profile.budget);
|
|
625
|
+
if (roleBudgetPeaks.get(sessionID) !== peak) setBounded(roleBudgetPeaks, sessionID, peak);
|
|
626
|
+
return { ...profile, cumulative: Math.max(profile.cumulative, peak * GUARD_CUMULATIVE_MULTIPLIER) };
|
|
627
|
+
};
|
|
628
|
+
/** Handoff 13 (P1.4 `run` signal): router-observed runs and edit times of role children, bounded per child and overall. */
|
|
629
|
+
const roleRuns = new Map<string, RunRecord[]>();
|
|
630
|
+
const roleEdits = new Map<string, number[]>();
|
|
631
|
+
/** QA-P21-1-7: role children that made a tool call while the router was bypassed (their edits were not recorded). */
|
|
632
|
+
const roleBypassedCalls = new Set<string>();
|
|
633
|
+
const noteBypassedRoleCall = (sessionID: unknown): void => {
|
|
634
|
+
if (typeof sessionID !== "string" || roleOfSession(sessionID) === undefined) return;
|
|
635
|
+
roleBypassedCalls.add(sessionID);
|
|
636
|
+
while (roleBypassedCalls.size > ROLE_STATE_MAX) roleBypassedCalls.delete(roleBypassedCalls.values().next().value!);
|
|
637
|
+
};
|
|
638
|
+
const pushBounded = <T>(map: Map<string, T[]>, key: string, value: T): void => {
|
|
639
|
+
const list = map.get(key) ?? [];
|
|
640
|
+
map.delete(key);
|
|
641
|
+
list.push(value);
|
|
642
|
+
while (list.length > 64) list.shift();
|
|
643
|
+
map.set(key, list);
|
|
644
|
+
while (map.size > ROLE_STATE_MAX) map.delete(map.keys().next().value!);
|
|
645
|
+
};
|
|
646
|
+
const ROLE_EDIT_TOOLS: ReadonlySet<string> = new Set(["edit", "write", "patch", "multiedit", "apply_patch"]);
|
|
647
|
+
/** Handoffs 16-18: the parent's role dispatches (by call), for the re-dispatch signal; bounded, oldest out. */
|
|
648
|
+
const roleDispatchTexts = new Map<string, DispatchText>();
|
|
649
|
+
/** IngestSettings.roleAgentIds from `resolveRoles` (handoff 21): the same object per base settings, so ingestion keeps its caches. */
|
|
650
|
+
const roleIngestSettings = new WeakMap<IngestSettings, IngestSettings>();
|
|
651
|
+
const withRoleAgents = (settings: IngestSettings | null): IngestSettings | null => {
|
|
652
|
+
const roles = rolesNow();
|
|
653
|
+
if (settings === null || roles.size === 0) return settings;
|
|
654
|
+
let extended = roleIngestSettings.get(settings);
|
|
655
|
+
if (extended === undefined) {
|
|
656
|
+
extended = Object.freeze({ ...settings, roleAgentIds: new Set(roles.keys()) });
|
|
657
|
+
roleIngestSettings.set(settings, extended);
|
|
658
|
+
}
|
|
659
|
+
return extended;
|
|
660
|
+
};
|
|
661
|
+
// 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
|
|
662
|
+
// routing.engine != static. Verdicts and false refusals come from the hooks below; the v2 adapter receives this same
|
|
663
|
+
// instance through `routerOnIngest` and feeds it the step and session events, so there is a single settings source.
|
|
664
|
+
const ingestAbort = new AbortController();
|
|
665
|
+
const ingest: Ingest | undefined = ctx.routerHost === "v2" ? (() => {
|
|
666
|
+
const core = createIngest({
|
|
667
|
+
settings: () => withRoleAgents(ingestSettings(cfg, "v2")),
|
|
668
|
+
logger,
|
|
669
|
+
...(ctx.routerCatalog
|
|
670
|
+
? { pricing: createCatalogPricing(ctx.routerCatalog, { logger, cacheKey: ctx.directory, signal: ingestAbort.signal }) }
|
|
671
|
+
: {}),
|
|
672
|
+
});
|
|
673
|
+
// Disposing also releases any lookup still waiting for the catalog (QA-2.1-5): shutdown never waits for it.
|
|
674
|
+
return { ...core, dispose: async () => { ingestAbort.abort(); await core.dispose(); } };
|
|
675
|
+
})() : undefined;
|
|
676
|
+
if (ingest) ctx.routerOnIngest?.(ingest);
|
|
677
|
+
// Phase 2.3: what the delegate ladder tells the telemetry about each attempt (registry entry + decision row). v2 only (D1).
|
|
678
|
+
const attemptRecorder: AttemptRecorder | undefined = ctx.routerHost === "v2"
|
|
679
|
+
? createAttemptRecorder({ host: "v2", config: () => cfg, logger })
|
|
680
|
+
: undefined;
|
|
681
|
+
resolveRouting(cfg, ctx.routerHost === "v2" ? "v2" : "v1", logger); // v1 + engine != static: log the notice once, at startup (QA-1.1-8)
|
|
682
|
+
// #84 P2.1 (handoff 1): v1 + any roles key: the "roles delegation requires OpenCode v2" notice, once, at startup.
|
|
683
|
+
resolveRolesRouting(cfg, ctx.routerHost === "v2" ? "v2" : "v1", logger);
|
|
386
684
|
const depthTracker = createDepthTracker({
|
|
387
685
|
async getParent(id) {
|
|
388
686
|
if (sessionRootMemo.get(id) === true) return null;
|
|
@@ -479,20 +777,188 @@ const ModelRouterPlugin: Plugin = async (ctx: RouterPluginInput) => {
|
|
|
479
777
|
// subagent tracking, cap enforcement, and narration detection for the
|
|
480
778
|
// current plugin lifetime (i.e., until OpenCode is restarted).
|
|
481
779
|
let bypassed = false;
|
|
780
|
+
// #84 P2.1: the v2 adapter's role path reads the bypass state (the router gate does not run while bypassed, S10/P-9).
|
|
781
|
+
(ctx as RouterPluginInput & { routerOnBypassState?: (read: () => boolean) => void }).routerOnBypassState?.(() => bypassed);
|
|
782
|
+
/** QA-P21-1-3: the budget snapshot of a role child as the signals AND the adapter's budget notice read it (guard + read cap). */
|
|
783
|
+
const roleBudgetSnapshot = (childSessionID: string) => captureBudget(childSessionID, sessionStore.readCapReached(childSessionID));
|
|
784
|
+
(ctx as RouterPluginInput & { routerOnBudgetSnapshot?: (read: typeof roleBudgetSnapshot) => void }).routerOnBudgetSnapshot?.(roleBudgetSnapshot);
|
|
785
|
+
/**
|
|
786
|
+
* QA-G-A3-2 (§2.9 E6, R7 REFUSAL_CAP): a role child's call refused where the guard's before-hook never sees it — the v2
|
|
787
|
+
* adapter's role-authority check (thrown in its `execute.before`, before this plugin's hook) and host permission denials (its
|
|
788
|
+
* `execute.after` with a permission error) — counted on the child's guard state like the guard's own refusals, so `denied_cap`
|
|
789
|
+
* stops a child that keeps retrying refused actions. Returns the guard's text for the refusal (its stop, or the advisory
|
|
790
|
+
* banner), or undefined. Role children only; nothing while bypassed or when enforcement is off. Never throws.
|
|
791
|
+
*/
|
|
792
|
+
const recordRoleRefusal = (sessionID: string, agent: string | undefined, tool: string, args: unknown): string | undefined => {
|
|
793
|
+
try {
|
|
794
|
+
if (bypassed) return undefined;
|
|
795
|
+
// A child whose first calls are all refused never reached the before-hook that marks it: as there, from its own agent.
|
|
796
|
+
if (rememberRoleSession(sessionID, agent)) sessionStore.markChildSession(sessionID);
|
|
797
|
+
if (roleOfSession(sessionID) === undefined || !sessionStore.isSubagent(sessionID)) return undefined;
|
|
798
|
+
const profile = roleGuardProfileOf(sessionID, agent);
|
|
799
|
+
return guardRefusedCall({
|
|
800
|
+
cfg,
|
|
801
|
+
tier: sessionStore.getTier(sessionID),
|
|
802
|
+
trivial: sessionStore.isTrivial(sessionID),
|
|
803
|
+
cap: sessionStore.getCap(sessionID),
|
|
804
|
+
sessionID,
|
|
805
|
+
tool,
|
|
806
|
+
toolArgs: args,
|
|
807
|
+
store: guardStore,
|
|
808
|
+
env: process.env,
|
|
809
|
+
...(profile === undefined ? {} : { profile }),
|
|
810
|
+
});
|
|
811
|
+
} catch {
|
|
812
|
+
return undefined; // never break a real session on a guard-internal error
|
|
813
|
+
}
|
|
814
|
+
};
|
|
815
|
+
(ctx as RouterPluginInput & { routerOnRefusal?: (record: typeof recordRoleRefusal) => void }).routerOnRefusal?.(recordRoleRefusal);
|
|
816
|
+
/** #84 P2.1 (handoff 22): the v2 adapter's host-side budget observation of a role child (step limit, context overflow). */
|
|
817
|
+
const hostBudgetOf = (ctx as RouterPluginInput & {
|
|
818
|
+
routerHostBudget?: (childSessionID: string, stepLimit: number | null) => HostBudgetObservation | undefined;
|
|
819
|
+
}).routerHostBudget;
|
|
482
820
|
|
|
483
|
-
|
|
821
|
+
warnConfigIssues(cfg, logger);
|
|
484
822
|
|
|
485
823
|
// Fetch and normalize opencode's live provider/model catalog. Best-effort:
|
|
486
824
|
// returns null when the client call fails, e.g. the server is not ready yet.
|
|
487
825
|
// The pure analysis (validateModels) lives in src/router/catalog.ts.
|
|
488
|
-
const
|
|
826
|
+
const fetchCatalogRaw = async (): Promise<{ catalog: Catalog; raw: unknown } | null> => {
|
|
489
827
|
try {
|
|
490
828
|
const res: any = await ctx.client.config.providers();
|
|
491
|
-
return normalizeCatalog(res?.data);
|
|
829
|
+
return { catalog: normalizeCatalog(res?.data), raw: res?.data };
|
|
492
830
|
} catch {
|
|
493
831
|
return null;
|
|
494
832
|
}
|
|
495
833
|
};
|
|
834
|
+
const fetchCatalog = async (): Promise<Catalog | null> => (await fetchCatalogRaw())?.catalog ?? null;
|
|
835
|
+
|
|
836
|
+
// M8 (Phase 2.4): the cost doctor reads the host's agents and model catalog (v2 only, D1). Each call is bounded and failing
|
|
837
|
+
// one only leaves the checks that need it silent; nothing here ever throws into a session.
|
|
838
|
+
// 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).
|
|
839
|
+
let lastPrimary: { providerID: string; modelID: string | null } | null = null;
|
|
840
|
+
const ADVISOR_HOST_TIMEOUT_MS = 3_000;
|
|
841
|
+
// The catalog comes from `config.providers()` (the call `/router` already makes for the model check, enriched with cost and capabilities
|
|
842
|
+
// 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
|
|
843
|
+
// when the caller already has it.
|
|
844
|
+
/** #84 P2.2: the window of the decision log the roles checks of the cost doctor read. */
|
|
845
|
+
const ADVISOR_ROLE_WINDOW_MS = 7 * 24 * 60 * 60 * 1000;
|
|
846
|
+
/**
|
|
847
|
+
* #84 P2.2: the extras of the cost doctor's roles checks — the host and, in roles mode with a live engine, the role × tier
|
|
848
|
+
* statistics and the tier dispatch count of the decision log over {@link ADVISOR_ROLE_WINDOW_MS}. Tiers mode and v1 read nothing
|
|
849
|
+
* (`{ host }` only, which no tier check reads); a read failure leaves the statistics out, so those checks stay silent.
|
|
850
|
+
*/
|
|
851
|
+
const advisorExtras = async (): Promise<AdvisorExtras> => {
|
|
852
|
+
const host = isV2Host ? "v2" as const : "v1" as const;
|
|
853
|
+
if (rolesNow().size === 0) return { host };
|
|
854
|
+
const live = ingestSettings(cfg, "v2");
|
|
855
|
+
if (live === null) return { host }; // engine static: no decision log
|
|
856
|
+
try {
|
|
857
|
+
const read = await createPersister(live.outcomesDir, nodePersistDeps({ warn: () => undefined })).readRows();
|
|
858
|
+
const since = Date.now() - ADVISOR_ROLE_WINDOW_MS;
|
|
859
|
+
return { host, roleStats: summarizeRoles(null, read.rows, { since, until: null }), tierDispatches: tierDispatchCount(read.rows, since) };
|
|
860
|
+
} catch (error) {
|
|
861
|
+
logger.warn("[router] cost doctor: the role statistics are unavailable", { error: describeError(error) });
|
|
862
|
+
return { host };
|
|
863
|
+
}
|
|
864
|
+
};
|
|
865
|
+
const gatherAdvisorInputs = async (
|
|
866
|
+
prefetched?: { raw: unknown } | null,
|
|
867
|
+
): Promise<{ host: HostConfigView | null; catalog: AdvisorCatalogModel[] | null; extras: AdvisorExtras }> => {
|
|
868
|
+
const attempt = async <T>(label: string, call: (() => Promise<T>) | undefined): Promise<T | null> => {
|
|
869
|
+
if (call === undefined) return null;
|
|
870
|
+
try {
|
|
871
|
+
return await withTimeout(call(), ADVISOR_HOST_TIMEOUT_MS, label);
|
|
872
|
+
} catch (error) {
|
|
873
|
+
logger.warn(`[router] cost doctor: the ${label} is unavailable`, { error: describeError(error) });
|
|
874
|
+
return null;
|
|
875
|
+
}
|
|
876
|
+
};
|
|
877
|
+
const [agents, providers, extras] = await Promise.all([
|
|
878
|
+
attempt("host agent list", ctx.routerAgents),
|
|
879
|
+
prefetched !== undefined ? Promise.resolve(prefetched) : attempt("model catalog", fetchCatalogRaw),
|
|
880
|
+
advisorExtras(),
|
|
881
|
+
]);
|
|
882
|
+
return {
|
|
883
|
+
host: agents === null ? null : hostConfigFromAgents(agents, lastPrimary),
|
|
884
|
+
catalog: providers === null ? null : catalogFromProviders(providers.raw),
|
|
885
|
+
extras,
|
|
886
|
+
};
|
|
887
|
+
};
|
|
888
|
+
const advisorNotifier = ctx.routerHost === "v2"
|
|
889
|
+
? createAdvisorNotifier({ settings: () => advisorSettings(cfg, "v2", { project: projectDir }), config: () => cfg, gather: gatherAdvisorInputs, logger })
|
|
890
|
+
: undefined;
|
|
891
|
+
// `/annotate-plan` (Phase 2.4.4): its own engine runtime (agent list, catalog, classifier backend, outcome store), created on the first use
|
|
892
|
+
// and only on v2; with `routing.engine: static` its `prepare()` answers null before any host call, store or file.
|
|
893
|
+
let annotateRuntime: EngineRuntime | undefined;
|
|
894
|
+
const annotatePlanRuntime = (): EngineRuntime | undefined => {
|
|
895
|
+
if (ctx.routerHost !== "v2" || ctx.routerAgents === undefined || ctx.routerCatalog === undefined) return undefined;
|
|
896
|
+
annotateRuntime ??= createEngineRuntime({
|
|
897
|
+
loadConfig: () => cfg,
|
|
898
|
+
listAgents: ctx.routerAgents,
|
|
899
|
+
listModels: ctx.routerCatalog,
|
|
900
|
+
...(ctx.routerGenerate === undefined ? {} : { generate: ctx.routerGenerate }),
|
|
901
|
+
logger,
|
|
902
|
+
});
|
|
903
|
+
return annotateRuntime;
|
|
904
|
+
};
|
|
905
|
+
// v1 only (A28): the host's agent list for the text-only roles line, read through `client.app.agents()` and never fetched unless
|
|
906
|
+
// `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
|
|
907
|
+
// 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
|
|
908
|
+
// failed refresh keeps the last list and is logged; a list that was never fetched leaves the line as it is without roles.
|
|
909
|
+
const V1_AGENTS_TTL_MS = 60_000;
|
|
910
|
+
let v1Agents: { at: number; infos: HostAgentInfo[] | null } | null = null;
|
|
911
|
+
let v1AgentsRefresh: Promise<void> | null = null;
|
|
912
|
+
const refreshV1Agents = (): void => {
|
|
913
|
+
if (v1AgentsRefresh !== null) return;
|
|
914
|
+
const run = (async (): Promise<void> => {
|
|
915
|
+
try {
|
|
916
|
+
const res = await withTimeout(Promise.resolve(ctx.client.app.agents()), 2_000, "v1 agent list");
|
|
917
|
+
const data: unknown = (res as { data?: unknown } | undefined)?.data;
|
|
918
|
+
v1Agents = { at: Date.now(), infos: Array.isArray(data) ? v1AgentInfos(data) : (v1Agents?.infos ?? null) };
|
|
919
|
+
} catch (error) {
|
|
920
|
+
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) });
|
|
921
|
+
v1Agents = { at: Date.now(), infos: v1Agents?.infos ?? null }; // keep serving the stale list; try again after the interval
|
|
922
|
+
}
|
|
923
|
+
})().finally(() => {
|
|
924
|
+
if (v1AgentsRefresh === run) v1AgentsRefresh = null;
|
|
925
|
+
});
|
|
926
|
+
v1AgentsRefresh = run;
|
|
927
|
+
};
|
|
928
|
+
/** The last known v1 agent list (possibly stale, possibly `null`), starting a background refresh when it is due. Synchronous. */
|
|
929
|
+
const v1AgentsNow = (): HostAgentInfo[] | null => {
|
|
930
|
+
if (v1Agents === null || Date.now() - v1Agents.at >= V1_AGENTS_TTL_MS) refreshV1Agents();
|
|
931
|
+
return v1Agents?.infos ?? null;
|
|
932
|
+
}; /** 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. */
|
|
933
|
+
const deliverAdvisorNotice = (sessionID: string, notice: string): void => {
|
|
934
|
+
const synthetic = ctx.routerSynthetic;
|
|
935
|
+
if (synthetic === undefined) {
|
|
936
|
+
logger.warn(notice); // no synthetic-message call on this host: the log line is the whole delivery
|
|
937
|
+
return;
|
|
938
|
+
}
|
|
939
|
+
const text = `Cost doctor notice for the user (say it once, in one short sentence, then carry on with the task):\n${notice}`;
|
|
940
|
+
void Promise.resolve()
|
|
941
|
+
.then(() => synthetic({ sessionID, text, description: "Model router cost doctor" }))
|
|
942
|
+
.catch((error: unknown) => {
|
|
943
|
+
logger.warn("[router] cost doctor: notice not delivered", { error: describeError(error) });
|
|
944
|
+
});
|
|
945
|
+
};
|
|
946
|
+
/** The `/router` section "Cost doctor" (on demand: runs the checks now, writes nothing). */
|
|
947
|
+
const buildCostDoctorLines = async (prefetched?: { raw: unknown } | null): Promise<string[]> => {
|
|
948
|
+
const routing = resolveRouting(cfg, "v2");
|
|
949
|
+
if (!routing.advisor.enabled) return ["Cost doctor: disabled (routing.advisor.enabled is false)."];
|
|
950
|
+
const { host, catalog, extras } = await gatherAdvisorInputs(prefetched);
|
|
951
|
+
const lines = formatFindings(runAdvisor(cfg, host, catalog, logger, extras), {
|
|
952
|
+
hostKnown: host !== null,
|
|
953
|
+
catalogKnown: catalog !== null && catalog.length > 0,
|
|
954
|
+
primaryKnown: lastPrimary !== null,
|
|
955
|
+
});
|
|
956
|
+
// Phase 2.3 handoff (decision 16): a ladder row's confidence is not the evidence share the dispatch rows carry.
|
|
957
|
+
if (routing.engine !== "static") {
|
|
958
|
+
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)).");
|
|
959
|
+
}
|
|
960
|
+
return lines;
|
|
961
|
+
};
|
|
496
962
|
|
|
497
963
|
// Deferred passive catalog check. The first orchestrator turn only STARTS the
|
|
498
964
|
// fetch (fire-and-forget, never awaited on the chat.message hot path) and
|
|
@@ -542,6 +1008,8 @@ const ModelRouterPlugin: Plugin = async (ctx: RouterPluginInput) => {
|
|
|
542
1008
|
} catch (error) {
|
|
543
1009
|
logger.warn("[verify] router_verify not registered: the enforcement mode could not be resolved", { error: scrubText(String(error)) });
|
|
544
1010
|
}
|
|
1011
|
+
// QA-P21-2 nit 3: the role path's deferral check follows it (nothing is deferred without router_verify).
|
|
1012
|
+
(ctx as RouterPluginInput & { routerOnVerifyEnabled?: (read: () => boolean) => void }).routerOnVerifyEnabled?.(() => routerVerifyEnabled);
|
|
545
1013
|
/**
|
|
546
1014
|
* 2.4.2 + 2.4.3b: a delegation defers only when `router_verify` exists to verify it later. A
|
|
547
1015
|
* footer never names a tool this instance did not register; without it the delegation keeps the
|
|
@@ -562,6 +1030,262 @@ const ModelRouterPlugin: Plugin = async (ctx: RouterPluginInput) => {
|
|
|
562
1030
|
return (await lookupRootSession(sessionID)) === true;
|
|
563
1031
|
};
|
|
564
1032
|
|
|
1033
|
+
/**
|
|
1034
|
+
* Phase 2.3: the host model catalog as the delegate ladder reads it (variants and limits per model). Best effort: a
|
|
1035
|
+
* missing, failing or slow catalog is `undefined`, and the ladder then behaves exactly as without variant info
|
|
1036
|
+
* (fresh sessions, tier ratios). QA-2.3-3: the answer, positive or negative, is cached for the TTL; delegations that
|
|
1037
|
+
* ask while a load is running share it; a call that outlived its timeout is not repeated behind itself (a late answer
|
|
1038
|
+
* still fills the cache); and a failure is logged once per streak, until a load succeeds. So with a hung catalog the
|
|
1039
|
+
* first delegation waits for the timeout and every later one answers at once.
|
|
1040
|
+
*/
|
|
1041
|
+
/** How long a failed ladder attempt waits for its child's execution end before it starts fresh (QA-2.3-2). */
|
|
1042
|
+
const RESUME_END_WAIT_MS = 1_000;
|
|
1043
|
+
const RUNNER_CATALOG_TTL_MS = 15_000;
|
|
1044
|
+
const RUNNER_CATALOG_TIMEOUT_MS = 3_000;
|
|
1045
|
+
/** A catalog call still pending after this long is abandoned: a new one may start behind it. */
|
|
1046
|
+
const RUNNER_CATALOG_ABANDON_MS = 60_000;
|
|
1047
|
+
/** The last answer, valid for the TTL; `lookup` undefined = the catalog was unavailable. */
|
|
1048
|
+
let runnerCatalog: { at: number; lookup: CatalogLookup | undefined } | undefined;
|
|
1049
|
+
/** The load in progress (bounded by the timeout), shared by every delegation that asks meanwhile. */
|
|
1050
|
+
let runnerCatalogLoad: Promise<CatalogLookup | undefined> | undefined;
|
|
1051
|
+
/** When the outstanding `routerCatalog()` call started; it may outlive its timeout. */
|
|
1052
|
+
let runnerCatalogCallAt: number | undefined;
|
|
1053
|
+
/** 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. */
|
|
1054
|
+
let runnerCatalogCallId = 0;
|
|
1055
|
+
let runnerCatalogFailing = false;
|
|
1056
|
+
const runnerCatalogFailed = (error: unknown): undefined => {
|
|
1057
|
+
runnerCatalog = { at: Date.now(), lookup: undefined };
|
|
1058
|
+
if (!runnerCatalogFailing) {
|
|
1059
|
+
runnerCatalogFailing = true;
|
|
1060
|
+
logger.warn("[router] ladder: the model catalog is unavailable; variant steps and resume are off until it answers", { error: describeError(error) });
|
|
1061
|
+
}
|
|
1062
|
+
return undefined;
|
|
1063
|
+
};
|
|
1064
|
+
const loadRunnerCatalog = (): Promise<CatalogLookup | undefined> => {
|
|
1065
|
+
const list = ctx.routerCatalog;
|
|
1066
|
+
if (!list) return Promise.resolve(undefined);
|
|
1067
|
+
const nowMs = Date.now();
|
|
1068
|
+
if (runnerCatalog !== undefined && nowMs - runnerCatalog.at < RUNNER_CATALOG_TTL_MS) return Promise.resolve(runnerCatalog.lookup);
|
|
1069
|
+
if (runnerCatalogLoad !== undefined) return runnerCatalogLoad;
|
|
1070
|
+
if (runnerCatalogCallAt !== undefined && nowMs - runnerCatalogCallAt < RUNNER_CATALOG_ABANDON_MS) {
|
|
1071
|
+
// An earlier call timed out and is still outstanding: no second `list()` behind it.
|
|
1072
|
+
runnerCatalog = { at: nowMs, lookup: undefined };
|
|
1073
|
+
return Promise.resolve(undefined);
|
|
1074
|
+
}
|
|
1075
|
+
runnerCatalogCallAt = nowMs;
|
|
1076
|
+
const callId = ++runnerCatalogCallId;
|
|
1077
|
+
const answer = Promise.resolve().then(() => list()).then(
|
|
1078
|
+
(models) => {
|
|
1079
|
+
// A late answer is still a catalog, whichever call it answers; only the latest call owns the marker.
|
|
1080
|
+
if (callId === runnerCatalogCallId) runnerCatalogCallAt = undefined;
|
|
1081
|
+
const lookup = createCatalogLookup(models);
|
|
1082
|
+
runnerCatalog = { at: Date.now(), lookup };
|
|
1083
|
+
runnerCatalogFailing = false;
|
|
1084
|
+
return lookup;
|
|
1085
|
+
},
|
|
1086
|
+
(error: unknown) => {
|
|
1087
|
+
// A failure of an abandoned call says nothing about the newer one: leave its marker and the cache alone.
|
|
1088
|
+
if (callId !== runnerCatalogCallId) return undefined;
|
|
1089
|
+
runnerCatalogCallAt = undefined;
|
|
1090
|
+
return runnerCatalogFailed(error);
|
|
1091
|
+
},
|
|
1092
|
+
);
|
|
1093
|
+
const load: Promise<CatalogLookup | undefined> = withTimeout(answer, RUNNER_CATALOG_TIMEOUT_MS, "model catalog")
|
|
1094
|
+
.catch((error: unknown) => runnerCatalogFailed(error))
|
|
1095
|
+
.finally(() => {
|
|
1096
|
+
if (runnerCatalogLoad === load) runnerCatalogLoad = undefined;
|
|
1097
|
+
});
|
|
1098
|
+
runnerCatalogLoad = load;
|
|
1099
|
+
return load;
|
|
1100
|
+
};
|
|
1101
|
+
|
|
1102
|
+
// #84 P2.1 (T2.1.3): the tools of roles mode. The tool map is fixed at plugin start (like `router_verify`): in tiers mode and on
|
|
1103
|
+
// v1 the set is exactly the previous one (router_run and router_request_authority are not registered; router_git_* keep their
|
|
1104
|
+
// directory resolution). Switching to roles mode registers them on the next start.
|
|
1105
|
+
const rolesAtStart = rolesNow().size > 0;
|
|
1106
|
+
const dynamicRolesAtStart = [...rolesNow().values()].some((spec) => spec.authority.mode === "dynamic");
|
|
1107
|
+
/** `router_request_authority` dependencies (P1.6): the role by child session; only the parent of `dispatchOf` is read. */
|
|
1108
|
+
const authorityDeps = {
|
|
1109
|
+
roleOf: (child: string) => roleOfSession(child),
|
|
1110
|
+
roles: () => rolesNow(),
|
|
1111
|
+
dispatchOf: (child: string) => {
|
|
1112
|
+
const parent = lookupDispatch(child)?.parentSessionID;
|
|
1113
|
+
// QA-P21-1-13: `callID: ""` = not attached yet. authority.ts reads only the parent (to drop the request with it);
|
|
1114
|
+
// `markAnnotated` attaches the request to the parent's call in the adapter's execute.after.
|
|
1115
|
+
return typeof parent === "string" && parent !== "" ? { parentSessionID: parent, callID: "" } : undefined;
|
|
1116
|
+
},
|
|
1117
|
+
bindingOf: (child: string) => currentBinding(child, { maxOf: roleMaxOf }),
|
|
1118
|
+
};
|
|
1119
|
+
/** Exact npm forms of a deterministic check's command → the `routing.run` script it names (`npm test`, `npm run <name>`). */
|
|
1120
|
+
const NPM_SCRIPT_RE = /^npm(?:\.cmd)?\s+(?:(test|t)|run(?:-script)?\s+([A-Za-z0-9_][A-Za-z0-9_.:@+-]*))$/;
|
|
1121
|
+
/** The acceptance commands of a role dispatch as `routing.run` names (handoff 13): only exact npm script forms count. */
|
|
1122
|
+
const acceptanceScripts = (prompt: unknown, description: unknown): string[] => {
|
|
1123
|
+
const dod = buildDelegationDoD({
|
|
1124
|
+
prompt: typeof prompt === "string" ? prompt : undefined,
|
|
1125
|
+
description: typeof description === "string" ? description : undefined,
|
|
1126
|
+
});
|
|
1127
|
+
if (dod.kind !== "deterministic") return [];
|
|
1128
|
+
return dod.checks.flatMap((check) => {
|
|
1129
|
+
const match = typeof check.command === "string" ? NPM_SCRIPT_RE.exec(check.command.trim()) : null;
|
|
1130
|
+
return match === null ? [] : [match[1] !== undefined ? "test" : (match[2] as string)];
|
|
1131
|
+
});
|
|
1132
|
+
};
|
|
1133
|
+
/**
|
|
1134
|
+
* QA-P21-2-3: the read-only cap a role dispatch asks for itself — `CAP:N`, or `CAP:none` with a `reason:` line (an unjustified
|
|
1135
|
+
* `CAP:none` is no cap, as for tier dispatches); `null` when it names none (then the child gets no read-only cap).
|
|
1136
|
+
*/
|
|
1137
|
+
const roleDispatchCap = (prompt: unknown): Cap | null => {
|
|
1138
|
+
if (typeof prompt !== "string") return null;
|
|
1139
|
+
const parsed = parseCapDirective(prompt);
|
|
1140
|
+
return parsed === "none" && !/\breason:/i.test(prompt) ? null : parsed;
|
|
1141
|
+
};
|
|
1142
|
+
/** Caps of fresh role dispatches, by the parent's call, until the child binds (bounded, oldest out). */
|
|
1143
|
+
const pendingRoleCaps = new Map<string, { agent: string; cap: Cap }>();
|
|
1144
|
+
const rememberPendingRoleCap = (callID: string, agent: string, cap: Cap): void => {
|
|
1145
|
+
pendingRoleCaps.delete(callID);
|
|
1146
|
+
pendingRoleCaps.set(callID, { agent, cap });
|
|
1147
|
+
while (pendingRoleCaps.size > ROLE_STATE_MAX) pendingRoleCaps.delete(pendingRoleCaps.keys().next().value!);
|
|
1148
|
+
};
|
|
1149
|
+
/**
|
|
1150
|
+
* The role child's read-only counter with the dispatch's cap, independent of `subagentTiers` (the session store's producer
|
|
1151
|
+
* registration: no trivial downgrade). The cap is keyed by the role agent's name, which is never a tier.
|
|
1152
|
+
*/
|
|
1153
|
+
const registerRoleCap = (child: string, agent: string, cap: Cap): void => {
|
|
1154
|
+
sessionStore.registerProducerSession(child, agent, { ...cfg, tierCaps: { ...(cfg.tierCaps ?? {}), [agent]: cap } } as RouterConfig);
|
|
1155
|
+
};
|
|
1156
|
+
/** A fresh role child's first call: its exact binding names the dispatch's call, whose cap is registered once. */
|
|
1157
|
+
const applyPendingRoleCap = (child: string): void => {
|
|
1158
|
+
if (pendingRoleCaps.size === 0) return;
|
|
1159
|
+
const binding = currentBinding(child, { maxOf: roleMaxOf });
|
|
1160
|
+
const callID = binding?.kind === "exact" ? binding.candidates[0] : undefined;
|
|
1161
|
+
const pending = callID === undefined ? undefined : pendingRoleCaps.get(callID);
|
|
1162
|
+
if (callID === undefined || pending === undefined) return;
|
|
1163
|
+
pendingRoleCaps.delete(callID);
|
|
1164
|
+
registerRoleCap(child, pending.agent, pending.cap);
|
|
1165
|
+
};
|
|
1166
|
+
/**
|
|
1167
|
+
* #84 P3.3 DF2-F1: where the `task` call `callID` is verified. A routed role dispatch (`routedRoleOf`, kept until the adapter's
|
|
1168
|
+
* `execute.after` is done) in its `verifyRoot` — the grant's work root (a resume keeps the child's bound root, QA-P33F1-1-1), else
|
|
1169
|
+
* its canonical session directory (QA-P33F1-1-3); the requested cwd (`requestedVerificationCwd`: the call's `cwd`, else the
|
|
1170
|
+
* block's `cwd:`, the order the dispatch-time detection uses, nit 3) still wins inside it, by P2.3's rule (QA-P33F1-1-2); one
|
|
1171
|
+
* outside it is refused by the gate. Every other dispatch: the explicit cwd, as before (I1).
|
|
1172
|
+
*/
|
|
1173
|
+
const verificationScopeOf = (callID: unknown, args: Record<string, unknown> | undefined, dod: { cwd?: string }): VerificationScope =>
|
|
1174
|
+
verificationScope(requestedVerificationCwd(args?.cwd, dod.cwd), typeof callID === "string" ? routedRoleOf(callID)?.verifyRoot : undefined);
|
|
1175
|
+
/** The prompt as the orchestrator wrote it: without the router's nonce line (handoff 18; role dispatches carry no header). */
|
|
1176
|
+
const withoutNonceLine = (prompt: string): string => prompt.replace(/\r?\n?OMR_NONCE=[A-Za-z0-9_-]+\s*$/, "");
|
|
1177
|
+
/**
|
|
1178
|
+
* The parent's `task` call of a routed role dispatch (before it runs): a resume opens a new guard round for the child (its
|
|
1179
|
+
* budget and `budgetExhausted` are per round), and the re-dispatch signal (P1.4, handoff 16) compares the dispatch with the
|
|
1180
|
+
* parent's earlier role dispatches: a failure lands on the previous attempt, addressed by its decision id.
|
|
1181
|
+
*/
|
|
1182
|
+
const noteRoleDispatch = (callID: string, parentSessionID: string, args: Record<string, unknown>): void => {
|
|
1183
|
+
const routed = routedRoleOf(callID);
|
|
1184
|
+
if (routed === undefined || routed.parentSessionID !== parentSessionID) return;
|
|
1185
|
+
// QA-G-B-5: the attempt starts now. QA-G-A3-3: the routed tier and `budget=` guard its child — a resume's at once (its new
|
|
1186
|
+
// guard round takes them), a fresh child's once it binds to this call.
|
|
1187
|
+
const guard: RoutedGuardInput = { agent: routed.agent, tier: routed.tier, routeBudget: routed.routeBudget };
|
|
1188
|
+
setBounded(roleAttempts, callID, { ...guard, at: Date.now() });
|
|
1189
|
+
if (routed.resumeID !== null) {
|
|
1190
|
+
// QA-G-A3-2-2 (§2.6): a resume that names no `budget=` keeps the child's previous routed `budget=` (raise-only, applied to
|
|
1191
|
+
// the resume's own tier); one that names a `budget=` takes its own.
|
|
1192
|
+
const previous = routedGuardOf(routed.resumeID);
|
|
1193
|
+
const inherited = routed.routeBudget ?? (previous?.agent === routed.agent ? previous.routeBudget : null);
|
|
1194
|
+
setBounded(roleChildGuards, routed.resumeID, { ...guard, routeBudget: inherited });
|
|
1195
|
+
guardStore.beginDispatch(routed.resumeID);
|
|
1196
|
+
}
|
|
1197
|
+
// QA-P21-2-3: the dispatch's own read-only cap. A resume names its child: registered now; a fresh child when it binds.
|
|
1198
|
+
// QA-P21-3-1: every routed resume starts a new round of the child's read counter (the previous cap kept unless it names one),
|
|
1199
|
+
// so a "continue and finish" resume after a CAP stop does not inherit the exhausted counter.
|
|
1200
|
+
const cap = roleDispatchCap(args.prompt);
|
|
1201
|
+
if (routed.resumeID !== null) {
|
|
1202
|
+
if (!sessionStore.resumeRoleSession(routed.resumeID, cap) && cap !== null) registerRoleCap(routed.resumeID, routed.agent, cap);
|
|
1203
|
+
} else if (cap !== null) {
|
|
1204
|
+
rememberPendingRoleCap(callID, routed.agent, cap);
|
|
1205
|
+
}
|
|
1206
|
+
if (routed.decisionID === null) return; // engine static: no rows
|
|
1207
|
+
const current: DispatchText = {
|
|
1208
|
+
decisionID: routed.decisionID,
|
|
1209
|
+
parentSessionID,
|
|
1210
|
+
childSessionID: routed.resumeID,
|
|
1211
|
+
class: routed.class,
|
|
1212
|
+
role: routed.agent,
|
|
1213
|
+
prompt: withoutNonceLine(typeof args.prompt === "string" ? args.prompt : ""),
|
|
1214
|
+
tier: routed.tier,
|
|
1215
|
+
at: Date.now(),
|
|
1216
|
+
resume: routed.resumeID !== null,
|
|
1217
|
+
};
|
|
1218
|
+
const match = detectRedispatch(current, [...roleDispatchTexts.values()], roleTierOrder(cfg));
|
|
1219
|
+
if (match !== null && match.previous.childSessionID !== null) {
|
|
1220
|
+
ingest?.onSignal?.(match.previous.childSessionID, match.observation, { expectDecisionID: match.previous.decisionID });
|
|
1221
|
+
}
|
|
1222
|
+
roleDispatchTexts.delete(callID);
|
|
1223
|
+
roleDispatchTexts.set(callID, current);
|
|
1224
|
+
while (roleDispatchTexts.size > 200) roleDispatchTexts.delete(roleDispatchTexts.keys().next().value!);
|
|
1225
|
+
};
|
|
1226
|
+
/**
|
|
1227
|
+
* The parent's `task` call of a role child returned (P1.4, handoffs 15-17, 23): the return signal with the REAL guard state
|
|
1228
|
+
* (budget: the guard's enforced stop, or a `NEED MORE: budget` return the guard backs — QA-G-A3-1; `unobserved` when the guard
|
|
1229
|
+
* never tracked the child; authority: the child's recorded request for this call), the router-observed run signal of THIS
|
|
1230
|
+
* attempt (QA-G-B-5), and the dispatch text's end state for later re-dispatch checks.
|
|
1231
|
+
* Verdict rows stay with `onVerdict`.
|
|
1232
|
+
*/
|
|
1233
|
+
const observeRoleReturn = (callID: string, args: Record<string, unknown>, output: unknown): void => {
|
|
1234
|
+
const { finalReturnText, childSessionID } = parseTaskResult(output);
|
|
1235
|
+
const spec = childSessionID ? roleOfSession(childSessionID) ?? roleSpecOf(args.subagent_type) : undefined;
|
|
1236
|
+
if (!childSessionID || spec === undefined) return;
|
|
1237
|
+
rememberRoleSession(childSessionID, spec.agent);
|
|
1238
|
+
// QA-P21-1-3: the snapshot includes the read-only CAP state. QA-P21-3-1: a reached read cap is a budget stop only when the
|
|
1239
|
+
// child says so (`NEED MORE`, as the gate's claim check): a `DONE` or an unrelated `ESCALATE` at the cap is not one.
|
|
1240
|
+
const snapshot = roleBudgetSnapshot(childSessionID);
|
|
1241
|
+
const capStop = snapshot.readCapReached === true && parseReturnPrefix(finalReturnText)?.prefix === "need-more";
|
|
1242
|
+
// QA-G-A3-1 (I7): advisory mode (the default) never enforces a stop; a `NEED MORE: budget` return of a tracked child whose
|
|
1243
|
+
// budget or refusals are used up is a budget stop all the same — the gate's rule for honouring the claim (claimHonoured).
|
|
1244
|
+
const claimStop = budgetClaimObserved(finalReturnText, snapshot);
|
|
1245
|
+
// Handoff 22: the guard's stop folded with the host's own (step limit, context overflow), as the v2 adapter observed them.
|
|
1246
|
+
const budgetObserved = foldBudgetObservation(
|
|
1247
|
+
capStop || claimStop ? true : snapshot.tracked ? snapshot.stopped : "unobserved",
|
|
1248
|
+
hostBudgetOf?.(childSessionID, roleAgentSteps(spec)),
|
|
1249
|
+
);
|
|
1250
|
+
const request = requestedAuthority(childSessionID);
|
|
1251
|
+
const authorityObserved = request !== undefined && (!request.annotated || request.callID === callID);
|
|
1252
|
+
const signal = returnSignal({ text: finalReturnText, budgetExhausted: budgetObserved, authorityRequested: authorityObserved });
|
|
1253
|
+
if (signal !== null) ingest?.onSignal?.(childSessionID, signal);
|
|
1254
|
+
const run = runSignal({
|
|
1255
|
+
childSessionID,
|
|
1256
|
+
runs: roleRuns.get(childSessionID) ?? [],
|
|
1257
|
+
// QA-P21-1-7: a child that made any tool call while the router was bypassed has unrecorded edits.
|
|
1258
|
+
editsObserved: !roleBypassedCalls.has(childSessionID),
|
|
1259
|
+
edits: roleEdits.get(childSessionID) ?? [],
|
|
1260
|
+
acceptance: acceptanceScripts(args.prompt, args.description),
|
|
1261
|
+
// QA-G-B-5: only this attempt's runs count (an earlier attempt's run of the same child is that attempt's evidence). An
|
|
1262
|
+
// attempt this instance did not note has no known start: NaN, so it gets no run signal (I6: never unscoped evidence).
|
|
1263
|
+
since: roleAttempts.get(callID)?.at ?? Number.NaN,
|
|
1264
|
+
});
|
|
1265
|
+
if (run !== null) ingest?.onSignal?.(childSessionID, run);
|
|
1266
|
+
const sent = roleDispatchTexts.get(callID);
|
|
1267
|
+
if (sent !== undefined) {
|
|
1268
|
+
roleDispatchTexts.set(callID, {
|
|
1269
|
+
...sent,
|
|
1270
|
+
childSessionID: sent.childSessionID ?? childSessionID,
|
|
1271
|
+
endedAt: Date.now(),
|
|
1272
|
+
returnPrefix: parseReturnPrefix(finalReturnText)?.prefix ?? null,
|
|
1273
|
+
returned: signal?.kind === "budget" || signal?.kind === "authority" ? signal.kind : null,
|
|
1274
|
+
budgetExhausted: budgetObserved,
|
|
1275
|
+
authorityRequested: authorityObserved,
|
|
1276
|
+
});
|
|
1277
|
+
}
|
|
1278
|
+
};
|
|
1279
|
+
/** Forget a deleted session's role state (as a child, and as the parent of role dispatches). */
|
|
1280
|
+
const forgetRoleSession = (sessionID: string): void => {
|
|
1281
|
+
roleSessions.delete(sessionID);
|
|
1282
|
+
roleRuns.delete(sessionID);
|
|
1283
|
+
roleEdits.delete(sessionID);
|
|
1284
|
+
roleBypassedCalls.delete(sessionID);
|
|
1285
|
+
roleChildGuards.delete(sessionID);
|
|
1286
|
+
roleBudgetPeaks.delete(sessionID);
|
|
1287
|
+
for (const [callID, sent] of roleDispatchTexts) if (sent.parentSessionID === sessionID) roleDispatchTexts.delete(callID);
|
|
1288
|
+
};
|
|
565
1289
|
return {
|
|
566
1290
|
// Warnings post to /log fire-and-forget, which loses the message when the
|
|
567
1291
|
// process is about to exit — `opencode run` and `opencode debug` are short
|
|
@@ -569,15 +1293,33 @@ const ModelRouterPlugin: Plugin = async (ctx: RouterPluginInput) => {
|
|
|
569
1293
|
// that dispose is both called and awaited, so flushing here is enough.
|
|
570
1294
|
dispose: async () => {
|
|
571
1295
|
stopReferenceGc();
|
|
1296
|
+
// Stop new advisor work and finish state/claim writes and lock removal before teardown.
|
|
1297
|
+
await advisorNotifier?.dispose();
|
|
572
1298
|
// 2.4.5: abort a background run and drop its queue and notices before the registry goes.
|
|
573
1299
|
background?.dispose();
|
|
574
1300
|
// 2.4.2b: evict every pending delegation; in-flight router_verify runs resolve (pending.ts R5).
|
|
575
1301
|
pending.dispose();
|
|
576
1302
|
// 2.2.3: settle batched testsPass requests and kill running batches (never rejects).
|
|
577
1303
|
await disposeVerification();
|
|
1304
|
+
// 2.1.3: flush and release the outcome bundle held by this instance (never rejects).
|
|
1305
|
+
await ingest?.dispose();
|
|
1306
|
+
await annotateRuntime?.dispose();
|
|
1307
|
+
await attemptRecorder?.dispose();
|
|
578
1308
|
await logger.flush();
|
|
579
1309
|
},
|
|
580
1310
|
tool: {
|
|
1311
|
+
// QA-G-A2-2: a role session's work root must belong to the repository its dispatch listed the worktrees in (this directory's).
|
|
1312
|
+
...gitTools(rolesAtStart ? { resolveWorkRoot: resolveWorkRootFor("router_git"), ...(ctx.directory ? { dispatchRepository: ctx.directory } : {}) } : {}),
|
|
1313
|
+
// #84 P2.1 (handoffs 11, 13): roles mode only. `router_run` runs in the bound work root; each run feeds the `run` signal.
|
|
1314
|
+
...(rolesAtStart ? {
|
|
1315
|
+
router_run: routerRunTool({
|
|
1316
|
+
config: () => resolveRolesRouting(cfg, "v2").run,
|
|
1317
|
+
resolveWorkRoot: resolveWorkRootFor("router_run"),
|
|
1318
|
+
recordRun: (run) => pushBounded(roleRuns, run.sessionID, run),
|
|
1319
|
+
}),
|
|
1320
|
+
} : {}),
|
|
1321
|
+
// #84 P2.1: the authority ladder (P1.6) for dynamic roles (`general`).
|
|
1322
|
+
...(rolesAtStart && dynamicRolesAtStart ? { router_request_authority: authorityTool(authorityDeps) } : {}),
|
|
581
1323
|
...(enableDelegateTool ? { delegate: tool({
|
|
582
1324
|
description: DELEGATE_TOOL_DESCRIPTION,
|
|
583
1325
|
args: {
|
|
@@ -608,7 +1350,7 @@ const ModelRouterPlugin: Plugin = async (ctx: RouterPluginInput) => {
|
|
|
608
1350
|
acceptance?: string;
|
|
609
1351
|
cwd?: string;
|
|
610
1352
|
},
|
|
611
|
-
toolCtx?: { sessionID?: string },
|
|
1353
|
+
toolCtx?: { sessionID?: string; abort?: AbortSignal },
|
|
612
1354
|
): Promise<string> {
|
|
613
1355
|
// Every ladder iteration creates its own producer session. Tracked out
|
|
614
1356
|
// here (not inside the try) so the finally below can dispose any that an
|
|
@@ -644,7 +1386,7 @@ const ModelRouterPlugin: Plugin = async (ctx: RouterPluginInput) => {
|
|
|
644
1386
|
let activeCfg = cfg;
|
|
645
1387
|
try {
|
|
646
1388
|
activeCfg = loadConfig(projectDir);
|
|
647
|
-
|
|
1389
|
+
warnConfigIssues(activeCfg, logger);
|
|
648
1390
|
} catch {
|
|
649
1391
|
activeCfg = cfg;
|
|
650
1392
|
}
|
|
@@ -658,9 +1400,36 @@ const ModelRouterPlugin: Plugin = async (ctx: RouterPluginInput) => {
|
|
|
658
1400
|
});
|
|
659
1401
|
const effectiveCwd = typeof args.cwd === "string" && args.cwd.trim() ? args.cwd : dod.cwd;
|
|
660
1402
|
|
|
661
|
-
|
|
1403
|
+
// Phase 2.3 (D10/D11): on v2 with `variantSteps: auto` (A15: only with a `routing` block) and a catalog,
|
|
1404
|
+
// the ladder is session-aware: variant steps on the same model first, resume of the child session
|
|
1405
|
+
// under the context threshold. Anything else keeps the policy exactly as before (no variants key).
|
|
1406
|
+
const host = ctx.routerHost === "v2" ? "v2" : "v1";
|
|
1407
|
+
const variantMode = resolveVariantSteps(activeCfg, host);
|
|
1408
|
+
const catalog = host === "v2" && ctx.routerChildRunner && variantMode === "auto" ? await loadRunnerCatalog() : undefined;
|
|
1409
|
+
const policy = buildEscalatePolicy(
|
|
1410
|
+
activeCfg,
|
|
1411
|
+
catalog === undefined
|
|
1412
|
+
? undefined
|
|
1413
|
+
: {
|
|
1414
|
+
host,
|
|
1415
|
+
variantSteps: variantMode,
|
|
1416
|
+
maxContextFraction: resolveRouting(activeCfg, host).sessionReuse.maxContextFraction,
|
|
1417
|
+
catalog,
|
|
1418
|
+
warn: (message) => logger.warn(message),
|
|
1419
|
+
},
|
|
1420
|
+
);
|
|
1421
|
+
const sessionAware = policy.variants != null;
|
|
662
1422
|
let state = newLadderState(initialTier, policy);
|
|
663
1423
|
const tiersForCost: any = getActiveTiers(activeCfg);
|
|
1424
|
+
// A17 / QA-1.5-20: the first attempt runs the start tier's base rung; every later one charges its action's rung.
|
|
1425
|
+
let rungCost: number | undefined = startCostRatio(policy, state);
|
|
1426
|
+
let plan: AttemptPlan = planFirstAttempt(activeCfg, state.currentTier);
|
|
1427
|
+
// Registry entry + decision row per attempt: for the ladder's own resume decision (the child's last step
|
|
1428
|
+
// context) and for the outcome store. Without a routing block both are off and nothing is registered.
|
|
1429
|
+
const recording = attemptRecorder !== undefined && (sessionAware || attemptRecorder.engineLive(activeCfg));
|
|
1430
|
+
const delegation: DelegationFacts | null = recording
|
|
1431
|
+
? await classifyDelegation(activeCfg, host, args.task, args.acceptance, logger)
|
|
1432
|
+
: null;
|
|
664
1433
|
|
|
665
1434
|
// Independent safety net: even a policy bug cannot loop unbounded.
|
|
666
1435
|
const safetyMax =
|
|
@@ -672,7 +1441,6 @@ const ModelRouterPlugin: Plugin = async (ctx: RouterPluginInput) => {
|
|
|
672
1441
|
|
|
673
1442
|
let producerText = "";
|
|
674
1443
|
let forcing: string | null = null;
|
|
675
|
-
let effort: EffortLevel | undefined;
|
|
676
1444
|
|
|
677
1445
|
/**
|
|
678
1446
|
* One turn of the escalation ladder: create a producer session, run
|
|
@@ -685,31 +1453,53 @@ const ModelRouterPlugin: Plugin = async (ctx: RouterPluginInput) => {
|
|
|
685
1453
|
* in the middle of it obscured both halves.
|
|
686
1454
|
*/
|
|
687
1455
|
const runProducerAttempt = async (
|
|
688
|
-
|
|
1456
|
+
attemptPlan: AttemptPlan,
|
|
689
1457
|
forcingNote: string | null,
|
|
690
|
-
effort?: EffortLevel,
|
|
691
1458
|
): Promise<{
|
|
692
1459
|
sessionID: string;
|
|
693
1460
|
text: string;
|
|
694
1461
|
gateRes: Awaited<ReturnType<typeof accept>>;
|
|
1462
|
+
/** The producer errored or timed out: its context is not trusted for a resume (D11). */
|
|
1463
|
+
producerFailed: boolean;
|
|
1464
|
+
confirmProducer?: () => void;
|
|
695
1465
|
} | {
|
|
696
1466
|
sessionID: string;
|
|
697
1467
|
text: string;
|
|
698
1468
|
/** 2.4.2c: deferred; the section 1.5-16 footer to append to the result. */
|
|
699
1469
|
deferredFooter: string;
|
|
700
1470
|
} | null> => {
|
|
1471
|
+
const tier = attemptPlan.tier;
|
|
1472
|
+
const effort = attemptPlan.effort;
|
|
701
1473
|
const taskText = forcingNote
|
|
702
1474
|
? `${scrubText(forcingNote)}\n\n${args.task}`
|
|
703
1475
|
: args.task;
|
|
704
1476
|
|
|
705
1477
|
let producerSid: string | undefined;
|
|
1478
|
+
/** The child this attempt actually runs on; a resume the host refuses starts a fresh one instead. */
|
|
1479
|
+
let resumeTarget: string | undefined = attemptPlan.resumeSessionID;
|
|
1480
|
+
let confirmProducer: (() => void) | undefined;
|
|
706
1481
|
const registerProducer = async (sid: string) => {
|
|
707
1482
|
producerSid = sid;
|
|
708
|
-
producerSessions.push(sid);
|
|
1483
|
+
if (!producerSessions.includes(sid)) producerSessions.push(sid);
|
|
709
1484
|
depthTracker.recordPluginChild(sid, toolCtx?.sessionID ?? null);
|
|
710
1485
|
if (effort !== undefined) {
|
|
711
1486
|
const tierCfg = getActiveTiers(activeCfg)[tier];
|
|
712
|
-
|
|
1487
|
+
// The D10 fallback (an invalid variant) delivers the step's effort through the override on a bare
|
|
1488
|
+
// model, so the override's tier carries that effort and no variant (effortCeilingFor needs both).
|
|
1489
|
+
if (tierCfg) effortOverrides.set(sid, tier, attemptPlan.fresh === "invalid-variant" ? { ...tierCfg, variant: undefined, effort } : tierCfg, effort);
|
|
1490
|
+
}
|
|
1491
|
+
// Phase 2.3: a distinct attempt in the dispatch registry (with its step label) and, when the engine is
|
|
1492
|
+
// live, a decision row. Register before the first step; a resume's row waits for host identity confirmation.
|
|
1493
|
+
if (recording && delegation !== null) {
|
|
1494
|
+
confirmProducer = attemptRecorder?.record({
|
|
1495
|
+
childSessionID: sid,
|
|
1496
|
+
parentSessionID: toolCtx?.sessionID ?? null,
|
|
1497
|
+
plan: attemptPlan,
|
|
1498
|
+
config: activeCfg,
|
|
1499
|
+
facts: delegation.facts,
|
|
1500
|
+
acceptance: delegation.acceptance,
|
|
1501
|
+
resumed: sid === resumeTarget,
|
|
1502
|
+
}, ctx.routerChildRunner !== undefined && sid === resumeTarget);
|
|
713
1503
|
}
|
|
714
1504
|
// Keep the ORIGINAL dispatch reference across retries/escalations:
|
|
715
1505
|
// recapturing after a failed attempt would excuse its regression.
|
|
@@ -737,6 +1527,26 @@ const ModelRouterPlugin: Plugin = async (ctx: RouterPluginInput) => {
|
|
|
737
1527
|
}
|
|
738
1528
|
|
|
739
1529
|
const model = tierModel(activeCfg, tier) ?? undefined;
|
|
1530
|
+
if (sessionAware && attemptPlan.step !== "dispatch") {
|
|
1531
|
+
// D11: the decision and both numbers are in the decision row (engine != static). The log line is for
|
|
1532
|
+
// anomalies (QA-2.3-4): a fresh start nobody chose (unknown context, no budget, an invalid catalog
|
|
1533
|
+
// variant). The routine ones are only logged with the existing opt-in debug flag: a resume, a start over
|
|
1534
|
+
// the threshold, and the two conservative overrides that the shipped presets hit on every escalation
|
|
1535
|
+
// (`effort-path`, `bare-model-after-variant`; QA-2.3-R2-2).
|
|
1536
|
+
const basis = attemptPlan.resumeBasis;
|
|
1537
|
+
const routine =
|
|
1538
|
+
resumeTarget !== undefined ||
|
|
1539
|
+
basis?.reason === "at-or-over-threshold" ||
|
|
1540
|
+
attemptPlan.fresh === "effort-path" ||
|
|
1541
|
+
attemptPlan.fresh === "bare-model-after-variant";
|
|
1542
|
+
if (!routine || process.env.MODEL_ROUTER_TRAJECTORY_DEBUG === "1") {
|
|
1543
|
+
logger.warn(
|
|
1544
|
+
`[router] ladder ${attemptPlan.step} on ${tier}: ${resumeTarget !== undefined ? "resuming the child session" : "fresh child session"}` +
|
|
1545
|
+
`${basis ? ` (${basis.reason}; tokens=${basis.tokens} budget=${basis.budget} threshold=${basis.threshold})` : ""}` +
|
|
1546
|
+
`${attemptPlan.fresh ? `; runner: ${attemptPlan.fresh}` : ""}`,
|
|
1547
|
+
);
|
|
1548
|
+
}
|
|
1549
|
+
}
|
|
740
1550
|
let producerText = "";
|
|
741
1551
|
// Provider-failover vs quality-escalation precedence (Phase 3.3):
|
|
742
1552
|
// Provider-failover is advisory only — a text chain injected into the orchestrator
|
|
@@ -753,15 +1563,33 @@ const ModelRouterPlugin: Plugin = async (ctx: RouterPluginInput) => {
|
|
|
753
1563
|
let producerError: string | null = null;
|
|
754
1564
|
const childAbort = ctx.routerChildRunner ? new AbortController() : undefined;
|
|
755
1565
|
try {
|
|
1566
|
+
const runChild = (resume: string | undefined) => ctx.routerChildRunner!.run({
|
|
1567
|
+
parentSessionID: toolCtx?.sessionID,
|
|
1568
|
+
agent: attemptPlan.agent,
|
|
1569
|
+
model: attemptPlan.model,
|
|
1570
|
+
prompt: taskText,
|
|
1571
|
+
signal: childAbort!.signal,
|
|
1572
|
+
...(resume === undefined ? {} : { resumeSessionID: resume }),
|
|
1573
|
+
onCreated: registerProducer,
|
|
1574
|
+
...(resume === undefined ? {} : {
|
|
1575
|
+
onConfirmed: async (sid: string) => { if (sid === producerSid) confirmProducer?.(); },
|
|
1576
|
+
}),
|
|
1577
|
+
});
|
|
756
1578
|
const res: any = await withTimeout<unknown>(
|
|
757
|
-
ctx.routerChildRunner ?
|
|
758
|
-
|
|
759
|
-
|
|
760
|
-
|
|
761
|
-
|
|
762
|
-
|
|
763
|
-
|
|
764
|
-
|
|
1579
|
+
ctx.routerChildRunner ? (async () => {
|
|
1580
|
+
try {
|
|
1581
|
+
return await runChild(resumeTarget);
|
|
1582
|
+
} catch (error) {
|
|
1583
|
+
// D11 fallback: a resume the host side refuses before anything ran (the child is gone, or is not
|
|
1584
|
+
// ours) is not a failed attempt: the same attempt starts on a fresh child.
|
|
1585
|
+
if (resumeTarget === undefined || !(error instanceof ResumeRejectedError)) throw error;
|
|
1586
|
+
logger.warn(`[router] ladder ${attemptPlan.step} on ${tier}: ${error.message}; starting a fresh child session`);
|
|
1587
|
+
const refused = resumeTarget;
|
|
1588
|
+
resumeTarget = undefined;
|
|
1589
|
+
await disposeChildSession(refused);
|
|
1590
|
+
return await runChild(undefined);
|
|
1591
|
+
}
|
|
1592
|
+
})() : ctx.client.session.prompt({
|
|
765
1593
|
path: { id: producerSid! },
|
|
766
1594
|
body: {
|
|
767
1595
|
...(model ? { model } : {}),
|
|
@@ -801,6 +1629,8 @@ const ModelRouterPlugin: Plugin = async (ctx: RouterPluginInput) => {
|
|
|
801
1629
|
cwd: effectiveCwd,
|
|
802
1630
|
dod,
|
|
803
1631
|
dispatchedAt: dispatchStart.dispatchedAt,
|
|
1632
|
+
// Handoff 24, R7 (I1/I8 exemption: the I7 budget-incomplete rule): router_verify judges the budget at return.
|
|
1633
|
+
budget: captureBudget(producerSid, sessionStore.readCapReached(producerSid)),
|
|
804
1634
|
})
|
|
805
1635
|
: undefined;
|
|
806
1636
|
// QA-2.4-4 / QA-2.4-10: a finish that did not defer falls through to the required gate
|
|
@@ -949,9 +1779,12 @@ const ModelRouterPlugin: Plugin = async (ctx: RouterPluginInput) => {
|
|
|
949
1779
|
// Dispose this attempt's backend session before the next iteration
|
|
950
1780
|
// so a long ladder never accumulates live sessions.
|
|
951
1781
|
effortOverrides.clear(producerSid);
|
|
952
|
-
|
|
1782
|
+
// A session-aware ladder (2.3) may resume this child on the next attempt, so its disposal is the loop's
|
|
1783
|
+
// decision, taken once the ladder has said retry/escalate and whether it resumes; every exit path is
|
|
1784
|
+
// still covered by the `finally` below. Without a session-aware policy: as before.
|
|
1785
|
+
if (!sessionAware) await disposeChildSession(producerSid);
|
|
953
1786
|
|
|
954
|
-
return { sessionID: producerSid, text: producerText, gateRes };
|
|
1787
|
+
return { sessionID: producerSid, text: producerText, gateRes, producerFailed: producerError !== null, confirmProducer };
|
|
955
1788
|
};
|
|
956
1789
|
|
|
957
1790
|
while (true) {
|
|
@@ -962,7 +1795,7 @@ const ModelRouterPlugin: Plugin = async (ctx: RouterPluginInput) => {
|
|
|
962
1795
|
);
|
|
963
1796
|
}
|
|
964
1797
|
const tier = state.currentTier;
|
|
965
|
-
const attempt = await runProducerAttempt(
|
|
1798
|
+
const attempt = await runProducerAttempt(plan, forcing);
|
|
966
1799
|
if (!attempt) {
|
|
967
1800
|
return withDepthBanner("[router] delegate failed: could not create a producer session.");
|
|
968
1801
|
}
|
|
@@ -975,16 +1808,55 @@ const ModelRouterPlugin: Plugin = async (ctx: RouterPluginInput) => {
|
|
|
975
1808
|
const producerSid = attempt.sessionID;
|
|
976
1809
|
const gateRes = attempt.gateRes;
|
|
977
1810
|
|
|
1811
|
+
// A17: charge the rung this attempt ran (a candidate's own ratio), the tier's ratio when it has none.
|
|
978
1812
|
const costRatio =
|
|
979
|
-
|
|
1813
|
+
rungCost ??
|
|
1814
|
+
(typeof tiersForCost?.[tier]?.costRatio === "number"
|
|
980
1815
|
? tiersForCost[tier].costRatio
|
|
981
|
-
: 1;
|
|
982
|
-
|
|
1816
|
+
: 1);
|
|
1817
|
+
// D11: the child and its last-step context (from the registry) decide a resume. A producer that errored
|
|
1818
|
+
// or timed out reports no context, so the next attempt starts fresh. The context is read only once the
|
|
1819
|
+
// child's execution end has been seen (QA-2.3-2): that event follows every step event on the stream, so
|
|
1820
|
+
// the number includes the final, largest step. The gate has usually run long enough for it to be there;
|
|
1821
|
+
// when it is not, wait for it, at most RESUME_END_WAIT_MS and no longer than the delegation lives, and
|
|
1822
|
+
// otherwise start fresh (`unknown-tokens`). Nothing is awaited when no retry can follow.
|
|
1823
|
+
let lastStepTokens: number | null = null;
|
|
1824
|
+
if (sessionAware && !attempt.producerFailed) {
|
|
1825
|
+
// No wait when nothing can follow this attempt (QA-2.3-R2-5): accepted, unverifiable, or the ladder's
|
|
1826
|
+
// own limits (checks 3 and 4 of `nextAction`) are reached after it.
|
|
1827
|
+
const firstCost = state.firstAttemptCost ?? costRatio;
|
|
1828
|
+
const limitReached =
|
|
1829
|
+
state.totalAttempts + 1 >= policy.maxTotalAttempts ||
|
|
1830
|
+
(policy.costMultiple != null && state.cumulativeCost + costRatio > firstCost * policy.costMultiple);
|
|
1831
|
+
if (!gateRes.accepted && gateRes.verdict.outcome !== "unverifiable" && !limitReached) {
|
|
1832
|
+
await awaitExecutionEnd(producerSid, RESUME_END_WAIT_MS, toolCtx?.abort);
|
|
1833
|
+
}
|
|
1834
|
+
lastStepTokens = lastStepContext(producerSid);
|
|
1835
|
+
}
|
|
1836
|
+
state = recordAttempt(
|
|
1837
|
+
state,
|
|
1838
|
+
costRatio,
|
|
1839
|
+
sessionAware ? { sessionID: producerSid, lastStepTokens } : undefined,
|
|
1840
|
+
);
|
|
1841
|
+
// The verdict of this attempt, on the attempt's own registration (variant steps feed the store separately).
|
|
1842
|
+
if (recording && !gateRes.verdict.skipped) {
|
|
1843
|
+
// R2-2: a failed/timed-out producer may never deliver host confirmation. The ladder's
|
|
1844
|
+
// verdict still needs its decision row; the same callback is idempotent after host progress/result.
|
|
1845
|
+
attempt.confirmProducer?.();
|
|
1846
|
+
// #84 P3.3 fix 2 (plan §2.6, I6): a grader's verdict is a grader signal of a role dispatch, never a deterministic one.
|
|
1847
|
+
ingest?.onVerdict(producerSid, verdictOf(gateRes.verdict), verdictGraderOf(gateRes.verdict));
|
|
1848
|
+
}
|
|
983
1849
|
|
|
984
1850
|
const action = nextAction(
|
|
985
1851
|
state,
|
|
986
|
-
{
|
|
1852
|
+
{
|
|
1853
|
+
pass: gateRes.accepted, outcome: gateRes.verdict.outcome, reasons: gateRes.verdict.reasons,
|
|
1854
|
+
// Handoff 25, R7 (I1/I8 exemption: §2.9 E8, the I7 budget-incomplete rule): the structured incomplete flag; absent
|
|
1855
|
+
// when false, so the action is unchanged.
|
|
1856
|
+
...(isIncompleteVerdict(gateRes.verdict) ? { incomplete: true } : {}),
|
|
1857
|
+
},
|
|
987
1858
|
policy,
|
|
1859
|
+
sessionAware ? { dispatchPromptChars: args.task.length } : undefined,
|
|
988
1860
|
);
|
|
989
1861
|
|
|
990
1862
|
if (action.action === "accept") {
|
|
@@ -1003,7 +1875,8 @@ const ModelRouterPlugin: Plugin = async (ctx: RouterPluginInput) => {
|
|
|
1003
1875
|
false,
|
|
1004
1876
|
gateRes.verdict.method,
|
|
1005
1877
|
);
|
|
1006
|
-
|
|
1878
|
+
// Handoff 25, R7 (I1/I8 exemption: the I7 budget-incomplete rule): no flag when false, so the note is unchanged.
|
|
1879
|
+
const note = scrubText(buildForcingNote(gateRes.verdict.reasons, isIncompleteVerdict(gateRes.verdict) ? { incomplete: true } : undefined));
|
|
1007
1880
|
return withDepthBanner(
|
|
1008
1881
|
`[router status: unmet] The delegated result was not accepted after ` +
|
|
1009
1882
|
`${state.totalAttempts} attempt(s) across ${state.escalations} escalation(s) ` +
|
|
@@ -1013,8 +1886,13 @@ const ModelRouterPlugin: Plugin = async (ctx: RouterPluginInput) => {
|
|
|
1013
1886
|
}
|
|
1014
1887
|
// retry or escalate
|
|
1015
1888
|
forcing = action.forcingMessage ?? null;
|
|
1016
|
-
effort = action.effort;
|
|
1017
1889
|
state = advance(state, action);
|
|
1890
|
+
plan = planNextAttempt({ action, state, previous: plan, cfg: activeCfg, policy, catalog });
|
|
1891
|
+
// The rung the plan actually dispatches (QA-2.3-8: not the action's when the plan fell back to the tier's model).
|
|
1892
|
+
rungCost = plan.costRatio;
|
|
1893
|
+
// The child this attempt ran on is kept only when the next attempt resumes it (D11); otherwise it is
|
|
1894
|
+
// discarded now, so a long ladder never accumulates live sessions.
|
|
1895
|
+
if (sessionAware && plan.resumeSessionID !== producerSid) await disposeChildSession(producerSid);
|
|
1018
1896
|
}
|
|
1019
1897
|
} catch {
|
|
1020
1898
|
return withDepthBanner("[router] delegate failed (fail-closed): the delegation or verification could not complete.");
|
|
@@ -1117,11 +1995,31 @@ const ModelRouterPlugin: Plugin = async (ctx: RouterPluginInput) => {
|
|
|
1117
1995
|
},
|
|
1118
1996
|
|
|
1119
1997
|
"chat.message": async (input: any, output: any) => {
|
|
1998
|
+
// Recorded even while bypassed: the grep redaction in `tool.execute.after` runs regardless of bypass (QA-81-R2-2).
|
|
1999
|
+
if (typeof input?.sessionID === "string" && typeof input?.agent === "string" && Object.hasOwn(cfg.agents ?? {}, input.agent)) {
|
|
2000
|
+
rememberPluginAgentSession(input.sessionID, input.agent);
|
|
2001
|
+
}
|
|
1120
2002
|
if (bypassed) return;
|
|
1121
|
-
//
|
|
2003
|
+
// 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
|
|
2004
|
+
// typed). It is a synthetic transcript entry, through the same host call the adapter uses for the config-reload and narration notices
|
|
2005
|
+
// (`ctx.session.synthetic({ …, resume: false })`, exposed as `routerSynthetic`): it enters the context of the orchestrator's next
|
|
2006
|
+
// request without resuming or answering anything. Delivery is not awaited (the host may be admitting this very prompt); a failure is
|
|
2007
|
+
// logged. A host without `routerSynthetic` (OpenCode v1 has no such call and no advisor either) gets a log line instead. Only a PROVEN
|
|
2008
|
+
// root session takes it (never a subagent or a grader), and only when one may be waiting.
|
|
2009
|
+
if (advisorNotifier !== undefined && advisorNotifier.maybePending() && typeof input?.sessionID === "string") {
|
|
2010
|
+
const noticeSession: string = input.sessionID;
|
|
2011
|
+
try {
|
|
2012
|
+
if (!graderSessions.has(noticeSession) && !sessionStore.isSubagent(noticeSession) && (await lookupRootSession(noticeSession)) === true) {
|
|
2013
|
+
const notice = await advisorNotifier.take();
|
|
2014
|
+
if (notice !== null) deliverAdvisorNotice(noticeSession, notice);
|
|
2015
|
+
}
|
|
2016
|
+
} catch (error) {
|
|
2017
|
+
logger.warn("[router] cost doctor: notice not delivered", { error: describeError(error) });
|
|
2018
|
+
}
|
|
2019
|
+
} // Re-read cfg so /preset switches take effect without restart
|
|
1122
2020
|
try {
|
|
1123
2021
|
cfg = loadConfig(projectDir);
|
|
1124
|
-
|
|
2022
|
+
warnConfigIssues(cfg, logger);
|
|
1125
2023
|
} catch {}
|
|
1126
2024
|
try {
|
|
1127
2025
|
sweepIdleStores();
|
|
@@ -1130,6 +2028,7 @@ const ModelRouterPlugin: Plugin = async (ctx: RouterPluginInput) => {
|
|
|
1130
2028
|
}
|
|
1131
2029
|
const tierNames = Object.keys(getActiveTiers(cfg));
|
|
1132
2030
|
const sid = input?.sessionID;
|
|
2031
|
+
// v1 `tool.execute.after` carries no agent: plugin-agent sessions are recorded at the top of this hook (QA-81-2).
|
|
1133
2032
|
try {
|
|
1134
2033
|
const registration = sessionStore.registerFromChatMessage(
|
|
1135
2034
|
input,
|
|
@@ -1221,7 +2120,17 @@ const ModelRouterPlugin: Plugin = async (ctx: RouterPluginInput) => {
|
|
|
1221
2120
|
// non-subagent sessions or when enforcement is off (GA-1 preserved).
|
|
1222
2121
|
// -----------------------------------------------------------------------
|
|
1223
2122
|
"tool.execute.before": async (input: any, output: any) => {
|
|
1224
|
-
|
|
2123
|
+
// #84 P2.1: a role child's own call names its role agent (the v2 adapter passes the calling agent). Remembered even while
|
|
2124
|
+
// bypassed (the work-root resolver and the authority tool are authority, not routing), and marked a child session: role
|
|
2125
|
+
// agents are subagents, so the guard engages from their first call. Never on v1 / in tiers mode (no role table).
|
|
2126
|
+
if (rememberRoleSession(input?.sessionID, input?.agent)) {
|
|
2127
|
+
sessionStore.markChildSession(input.sessionID);
|
|
2128
|
+
applyPendingRoleCap(input.sessionID); // QA-P21-2-3
|
|
2129
|
+
}
|
|
2130
|
+
if (bypassed) {
|
|
2131
|
+
noteBypassedRoleCall(input?.sessionID); // QA-P21-1-7
|
|
2132
|
+
return;
|
|
2133
|
+
}
|
|
1225
2134
|
if (input?.tool === "task") {
|
|
1226
2135
|
const depth = await depthGuard.checkDispatch(input.sessionID);
|
|
1227
2136
|
if (depth.block) {
|
|
@@ -1249,12 +2158,12 @@ const ModelRouterPlugin: Plugin = async (ctx: RouterPluginInput) => {
|
|
|
1249
2158
|
const prompt = typeof output?.args?.prompt === "string" ? output.args.prompt : undefined;
|
|
1250
2159
|
const description = typeof output?.args?.description === "string" ? output.args.description : undefined;
|
|
1251
2160
|
const dod = buildDelegationDoD({ prompt, description });
|
|
1252
|
-
const effectiveCwd = typeof output?.args?.cwd === "string" && output.args.cwd.trim() ? output.args.cwd : dod.cwd;
|
|
1253
2161
|
// 2.4.2b: the directives come from the orchestrator's own prompt, read here before the
|
|
1254
2162
|
// dispatch header or any repair touches it, and are kept for the after hook. The capture
|
|
1255
2163
|
// is awaited for at most VERIFY_WAIT (section 1.5-14) and continues in the background.
|
|
2164
|
+
// DF2-F1: a role dispatch's capture is taken in its verification root (never in a refused cwd).
|
|
1256
2165
|
await startDispatch(changedFileStore, `task:${input.sessionID}:${input.callID}`,
|
|
1257
|
-
|
|
2166
|
+
verificationScopeOf(input.callID, output?.args, dod).cwd,
|
|
1258
2167
|
dod,
|
|
1259
2168
|
dispatchDirectiveText(prompt, description),
|
|
1260
2169
|
true);
|
|
@@ -1304,7 +2213,7 @@ const ModelRouterPlugin: Plugin = async (ctx: RouterPluginInput) => {
|
|
|
1304
2213
|
typeof tier === "string" &&
|
|
1305
2214
|
Object.prototype.hasOwnProperty.call(getActiveTiers(cfg), tier) &&
|
|
1306
2215
|
typeof args.prompt === "string" &&
|
|
1307
|
-
!args.prompt.startsWith(
|
|
2216
|
+
!args.prompt.startsWith(DISPATCH_HEADER_PREFIX)
|
|
1308
2217
|
) {
|
|
1309
2218
|
// Resolve from the original dispatch, using the registration rules.
|
|
1310
2219
|
const parsed = parseCapDirective(args.prompt);
|
|
@@ -1312,8 +2221,11 @@ const ModelRouterPlugin: Plugin = async (ctx: RouterPluginInput) => {
|
|
|
1312
2221
|
parsed === "none" && !/\breason:/i.test(args.prompt) ? null : parsed;
|
|
1313
2222
|
const baseline = cfg.tierCaps?.[tier] ?? DEFAULT_TIER_CAPS[tier] ?? 5;
|
|
1314
2223
|
const cap = override ?? baseline;
|
|
1315
|
-
|
|
1316
|
-
|
|
2224
|
+
// Handoff 30, R7 (I1/I8 exemption: T1.5.3a, the header names `root=`): on v2 shadow/advise/enforce the engine stripped the
|
|
2225
|
+
// route line already; its `root=` comes from the router. No root → the header is byte-identical to before.
|
|
2226
|
+
const root = routeLineRoot(args.prompt) ?? (typeof input.callID === "string" ? strippedRouteRoot(input.callID) : undefined);
|
|
2227
|
+
const prompt = buildDispatchHeader({ tier, cap, projectDirectory: ctx.directory, root }) +
|
|
2228
|
+
DISPATCH_HEADER_SEPARATOR + args.prompt;
|
|
1317
2229
|
args.prompt = prompt;
|
|
1318
2230
|
if (process.env.MODEL_ROUTER_DISPATCH_DEBUG === "1" && !dispatchDebugLogged) {
|
|
1319
2231
|
dispatchDebugLogged = true;
|
|
@@ -1329,6 +2241,15 @@ const ModelRouterPlugin: Plugin = async (ctx: RouterPluginInput) => {
|
|
|
1329
2241
|
} catch {
|
|
1330
2242
|
// Best-effort: malformed args or debug I/O must never break a dispatch.
|
|
1331
2243
|
}
|
|
2244
|
+
// #84 P2.1: a routed role dispatch of this session (roles mode on v2 only): resume round, re-dispatch signal.
|
|
2245
|
+
if (input?.tool === "task" && typeof input.callID === "string" && typeof input.sessionID === "string"
|
|
2246
|
+
&& output?.args && typeof output.args === "object") {
|
|
2247
|
+
try {
|
|
2248
|
+
noteRoleDispatch(input.callID, input.sessionID, output.args as Record<string, unknown>);
|
|
2249
|
+
} catch (error) {
|
|
2250
|
+
logger.warn("[router] roles: the role dispatch could not be noted", { error: describeError(error) });
|
|
2251
|
+
}
|
|
2252
|
+
}
|
|
1332
2253
|
const sid = input?.sessionID;
|
|
1333
2254
|
if (!sid || !sessionStore.isSubagent(sid) || typeof input?.tool !== "string") {
|
|
1334
2255
|
return;
|
|
@@ -1338,15 +2259,19 @@ const ModelRouterPlugin: Plugin = async (ctx: RouterPluginInput) => {
|
|
|
1338
2259
|
sessionStore.touchIfTracked(sid);
|
|
1339
2260
|
let res;
|
|
1340
2261
|
try {
|
|
2262
|
+
// Handoff 27: a role child is guarded with its role profile (reader/producer, role budget); tier agents get none.
|
|
2263
|
+
const profile = roleGuardProfileOf(sid, input?.agent);
|
|
1341
2264
|
res = guardBeforeCall({
|
|
1342
2265
|
cfg,
|
|
1343
2266
|
tier: sessionStore.getTier(sid),
|
|
1344
2267
|
trivial: sessionStore.isTrivial(sid),
|
|
2268
|
+
cap: sessionStore.getCap(sid),
|
|
1345
2269
|
sessionID: sid,
|
|
1346
2270
|
tool: input.tool,
|
|
1347
2271
|
toolArgs: output?.args,
|
|
1348
2272
|
store: guardStore,
|
|
1349
2273
|
env: process.env,
|
|
2274
|
+
...(profile === undefined ? {} : { profile }),
|
|
1350
2275
|
});
|
|
1351
2276
|
} catch {
|
|
1352
2277
|
return; // never break a real session on a guard-internal error
|
|
@@ -1370,9 +2295,32 @@ const ModelRouterPlugin: Plugin = async (ctx: RouterPluginInput) => {
|
|
|
1370
2295
|
// treats them as ground truth rather than advisory system noise.
|
|
1371
2296
|
// -----------------------------------------------------------------------
|
|
1372
2297
|
"tool.execute.after": async (input: any, output: any) => {
|
|
1373
|
-
if (
|
|
2298
|
+
if (input?.tool === "grep" && typeof output.output === "string") {
|
|
2299
|
+
const tier = input.agent ?? pluginAgentSessions.get(input.sessionID) ?? sessionStore.getTier(input.sessionID);
|
|
2300
|
+
const definition = tier && getActiveTiers(cfg)[tier];
|
|
2301
|
+
// Every plugin agent is redacted (a denied grep produces no output anyway), readOnly or explicit-permission.
|
|
2302
|
+
const isPlugin = typeof tier === "string" && Object.hasOwn(cfg.agents ?? {}, tier);
|
|
2303
|
+
if ((definition && isReadOnlyTier(tier, definition)) || isPlugin) output.output = filterSensitiveGrep(output.output);
|
|
2304
|
+
}
|
|
2305
|
+
if (bypassed) {
|
|
2306
|
+
noteBypassedRoleCall(input?.sessionID); // QA-P21-1-7
|
|
2307
|
+
return;
|
|
2308
|
+
}
|
|
1374
2309
|
sessionStore.recordToolCall(input, output);
|
|
1375
2310
|
|
|
2311
|
+
// #84 P2.1 (handoffs 13, 15-17, 23): role children only (roles mode on v2). Edit times feed the `run` signal; the parent's
|
|
2312
|
+
// `task` return feeds the return/run signals, read BEFORE any router note is put in front of the child's text.
|
|
2313
|
+
try {
|
|
2314
|
+
if (typeof input?.sessionID === "string" && ROLE_EDIT_TOOLS.has(input?.tool) && roleOfSession(input.sessionID) !== undefined) {
|
|
2315
|
+
pushBounded(roleEdits, input.sessionID, Date.now());
|
|
2316
|
+
}
|
|
2317
|
+
if (input?.tool === "task" && typeof input.callID === "string" && rolesNow().size > 0) {
|
|
2318
|
+
observeRoleReturn(input.callID, input?.args && typeof input.args === "object" ? input.args : {}, output);
|
|
2319
|
+
}
|
|
2320
|
+
} catch (error) {
|
|
2321
|
+
logger.warn("[router] roles: the role return could not be observed", { error: describeError(error) });
|
|
2322
|
+
}
|
|
2323
|
+
|
|
1376
2324
|
// Best-effort false-refusal observation alongside the existing guard path.
|
|
1377
2325
|
// Keep scorecards unchanged; counts live in the TTL-managed trajectory.
|
|
1378
2326
|
try {
|
|
@@ -1383,6 +2331,7 @@ const ModelRouterPlugin: Plugin = async (ctx: RouterPluginInput) => {
|
|
|
1383
2331
|
if (detectFalseRefusal({ toolCalls: calls, resultText: text }).suspected) {
|
|
1384
2332
|
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
2333
|
trajectoryStore.recordFalseRefusal(childSessionID);
|
|
2334
|
+
ingest?.onFalseRefusal(childSessionID);
|
|
1386
2335
|
}
|
|
1387
2336
|
}
|
|
1388
2337
|
}
|
|
@@ -1421,6 +2370,7 @@ const ModelRouterPlugin: Plugin = async (ctx: RouterPluginInput) => {
|
|
|
1421
2370
|
readOnly: READ_ONLY_TOOLS.has(input.tool),
|
|
1422
2371
|
});
|
|
1423
2372
|
try {
|
|
2373
|
+
const profile = roleGuardProfileOf(sid, input?.agent); // handoff 27, as in the before-hook
|
|
1424
2374
|
guardAfterCall({
|
|
1425
2375
|
cfg,
|
|
1426
2376
|
tier: sessionStore.getTier(sid),
|
|
@@ -1429,6 +2379,7 @@ const ModelRouterPlugin: Plugin = async (ctx: RouterPluginInput) => {
|
|
|
1429
2379
|
toolArgs: input?.args,
|
|
1430
2380
|
output,
|
|
1431
2381
|
store: guardStore,
|
|
2382
|
+
...(profile === undefined ? {} : { profile }),
|
|
1432
2383
|
});
|
|
1433
2384
|
} catch {
|
|
1434
2385
|
// best-effort: enforcement must never crash a real session
|
|
@@ -1459,8 +2410,16 @@ const ModelRouterPlugin: Plugin = async (ctx: RouterPluginInput) => {
|
|
|
1459
2410
|
prompt: input?.args?.prompt,
|
|
1460
2411
|
description: input?.args?.description,
|
|
1461
2412
|
});
|
|
1462
|
-
|
|
2413
|
+
// DF2-F1: a role dispatch is verified in its verification root (capture, change set, checks, deferral); a requested
|
|
2414
|
+
// cwd outside that root is refused by the gate below, never deferred to run there later.
|
|
2415
|
+
const scope = verificationScopeOf(input.callID, input?.args, dod);
|
|
2416
|
+
const cwdSource = requestedVerificationCwdSource(input?.args?.cwd, dod.cwd);
|
|
2417
|
+
const effectiveCwd = scope.cwd;
|
|
1463
2418
|
const dispatchID = `task:${input.sessionID}:${input.callID}`;
|
|
2419
|
+
// #84 QA-G-B-2-1: a routed role dispatch keeps its child's verification lineage; a resume that CARRIES the acceptance of an
|
|
2420
|
+
// earlier attempt is gated at once (never deferred) on the child's cumulative change set (roleAttemptVerification).
|
|
2421
|
+
const routedRole = typeof input.callID === "string" ? routedRoleOf(input.callID) : undefined;
|
|
2422
|
+
const carriedRole = routedRole?.carried === true && childSessionID !== null && routedRole.resumeID === childSessionID;
|
|
1464
2423
|
const orchestratorSessionID = typeof input.sessionID === "string" ? input.sessionID : "";
|
|
1465
2424
|
const taskPrompt = typeof input?.args?.prompt === "string" ? input.args.prompt : undefined;
|
|
1466
2425
|
const taskDescription = typeof input?.args?.description === "string" ? input.args.description : undefined;
|
|
@@ -1471,7 +2430,7 @@ const ModelRouterPlugin: Plugin = async (ctx: RouterPluginInput) => {
|
|
|
1471
2430
|
: false;
|
|
1472
2431
|
// QA-2.4-10: `trivial` as the gate sees it below; a dispatch the gate would skip is not
|
|
1473
2432
|
// deferred (isDeferred). QA-2.4-2: only a proven root orchestrator defers.
|
|
1474
|
-
if (isDeferred(dod, start.directives, trivial) && await isProvenRootCaller(orchestratorSessionID)) {
|
|
2433
|
+
if (!scope.outside && !carriedRole && isDeferred(dod, start.directives, trivial) && await isProvenRootCaller(orchestratorSessionID)) {
|
|
1475
2434
|
// Section 1.5-16: no gate, no test process; the result goes back now with the
|
|
1476
2435
|
// footer, which is appended last and never says accepted or verified.
|
|
1477
2436
|
const finish = await finishDeferred(changedFileStore, {
|
|
@@ -1481,8 +2440,12 @@ const ModelRouterPlugin: Plugin = async (ctx: RouterPluginInput) => {
|
|
|
1481
2440
|
producerTier,
|
|
1482
2441
|
description: taskDescription?.trim() ? taskDescription : (taskPrompt ?? ""),
|
|
1483
2442
|
cwd: effectiveCwd,
|
|
2443
|
+
// #84 P3.3 DF2-F1 (fix-1 review nit): router_verify's gate re-checks containment in the role's work root.
|
|
2444
|
+
...(scope.workRoot !== undefined ? { workRoot: scope.workRoot } : {}),
|
|
1484
2445
|
dod,
|
|
1485
2446
|
dispatchedAt: start.dispatchedAt,
|
|
2447
|
+
// Handoff 24, R7 (I1/I8 exemption: the I7 budget-incomplete rule): router_verify judges the budget at return.
|
|
2448
|
+
budget: captureBudget(childSessionID ?? "", childSessionID ? sessionStore.readCapReached(childSessionID) : undefined),
|
|
1486
2449
|
});
|
|
1487
2450
|
if (finish.deferred) {
|
|
1488
2451
|
output.output = appendRouterFooter(typeof output.output === "string" ? output.output : "", finish.footer);
|
|
@@ -1506,6 +2469,11 @@ const ModelRouterPlugin: Plugin = async (ctx: RouterPluginInput) => {
|
|
|
1506
2469
|
gateDeadline.dispose();
|
|
1507
2470
|
throw error;
|
|
1508
2471
|
}
|
|
2472
|
+
// #84 QA-G-B-2-1: the role child's lineage — this attempt starts it (its own block) or is judged on everything the child
|
|
2473
|
+
// changed since the attempt that introduced the carried block, against that attempt's reference.
|
|
2474
|
+
if (routedRole !== undefined && childSessionID) verification = roleAttemptVerification(childSessionID, verification, { carried: carriedRole });
|
|
2475
|
+
// #84 P2.1: a role agent follows the return contract (handoff 26; roles mode only).
|
|
2476
|
+
const roleProducer = roleSpecOf(producerTier) !== undefined;
|
|
1509
2477
|
const artefact = {
|
|
1510
2478
|
changedFiles: verification.changedFiles,
|
|
1511
2479
|
changeBaseline: verification.changeBaseline,
|
|
@@ -1513,6 +2481,10 @@ const ModelRouterPlugin: Plugin = async (ctx: RouterPluginInput) => {
|
|
|
1513
2481
|
declaredOutputs: dod.deliverable ? [dod.deliverable] : [],
|
|
1514
2482
|
producerSessionID: childSessionID ?? "",
|
|
1515
2483
|
producerTier,
|
|
2484
|
+
...(roleProducer ? { returnContract: true } : {}),
|
|
2485
|
+
// Handoff 24, R7 (I1/I8 exemption: the I7 budget-incomplete rule; every mode): the guard's budget state when the task
|
|
2486
|
+
// returned, not when the gate runs. Without a stop it judges like the live read it replaces.
|
|
2487
|
+
budget: captureBudget(childSessionID ?? "", childSessionID ? sessionStore.readCapReached(childSessionID) : undefined),
|
|
1516
2488
|
};
|
|
1517
2489
|
|
|
1518
2490
|
// Read-only / research delegation: an auto-inferred, criteria-only DoD on a
|
|
@@ -1538,6 +2510,8 @@ const ModelRouterPlugin: Plugin = async (ctx: RouterPluginInput) => {
|
|
|
1538
2510
|
// Keep the native grader unparented on the backend; only depth tracking uses its caller.
|
|
1539
2511
|
const gateDeps = buildGateDeps(undefined, gateGraderSessions, verification, gateDeadline, false, orchestratorSessionID || null);
|
|
1540
2512
|
gateDeps.deterministic.onFailure = reason => completedFailures.push(reason);
|
|
2513
|
+
// #84 QA-G-B-2-1: a carried acceptance never passes on a testsPass/lintClean that ran no process.
|
|
2514
|
+
if (carriedRole) gateDeps.deterministic.noAffectedUnverifiable = CARRIED_NO_PROCESS_REASON;
|
|
1541
2515
|
let res;
|
|
1542
2516
|
try {
|
|
1543
2517
|
res = await withTimeout(
|
|
@@ -1547,7 +2521,11 @@ const ModelRouterPlugin: Plugin = async (ctx: RouterPluginInput) => {
|
|
|
1547
2521
|
trivial,
|
|
1548
2522
|
mode: "modeA",
|
|
1549
2523
|
// Native task has no cwd argument; the acceptance block can supply it.
|
|
1550
|
-
...(
|
|
2524
|
+
...(scope.requested ? { cwd: scope.requested } : {}),
|
|
2525
|
+
...(scope.workRoot !== undefined ? { workRoot: scope.workRoot } : {}),
|
|
2526
|
+
...(scope.refused !== undefined ? { refusedCwd: scope.refused } : {}),
|
|
2527
|
+
// Fix-1 review nit: a refusal names where the cwd came from (the call's `cwd`, else the block's `cwd:`).
|
|
2528
|
+
...(scope.workRoot !== undefined && cwdSource !== undefined ? { cwdSource } : {}),
|
|
1551
2529
|
},
|
|
1552
2530
|
artefact,
|
|
1553
2531
|
gateDeps,
|
|
@@ -1592,11 +2570,23 @@ const ModelRouterPlugin: Plugin = async (ctx: RouterPluginInput) => {
|
|
|
1592
2570
|
});
|
|
1593
2571
|
// QA-3.1-2 / QA-3.1-3: concurrent delegations in this tree; a tool that discarded the baseline.
|
|
1594
2572
|
res = applyDispatchCaveats(res, verification);
|
|
2573
|
+
// M6 (2.1.3): a real verdict of a registered child dispatch feeds the outcome store (v2, engine != static).
|
|
2574
|
+
// #84 P3.3 fix 2 (plan §2.6, I6): a grader's verdict is a grader signal of a role dispatch, never a deterministic one.
|
|
2575
|
+
if (childSessionID && !res.verdict.skipped) ingest?.onVerdict(childSessionID, verdictOf(res.verdict), verdictGraderOf(res.verdict));
|
|
1595
2576
|
if (!res.accepted && !res.verdict.skipped) {
|
|
1596
2577
|
const ladder = cfg.enforcement?.escalate?.ladder ?? ["fast", "medium", "heavy"];
|
|
1597
2578
|
const li = ladder.indexOf(producerTier);
|
|
1598
2579
|
const nextTier = res.verdict.outcome !== "unverifiable" && li >= 0 && li < ladder.length - 1 ? ladder[li + 1] : null;
|
|
1599
|
-
|
|
2580
|
+
// Handoff 25, R7 (I1/I8 exemption: the I7 budget-incomplete rule): absent when false, so the note is unchanged.
|
|
2581
|
+
const incomplete = isIncompleteVerdict(res.verdict);
|
|
2582
|
+
let note = scrubText(buildForcingNote(res.verdict.reasons, { producerTier, nextTier, ...(incomplete ? { incomplete: true } : {}) }));
|
|
2583
|
+
// P-8 (handoff 39): a role agent is resumed on a higher tier of its range, never re-run on a tier agent.
|
|
2584
|
+
// QA-P21-1-4: only after a FAIL (an unverifiable result keeps the generic line: there is nothing to escalate on).
|
|
2585
|
+
// QA-P21-2-2: the hint promises the raise, and records it for this parent's next resume of the child.
|
|
2586
|
+
const roleHint = roleProducer && !incomplete && res.verdict.outcome === "fail" && childSessionID
|
|
2587
|
+
? roleEscalationAfterFail(cfg, childSessionID, orchestratorSessionID) : null;
|
|
2588
|
+
const genericNext = "NEXT: address the above and re-run the delegation; do not treat the prior result as complete.";
|
|
2589
|
+
if (roleHint !== null && note.endsWith(genericNext)) note = note.slice(0, note.length - genericNext.length) + scrubText(roleHint);
|
|
1600
2590
|
output.output =
|
|
1601
2591
|
typeof output.output === "string"
|
|
1602
2592
|
? output.output + "\n\n" + note
|
|
@@ -1653,6 +2643,7 @@ const ModelRouterPlugin: Plugin = async (ctx: RouterPluginInput) => {
|
|
|
1653
2643
|
if (typeof id === "string") {
|
|
1654
2644
|
sessionRootMemo.delete(id);
|
|
1655
2645
|
sessionLookupFailedAt.delete(id);
|
|
2646
|
+
pluginAgentSessions.delete(id);
|
|
1656
2647
|
sessionStore.unregister(id);
|
|
1657
2648
|
effortOverrides.clear(id);
|
|
1658
2649
|
depthTracker.forget(id);
|
|
@@ -1660,6 +2651,7 @@ const ModelRouterPlugin: Plugin = async (ctx: RouterPluginInput) => {
|
|
|
1660
2651
|
if (key.startsWith(`${id}:`)) depthBanners.delete(key);
|
|
1661
2652
|
}
|
|
1662
2653
|
warnedNoCallID.delete(id);
|
|
2654
|
+
forgetRoleSession(id); // #84 P2.1 (the binding and authority registries are evicted by the v2 adapter)
|
|
1663
2655
|
// 2.4.2b: a deleted orchestrator's handles, tombstones and lineage records go with it.
|
|
1664
2656
|
// 2.4.5: so do its background requests and late notices; its run in flight is aborted.
|
|
1665
2657
|
background?.forgetSession(id);
|
|
@@ -1696,6 +2688,7 @@ const ModelRouterPlugin: Plugin = async (ctx: RouterPluginInput) => {
|
|
|
1696
2688
|
) {
|
|
1697
2689
|
try {
|
|
1698
2690
|
sessionStore.markChildSession(info.id);
|
|
2691
|
+
rememberRoleSession(info.id, info.agent); // #84 P2.1: a role child is known before its first tool call (v2 carries the agent)
|
|
1699
2692
|
} catch {
|
|
1700
2693
|
// best-effort: classification must never crash a real session
|
|
1701
2694
|
}
|
|
@@ -1783,6 +2776,17 @@ const ModelRouterPlugin: Plugin = async (ctx: RouterPluginInput) => {
|
|
|
1783
2776
|
prompt: finalPrompt,
|
|
1784
2777
|
color: tier.color,
|
|
1785
2778
|
};
|
|
2779
|
+
if (isReadOnlyTier(name, tier)) {
|
|
2780
|
+
const permission = mergePermissions(readOnlyPermissions(Boolean(opencodeConfig.mcp?.context7)
|
|
2781
|
+
&& opencodeConfig.mcp.context7.enabled !== false), opencodeConfig.agent[name]?.permission);
|
|
2782
|
+
agentDef.permission = permission;
|
|
2783
|
+
agentDef.tools = { ...legacyReadOnlyTools(permission), ...opencodeConfig.agent[name]?.tools };
|
|
2784
|
+
} else if (name === "fast" || tier.readOnly === false) {
|
|
2785
|
+
// Opt-out removes OUR policy, not restrictions the user supplied.
|
|
2786
|
+
for (const key of ["permission", "tools"]) {
|
|
2787
|
+
if (opencodeConfig.agent[name]?.[key] !== undefined) agentDef[key] = opencodeConfig.agent[name][key];
|
|
2788
|
+
}
|
|
2789
|
+
}
|
|
1786
2790
|
|
|
1787
2791
|
// Apply variant (thinking/reasoning mode)
|
|
1788
2792
|
if (tier.variant) {
|
|
@@ -1809,10 +2813,71 @@ const ModelRouterPlugin: Plugin = async (ctx: RouterPluginInput) => {
|
|
|
1809
2813
|
// preset's models. Opt-in: with no map, nothing here runs and the agent
|
|
1810
2814
|
// record is left exactly as opencode built it. Runs after tier
|
|
1811
2815
|
// registration so the tier-name collision guard sees the real tiers.
|
|
2816
|
+
// Plugin agents (#81): subagents defined by the router `agents` block.
|
|
2817
|
+
// Model/variant/steps always follow the ACTIVE preset's tier, so this
|
|
2818
|
+
// re-run on /preset rebuilds them. An opencode.json `agent.<name>` entry
|
|
2819
|
+
// wins for the fields it sets (its permission rules go after ours).
|
|
2820
|
+
const context7 = Boolean(opencodeConfig.mcp?.context7) && opencodeConfig.mcp.context7.enabled !== false;
|
|
2821
|
+
const builtNow = new Map<string, Record<string, unknown> | undefined>();
|
|
2822
|
+
const pluginTiers = resolveActiveTiers(cfg);
|
|
2823
|
+
for (const [name, entry] of Object.entries(cfg.agents ?? {})) {
|
|
2824
|
+
const tier = pluginTiers[entry.tier];
|
|
2825
|
+
if (!tier) continue;
|
|
2826
|
+
const existing = opencodeConfig.agent[name];
|
|
2827
|
+
const seed = (opencodeConfig as Record<symbol, unknown>)[HOST_SEED_AGENTS];
|
|
2828
|
+
const fromHostSeed = seed instanceof Set && seed.has(name);
|
|
2829
|
+
if (fromHostSeed && existing?.mode !== undefined && existing.mode !== "subagent") {
|
|
2830
|
+
warnAgentOptionsEffortOnce(`plugin-agent-host-mode:${name}`, `agent ${name} collides with a host built-in agent whose mode is '${String(existing.mode)}'; the router \`agents\` entry is skipped`, logger);
|
|
2831
|
+
continue;
|
|
2832
|
+
}
|
|
2833
|
+
// A definition this hook built on a previous run is not a user entry.
|
|
2834
|
+
const previous = pluginAgentMarker(existing);
|
|
2835
|
+
const hostEntry: Record<string, unknown> | undefined = previous
|
|
2836
|
+
? previous.hostEntry
|
|
2837
|
+
: existing !== undefined && typeof existing === "object" && existing !== null && !Array.isArray(existing)
|
|
2838
|
+
? existing as Record<string, unknown>
|
|
2839
|
+
: undefined;
|
|
2840
|
+
let definition = buildPluginAgentDefinition(entry, tier, { context7, host: "v1" });
|
|
2841
|
+
if (hostEntry !== undefined) {
|
|
2842
|
+
definition = mergeHostAgentEntry(definition, hostEntry);
|
|
2843
|
+
warnAgentOptionsEffortOnce(
|
|
2844
|
+
`plugin-agent-host-entry:${name}`,
|
|
2845
|
+
`agent ${name} is defined both in the router \`agents\` block and in ${fromHostSeed ? "a host built-in agent" : "opencode.json"}; ${fromHostSeed ? "the host definition" : "opencode.json"} wins for the fields it sets`,
|
|
2846
|
+
logger,
|
|
2847
|
+
);
|
|
2848
|
+
}
|
|
2849
|
+
opencodeConfig.agent[name] = definition;
|
|
2850
|
+
builtNow.set(name, hostEntry);
|
|
2851
|
+
}
|
|
2852
|
+
// QA-81-8 invariant: after this loop every plugin agent in `opencodeConfig.agent` was built THIS run, or is the host entry
|
|
2853
|
+
// the router replaced (restored), or is absent. Anything built on a previous run and not rebuilt now (removed or invalid) must not linger.
|
|
2854
|
+
// Detection is the symbol marker OR the closure set, so a cloned config (marker lost) is covered too.
|
|
2855
|
+
for (const name of Object.keys(opencodeConfig.agent)) {
|
|
2856
|
+
if (builtNow.has(name)) continue;
|
|
2857
|
+
const marker = pluginAgentMarker(opencodeConfig.agent[name]);
|
|
2858
|
+
if (marker === undefined && !builtPluginAgents.has(name)) continue;
|
|
2859
|
+
const restore = marker ? marker.hostEntry : builtPluginAgents.get(name);
|
|
2860
|
+
if (restore !== undefined) opencodeConfig.agent[name] = restore;
|
|
2861
|
+
else delete opencodeConfig.agent[name];
|
|
2862
|
+
}
|
|
2863
|
+
builtPluginAgents = builtNow;
|
|
2864
|
+
|
|
1812
2865
|
const subagentOverrides = resolveSubagentOverrides({
|
|
1813
2866
|
subagentTiers: cfg.subagentTiers,
|
|
1814
2867
|
tiers: activeTiers,
|
|
1815
|
-
|
|
2868
|
+
// The built-in list is the v1 host's; on v2 the setup seed already carries the real host agents.
|
|
2869
|
+
existingAgents: ctx.routerHost === "v2" ? opencodeConfig.agent : { ...V1_HOST_BUILTIN_AGENTS, ...opencodeConfig.agent },
|
|
2870
|
+
pluginAgents: cfg.agents,
|
|
2871
|
+
onSkip: (agentName, reason) =>
|
|
2872
|
+
reason === "missing" && opencodeConfig[DEFER_MISSING_SUBAGENT_NOTICE] === true
|
|
2873
|
+
? undefined
|
|
2874
|
+
: warnAgentOptionsEffortOnce(
|
|
2875
|
+
`subagent-tiers:${reason}:${agentName}`,
|
|
2876
|
+
reason === "missing"
|
|
2877
|
+
? `subagentTiers: '${agentName}' is not defined in opencode.json or the router \`agents\` block; skipped (the router never creates it)`
|
|
2878
|
+
: `subagentTiers: '${agentName}' is defined by the router \`agents\` block, whose tier wins; entry skipped`,
|
|
2879
|
+
logger,
|
|
2880
|
+
),
|
|
1816
2881
|
});
|
|
1817
2882
|
for (const [agentName, override] of Object.entries(subagentOverrides)) {
|
|
1818
2883
|
opencodeConfig.agent[agentName] = mergeSubagentOverride(
|
|
@@ -1902,7 +2967,7 @@ const ModelRouterPlugin: Plugin = async (ctx: RouterPluginInput) => {
|
|
|
1902
2967
|
if (bypassed) return;
|
|
1903
2968
|
try {
|
|
1904
2969
|
cfg = loadConfig(projectDir); // Returns cache unless invalidated
|
|
1905
|
-
|
|
2970
|
+
warnConfigIssues(cfg, logger);
|
|
1906
2971
|
} catch {
|
|
1907
2972
|
// Use last known config if file read fails
|
|
1908
2973
|
}
|
|
@@ -1955,10 +3020,31 @@ const ModelRouterPlugin: Plugin = async (ctx: RouterPluginInput) => {
|
|
|
1955
3020
|
const providerID = _input?.model?.providerID ?? "";
|
|
1956
3021
|
const modelID = _input?.model?.modelID ?? "";
|
|
1957
3022
|
const orchestratorModel = providerID && modelID ? `${providerID}/${modelID}` : modelID;
|
|
3023
|
+
if (providerID !== "") lastPrimary = { providerID, modelID: modelID === "" ? null : modelID };
|
|
1958
3024
|
|
|
1959
3025
|
let enfOn = false;
|
|
1960
3026
|
try { enfOn = resolveEnforcementMode({ config: cfg, env: process.env }).mode !== "off"; } catch {}
|
|
1961
|
-
|
|
3027
|
+
// #84 P2.1 (T2.1.3): v2 roles mode carries the roles protocol (P2.2); "" (v1, tiers mode, no enabled role) keeps today's prompt.
|
|
3028
|
+
const rolesPrompt = isV2Host ? assembleRolesSystemPrompt(cfg, rolesNow(), orchestratorModel, enfOn) : "";
|
|
3029
|
+
let systemPrompt = rolesPrompt !== "" ? rolesPrompt : assembleSystemPrompt(cfg, orchestratorModel, enfOn);
|
|
3030
|
+
// A28 (D1): on v1 only, and only with an explicit `routing.roles`, the `R:` line lists those agents as destinations (prose; no model
|
|
3031
|
+
// override). Anything else leaves `systemPrompt` the very string it is: the v1 protocol stays byte-identical.
|
|
3032
|
+
// Any failure leaves the baseline prompt (QA-2.4-13): the line is an extra, never a reason to lose the protocol.
|
|
3033
|
+
if (ctx.routerHost !== "v2") {
|
|
3034
|
+
const baseline = systemPrompt;
|
|
3035
|
+
try {
|
|
3036
|
+
if (hasExplicitV1Roles(cfg, logger)) systemPrompt = applyV1Roles(baseline, cfg, v1AgentsNow(), logger);
|
|
3037
|
+
} catch (error) {
|
|
3038
|
+
systemPrompt = baseline;
|
|
3039
|
+
logger.warn("[router] routing.roles: the R: line could not be extended; the protocol is unchanged", { error: describeError(error) });
|
|
3040
|
+
}
|
|
3041
|
+
}
|
|
3042
|
+
output.system.push(systemPrompt);
|
|
3043
|
+
|
|
3044
|
+
// 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
|
|
3045
|
+
// from here; in advise/enforce it is delivered with the user's next turn (the `chat.message` hook below), never in the system prompt:
|
|
3046
|
+
// a system part that changes would cost the orchestrator its prompt cache (QA-2.4-9).
|
|
3047
|
+
advisorNotifier?.poll();
|
|
1962
3048
|
|
|
1963
3049
|
// 2.4.4, section 1.5-20: this orchestrator's still-unverified delegations (at most 5 shown,
|
|
1964
3050
|
// newest first), as one short block. Nothing is pushed when the list is empty, so the prompt
|
|
@@ -1992,7 +3078,7 @@ const ModelRouterPlugin: Plugin = async (ctx: RouterPluginInput) => {
|
|
|
1992
3078
|
if (input.command === "tiers") {
|
|
1993
3079
|
try {
|
|
1994
3080
|
cfg = loadConfig(projectDir);
|
|
1995
|
-
|
|
3081
|
+
warnConfigIssues(cfg, logger);
|
|
1996
3082
|
} catch {}
|
|
1997
3083
|
output.parts.push({
|
|
1998
3084
|
type: "text" as const,
|
|
@@ -2000,6 +3086,31 @@ const ModelRouterPlugin: Plugin = async (ctx: RouterPluginInput) => {
|
|
|
2000
3086
|
});
|
|
2001
3087
|
}
|
|
2002
3088
|
|
|
3089
|
+
if (input.command === "annotate-plan") {
|
|
3090
|
+
// 2.4.4: the template (registered in the config hook) is unchanged. With a live engine on v2 this adds ONE message part: the
|
|
3091
|
+
// route lines the router computed for the plan's steps (one batched classification). Everything else is as before.
|
|
3092
|
+
try {
|
|
3093
|
+
cfg = loadConfig(projectDir);
|
|
3094
|
+
warnConfigIssues(cfg, logger);
|
|
3095
|
+
} catch {}
|
|
3096
|
+
try {
|
|
3097
|
+
const runtime = annotatePlanRuntime();
|
|
3098
|
+
if (runtime !== undefined && ctx.routerAgents !== undefined) {
|
|
3099
|
+
const directives = await buildAnnotateDirectives(input.arguments ?? "", {
|
|
3100
|
+
cfg,
|
|
3101
|
+
runtime,
|
|
3102
|
+
listAgents: ctx.routerAgents,
|
|
3103
|
+
dirs: [...new Set([ctx.directory, ctx.worktree].filter((dir): dir is string => typeof dir === "string" && dir !== ""))],
|
|
3104
|
+
logger,
|
|
3105
|
+
});
|
|
3106
|
+
if (directives !== null) output.parts.push({ type: "text" as const, text: directives });
|
|
3107
|
+
}
|
|
3108
|
+
} catch (error) {
|
|
3109
|
+
// No part: the command is then exactly what it was (QA-2.4-15).
|
|
3110
|
+
logger.warn("[router] /annotate-plan: route lines unavailable; the plan is annotated without them", { error: describeError(error) });
|
|
3111
|
+
}
|
|
3112
|
+
}
|
|
3113
|
+
|
|
2003
3114
|
if (input.command === "router-reload") {
|
|
2004
3115
|
invalidateConfigCache();
|
|
2005
3116
|
cfg = loadConfig(projectDir);
|
|
@@ -2035,7 +3146,7 @@ const ModelRouterPlugin: Plugin = async (ctx: RouterPluginInput) => {
|
|
|
2035
3146
|
if (input.command === "preset") {
|
|
2036
3147
|
try {
|
|
2037
3148
|
cfg = loadConfig(projectDir);
|
|
2038
|
-
|
|
3149
|
+
warnConfigIssues(cfg, logger);
|
|
2039
3150
|
} catch {}
|
|
2040
3151
|
output.parts.push({
|
|
2041
3152
|
type: "text" as const,
|
|
@@ -2061,7 +3172,7 @@ const ModelRouterPlugin: Plugin = async (ctx: RouterPluginInput) => {
|
|
|
2061
3172
|
if (input.command === "budget") {
|
|
2062
3173
|
try {
|
|
2063
3174
|
cfg = loadConfig(projectDir);
|
|
2064
|
-
|
|
3175
|
+
warnConfigIssues(cfg, logger);
|
|
2065
3176
|
} catch {}
|
|
2066
3177
|
output.parts.push({
|
|
2067
3178
|
type: "text" as const,
|
|
@@ -2072,7 +3183,7 @@ const ModelRouterPlugin: Plugin = async (ctx: RouterPluginInput) => {
|
|
|
2072
3183
|
if (input.command === "router") {
|
|
2073
3184
|
try {
|
|
2074
3185
|
cfg = loadConfig(projectDir);
|
|
2075
|
-
|
|
3186
|
+
warnConfigIssues(cfg, logger);
|
|
2076
3187
|
} catch {}
|
|
2077
3188
|
const args = (input.arguments ?? "").trim();
|
|
2078
3189
|
const parts = args.split(/\s+/).filter(Boolean);
|
|
@@ -2082,17 +3193,43 @@ const ModelRouterPlugin: Plugin = async (ctx: RouterPluginInput) => {
|
|
|
2082
3193
|
const catalog = await fetchCatalog();
|
|
2083
3194
|
const orphans = catalog ? findOrphanedStrongPatterns(cfg, catalog) : [];
|
|
2084
3195
|
text = buildModelsOutput(catalog, parts.slice(1).join(" "), orphans);
|
|
3196
|
+
} else if (sub === "stats" && cfg.routing !== undefined) {
|
|
3197
|
+
// 2.4.5 (D18): the table of `npm run routing:stats`, run by the very same driver over the configured store.
|
|
3198
|
+
try {
|
|
3199
|
+
text = formatStatsReply(await runStatsCommand(parts.slice(1).join(" "), { cfg, host: ctx.routerHost === "v2" ? "v2" : "v1", logger }));
|
|
3200
|
+
} catch (error) {
|
|
3201
|
+
logger.warn("[router] /router stats failed", { error: describeError(error) });
|
|
3202
|
+
text = `routing-stats: ${describeError(error)}`;
|
|
3203
|
+
}
|
|
2085
3204
|
} else {
|
|
2086
|
-
|
|
3205
|
+
// #84 P2.2: `/router` lists the roles in roles mode on v2 (`rolesNow()` is empty in tiers mode and on v1).
|
|
3206
|
+
text = buildRouterOutput(cfg, args, projectDir, rolesNow().size > 0 ? rolesNow().values() : undefined);
|
|
2087
3207
|
// On the bare status view, surface stale or missing models inline.
|
|
2088
3208
|
if (sub === "") {
|
|
2089
|
-
|
|
3209
|
+
text += "\n" + routerStatusLines(cfg, ctx.routerHost === "v2" ? "v2" : "v1", logger, projectDir).join("\n");
|
|
3210
|
+
// 2.4.5: the last dogfood checkpoint recorded next to this code (omitted when there is none). Only with a `routing` block:
|
|
3211
|
+
// without one `/router` is exactly what it was (QA-2.4-3, §1.2).
|
|
3212
|
+
const optedIn = cfg.routing !== undefined;
|
|
3213
|
+
const checkpoint = optedIn ? checkpointLine() : null;
|
|
3214
|
+
if (checkpoint !== null) text += "\n" + checkpoint;
|
|
3215
|
+
// One `config.providers()` call serves the model check below and the cost doctor.
|
|
3216
|
+
const fetched = await fetchCatalogRaw();
|
|
3217
|
+
const catalog = fetched?.catalog ?? null;
|
|
2090
3218
|
if (catalog) {
|
|
2091
3219
|
const issues = validateModels(cfg, catalog);
|
|
2092
3220
|
if (issues.length > 0) {
|
|
2093
3221
|
text += "\n\n" + formatModelIssues(issues);
|
|
2094
3222
|
}
|
|
2095
3223
|
}
|
|
3224
|
+
// 2.4.3: the cost doctor (v2 only, and only with a `routing` block; the advisor needs the v2 agent list and catalog).
|
|
3225
|
+
if (ctx.routerHost === "v2" && optedIn) {
|
|
3226
|
+
try {
|
|
3227
|
+
text += "\n\n" + (await buildCostDoctorLines(fetched)).join("\n");
|
|
3228
|
+
} catch (error) {
|
|
3229
|
+
logger.warn("[router] cost doctor failed", { error: describeError(error) });
|
|
3230
|
+
text += `\n\nCost doctor: unavailable (${describeError(error)}).`;
|
|
3231
|
+
}
|
|
3232
|
+
}
|
|
2096
3233
|
}
|
|
2097
3234
|
}
|
|
2098
3235
|
output.parts.push({ type: "text" as const, text });
|