opencode-model-router 1.3.1 → 1.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/README.md CHANGED
@@ -2,7 +2,7 @@
2
2
 
3
3
  > **Use the cheapest model that can do the job. Automatically.**
4
4
 
5
- An [OpenCode](https://opencode.ai) plugin that routes every coding task to the right-priced AI tier — automatically, on every message, with ~210 tokens of overhead.
5
+ An [OpenCode](https://opencode.ai) plugin that routes every coding task to the right-priced AI tier — automatically, on every message, with 2,970–4,540 characters of system-prompt overhead depending on the orchestrator and enforcement mode.
6
6
 
7
7
  ## Why it's different
8
8
 
@@ -12,7 +12,7 @@ Most AI coding tools give you one model for everything. You pay Opus prices to r
12
12
  The orchestrator runs on *every* message. Put Sonnet there, not Opus. Sonnet reads a routing protocol and delegates just as well as Opus — at 4x lower cost. Reserve Opus for when it genuinely matters.
13
13
 
14
14
  **Inject a compressed, LLM-optimized routing protocol.**
15
- Instead of verbose instructions, the plugin injects ~210 tokens of dense, machine-readable notation the orchestrator understands perfectly. Same routing intelligence as 870 tokens of prose — 75% smaller. Every message, every session.
15
+ Instead of duplicated prose, the plugin injects a dense, machine-readable routing protocol. The protocol itself is 2,970 characters; a Claude orchestrator receives 3,742 characters after its authority prefix (roughly 935–1,040 tokens at 3.6–4.0 characters per token). Every message, every session.
16
16
 
17
17
  **Match task to tier using a configurable taxonomy.**
18
18
  A keyword routing guide (`@fast→search/grep/read`, `@medium→impl/refactor/test`, `@heavy→arch/debug/security`) tells the orchestrator exactly which tier fits each task type. Fully customizable. No ambiguity.
@@ -65,7 +65,7 @@ opencode-model-router injects a **delegation protocol** into the system prompt t
65
65
  4. **Never over-qualify** — use the cheapest tier that can reliably handle the task
66
66
  5. **Fallback** across providers when one fails
67
67
 
68
- All of this adds ~210 tokens of system prompt overhead per message.
68
+ All of this adds 2,970 characters for a non-Claude orchestrator or 3,742 characters for a Claude orchestrator (roughly 740–1,040 tokens at 3.6–4.0 characters per token).
69
69
 
70
70
  ## Cost simulation
71
71
 
@@ -114,7 +114,7 @@ Task distribution: 18 exploration (60%), 10 implementation (33%), 2 architecture
114
114
 
115
115
  ## How it works
116
116
 
117
- On every message, the plugin injects ~210 tokens into the system prompt. The notation is intentionally dense and compressed — it's **optimized for LLM comprehension, not human readability**. An agent reads it as a precise routing grammar; a human might squint at it. That's by design: verbose prose would cost 4x more tokens per message with no routing benefit.
117
+ On every message, the plugin injects a 2,970-character routing protocol. A Claude orchestrator receives 3,742 characters after its authority prefix (roughly 935–1,040 tokens at 3.6–4.0 characters per token). The notation is intentionally dense and compressed — it's **optimized for LLM comprehension, not human readability**. An agent reads it as a precise routing grammar; a human might squint at it.
118
118
 
119
119
  What the orchestrator sees (Anthropic preset, normal mode):
120
120
 
@@ -166,7 +166,7 @@ With router → split:
166
166
  | Cross-provider fallback | ✅ | ❌ | ❌ | ❌ | ❌ |
167
167
  | Cost ratio awareness | ✅ | ❌ | ❌ | ❌ | ❌ |
168
168
  | Plan annotation with tiers | ✅ | ❌ | ❌ | ❌ | ❌ |
169
- | ~210 token overhead | ✅ | — | ❌ | ❌ | ❌ |
169
+ | Measured prompt overhead: 2,970–4,540 chars | ✅ | — | ❌ | ❌ | ❌ |
170
170
 
171
171
  **Claude native**: single model for everything, no cost routing. If you're using claude.ai or OpenCode without plugins, you're paying the same price for `grep` as for architecture design.
172
172
 
@@ -526,11 +526,17 @@ Detection is by model string, not preset. A `hybrid` preset that mixes providers
526
526
 
527
527
  No configuration is needed — the prefixes are always applied for Claude-backed tiers. If you want to disable them, override the tier's `prompt` field (per-tier overrides replace the whole prompt, including the prefix).
528
528
 
529
- ### Anti-narration guardrail (Claude models)
529
+ ### Anti-narration guardrail (Claude models, opt-in)
530
530
 
531
- Thinking-enabled Claude models (especially Sonnet with the `max` variant) sometimes produce progress narration instead of actual work — phrasings like *"Still writing the X function..."*, *"Now I'll implement Y..."*, *"Let me add Z..."* — without the X/Y/Z ever appearing. This is a known thinking-mode failure pattern.
531
+ Some Claude models (historically, thinking-enabled Sonnet with the `max` variant) can produce progress narration instead of actual work, phrasings like *"Still writing the X function..."*, *"Now I'll implement Y..."*, *"Let me add Z..."*, without the X/Y/Z ever appearing.
532
532
 
533
- The router counters this on two layers:
533
+ This guardrail is **off by default**. On the Claude orchestrator path, enabling it adds 650 characters per message (roughly 160–180 tokens at 3.6–4.0 characters per token), and its detector false-positives on normal productive phrasing like "Now I'll add the test" when the test does follow, so it is opt-in. Enable it only if you actually observe narration-without-production on your models:
534
+
535
+ ```jsonc
536
+ { "antiNarration": true }
537
+ ```
538
+
539
+ When enabled, it works on two layers:
534
540
 
535
541
  **1. Prompt-level clause (prevention).** A dedicated `ANTI-NARRATION` block is appended to every Claude-backed tier prompt and to the Claude-backed orchestrator delegation protocol. It names the forbidden phrasings explicitly and requires concrete output to follow any such phrase. A carve-out preserves legitimate explanation/plan requests from the user.
536
542
 
@@ -556,7 +562,7 @@ Detected patterns (conservative set to minimize false positives):
556
562
  - `Going to (write|implement|...) the X`
557
563
  - `Continuing (with|by ...ing) (the )? X`
558
564
 
559
- Applies to all models, not only Claude — but the prompt-level clause is Claude-only, so non-Claude models get detector-only.
565
+ When `antiNarration` is enabled, the detector runs for all models (not only Claude), while the prompt-level clause is Claude-only, so non-Claude models get detector-only. With the default (`antiNarration` off), neither layer runs.
560
566
 
561
567
  ### Tier fields reference
562
568
 
@@ -589,7 +595,7 @@ Defines provider fallback order when a delegated task fails:
589
595
 
590
596
  ## Delegation enforcement (advisory by default)
591
597
 
592
- The read-only cap banners described above are advisory: a well-behaved subagent will respect them, but nothing prevents a model from making one more read after the `[⚠ CAP REACHED]` banner. The **enforcement layer** turns delegation into a produce → verify → accept/escalate loop with independent acceptance and quality escalation. As of v1.3.0 it runs in **`advisory` mode by default**: every non-trivial delegation is verified and any miss surfaces a forcing-note, but nothing is ever hard-blocked (the orchestrator system prompt grows by ~200 tokens for the DoD/acceptance section, and subagents may receive non-blocking guard banners). Set `"mode": "off"` — or run `/router enforce off` — to restore byte-for-byte-unchanged routing with zero added prompt tokens and zero new latency. Hard-blocks only activate in `"mode": "enforced"`.
598
+ The read-only cap banners described above are advisory: a well-behaved subagent will respect them, but nothing prevents a model from making one more read after the `[⚠ CAP REACHED]` banner. The **enforcement layer** turns delegation into a produce → verify → accept/escalate loop with independent acceptance and quality escalation. As of v1.3.0 it runs in **`advisory` mode by default**: every non-trivial delegation is verified and any miss surfaces a forcing-note, but nothing is ever hard-blocked (the DoD/acceptance section adds 798 characters to the orchestrator system prompt, roughly 200–220 tokens at 3.6–4.0 characters per token, and subagents may receive non-blocking guard banners). Set `"mode": "off"` — or run `/router enforce off` — to restore byte-for-byte-unchanged routing with zero added prompt tokens and zero new latency. Hard-blocks only activate in `"mode": "enforced"`.
593
599
 
594
600
  ### The three enforcement layers
595
601
 
@@ -659,18 +665,17 @@ After `/annotate-plan`:
659
665
 
660
666
  ## Token overhead
661
667
 
662
- The system prompt injection is ~210 tokens per message — roughly the same as v1.0 (before cost-aware features were added). Dense notation keeps overhead flat while adding full routing intelligence.
668
+ Measured with the bundled Anthropic preset in normal mode, the routing protocol is 2,970 characters for a non-Claude orchestrator. A Claude orchestrator receives 3,742 characters after its authority prefix, or 4,540 characters when the 798-character DoD/enforcement section is enabled. That is roughly 740–1,260 tokens across the three paths at 3.6–4.0 characters per token. The optional anti-narration clause adds another 650 characters to the Claude path.
663
669
 
664
- | Version | Tokens | Features |
665
- |---------|--------|----------|
666
- | v1.0.7 | ~208 | Basic tier routing |
667
- | v1.1.0 | ~870 | All features, verbose format |
668
- | v1.1.1+ | ~210 | All features, compressed format |
670
+ | Version | Measured overhead | Features |
671
+ |---------|-------------------|----------|
672
+ | Before v1.4.0 | Earlier README token estimates were not measured and were inaccurate | Routing, caps, and enforcement evolved across releases |
673
+ | v1.4.0 | 2,970–4,540 chars (~740–1,260 tokens at 3.6–4.0 chars/token) | Trimmed protocol; path-dependent Claude and enforcement prefixes |
669
674
 
670
675
  ## Requirements
671
676
 
672
677
  - [OpenCode](https://opencode.ai) v1.0 or later
673
- - Node.js 18+
678
+ - Node.js 20+
674
679
  - Provider API keys configured in OpenCode
675
680
 
676
681
  ## License
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "opencode-model-router",
3
- "version": "1.3.1",
3
+ "version": "1.4.0",
4
4
  "description": "OpenCode plugin that routes tasks to tiered subagents (fast/medium/heavy) based on complexity",
5
5
  "type": "module",
6
6
  "main": "./src/index.ts",
@@ -12,6 +12,9 @@
12
12
  "typecheck": "tsc --noEmit"
13
13
  },
14
14
  "license": "GPL-3.0-only",
15
+ "engines": {
16
+ "node": ">=20"
17
+ },
15
18
  "repository": {
16
19
  "type": "git",
17
20
  "url": "git+https://github.com/marco-jardim/opencode-model-router.git"
@@ -44,10 +47,10 @@
44
47
  "@opencode-ai/plugin": ">=1.0.0"
45
48
  },
46
49
  "devDependencies": {
47
- "@types/node": "^25.2.3",
50
+ "@types/node": "^26.2.0",
48
51
  "@vitest/coverage-v8": "^4.1.8",
49
- "cross-env": "^7.0.3",
50
- "typescript": "^5.9.3",
52
+ "cross-env": "^10.1.0",
53
+ "typescript": "^7.0.2",
51
54
  "vitest": "^4.1.8"
52
55
  }
53
56
  }
package/src/index.ts CHANGED
@@ -356,12 +356,34 @@ const ModelRouterPlugin: Plugin = async (ctx: PluginInput) => {
356
356
  },
357
357
  };
