opencode-model-router 2.0.0 → 2.2.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/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 { TASK_VERIFICATION } from "./compat/child-session";
3
+ import { DEPTH_BANNER, TASK_VERIFICATION } from "./compat/child-session";
4
4
 
5
5
  // Imports for internal use within this module
6
6
  import {
@@ -8,13 +8,15 @@ import {
8
8
  resolvePresetName,
9
9
  writeState,
10
10
  invalidateConfigCache,
11
+ getConfigReloadError,
11
12
  overridePath,
12
13
  localOverridePath,
13
14
  findProjectOverride,
14
15
  resolveVerifyBudget,
16
+ resolveDepthLimit,
15
17
  warnDeprecatedVerifyKeys,
16
18
  } from "./router/config";
17
- import type { RouterConfig, TierConfig, Preset, ModeConfig } from "./router/config";
19
+ import type { RouterConfig, TierConfig, Preset, ModeConfig, EffortLevel } from "./router/config";
18
20
  import { buildAgentOptions, warnAgentOptionsEffortOnce } from "./router/agent-options";
19
21
  import { selectTierPrompt, TOOL_AUTHORITY_CLAUSE } from "./router/prompts";
20
22
  import { stripDelegateInstructions } from "./router/instructions";
@@ -99,6 +101,9 @@ import {
99
101
  buildAcceptedSuffix,
100
102
  } from "./verify/dispatch";
101
103
  import { newLadderState, recordAttempt, nextAction, advance, buildEscalatePolicy, formatLadderScorecard } from "./escalate/ladder";
104
+ import { createDepthTracker, DEPTH_LOOKUP_RETRY_MS } from "./router/depth";
105
+ import { createDepthGuard } from "./router/depth-guard";
106
+ import { applyEffortOverride, createEffortOverrideStore } from "./escalate/effort-override";
102
107
 
103
108
  // ---------------------------------------------------------------------------
104
109
  // Re-exports — type-only re-exports for IDE/test consumers.
@@ -114,8 +119,17 @@ export type { TrajectoryState, TrajectoryToolEvent } from "./telemetry/trajector
114
119
  export type { EnforcementMode } from "./router/enforcement";
115
120
  export type { GuardPolicy, GuardState, GuardCall, GuardDecision } from "./guard/guards";
116
121
 
117
- function saveActivePreset(presetName: string): void {
118
- const cfg = loadConfig();
122
+ /** Diagnostics must also tolerate thrown values without primitive conversion. */
123
+ function describeError(error: unknown): string {
124
+ try {
125
+ return scrubText(String(error));
126
+ } catch {
127
+ return "unprintable error";
128
+ }
129
+ }
130
+
131
+ function saveActivePreset(presetName: string, projectDir?: string): void {
132
+ const cfg = loadConfig(projectDir);
119
133
  const resolved = resolvePresetName(cfg, presetName);
120
134
  if (!resolved) {
121
135
  return;
@@ -130,8 +144,8 @@ function saveActivePreset(presetName: string): void {
130
144
  invalidateConfigCache();
131
145
  }
132
146
 
133
- function saveActiveMode(modeName: string): void {
134
- const cfg = loadConfig();
147
+ function saveActiveMode(modeName: string, projectDir?: string): void {
148
+ const cfg = loadConfig(projectDir);
135
149
  if (!cfg.modes?.[modeName]) {
136
150
  return;
137
151
  }
@@ -150,7 +164,7 @@ function saveEnforcementMode(mode: "off" | "advisory" | "enforced"): void {
150
164
  * `/router` dispatch. Decides and persists here; rendering lives in
151
165
  * src/commands/output.ts.
152
166
  */
153
- function buildRouterOutput(cfg: RouterConfig, args: string): string {
167
+ function buildRouterOutput(cfg: RouterConfig, args: string, projectDir?: string): string {
154
168
  const tokens = (args ?? "").trim().split(/\s+/).filter(Boolean);
155
169
  const sub = (tokens[0] ?? "").toLowerCase();
156
170
 
@@ -167,8 +181,8 @@ function buildRouterOutput(cfg: RouterConfig, args: string): string {
167
181
 
168
182
  if (sub === "overrides") {
169
183
  const globalPath = overridePath();
170
- const foundLocal = findProjectOverride();
171
- const localPath = foundLocal ?? localOverridePath();
184
+ const foundLocal = findProjectOverride(projectDir);
185
+ const localPath = foundLocal ?? localOverridePath(projectDir);
172
186
  return buildOverridesOutput({
173
187
  globalPath,
174
188
  globalPresent: existsSync(globalPath),
@@ -185,7 +199,7 @@ function buildRouterOutput(cfg: RouterConfig, args: string): string {
185
199
  }
186
200
 
187
201
  /** `/budget` dispatch. Persists the switch, then renders. */
188
- function buildBudgetOutput(cfg: RouterConfig, args: string): string {
202
+ function buildBudgetOutput(cfg: RouterConfig, args: string, projectDir?: string): string {
189
203
  const modes = cfg.modes;
190
204
  if (!modes || Object.keys(modes).length === 0) return buildNoModes();
191
205
 
@@ -194,7 +208,7 @@ function buildBudgetOutput(cfg: RouterConfig, args: string): string {
194
208
 
195
209
  const mode = modes[requested];
196
210
  if (mode) {
197
- saveActiveMode(requested);
211
+ saveActiveMode(requested, projectDir);
198
212
  return buildBudgetSwitched(mode, requested);
199
213
  }
200
214
 
@@ -202,13 +216,13 @@ function buildBudgetOutput(cfg: RouterConfig, args: string): string {
202
216
  }
203
217
 
204
218
  /** `/preset` dispatch. Persists the switch, then renders. */
205
- function buildPresetOutput(cfg: RouterConfig, args: string): string {
219
+ function buildPresetOutput(cfg: RouterConfig, args: string, projectDir?: string): string {
206
220
  const requestedPreset = args.trim();
207
221
  if (!requestedPreset) return buildPresetList(cfg);
208
222
 
209
223
  const resolvedPreset = resolvePresetName(cfg, requestedPreset);
210
224
  if (resolvedPreset) {
211
- saveActivePreset(resolvedPreset);
225
+ saveActivePreset(resolvedPreset, projectDir);
212
226
  cfg.activePreset = resolvedPreset;
213
227
  return buildPresetSwitched(cfg, resolvedPreset);
214
228
  }
@@ -238,11 +252,15 @@ function warnSessionLookupFailedOnce(): void {
238
252
  }
239
253
 
240
254
  const SESSION_ROOT_MEMO_MAX = 500;
241
- const SESSION_LOOKUP_RETRY_MS = 30_000;
255
+ const SESSION_LOOKUP_RETRY_MS = DEPTH_LOOKUP_RETRY_MS;
242
256
 
243
257
  const ModelRouterPlugin: Plugin = async (ctx: RouterPluginInput) => {
244
- let cfg = loadConfig();
245
- const activeTiers = getActiveTiers(cfg);
258
+ // Project directory this plugin instance serves. Hosts that run several
259
+ // projects in one process (OpenCode v2) may also move process.cwd() away from
260
+ // it, so config/override lookup must use this and never the working directory.
261
+ const projectDir: string | undefined = ctx.directory || ctx.worktree || undefined;
262
+ let cfg = loadConfig(projectDir);
263
+ let activeTiers = getActiveTiers(cfg);
246
264
 
247
265
  // Per-plugin-instance session store: owns subagentSessionIDs and subagentCapState.
248
266
  const sessionStore = createSessionStore();
@@ -290,6 +308,7 @@ const ModelRouterPlugin: Plugin = async (ctx: RouterPluginInput) => {
290
308
  const memo = sessionRootMemo.get(sessionID);
291
309
  if (memo !== undefined) {
292
310
  if (!memo) sessionStore.markChildSession(sessionID);
311
+ else depthTracker.recordRoot(sessionID);
293
312
  return memo;
294
313
  }
295
314
  const failedAt = sessionLookupFailedAt.get(sessionID);
@@ -311,6 +330,8 @@ const ModelRouterPlugin: Plugin = async (ctx: RouterPluginInput) => {
311
330
  sessionRootMemo.delete(oldest);
312
331
  }
313
332
  if (!isRoot) sessionStore.markChildSession(sessionID);
333
+ if (isRoot) depthTracker.recordRoot(sessionID);
334
+ else depthTracker.recordCreated(sessionID, parentID as string);
314
335
  return isRoot;
315
336
  } catch {
316
337
  sessionLookupFailedAt.set(sessionID, Date.now());
@@ -346,6 +367,7 @@ const ModelRouterPlugin: Plugin = async (ctx: RouterPluginInput) => {
346
367
  () => guardStore.sweep(),
347
368
  () => trajectoryStore.sweep(),
348
369
  () => changedFileStore.sweep(),
370
+ () => depthTracker.sweep(),
349
371
  // 2.2.3: the S5 batch coordinator's defensive eviction (batch.ts B11). Declared below; the
350
372
  // sweeper only runs from chat.message, long after this factory has returned.
351
373
  () => { sweepVerification(); },
@@ -360,6 +382,60 @@ const ModelRouterPlugin: Plugin = async (ctx: RouterPluginInput) => {
360
382
  // from a plugin paints over the TUI. Falls back to console when the server
361
383
  // has no /log endpoint. See src/router/logger.ts.
362
384
  const logger = createPluginLogger(ctx.client);
385
+ const routerWarn = { warn: (message: string) => logger.warn(message) };
386
+ const depthTracker = createDepthTracker({
387
+ async getParent(id) {
388
+ if (sessionRootMemo.get(id) === true) return null;
389
+ const res = await ctx.client.session.get({ path: { id } });
390
+ if (!res || (res as { error?: unknown }).error || !res.data) {
391
+ throw new Error("session.get returned no session data");
392
+ }
393
+ const parentID = res.data.parentID;
394
+ return typeof parentID === "string" && parentID !== "" ? parentID : null;
395
+ },
396
+ now: () => Date.now(),
397
+ logger: routerWarn,
398
+ });
399
+ const depthGuard = createDepthGuard({
400
+ tracker: depthTracker,
401
+ limit: () => resolveDepthLimit(cfg),
402
+ mode: (sid) => resolveEnforcementMode({
403
+ config: cfg,
404
+ tier: (typeof sid === "string" ? sessionStore.getTier(sid) : null) ?? undefined,
405
+ env: process.env,
406
+ }).mode,
407
+ logger: routerWarn,
408
+ });
409
+ const effortOverrides = createEffortOverrideStore({ logger: routerWarn });
410
+ let warnedGraderParams = false;
411
+ const depthBanners = new Map<string, string>();
412
+ const warnedNoCallID = new Set<string>();
413
+ const stashDepthBanner = (
414
+ input: { sessionID?: string; callID?: string },
415
+ output: Record<PropertyKey, unknown>,
416
+ banner: string,
417
+ ): void => {
418
+ try {
419
+ if (ctx.routerHost === "v2") {
420
+ output[DEPTH_BANNER] = banner;
421
+ return;
422
+ }
423
+ if (typeof input.callID === "string" && input.callID !== "") {
424
+ const key = `${input.sessionID}:${input.callID}`;
425
+ depthBanners.delete(key);
426
+ depthBanners.set(key, banner);
427
+ while (depthBanners.size > 1000) depthBanners.delete(depthBanners.keys().next().value!);
428
+ } else {
429
+ const sid = String(input.sessionID);
430
+ if (warnedNoCallID.has(sid)) return;
431
+ logger.warn(`[router] delegation depth: task call without callID in session ${sid}; advisory banner not delivered`);
432
+ warnedNoCallID.add(sid);
433
+ while (warnedNoCallID.size > 1000) warnedNoCallID.delete(warnedNoCallID.values().next().value!);
434
+ }
435
+ } catch (error) {
436
+ logger.warn("[router] delegation depth: advisory banner not stored", { error: describeError(error) });
437
+ }
438
+ };
363
439
 
364
440
  const {
365
441
  graderSessions, dispatchGrader, buildGateDeps, disposeChildSession,
@@ -372,6 +448,7 @@ const ModelRouterPlugin: Plugin = async (ctx: RouterPluginInput) => {
372
448
  } = createVerificationWiring({
373
449
  client: ctx.client,
374
450
  childRunner: ctx.routerChildRunner,
451
+ onChildSessionCreated: (sid, creator) => depthTracker.recordPluginChild(sid, creator),
375
452
  directory: ctx.directory,
376
453
  getConfig: () => cfg,
377
454
  logger,
@@ -545,10 +622,28 @@ const ModelRouterPlugin: Plugin = async (ctx: RouterPluginInput) => {
545
622
  * settled; clearing it in the finally below would abort a capture still in flight.
546
623
  */
547
624
  let deferredOwnsBaseline = false;
625
+ const depth = bypassed ? undefined : await depthGuard.checkDispatch(toolCtx?.sessionID);
626
+ if (depth?.block) {
627
+ try {
628
+ // Known subagents are counted by the normal after-hook: delegate
629
+ // returns a refusal rather than throwing (unlike native task).
630
+ if (typeof toolCtx?.sessionID === "string" && !sessionStore.isSubagent(toolCtx.sessionID)) {
631
+ trajectoryStore.recordToolEvent(toolCtx.sessionID, { tool: "delegate", readOnly: false, blocked: true });
632
+ }
633
+ } catch {
634
+ // Best-effort observation must never lose the depth refusal.
635
+ }
636
+ return depth.message!;
637
+ }
638
+ const withDepthBanner = (text: string): string => {
639
+ if (!depth?.banner) return text;
640
+ const trimmed = text.trimEnd();
641
+ return trimmed ? `${trimmed}\n\n${depth.banner}` : depth.banner;
642
+ };
548
643
  try {
549
644
  let activeCfg = cfg;
550
645
  try {
551
- activeCfg = loadConfig();
646
+ activeCfg = loadConfig(projectDir);
552
647
  warnDeprecatedVerifyKeys(activeCfg, logger);
553
648
  } catch {
554
649
  activeCfg = cfg;
@@ -577,6 +672,7 @@ const ModelRouterPlugin: Plugin = async (ctx: RouterPluginInput) => {
577
672
 
578
673
  let producerText = "";
579
674
  let forcing: string | null = null;
675
+ let effort: EffortLevel | undefined;
580
676
 
581
677
  /**
582
678
  * One turn of the escalation ladder: create a producer session, run
@@ -591,6 +687,7 @@ const ModelRouterPlugin: Plugin = async (ctx: RouterPluginInput) => {
591
687
  const runProducerAttempt = async (
592
688
  tier: string,
593
689
  forcingNote: string | null,
690
+ effort?: EffortLevel,
594
691
  ): Promise<{
595
692
  sessionID: string;
596
693
  text: string;
@@ -609,6 +706,11 @@ const ModelRouterPlugin: Plugin = async (ctx: RouterPluginInput) => {
609
706
  const registerProducer = async (sid: string) => {
610
707
  producerSid = sid;
611
708
  producerSessions.push(sid);
709
+ depthTracker.recordPluginChild(sid, toolCtx?.sessionID ?? null);
710
+ if (effort !== undefined) {
711
+ const tierCfg = getActiveTiers(activeCfg)[tier];
712
+ if (tierCfg) effortOverrides.set(sid, tier, tierCfg, effort);
713
+ }
612
714
  // Keep the ORIGINAL dispatch reference across retries/escalations:
613
715
  // recapturing after a failed attempt would excuse its regression.
614
716
  if (!baselineID) {
@@ -717,6 +819,7 @@ const ModelRouterPlugin: Plugin = async (ctx: RouterPluginInput) => {
717
819
  } catch {
718
820
  // non-fatal
719
821
  }
822
+ effortOverrides.clear(producerSid);
720
823
  await disposeChildSession(producerSid);
721
824
  return { sessionID: producerSid, text: producerText, deferredFooter: finish.footer };
722
825
  }
@@ -845,6 +948,7 @@ const ModelRouterPlugin: Plugin = async (ctx: RouterPluginInput) => {
845
948
  }
846
949
  // Dispose this attempt's backend session before the next iteration
847
950
  // so a long ladder never accumulates live sessions.
951
+ effortOverrides.clear(producerSid);
848
952
  await disposeChildSession(producerSid);
849
953
 
850
954
  return { sessionID: producerSid, text: producerText, gateRes };
@@ -852,21 +956,21 @@ const ModelRouterPlugin: Plugin = async (ctx: RouterPluginInput) => {
852
956
 
853
957
  while (true) {
854
958
  if (safety++ > safetyMax) {
855
- return (
959
+ return withDepthBanner(
856
960
  `[router status: unmet] delegation stopped by the safety net after ` +
857
961
  `${state.totalAttempts} attempt(s).\n\n${scrubText(producerText)}`
858
962
  );
859
963
  }
860
964
  const tier = state.currentTier;
861
- const attempt = await runProducerAttempt(tier, forcing);
965
+ const attempt = await runProducerAttempt(tier, forcing, effort);
862
966
  if (!attempt) {
863
- return "[router] delegate failed: could not create a producer session.";
967
+ return withDepthBanner("[router] delegate failed: could not create a producer session.");
864
968
  }
865
969
  producerText = attempt.text;
866
970
  if ("deferredFooter" in attempt) {
867
971
  // Section 1.5-16: the result unchanged plus the footer, appended last. Never
868
972
  // labelled accepted or verified, and never retried or escalated.
869
- return appendRouterFooter(producerText, attempt.deferredFooter);
973
+ return appendRouterFooter(withDepthBanner(producerText), attempt.deferredFooter);
870
974
  }
871
975
  const producerSid = attempt.sessionID;
872
976
  const gateRes = attempt.gateRes;
@@ -890,7 +994,7 @@ const ModelRouterPlugin: Plugin = async (ctx: RouterPluginInput) => {
890
994
  true,
891
995
  gateRes.verdict.method,
892
996
  );
893
- return producerText + buildAcceptedSuffix(gateRes.verdict.method, gateRes.verdict.outcome, gateRes.verdict.caveats, gateRes.verdict.notes);
997
+ return withDepthBanner(producerText) + buildAcceptedSuffix(gateRes.verdict.method, gateRes.verdict.outcome, gateRes.verdict.caveats, gateRes.verdict.notes);
894
998
  }
895
999
  if (action.action === "give_up") {
896
1000
  dumpDelegateScorecard(
@@ -900,7 +1004,7 @@ const ModelRouterPlugin: Plugin = async (ctx: RouterPluginInput) => {
900
1004
  gateRes.verdict.method,
901
1005
  );
902
1006
  const note = scrubText(buildForcingNote(gateRes.verdict.reasons));
903
- return (
1007
+ return withDepthBanner(
904
1008
  `[router status: unmet] The delegated result was not accepted after ` +
905
1009
  `${state.totalAttempts} attempt(s) across ${state.escalations} escalation(s) ` +
906
1010
  `(final tier ${state.currentTier}; ${action.reason ?? "verification failed"}).\n\n` +
@@ -909,10 +1013,11 @@ const ModelRouterPlugin: Plugin = async (ctx: RouterPluginInput) => {
909
1013
  }
910
1014
  // retry or escalate
911
1015
  forcing = action.forcingMessage ?? null;
1016
+ effort = action.effort;
912
1017
  state = advance(state, action);
913
1018
  }
914
1019
  } catch {
915
- return "[router] delegate failed (fail-closed): the delegation or verification could not complete.";
1020
+ return withDepthBanner("[router] delegate failed (fail-closed): the delegation or verification could not complete.");
916
1021
  } finally {
917
1022
  // Safety net for every exit path an end-of-iteration dispose cannot
918
1023
  // reach: accept/give-up returns, the safety-net return, and throws.
@@ -920,6 +1025,7 @@ const ModelRouterPlugin: Plugin = async (ctx: RouterPluginInput) => {
920
1025
  // disposed session is harmless.
921
1026
  for (const sid of producerSessions) {
922
1027
  if (!(deferredOwnsBaseline && sid === baselineID)) changedFileStore.clear(sid);
1028
+ effortOverrides.clear(sid);
923
1029
  await disposeChildSession(sid);
924
1030
  }
925
1031
  }
@@ -987,8 +1093,26 @@ const ModelRouterPlugin: Plugin = async (ctx: RouterPluginInput) => {
987
1093
  output.temperature = graderTemperature;
988
1094
  }
989
1095
  }
990
- } catch {
991
- // best-effort: never crash a real session
1096
+ } catch (error) {
1097
+ if (!warnedGraderParams) {
1098
+ warnedGraderParams = true;
1099
+ try {
1100
+ logger.warn("[verify] grader temperature not applied", { error: describeError(error) });
1101
+ } catch {
1102
+ // Even a failed diagnostic sink must not interrupt chat.params.
1103
+ }
1104
+ }
1105
+ }
1106
+ try {
1107
+ if (input && typeof input === "object") {
1108
+ applyEffortOverride(effortOverrides, input, ctx.routerHost === "v2" ? output : output?.options, routerWarn);
1109
+ }
1110
+ } catch (error) {
1111
+ try {
1112
+ logger.warn("[router] effort override not applied", { error: describeError(error) });
1113
+ } catch {
1114
+ // Host accessors and diagnostic sinks are both best-effort here.
1115
+ }
992
1116
  }
993
1117
  },
994
1118
 
@@ -996,7 +1120,7 @@ const ModelRouterPlugin: Plugin = async (ctx: RouterPluginInput) => {
996
1120
  if (bypassed) return;
997
1121
  // Re-read cfg so /preset switches take effect without restart
998
1122
  try {
999
- cfg = loadConfig();
1123
+ cfg = loadConfig(projectDir);
1000
1124
  warnDeprecatedVerifyKeys(cfg, logger);
1001
1125
  } catch {}
1002
1126
  try {
@@ -1098,6 +1222,22 @@ const ModelRouterPlugin: Plugin = async (ctx: RouterPluginInput) => {
1098
1222
  // -----------------------------------------------------------------------
1099
1223
  "tool.execute.before": async (input: any, output: any) => {
1100
1224
  if (bypassed) return;
1225
+ if (input?.tool === "task") {
1226
+ const depth = await depthGuard.checkDispatch(input.sessionID);
1227
+ if (depth.block) {
1228
+ try {
1229
+ if (typeof input.sessionID === "string") {
1230
+ trajectoryStore.recordToolEvent(input.sessionID, {
1231
+ tool: input.tool, readOnly: READ_ONLY_TOOLS.has(input.tool), blocked: true,
1232
+ });
1233
+ }
1234
+ } catch (error) {
1235
+ logger.warn("[router] delegation depth: refusal not recorded", { error: describeError(error) });
1236
+ }
1237
+ throw new Error(depth.message);
1238
+ }
1239
+ if (depth.banner) stashDepthBanner(input, output, depth.banner);
1240
+ }
1101
1241
  // Observe before execution too: an in-flight edit must contaminate a
1102
1242
  // capture even if the test finishes before the edit's after-hook fires.
1103
1243
  if (typeof input?.tool === "string") changedFileStore.observeEdit(input.tool,
@@ -1259,6 +1399,22 @@ const ModelRouterPlugin: Plugin = async (ctx: RouterPluginInput) => {
1259
1399
  changedFileStore.record(sid, input.tool, input?.args);
1260
1400
  }
1261
1401
 
1402
+ let unbannered: { output: unknown } | undefined;
1403
+ if (input?.tool === "task") {
1404
+ const key = `${sid}:${input.callID}`;
1405
+ const banner = depthBanners.get(key);
1406
+ depthBanners.delete(key);
1407
+ if (banner !== undefined) {
1408
+ try {
1409
+ unbannered = { output: output.output };
1410
+ const text = typeof output.output === "string" ? output.output.trimEnd() : "";
1411
+ output.output = text ? `${text}\n\n${banner}` : banner;
1412
+ } catch (error) {
1413
+ logger.warn("[router] delegation depth: advisory banner not delivered", { error: describeError(error) });
1414
+ }
1415
+ }
1416
+ }
1417
+
1262
1418
  if (sid && sessionStore.isSubagent(sid) && typeof input?.tool === "string") {
1263
1419
  trajectoryStore.recordToolEvent(sid, {
1264
1420
  tool: input.tool,
@@ -1294,7 +1450,7 @@ const ModelRouterPlugin: Plugin = async (ctx: RouterPluginInput) => {
1294
1450
  try {
1295
1451
  // pending.ts R11: the producer's changes landed by now.
1296
1452
  const returnedAt = Date.now();
1297
- const { finalReturnText, childSessionID } = parseTaskResult(output);
1453
+ const { finalReturnText, childSessionID } = parseTaskResult(unbannered ? { ...output, output: unbannered.output } : output);
1298
1454
  const producerTier =
1299
1455
  typeof input?.args?.subagent_type === "string"
1300
1456
  ? input.args.subagent_type
@@ -1379,7 +1535,8 @@ const ModelRouterPlugin: Plugin = async (ctx: RouterPluginInput) => {
1379
1535
 
1380
1536
  const gateGraderSessions = new Set<string>();
1381
1537
  const completedFailures: string[] = [];
1382
- const gateDeps = buildGateDeps(undefined, gateGraderSessions, verification, gateDeadline);
1538
+ // Keep the native grader unparented on the backend; only depth tracking uses its caller.
1539
+ const gateDeps = buildGateDeps(undefined, gateGraderSessions, verification, gateDeadline, false, orchestratorSessionID || null);
1383
1540
  gateDeps.deterministic.onFailure = reason => completedFailures.push(reason);
1384
1541
  let res;
1385
1542
  try {
@@ -1497,6 +1654,12 @@ const ModelRouterPlugin: Plugin = async (ctx: RouterPluginInput) => {
1497
1654
  sessionRootMemo.delete(id);
1498
1655
  sessionLookupFailedAt.delete(id);
1499
1656
  sessionStore.unregister(id);
1657
+ effortOverrides.clear(id);
1658
+ depthTracker.forget(id);
1659
+ for (const key of depthBanners.keys()) {
1660
+ if (key.startsWith(`${id}:`)) depthBanners.delete(key);
1661
+ }
1662
+ warnedNoCallID.delete(id);
1500
1663
  // 2.4.2b: a deleted orchestrator's handles, tombstones and lineage records go with it.
1501
1664
  // 2.4.5: so do its background requests and late notices; its run in flight is aborted.
1502
1665
  background?.forgetSession(id);
@@ -1518,6 +1681,14 @@ const ModelRouterPlugin: Plugin = async (ctx: RouterPluginInput) => {
1518
1681
  // subagent that has no task tool, and the subagent refused the work.
1519
1682
  if (event?.type === "session.created") {
1520
1683
  const info = event?.properties?.info;
1684
+ try {
1685
+ if (typeof info?.id === "string") {
1686
+ depthTracker.recordCreated(info.id,
1687
+ typeof info.parentID === "string" && info.parentID !== "" ? info.parentID : null);
1688
+ }
1689
+ } catch (error) {
1690
+ logger.warn("[router] delegation depth: session creation not recorded", { error: describeError(error) });
1691
+ }
1521
1692
  if (
1522
1693
  typeof info?.id === "string" &&
1523
1694
  typeof info?.parentID === "string" &&
@@ -1568,6 +1739,10 @@ const ModelRouterPlugin: Plugin = async (ctx: RouterPluginInput) => {
1568
1739
  config: async (opencodeConfig: any) => {
1569
1740
  opencodeConfig.agent ??= {};
1570
1741
 
1742
+ // Re-read so re-running this hook (v2 refresh) yields the current preset.
1743
+ cfg = loadConfig(projectDir);
1744
+ activeTiers = getActiveTiers(cfg);
1745
+
1571
1746
  for (const [name, tier] of Object.entries(activeTiers)) {
1572
1747
  // Resolve prompt: per-tier override wins; otherwise fall back to the
1573
1748
  // style-appropriate default (goal-oriented or global tierPrompts[name]).
@@ -1703,6 +1878,13 @@ const ModelRouterPlugin: Plugin = async (ctx: RouterPluginInput) => {
1703
1878
  description:
1704
1879
  "Annotate a plan with [tier:fast/medium/heavy] delegation tags",
1705
1880
  };
1881
+ opencodeConfig.command["router-reload"] = {
1882
+ template: "",
1883
+ description:
1884
+ ctx.routerHost === "v2"
1885
+ ? "Reload model-router config (tiers.json, overrides, state) without restarting"
1886
+ : "Reload model-router config (tiers.json, overrides, state); subagent models apply after an opencode restart",
1887
+ };
1706
1888
  opencodeConfig.command["router"] = {
1707
1889
  template: "$ARGUMENTS",
1708
1890
  description:
@@ -1719,7 +1901,7 @@ const ModelRouterPlugin: Plugin = async (ctx: RouterPluginInput) => {
1719
1901
  "experimental.chat.system.transform": async (_input: any, output: any) => {
1720
1902
  if (bypassed) return;
1721
1903
  try {
1722
- cfg = loadConfig(); // Returns cache unless invalidated
1904
+ cfg = loadConfig(projectDir); // Returns cache unless invalidated
1723
1905
  warnDeprecatedVerifyKeys(cfg, logger);
1724
1906
  } catch {
1725
1907
  // Use last known config if file read fails
@@ -1809,7 +1991,7 @@ const ModelRouterPlugin: Plugin = async (ctx: RouterPluginInput) => {
1809
1991
  "command.execute.before": async (input: any, output: any) => {
1810
1992
  if (input.command === "tiers") {
1811
1993
  try {
1812
- cfg = loadConfig();
1994
+ cfg = loadConfig(projectDir);
1813
1995
  warnDeprecatedVerifyKeys(cfg, logger);
1814
1996
  } catch {}
1815
1997
  output.parts.push({
@@ -1818,14 +2000,46 @@ const ModelRouterPlugin: Plugin = async (ctx: RouterPluginInput) => {
1818
2000
  });
1819
2001
  }
1820
2002
 
2003
+ if (input.command === "router-reload") {
2004
+ invalidateConfigCache();
2005
+ cfg = loadConfig(projectDir);
2006
+ activeTiers = getActiveTiers(cfg);
2007
+ const mapping = Object.entries(activeTiers)
2008
+ .map(([name, tier]) => ` ${name} -> ${tier.model}`)
2009
+ .join("\n");
2010
+ const reloadError = getConfigReloadError(projectDir);
2011
+ output.parts.push({
2012
+ type: "text" as const,
2013
+ text: [
2014
+ ...(reloadError
2015
+ ? [
2016
+ `Config reload FAILED — keeping last valid config:\n${reloadError}`,
2017
+ "Model router is still using the last valid config.",
2018
+ ]
2019
+ : ["Model router config reloaded."]),
2020
+ `Preset: ${cfg.activePreset}`,
2021
+ `Mode: ${cfg.activeMode ?? "normal"}`,
2022
+ "Tiers:",
2023
+ mapping,
2024
+ // opencode v1 builds its agent registry once at startup; only the v2
2025
+ // adapter re-runs the config hook + agent reload after /router-reload.
2026
+ ...(ctx.routerHost === "v2"
2027
+ ? []
2028
+ : [
2029
+ "Note: opencode v1 keeps subagent (task) models from startup; restart opencode to apply tier model changes to subagents. Routing and protocol already use the new config.",
2030
+ ]),
2031
+ ].join("\n"),
2032
+ });
2033
+ }
2034
+
1821
2035
  if (input.command === "preset") {
1822
2036
  try {
1823
- cfg = loadConfig();
2037
+ cfg = loadConfig(projectDir);
1824
2038
  warnDeprecatedVerifyKeys(cfg, logger);
1825
2039
  } catch {}
1826
2040
  output.parts.push({
1827
2041
  type: "text" as const,
1828
- text: buildPresetOutput(cfg, input.arguments ?? ""),
2042
+ text: buildPresetOutput(cfg, input.arguments ?? "", projectDir),
1829
2043
  });
1830
2044
  }
1831
2045
 
@@ -1846,18 +2060,18 @@ const ModelRouterPlugin: Plugin = async (ctx: RouterPluginInput) => {
1846
2060
 
1847
2061
  if (input.command === "budget") {
1848
2062
  try {
1849
- cfg = loadConfig();
2063
+ cfg = loadConfig(projectDir);
1850
2064
  warnDeprecatedVerifyKeys(cfg, logger);
1851
2065
  } catch {}
1852
2066
  output.parts.push({
1853
2067
  type: "text" as const,
1854
- text: buildBudgetOutput(cfg, input.arguments ?? ""),
2068
+ text: buildBudgetOutput(cfg, input.arguments ?? "", projectDir),
1855
2069
  });
1856
2070
  }
1857
2071
 
1858
2072
  if (input.command === "router") {
1859
2073
  try {
1860
- cfg = loadConfig();
2074
+ cfg = loadConfig(projectDir);
1861
2075
  warnDeprecatedVerifyKeys(cfg, logger);
1862
2076
  } catch {}
1863
2077
  const args = (input.arguments ?? "").trim();
@@ -1869,7 +2083,7 @@ const ModelRouterPlugin: Plugin = async (ctx: RouterPluginInput) => {
1869
2083
  const orphans = catalog ? findOrphanedStrongPatterns(cfg, catalog) : [];
1870
2084
  text = buildModelsOutput(catalog, parts.slice(1).join(" "), orphans);
1871
2085
  } else {
1872
- text = buildRouterOutput(cfg, args);
2086
+ text = buildRouterOutput(cfg, args, projectDir);
1873
2087
  // On the bare status view, surface stale or missing models inline.
1874
2088
  if (sub === "") {
1875
2089
  const catalog = await fetchCatalog();