opencode-model-router 1.15.0 → 2.1.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,4 +1,6 @@
1
- import type { Plugin, PluginInput } from "@opencode-ai/plugin";
1
+ import type { Plugin } from "@opencode-ai/plugin";
2
+ import type { RouterPluginInput } from "./compat/child-session";
3
+ import { DEPTH_BANNER, TASK_VERIFICATION } from "./compat/child-session";
2
4
 
3
5
  // Imports for internal use within this module
4
6
  import {
@@ -10,9 +12,10 @@ import {
10
12
  localOverridePath,
11
13
  findProjectOverride,
12
14
  resolveVerifyBudget,
15
+ resolveDepthLimit,
13
16
  warnDeprecatedVerifyKeys,
14
17
  } from "./router/config";
15
- import type { RouterConfig, TierConfig, Preset, ModeConfig } from "./router/config";
18
+ import type { RouterConfig, TierConfig, Preset, ModeConfig, EffortLevel } from "./router/config";
16
19
  import { buildAgentOptions, warnAgentOptionsEffortOnce } from "./router/agent-options";
17
20
  import { selectTierPrompt, TOOL_AUTHORITY_CLAUSE } from "./router/prompts";
18
21
  import { stripDelegateInstructions } from "./router/instructions";
@@ -97,6 +100,9 @@ import {
97
100
  buildAcceptedSuffix,
98
101
  } from "./verify/dispatch";
99
102
  import { newLadderState, recordAttempt, nextAction, advance, buildEscalatePolicy, formatLadderScorecard } from "./escalate/ladder";
103
+ import { createDepthTracker, DEPTH_LOOKUP_RETRY_MS } from "./router/depth";
104
+ import { createDepthGuard } from "./router/depth-guard";
105
+ import { applyEffortOverride, createEffortOverrideStore } from "./escalate/effort-override";
100
106
 
101
107
  // ---------------------------------------------------------------------------
102
108
  // Re-exports — type-only re-exports for IDE/test consumers.
@@ -112,6 +118,15 @@ export type { TrajectoryState, TrajectoryToolEvent } from "./telemetry/trajector
112
118
  export type { EnforcementMode } from "./router/enforcement";
113
119
  export type { GuardPolicy, GuardState, GuardCall, GuardDecision } from "./guard/guards";
114
120
 
121
+ /** Diagnostics must also tolerate thrown values without primitive conversion. */
122
+ function describeError(error: unknown): string {
123
+ try {
124
+ return scrubText(String(error));
125
+ } catch {
126
+ return "unprintable error";
127
+ }
128
+ }
129
+
115
130
  function saveActivePreset(presetName: string): void {
116
131
  const cfg = loadConfig();
117
132
  const resolved = resolvePresetName(cfg, presetName);
@@ -236,9 +251,9 @@ function warnSessionLookupFailedOnce(): void {
236
251
  }
237
252
 
238
253
  const SESSION_ROOT_MEMO_MAX = 500;
239
- const SESSION_LOOKUP_RETRY_MS = 30_000;
254
+ const SESSION_LOOKUP_RETRY_MS = DEPTH_LOOKUP_RETRY_MS;
240
255
 
241
- const ModelRouterPlugin: Plugin = async (ctx: PluginInput) => {
256
+ const ModelRouterPlugin: Plugin = async (ctx: RouterPluginInput) => {
242
257
  let cfg = loadConfig();
243
258
  const activeTiers = getActiveTiers(cfg);
244
259
 
@@ -288,6 +303,7 @@ const ModelRouterPlugin: Plugin = async (ctx: PluginInput) => {
288
303
  const memo = sessionRootMemo.get(sessionID);
289
304
  if (memo !== undefined) {
290
305
  if (!memo) sessionStore.markChildSession(sessionID);
306
+ else depthTracker.recordRoot(sessionID);
291
307
  return memo;
292
308
  }
293
309
  const failedAt = sessionLookupFailedAt.get(sessionID);
@@ -309,6 +325,8 @@ const ModelRouterPlugin: Plugin = async (ctx: PluginInput) => {
309
325
  sessionRootMemo.delete(oldest);
310
326
  }
311
327
  if (!isRoot) sessionStore.markChildSession(sessionID);
328
+ if (isRoot) depthTracker.recordRoot(sessionID);
329
+ else depthTracker.recordCreated(sessionID, parentID as string);
312
330
  return isRoot;
313
331
  } catch {
314
332
  sessionLookupFailedAt.set(sessionID, Date.now());
@@ -344,6 +362,7 @@ const ModelRouterPlugin: Plugin = async (ctx: PluginInput) => {
344
362
  () => guardStore.sweep(),
345
363
  () => trajectoryStore.sweep(),
346
364
  () => changedFileStore.sweep(),
365
+ () => depthTracker.sweep(),
347
366
  // 2.2.3: the S5 batch coordinator's defensive eviction (batch.ts B11). Declared below; the
348
367
  // sweeper only runs from chat.message, long after this factory has returned.
349
368
  () => { sweepVerification(); },
@@ -358,6 +377,60 @@ const ModelRouterPlugin: Plugin = async (ctx: PluginInput) => {
358
377
  // from a plugin paints over the TUI. Falls back to console when the server
359
378
  // has no /log endpoint. See src/router/logger.ts.
360
379
  const logger = createPluginLogger(ctx.client);
380
+ const routerWarn = { warn: (message: string) => logger.warn(message) };
381
+ const depthTracker = createDepthTracker({
382
+ async getParent(id) {
383
+ if (sessionRootMemo.get(id) === true) return null;
384
+ const res = await ctx.client.session.get({ path: { id } });
385
+ if (!res || (res as { error?: unknown }).error || !res.data) {
386
+ throw new Error("session.get returned no session data");
387
+ }
388
+ const parentID = res.data.parentID;
389
+ return typeof parentID === "string" && parentID !== "" ? parentID : null;
390
+ },
391
+ now: () => Date.now(),
392
+ logger: routerWarn,
393
+ });
394
+ const depthGuard = createDepthGuard({
395
+ tracker: depthTracker,
396
+ limit: () => resolveDepthLimit(cfg),
397
+ mode: (sid) => resolveEnforcementMode({
398
+ config: cfg,
399
+ tier: (typeof sid === "string" ? sessionStore.getTier(sid) : null) ?? undefined,
400
+ env: process.env,
401
+ }).mode,
402
+ logger: routerWarn,
403
+ });
404
+ const effortOverrides = createEffortOverrideStore({ logger: routerWarn });
405
+ let warnedGraderParams = false;
406
+ const depthBanners = new Map<string, string>();
407
+ const warnedNoCallID = new Set<string>();
408
+ const stashDepthBanner = (
409
+ input: { sessionID?: string; callID?: string },
410
+ output: Record<PropertyKey, unknown>,
411
+ banner: string,
412
+ ): void => {
413
+ try {
414
+ if (ctx.routerHost === "v2") {
415
+ output[DEPTH_BANNER] = banner;
416
+ return;
417
+ }
418
+ if (typeof input.callID === "string" && input.callID !== "") {
419
+ const key = `${input.sessionID}:${input.callID}`;
420
+ depthBanners.delete(key);
421
+ depthBanners.set(key, banner);
422
+ while (depthBanners.size > 1000) depthBanners.delete(depthBanners.keys().next().value!);
423
+ } else {
424
+ const sid = String(input.sessionID);
425
+ if (warnedNoCallID.has(sid)) return;
426
+ logger.warn(`[router] delegation depth: task call without callID in session ${sid}; advisory banner not delivered`);
427
+ warnedNoCallID.add(sid);
428
+ while (warnedNoCallID.size > 1000) warnedNoCallID.delete(warnedNoCallID.values().next().value!);
429
+ }
430
+ } catch (error) {
431
+ logger.warn("[router] delegation depth: advisory banner not stored", { error: describeError(error) });
432
+ }
433
+ };
361
434
 
362
435
  const {
363
436
  graderSessions, dispatchGrader, buildGateDeps, disposeChildSession,
@@ -369,6 +442,8 @@ const ModelRouterPlugin: Plugin = async (ctx: PluginInput) => {
369
442
  background,
370
443
  } = createVerificationWiring({
371
444
  client: ctx.client,
445
+ childRunner: ctx.routerChildRunner,
446
+ onChildSessionCreated: (sid, creator) => depthTracker.recordPluginChild(sid, creator),
372
447
  directory: ctx.directory,
373
448
  getConfig: () => cfg,
374
449
  logger,
@@ -542,6 +617,24 @@ const ModelRouterPlugin: Plugin = async (ctx: PluginInput) => {
542
617
  * settled; clearing it in the finally below would abort a capture still in flight.
543
618
  */
544
619
  let deferredOwnsBaseline = false;
620
+ const depth = bypassed ? undefined : await depthGuard.checkDispatch(toolCtx?.sessionID);
621
+ if (depth?.block) {
622
+ try {
623
+ // Known subagents are counted by the normal after-hook: delegate
624
+ // returns a refusal rather than throwing (unlike native task).
625
+ if (typeof toolCtx?.sessionID === "string" && !sessionStore.isSubagent(toolCtx.sessionID)) {
626
+ trajectoryStore.recordToolEvent(toolCtx.sessionID, { tool: "delegate", readOnly: false, blocked: true });
627
+ }
628
+ } catch {
629
+ // Best-effort observation must never lose the depth refusal.
630
+ }
631
+ return depth.message!;
632
+ }
633
+ const withDepthBanner = (text: string): string => {
634
+ if (!depth?.banner) return text;
635
+ const trimmed = text.trimEnd();
636
+ return trimmed ? `${trimmed}\n\n${depth.banner}` : depth.banner;
637
+ };
545
638
  try {
546
639
  let activeCfg = cfg;
547
640
  try {
@@ -558,6 +651,7 @@ const ModelRouterPlugin: Plugin = async (ctx: PluginInput) => {
558
651
  prompt: args.task,
559
652
  acceptance: args.acceptance,
560
653
  });
654
+ const effectiveCwd = typeof args.cwd === "string" && args.cwd.trim() ? args.cwd : dod.cwd;
561
655
 
562
656
  const policy = buildEscalatePolicy(activeCfg);
563
657
  let state = newLadderState(initialTier, policy);
@@ -573,6 +667,7 @@ const ModelRouterPlugin: Plugin = async (ctx: PluginInput) => {
573
667
 
574
668
  let producerText = "";
575
669
  let forcing: string | null = null;
670
+ let effort: EffortLevel | undefined;
576
671
 
577
672
  /**
578
673
  * One turn of the escalation ladder: create a producer session, run
@@ -587,6 +682,7 @@ const ModelRouterPlugin: Plugin = async (ctx: PluginInput) => {
587
682
  const runProducerAttempt = async (
588
683
  tier: string,
589
684
  forcingNote: string | null,
685
+ effort?: EffortLevel,
590
686
  ): Promise<{
591
687
  sessionID: string;
592
688
  text: string;
@@ -601,27 +697,38 @@ const ModelRouterPlugin: Plugin = async (ctx: PluginInput) => {
601
697
  ? `${scrubText(forcingNote)}\n\n${args.task}`
602
698
  : args.task;
603
699
 
604
- const created: any = await ctx.client.session.create({
605
- body: {
606
- ...(toolCtx?.sessionID ? { parentID: toolCtx.sessionID } : {}),
607
- },
608
- });
609
- const producerSid: string | undefined = created?.data?.id;
610
- if (!producerSid) return null;
611
- producerSessions.push(producerSid);
612
- // Keep the ORIGINAL dispatch reference across retries/escalations:
613
- // recapturing after a failed attempt would excuse its regression.
614
- if (!baselineID) {
615
- baselineID = producerSid;
616
- // 2.4.2c: the directives come from the orchestrator's `task` argument only; the
617
- // capture is awaited for at most VERIFY_WAIT and continues in the background.
618
- dispatchStart = await startDispatch(changedFileStore, baselineID, args.cwd, dod, args.task, false);
619
- }
620
- // Compose with Layer 1: guard the plugin-created producer session.
621
- try {
622
- sessionStore.registerProducerSession(producerSid, tier, activeCfg);
623
- } catch {
624
- // non-fatal
700
+ let producerSid: string | undefined;
701
+ const registerProducer = async (sid: string) => {
702
+ producerSid = sid;
703
+ producerSessions.push(sid);
704
+ depthTracker.recordPluginChild(sid, toolCtx?.sessionID ?? null);
705
+ if (effort !== undefined) {
706
+ const tierCfg = getActiveTiers(activeCfg)[tier];
707
+ if (tierCfg) effortOverrides.set(sid, tier, tierCfg, effort);
708
+ }
709
+ // Keep the ORIGINAL dispatch reference across retries/escalations:
710
+ // recapturing after a failed attempt would excuse its regression.
711
+ if (!baselineID) {
712
+ baselineID = sid;
713
+ // Capture before the child gets its first prompt, on either API.
714
+ dispatchStart = await startDispatch(changedFileStore, baselineID, effectiveCwd, dod, args.task, false);
715
+ }
716
+ // Compose with Layer 1: guard the plugin-created producer session.
717
+ try {
718
+ sessionStore.registerProducerSession(sid, tier, activeCfg);
719
+ } catch {
720
+ // non-fatal
721
+ }
722
+ };
723
+ if (!ctx.routerChildRunner) {
724
+ const created: any = await ctx.client.session.create({
725
+ body: {
726
+ ...(toolCtx?.sessionID ? { parentID: toolCtx.sessionID } : {}),
727
+ },
728
+ });
729
+ const sid: string | undefined = created?.data?.id;
730
+ if (!sid) return null;
731
+ await registerProducer(sid);
625
732
  }
626
733
 
627
734
  const model = tierModel(activeCfg, tier) ?? undefined;
@@ -639,10 +746,18 @@ const ModelRouterPlugin: Plugin = async (ctx: PluginInput) => {
639
746
  // the same failed-attempt path as any other producer error — it
640
747
  // is never an empty artefact that a lenient DoD could pass.
641
748
  let producerError: string | null = null;
749
+ const childAbort = ctx.routerChildRunner ? new AbortController() : undefined;
642
750
  try {
643
- const res: any = await withTimeout(
644
- ctx.client.session.prompt({
645
- path: { id: producerSid },
751
+ const res: any = await withTimeout<unknown>(
752
+ ctx.routerChildRunner ? ctx.routerChildRunner.run({
753
+ parentSessionID: toolCtx?.sessionID,
754
+ agent: tier,
755
+ model: model ? { ...model, variant: getActiveTiers(activeCfg)[tier]?.variant } : undefined,
756
+ prompt: taskText,
757
+ signal: childAbort!.signal,
758
+ onCreated: registerProducer,
759
+ }) : ctx.client.session.prompt({
760
+ path: { id: producerSid! },
646
761
  body: {
647
762
  ...(model ? { model } : {}),
648
763
  ...(tier ? { agent: tier } : {}),
@@ -655,12 +770,15 @@ const ModelRouterPlugin: Plugin = async (ctx: PluginInput) => {
655
770
  ),
656
771
  "delegate producer prompt",
657
772
  );
658
- producerText = extractAssistantText(res);
773
+ producerText = ctx.routerChildRunner ? res.text : extractAssistantText(res);
659
774
  } catch (error) {
660
775
  producerError =
661
776
  error instanceof Error ? error.message : String(error);
662
777
  producerText = "";
778
+ } finally {
779
+ childAbort?.abort();
663
780
  }
781
+ if (!producerSid || !baselineID) return null;
664
782
  // pending.ts R11: the producer's changes landed by now.
665
783
  const returnedAt = Date.now();
666
784
 
@@ -675,7 +793,7 @@ const ModelRouterPlugin: Plugin = async (ctx: PluginInput) => {
675
793
  producerSessionID: producerSid,
676
794
  producerTier: tier,
677
795
  description: args.task,
678
- cwd: args.cwd,
796
+ cwd: effectiveCwd,
679
797
  dod,
680
798
  dispatchedAt: dispatchStart.dispatchedAt,
681
799
  })
@@ -696,6 +814,7 @@ const ModelRouterPlugin: Plugin = async (ctx: PluginInput) => {
696
814
  } catch {
697
815
  // non-fatal
698
816
  }
817
+ effortOverrides.clear(producerSid);
699
818
  await disposeChildSession(producerSid);
700
819
  return { sessionID: producerSid, text: producerText, deferredFooter: finish.footer };
701
820
  }
@@ -714,7 +833,7 @@ const ModelRouterPlugin: Plugin = async (ctx: PluginInput) => {
714
833
  const gateDeadline = createDeadline(gateBudgetMs);
715
834
  let verification;
716
835
  try {
717
- verification = await prepareVerification(changedFileStore, baselineID, producerSid, args.cwd, gateDeadline);
836
+ verification = await prepareVerification(changedFileStore, baselineID, producerSid, effectiveCwd, gateDeadline);
718
837
  } catch (error) {
719
838
  gateDeadline.dispose();
720
839
  throw error;
@@ -751,7 +870,7 @@ const ModelRouterPlugin: Plugin = async (ctx: PluginInput) => {
751
870
  dod,
752
871
  trivial: false,
753
872
  mode: "modeA",
754
- ...(args.cwd ? { cwd: args.cwd } : {}),
873
+ ...(effectiveCwd ? { cwd: effectiveCwd } : {}),
755
874
  },
756
875
  artefact,
757
876
  gateDeps,
@@ -824,6 +943,7 @@ const ModelRouterPlugin: Plugin = async (ctx: PluginInput) => {
824
943
  }
825
944
  // Dispose this attempt's backend session before the next iteration
826
945
  // so a long ladder never accumulates live sessions.
946
+ effortOverrides.clear(producerSid);
827
947
  await disposeChildSession(producerSid);
828
948
 
829
949
  return { sessionID: producerSid, text: producerText, gateRes };
@@ -831,21 +951,21 @@ const ModelRouterPlugin: Plugin = async (ctx: PluginInput) => {
831
951
 
832
952
  while (true) {
833
953
  if (safety++ > safetyMax) {
834
- return (
954
+ return withDepthBanner(
835
955
  `[router status: unmet] delegation stopped by the safety net after ` +
836
956
  `${state.totalAttempts} attempt(s).\n\n${scrubText(producerText)}`
837
957
  );
838
958
  }
839
959
  const tier = state.currentTier;
840
- const attempt = await runProducerAttempt(tier, forcing);
960
+ const attempt = await runProducerAttempt(tier, forcing, effort);
841
961
  if (!attempt) {
842
- return "[router] delegate failed: could not create a producer session.";
962
+ return withDepthBanner("[router] delegate failed: could not create a producer session.");
843
963
  }
844
964
  producerText = attempt.text;
845
965
  if ("deferredFooter" in attempt) {
846
966
  // Section 1.5-16: the result unchanged plus the footer, appended last. Never
847
967
  // labelled accepted or verified, and never retried or escalated.
848
- return appendRouterFooter(producerText, attempt.deferredFooter);
968
+ return appendRouterFooter(withDepthBanner(producerText), attempt.deferredFooter);
849
969
  }
850
970
  const producerSid = attempt.sessionID;
851
971
  const gateRes = attempt.gateRes;
@@ -869,7 +989,7 @@ const ModelRouterPlugin: Plugin = async (ctx: PluginInput) => {
869
989
  true,
870
990
  gateRes.verdict.method,
871
991
  );
872
- return producerText + buildAcceptedSuffix(gateRes.verdict.method, gateRes.verdict.outcome, gateRes.verdict.caveats, gateRes.verdict.notes);
992
+ return withDepthBanner(producerText) + buildAcceptedSuffix(gateRes.verdict.method, gateRes.verdict.outcome, gateRes.verdict.caveats, gateRes.verdict.notes);
873
993
  }
874
994
  if (action.action === "give_up") {
875
995
  dumpDelegateScorecard(
@@ -879,7 +999,7 @@ const ModelRouterPlugin: Plugin = async (ctx: PluginInput) => {
879
999
  gateRes.verdict.method,
880
1000
  );
881
1001
  const note = scrubText(buildForcingNote(gateRes.verdict.reasons));
882
- return (
1002
+ return withDepthBanner(
883
1003
  `[router status: unmet] The delegated result was not accepted after ` +
884
1004
  `${state.totalAttempts} attempt(s) across ${state.escalations} escalation(s) ` +
885
1005
  `(final tier ${state.currentTier}; ${action.reason ?? "verification failed"}).\n\n` +
@@ -888,10 +1008,11 @@ const ModelRouterPlugin: Plugin = async (ctx: PluginInput) => {
888
1008
  }
889
1009
  // retry or escalate
890
1010
  forcing = action.forcingMessage ?? null;
1011
+ effort = action.effort;
891
1012
  state = advance(state, action);
892
1013
  }
893
1014
  } catch {
894
- return "[router] delegate failed (fail-closed): the delegation or verification could not complete.";
1015
+ return withDepthBanner("[router] delegate failed (fail-closed): the delegation or verification could not complete.");
895
1016
  } finally {
896
1017
  // Safety net for every exit path an end-of-iteration dispose cannot
897
1018
  // reach: accept/give-up returns, the safety-net return, and throws.
@@ -899,6 +1020,7 @@ const ModelRouterPlugin: Plugin = async (ctx: PluginInput) => {
899
1020
  // disposed session is harmless.
900
1021
  for (const sid of producerSessions) {
901
1022
  if (!(deferredOwnsBaseline && sid === baselineID)) changedFileStore.clear(sid);
1023
+ effortOverrides.clear(sid);
902
1024
  await disposeChildSession(sid);
903
1025
  }
904
1026
  }
@@ -960,12 +1082,32 @@ const ModelRouterPlugin: Plugin = async (ctx: PluginInput) => {
960
1082
  try {
961
1083
  if (input?.sessionID && graderSessions.has(input.sessionID)) {
962
1084
  const graderTemperature = cfg.enforcement?.verify?.graderTemperature;
963
- if (graderTemperature !== undefined) {
1085
+ if (graderTemperature === null) {
1086
+ delete output.temperature;
1087
+ } else if (graderTemperature !== undefined && input?.model?.capabilities?.temperature !== false) {
964
1088
  output.temperature = graderTemperature;
965
1089
  }
966
1090
  }
967
- } catch {
968
- // best-effort: never crash a real session
1091
+ } catch (error) {
1092
+ if (!warnedGraderParams) {
1093
+ warnedGraderParams = true;
1094
+ try {
1095
+ logger.warn("[verify] grader temperature not applied", { error: describeError(error) });
1096
+ } catch {
1097
+ // Even a failed diagnostic sink must not interrupt chat.params.
1098
+ }
1099
+ }
1100
+ }
1101
+ try {
1102
+ if (input && typeof input === "object") {
1103
+ applyEffortOverride(effortOverrides, input, ctx.routerHost === "v2" ? output : output?.options, routerWarn);
1104
+ }
1105
+ } catch (error) {
1106
+ try {
1107
+ logger.warn("[router] effort override not applied", { error: describeError(error) });
1108
+ } catch {
1109
+ // Host accessors and diagnostic sinks are both best-effort here.
1110
+ }
969
1111
  }
970
1112
  },
971
1113
 
@@ -1075,6 +1217,22 @@ const ModelRouterPlugin: Plugin = async (ctx: PluginInput) => {
1075
1217
  // -----------------------------------------------------------------------
1076
1218
  "tool.execute.before": async (input: any, output: any) => {
1077
1219
  if (bypassed) return;
1220
+ if (input?.tool === "task") {
1221
+ const depth = await depthGuard.checkDispatch(input.sessionID);
1222
+ if (depth.block) {
1223
+ try {
1224
+ if (typeof input.sessionID === "string") {
1225
+ trajectoryStore.recordToolEvent(input.sessionID, {
1226
+ tool: input.tool, readOnly: READ_ONLY_TOOLS.has(input.tool), blocked: true,
1227
+ });
1228
+ }
1229
+ } catch (error) {
1230
+ logger.warn("[router] delegation depth: refusal not recorded", { error: describeError(error) });
1231
+ }
1232
+ throw new Error(depth.message);
1233
+ }
1234
+ if (depth.banner) stashDepthBanner(input, output, depth.banner);
1235
+ }
1078
1236
  // Observe before execution too: an in-flight edit must contaminate a
1079
1237
  // capture even if the test finishes before the edit's after-hook fires.
1080
1238
  if (typeof input?.tool === "string") changedFileStore.observeEdit(input.tool,
@@ -1082,14 +1240,17 @@ const ModelRouterPlugin: Plugin = async (ctx: PluginInput) => {
1082
1240
  if (input?.tool === "task" && typeof input.callID === "string" && typeof input.sessionID === "string") {
1083
1241
  const mode = resolveEnforcementMode({ config: cfg, env: process.env }).mode;
1084
1242
  if (shouldVerifyTask("task", mode, cfg.enforcement?.verify?.require)) {
1243
+ if (output && typeof output === "object") output[TASK_VERIFICATION] = true;
1085
1244
  const prompt = typeof output?.args?.prompt === "string" ? output.args.prompt : undefined;
1086
1245
  const description = typeof output?.args?.description === "string" ? output.args.description : undefined;
1246
+ const dod = buildDelegationDoD({ prompt, description });
1247
+ const effectiveCwd = typeof output?.args?.cwd === "string" && output.args.cwd.trim() ? output.args.cwd : dod.cwd;
1087
1248
  // 2.4.2b: the directives come from the orchestrator's own prompt, read here before the
1088
1249
  // dispatch header or any repair touches it, and are kept for the after hook. The capture
1089
1250
  // is awaited for at most VERIFY_WAIT (section 1.5-14) and continues in the background.
1090
1251
  await startDispatch(changedFileStore, `task:${input.sessionID}:${input.callID}`,
1091
- typeof output?.args?.cwd === "string" ? output.args.cwd : undefined,
1092
- buildDelegationDoD({ prompt, description }),
1252
+ effectiveCwd,
1253
+ dod,
1093
1254
  dispatchDirectiveText(prompt, description),
1094
1255
  true);
1095
1256
  }
@@ -1233,6 +1394,22 @@ const ModelRouterPlugin: Plugin = async (ctx: PluginInput) => {
1233
1394
  changedFileStore.record(sid, input.tool, input?.args);
1234
1395
  }
1235
1396
 
1397
+ let unbannered: { output: unknown } | undefined;
1398
+ if (input?.tool === "task") {
1399
+ const key = `${sid}:${input.callID}`;
1400
+ const banner = depthBanners.get(key);
1401
+ depthBanners.delete(key);
1402
+ if (banner !== undefined) {
1403
+ try {
1404
+ unbannered = { output: output.output };
1405
+ const text = typeof output.output === "string" ? output.output.trimEnd() : "";
1406
+ output.output = text ? `${text}\n\n${banner}` : banner;
1407
+ } catch (error) {
1408
+ logger.warn("[router] delegation depth: advisory banner not delivered", { error: describeError(error) });
1409
+ }
1410
+ }
1411
+ }
1412
+
1236
1413
  if (sid && sessionStore.isSubagent(sid) && typeof input?.tool === "string") {
1237
1414
  trajectoryStore.recordToolEvent(sid, {
1238
1415
  tool: input.tool,
@@ -1268,7 +1445,7 @@ const ModelRouterPlugin: Plugin = async (ctx: PluginInput) => {
1268
1445
  try {
1269
1446
  // pending.ts R11: the producer's changes landed by now.
1270
1447
  const returnedAt = Date.now();
1271
- const { finalReturnText, childSessionID } = parseTaskResult(output);
1448
+ const { finalReturnText, childSessionID } = parseTaskResult(unbannered ? { ...output, output: unbannered.output } : output);
1272
1449
  const producerTier =
1273
1450
  typeof input?.args?.subagent_type === "string"
1274
1451
  ? input.args.subagent_type
@@ -1277,6 +1454,7 @@ const ModelRouterPlugin: Plugin = async (ctx: PluginInput) => {
1277
1454
  prompt: input?.args?.prompt,
1278
1455
  description: input?.args?.description,
1279
1456
  });
1457
+ const effectiveCwd = typeof input?.args?.cwd === "string" && input.args.cwd.trim() ? input.args.cwd : dod.cwd;
1280
1458
  const dispatchID = `task:${input.sessionID}:${input.callID}`;
1281
1459
  const orchestratorSessionID = typeof input.sessionID === "string" ? input.sessionID : "";
1282
1460
  const taskPrompt = typeof input?.args?.prompt === "string" ? input.args.prompt : undefined;
@@ -1297,7 +1475,7 @@ const ModelRouterPlugin: Plugin = async (ctx: PluginInput) => {
1297
1475
  producerSessionID: childSessionID ?? "",
1298
1476
  producerTier,
1299
1477
  description: taskDescription?.trim() ? taskDescription : (taskPrompt ?? ""),
1300
- cwd: typeof input?.args?.cwd === "string" ? input.args.cwd : undefined,
1478
+ cwd: effectiveCwd,
1301
1479
  dod,
1302
1480
  dispatchedAt: start.dispatchedAt,
1303
1481
  });
@@ -1318,7 +1496,7 @@ const ModelRouterPlugin: Plugin = async (ctx: PluginInput) => {
1318
1496
  const gateDeadline = createDeadline(gateBudgetMs);
1319
1497
  let verification;
1320
1498
  try {
1321
- verification = await prepareVerification(changedFileStore, dispatchID, childSessionID ?? "", input?.args?.cwd, gateDeadline);
1499
+ verification = await prepareVerification(changedFileStore, dispatchID, childSessionID ?? "", effectiveCwd, gateDeadline);
1322
1500
  } catch (error) {
1323
1501
  gateDeadline.dispose();
1324
1502
  throw error;
@@ -1352,7 +1530,8 @@ const ModelRouterPlugin: Plugin = async (ctx: PluginInput) => {
1352
1530
 
1353
1531
  const gateGraderSessions = new Set<string>();
1354
1532
  const completedFailures: string[] = [];
1355
- const gateDeps = buildGateDeps(undefined, gateGraderSessions, verification, gateDeadline);
1533
+ // Keep the native grader unparented on the backend; only depth tracking uses its caller.
1534
+ const gateDeps = buildGateDeps(undefined, gateGraderSessions, verification, gateDeadline, false, orchestratorSessionID || null);
1356
1535
  gateDeps.deterministic.onFailure = reason => completedFailures.push(reason);
1357
1536
  let res;
1358
1537
  try {
@@ -1362,12 +1541,8 @@ const ModelRouterPlugin: Plugin = async (ctx: PluginInput) => {
1362
1541
  dod,
1363
1542
  trivial,
1364
1543
  mode: "modeA",
1365
- // The built-in task tool declares no cwd of its own, but if a
1366
- // caller supplies one it scopes verification the same way the
1367
- // delegate tool's does.
1368
- ...(typeof input?.args?.cwd === "string" && input.args.cwd
1369
- ? { cwd: input.args.cwd }
1370
- : {}),
1544
+ // Native task has no cwd argument; the acceptance block can supply it.
1545
+ ...(effectiveCwd ? { cwd: effectiveCwd } : {}),
1371
1546
  },
1372
1547
  artefact,
1373
1548
  gateDeps,
@@ -1474,6 +1649,12 @@ const ModelRouterPlugin: Plugin = async (ctx: PluginInput) => {
1474
1649
  sessionRootMemo.delete(id);
1475
1650
  sessionLookupFailedAt.delete(id);
1476
1651
  sessionStore.unregister(id);
1652
+ effortOverrides.clear(id);
1653
+ depthTracker.forget(id);
1654
+ for (const key of depthBanners.keys()) {
1655
+ if (key.startsWith(`${id}:`)) depthBanners.delete(key);
1656
+ }
1657
+ warnedNoCallID.delete(id);
1477
1658
  // 2.4.2b: a deleted orchestrator's handles, tombstones and lineage records go with it.
1478
1659
  // 2.4.5: so do its background requests and late notices; its run in flight is aborted.
1479
1660
  background?.forgetSession(id);
@@ -1495,6 +1676,14 @@ const ModelRouterPlugin: Plugin = async (ctx: PluginInput) => {
1495
1676
  // subagent that has no task tool, and the subagent refused the work.
1496
1677
  if (event?.type === "session.created") {
1497
1678
  const info = event?.properties?.info;
1679
+ try {
1680
+ if (typeof info?.id === "string") {
1681
+ depthTracker.recordCreated(info.id,
1682
+ typeof info.parentID === "string" && info.parentID !== "" ? info.parentID : null);
1683
+ }
1684
+ } catch (error) {
1685
+ logger.warn("[router] delegation depth: session creation not recorded", { error: describeError(error) });
1686
+ }
1498
1687
  if (
1499
1688
  typeof info?.id === "string" &&
1500
1689
  typeof info?.parentID === "string" &&