358
358
  const verifyMutex = createMutexRegistry();
359
- const dispatchGrader = async (req: {
360
- tier: string;
361
- system: string;
362
- prompt: string;
363
- }): Promise<{ sessionID: string; text: string }> => {
364
- const created: any = await ctx.client.session.create({});
359
+ // Best-effort disposal of a plugin-created child session: abort any in-flight
360
+ // work, then delete it so it does not linger forever as a top-level session in
361
+ // the TUI. Fail-soft by contract — never throws, so it is safe to call from a
362
+ // finally without masking the original error.
363
+ const disposeChildSession = async (sid: string): Promise<void> => {
364
+ try {
365
+ await ctx.client.session.abort({ path: { id: sid } });
366
+ } catch {
367
+ // best-effort: the session may already have completed or been removed
368
+ }
369
+ try {
370
+ await ctx.client.session.delete({ path: { id: sid } });
371
+ } catch {
372
+ // best-effort: cleanup must never break the run
373
+ }
374
+ };
375
+
376
+ const dispatchGrader = async (
377
+ req: {
378
+ tier: string;
379
+ system: string;
380
+ prompt: string;
381
+ },
382
+ parentSessionID?: string,
383
+ ): Promise<{ sessionID: string; text: string }> => {
384
+ const created: any = await ctx.client.session.create({
385
+ body: { ...(parentSessionID ? { parentID: parentSessionID } : {}) },
386
+ });
365
387
  const sid: string | undefined = created?.data?.id;
366
388
  if (!sid) return { sessionID: "", text: "" };
367
389
  graderSessions.add(sid);
@@ -383,9 +405,10 @@ const ModelRouterPlugin: Plugin = async (ctx: PluginInput) => {
383
405
  return { sessionID: sid, text };
384
406
  } finally {
385
407
  graderSessions.delete(sid);
408
+ await disposeChildSession(sid);
386
409
  }
387
410
  };
388
- const buildGateDeps = () => ({
411
+ const buildGateDeps = (parentSessionID?: string) => ({
389
412
  deterministic: {
390
413
  exec: execSeam,
391
414
  fs: fsSeam,
@@ -393,7 +416,8 @@ const ModelRouterPlugin: Plugin = async (ctx: PluginInput) => {
393
416
  mutex: verifyMutex,
394
417
  },
395
418
  checker: {
396
- dispatchGrader,
419
+ dispatchGrader: (req: { tier: string; system: string; prompt: string }) =>
420
+ dispatchGrader(req, parentSessionID),
397
421
  ladder: ["fast", "medium", "heavy"],
398
422
  minGraderTier: cfg.enforcement?.verify?.minGraderTier ?? null,
399
423
  },
@@ -446,11 +470,18 @@ const ModelRouterPlugin: Plugin = async (ctx: PluginInput) => {
446
470
  "Optional [acceptance]...[/acceptance] block defining the Definition of Done (check: / criteria: / deliverable: directives).",
447
471
  ),
448
472
  },
449
- async execute(args: {
450
- task: string;
451
- tier?: string;
452
- acceptance?: string;
453
- }): Promise<string> {
473
+ async execute(
474
+ args: {
475
+ task: string;
476
+ tier?: string;
477
+ acceptance?: string;
478
+ },
479
+ toolCtx?: { sessionID?: string },
480
+ ): Promise<string> {
481
+ // Every ladder iteration creates its own producer session. Tracked out
482
+ // here (not inside the try) so the finally below can dispose any that an
483
+ // early return or a throw skipped — otherwise each retry leaks another.
484
+ const producerSessions: string[] = [];
454
485
  try {
455
486
  let activeCfg = cfg;
456
487
  try {
@@ -494,11 +525,16 @@ const ModelRouterPlugin: Plugin = async (ctx: PluginInput) => {
494
525
  ? `${scrubText(forcing)}\n\n${args.task}`
495
526
  : args.task;
496
527
 
497
- const created: any = await ctx.client.session.create({});
528
+ const created: any = await ctx.client.session.create({
529
+ body: {
530
+ ...(toolCtx?.sessionID ? { parentID: toolCtx.sessionID } : {}),
531
+ },
532
+ });
498
533
  const producerSid: string | undefined = created?.data?.id;
499
534
  if (!producerSid) {
500
535
  return "[router] delegate failed: could not create a producer session.";
501
536
  }
537
+ producerSessions.push(producerSid);
502
538
  // Compose with Layer 1: guard the plugin-created producer session.
503
539
  try {
504
540
  sessionStore.registerProducerSession(producerSid, tier, activeCfg);
@@ -546,7 +582,7 @@ const ModelRouterPlugin: Plugin = async (ctx: PluginInput) => {
546
582
  gateRes = await accept(
547
583
  { dod, trivial: false, mode: "modeA" },
548
584
  artefact,
549
- buildGateDeps(),
585
+ buildGateDeps(toolCtx?.sessionID),
550
586
  );
551
587
  } catch {
552
588
  gateRes = {
@@ -572,6 +608,9 @@ const ModelRouterPlugin: Plugin = async (ctx: PluginInput) => {
572
608
  } catch {
573
609
  // non-fatal
574
610
  }
611
+ // Dispose this attempt's backend session before the next iteration
612
+ // so a long ladder never accumulates live sessions.
613
+ await disposeChildSession(producerSid);
575
614
 
576
615
  const costRatio =
577
616
  typeof tiersForCost?.[tier]?.costRatio === "number"
@@ -615,6 +654,14 @@ const ModelRouterPlugin: Plugin = async (ctx: PluginInput) => {
615
654
  }
616
655
  } catch {
617
656
  return "[router] delegate failed (fail-closed): the delegation or verification could not complete.";
657
+ } finally {
658
+ // Safety net for every exit path an end-of-iteration dispose cannot
659
+ // reach: accept/give-up returns, the safety-net return, and throws.
660
+ // disposeChildSession is fail-soft, so re-disposing an already
661
+ // disposed session is harmless.
662
+ for (const sid of producerSessions) {
663
+ await disposeChildSession(sid);
664
+ }
618
665
  }
619
666
  },
620
667
  }) } : {}),
@@ -776,6 +823,23 @@ const ModelRouterPlugin: Plugin = async (ctx: PluginInput) => {
776
823
  const trivial = childSessionID
777
824
  ? sessionStore.isTrivial(childSessionID)
778
825
  : false;
826
+
827
+ // Read-only / research delegation: an auto-inferred, criteria-only DoD on a
828
+ // native Task() that changed no files is exploration, not implementation.
829
+ // There is nothing concrete to verify, so skip rather than grade the
830
+ // findings against the task's own summary, which otherwise appends false
831
+ // "not accepted" notes to legitimate read-only research delegations.
832
+ // Explicit [acceptance] blocks (source != "inferred") and inferred
833
+ // deterministic checks (dod.kind === "deterministic") still verify normally.
834
+ if (
835
+ dod.source === "inferred" &&
836
+ dod.kind === "checker" &&
837
+ artefact.changedFiles.length === 0
838
+ ) {
839
+ if (childSessionID) changedFileStore.clear(childSessionID);
840
+ return;
841
+ }
842
+
779
843
  const res = await accept(
780
844
  { dod, trivial, mode: "modeA" },
781
845
  artefact,
@@ -809,7 +873,7 @@ const ModelRouterPlugin: Plugin = async (ctx: PluginInput) => {
809
873
  // post-hoc signal.
810
874
  // -----------------------------------------------------------------------
811
875
  "experimental.text.complete": async (input: any, output: any) => {
812
- if (bypassed) return;
876
+ if (bypassed || !cfg.antiNarration) return;
813
877
  const text = output?.text;
814
878
  if (typeof text !== "string" || text.length < 20) return;
815
879
 
@@ -875,7 +939,9 @@ const ModelRouterPlugin: Plugin = async (ctx: PluginInput) => {
875
939
  // Detection is by model string, so hybrid presets get the override
876
940
  // only on their Claude-backed tiers.
877
941
  const claudePrefix = isClaudeModel(tier.model)
878
- ? `${CLAUDE_TIER_PREFIX[name]}\n\n${CLAUDE_ANTI_NARRATION}`
942
+ ? cfg.antiNarration
943
+ ? `${CLAUDE_TIER_PREFIX[name]}\n\n${CLAUDE_ANTI_NARRATION}`
944
+ : CLAUDE_TIER_PREFIX[name]
879
945
  : undefined;
880
946
  const finalPrompt =
881
947
  claudePrefix && resolvedPrompt
@@ -66,6 +66,14 @@ export interface RouterConfig {
66
66
  /** Read-only tool-call caps per tier, enforced at runtime via tool.execute.after banner injection. */
67
67
  tierCaps?: Record<string, number>;
68
68
  enforcement?: EnforcementConfig;
69
+ /**
70
+ * Claude-model anti-narration guardrail. When true, appends the anti-narration
71
+ * clause to Claude orchestrator/tier prompts and runs the post-hoc narration
72
+ * detector. Off by default: the clause costs ~162 tokens per Claude dispatch
73
+ * and the detector is non-blocking telemetry that false-positives on normal
74
+ * "Now I'll add X" phrasing.
75
+ */
76
+ antiNarration?: boolean;
69
77
  /** Experimental, opt-in features. Off by default. */
70
78
  experimental?: { verifiedDelegateTool?: boolean };
71
79
  }
@@ -183,6 +191,9 @@ export function validateConfig(raw: unknown): RouterConfig {
183
191
  if (typeof obj.defaultTier !== "string") {
184
192
  throw new Error("tiers.json: 'defaultTier' must be a string");
185
193
  }
194
+ if (obj.antiNarration !== undefined && typeof obj.antiNarration !== "boolean") {
195
+ throw new Error("tiers.json: 'antiNarration' must be a boolean");
196
+ }
186
197
 
187
198
  // Validate modes if present
188
199
  if (obj.modes !== undefined) {
@@ -111,44 +111,24 @@ export function buildDelegationProtocol(cfg: RouterConfig): string {
111
111
  const fallback = buildFallbackInstructions(cfg);
112
112
 
113
113
  return [
114
- `## Model Delegation Protocol — MANDATORY`,
114
+ `## Model Delegation Protocol (MANDATORY)`,
115
115
  ``,
116
- `You are the orchestrator. Information-gathering is NOT orchestration — it IS execution. Execution belongs to subagents, not to you.`,
116
+ `You are the orchestrator: route each task to the right tier and delegate it with \`Task(subagent_type="fast"|"medium"|"heavy", prompt="...")\`. Information-gathering (grep, read, glob, ls) is execution, so dispatch it to @fast rather than running it yourself; cap yourself at about 2 direct read-only calls per turn and dispatch @fast on the 3rd. Synthesize the subagents' results and answer the user yourself.`,
117
117
  ``,
118
118
  `Preset: ${cfg.activePreset}. Tiers: ${tierLine}.${modeSuffix}`,
119
119
  ``,
120
- `### HARD ROUTING (non-negotiable)`,
121
- `- **Read-only work** (grep, glob, read, ls, lookup, count, git-info, doc-lookup, type-check, exists-check) → default to \`Task(subagent_type="fast", ...)\`. Self-cap (TARGET): ≤2 direct read-only calls per user turn; on the 3rd read-only need, dispatch @fast instead. You may exceed with a 1-line \`reason:\` note when dispatching feels clearly wrong. Rationale: every tool-result token is billed at your tier rate — a grep via @fast costs ~20x less than the same grep here.`,
122
- `- **Implementation work** (write, edit, refactor, tests, bug-fix, build-fix, create-file, config, api-endpoint) → \`Task(subagent_type="medium", ...)\`.`,
123
- `- **Architecture / security / perf / debugging after ≥2 failures / multi-system tradeoffs / RCA** → \`Task(subagent_type="heavy", ...)\`, UNLESS you ARE @heavy (opus); then handle locally and never self-call @heavy.`,
124
- ``,
125
- `### DISPATCH CAPS (read-only budget per subagent)`,
126
- `Subagents carry a TARGET cap on their own read-only tool calls (baseline: @fast=8, @medium=5, @heavy=3). Include \`CAP:N\` in the dispatch prompt to override (e.g., \`CAP:3\` for a tight lookup, \`CAP:none\` to disable). Mode adjustments apply automatically via rules below. Subagents also run a redundancy check every call: if they detect repeated reads/greps of the same area, they STOP and return partial findings with \`DONE: ...\`, \`NEED MORE: ...\`, or \`ESCALATE: ...\` — you decide the next step from their return.`,
127
- ``,
128
- `### ROLE CONTRACT`,
129
- `The primary agent's job: decompose the user's request, dispatch subagents, synthesize their results, and answer the user. Keep orchestration-first posture: prefer dispatching read-only exploration to @fast rather than running repeated Grep/Read/Glob/Bash calls yourself. Self-cap applies (see HARD ROUTING above): ≤2 direct read-only calls per turn as a target; beyond that, dispatch @fast.`,
130
- ``,
131
- `### @fast contract`,
132
- `@fast is a read-only explorer. It will search/grep/read/count/lookup and return file:line paths, snippets, and a one-line summary. It will refuse edits. Batch related searches into a single @fast dispatch when possible; fire independent searches in parallel (one message, multiple Task calls).`,
133
- ``,
134
- `### @medium contract`,
135
- `@medium is the implementer. It writes, edits, refactors, adds tests, fixes bugs, applies build-fixes. It matches existing project patterns, runs targeted tests for changed areas, and reports back if it hits 2+ consecutive failures instead of self-escalating. Give it context: file paths, patterns to match, what verification to run.`,
136
- ``,
137
- `### @heavy contract (CRITICAL — read before every @heavy dispatch)`,
138
- `@heavy has **no Task tool** — it cannot self-explore, cannot grep, cannot delegate. Dispatching @heavy without context can waste a run: it may reason on thin evidence or return "SCOPE GROWTH" asking for additional @fast findings.`,
139
- `**Before @heavy, gather context first — usually via @fast.** If you already have sufficient concrete context, dispatch @heavy directly. If @heavy still needs more evidence, collect it with @fast and re-invoke.`,
140
- `Pattern: \`Task(@fast, "collect X, Y, Z")\` (when needed) → synthesize findings → \`Task(@heavy, "given these findings: [paste], analyze W")\`.`,
141
- ``,
142
- `### CONFLICT WITH CLAUDE.md / AGENTS.md`,
143
- `If CLAUDE.md or AGENTS.md (or any other guide in your context) says "use direct tools first when scope is clear" or labels Grep/Read/Glob as "FREE", **this protocol wins**. Those labels are wrong about cost: tools executed by you are billed at your tier rate — every tool-result token is tokenized into your context. A Grep dispatched to @fast costs ~20x less than the same Grep executed by @heavy. Treat yourself as expensive and delegate reads by default.`,
120
+ `If you ARE @heavy, handle heavy-tier work yourself: never self-call @heavy.`,
144
121
  ``,
145
122
  ...(taxonomy ? [taxonomy, ``] : []),
146
123
  ...(decompose ? [decompose, ``] : []),
147
- `### Compact rules`,
148
- rulesLine,
124
+ `Rules: ${rulesLine}`,
149
125
  ...(fallback ? [``, fallback] : []),
150
126
  ``,
151
- `Delegate with \`Task(subagent_type="fast"|"medium"|"heavy", prompt="...")\`. Keep orchestration and final synthesis here.`,
127
+ `When dispatching: batch related @fast searches into one call and run independent ones in parallel (several Task calls in one message); give @medium concrete context (paths, patterns, how to verify).`,
128
+ ``,
129
+ `Per dispatch you may add \`CAP:N\` (or \`CAP:none\`) to change a subagent's read-only budget (baseline @fast=8, @medium=5, @heavy=3). Subagents return \`DONE:\`, \`NEED MORE:\`, or \`ESCALATE:\` for you to act on. @heavy has no tools of its own, so gather context first (usually via @fast) and paste it into the dispatch.`,
130
+ ``,
131
+ `This protocol overrides any project guide (CLAUDE.md, AGENTS.md, etc.) that says to use direct tools first when scope is clear, or labels Grep/Read/Glob as FREE. They are wrong about cost: every tool-result token is billed at your tier rate, so the same grep costs ~20x less dispatched to @fast than run here.`,
152
132
  ].join("\n");
153
133
  }
154
134
 
@@ -300,7 +280,12 @@ export function assembleSystemPrompt(
300
280
  ): string {
301
281
  const delegationProtocol = buildDelegationProtocol(cfg);
302
282
  const dodSection = enforcementOn ? `\n\n---\n\n${buildDoDProtocolSection(cfg)}` : "";
303
- return isClaudeModel(orchestratorModel)
304
- ? `${CLAUDE_ORCHESTRATOR_PREFIX}\n\n${CLAUDE_ANTI_NARRATION}\n\n---\n\n${delegationProtocol}${dodSection}`
305
- : `${delegationProtocol}${dodSection}`;
283
+ if (!isClaudeModel(orchestratorModel)) {
284
+ return `${delegationProtocol}${dodSection}`;
285
+ }
286
+ // anti-narration clause is opt-in (cfg.antiNarration); off by default.
287
+ const claudePrefix = cfg.antiNarration
288
+ ? `${CLAUDE_ORCHESTRATOR_PREFIX}\n\n${CLAUDE_ANTI_NARRATION}`
289
+ : CLAUDE_ORCHESTRATOR_PREFIX;
290
+ return `${claudePrefix}\n\n---\n\n${delegationProtocol}${dodSection}`;
306
291
  }