opencode-model-router 1.1.11 → 1.1.12

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
@@ -358,6 +358,135 @@ The `rules` array is injected verbatim (in compact form) into the system prompt.
358
358
 
359
359
  Rules in `modes[x].overrideRules` replace this array entirely for that mode.
360
360
 
361
+ ### Read-only call caps
362
+
363
+ Subagents carry a cap on their own read-only tool calls (grep/read/glob/ls) per dispatch. Enforcement is **two-layered**: prompt-level stop rules + runtime banners injected into tool results. Baselines (configurable via `tierCaps` — see below):
364
+
365
+ | Tier | Baseline cap | Orchestrator self-cap |
366
+ |------|-------------:|----------------------:|
367
+ | `@fast` | 8 | — |
368
+ | `@medium` | 5 | — |
369
+ | `@heavy` | 3 | — |
370
+ | Orchestrator (direct tools) | — | 2 per turn (prompt-level only) |
371
+
372
+ The orchestrator can override any subagent's cap per dispatch by including a directive in the `Task` prompt:
373
+
374
+ - `CAP:N` — tighten or loosen to N calls (e.g., `CAP:3` for a focused lookup).
375
+ - `CAP:none` — disable the numeric cap entirely (used in `quality` mode and for `@heavy` in `deep` mode).
376
+
377
+ Omitting the directive falls back to the tier baseline. Subagents may **exceed** their cap with a 1-line `reason:` in the return (target, not hard block).
378
+
379
+ #### Runtime enforcement (subagents only)
380
+
381
+ Prompt-level rules alone are unreliable: many models (including strong ones like Opus 4.7) ignore "please stop at N reads" and loop on reconnaissance for tens of minutes. To address this, the plugin tracks read-only tool calls per subagent session and **appends a banner to every read-only tool result** via the `tool.execute.after` hook. The subagent sees this banner inside the tool's own response text — not as advisory system prompt noise — which makes it very hard to ignore.
382
+
383
+ What the subagent sees inside each `grep`/`read`/`glob`/`ls` result:
384
+
385
+ ```
386
+ ...normal tool output...
387
+
388
+ [cap: 3/5]
389
+ ```
390
+
391
+ Approaching or hitting the cap:
392
+
393
+ ```
394
+ [cap: 4/5]
395
+ [⚠ CAP WARNING: 1 read-only call(s) remaining before forced return]
396
+ ```
397
+
398
+ ```
399
+ [cap: 5/5]
400
+ [⚠ CAP REACHED (5/5): your NEXT response MUST be a return — do NOT make another read-only call. Start the response with DONE:, NEED MORE:, NEED CONTEXT:, SCOPE GROWTH:, or ESCALATE:.]
401
+ ```
402
+
403
+ Redundancy (same file re-read, same `grep` pattern re-run):
404
+
405
+ ```
406
+ [cap: 3/5]
407
+ [⚠ REDUNDANT: this is the same grep you ran at call #1. STOP now — repeated reads add no information. Return with DONE/NEED MORE/NEED CONTEXT/SCOPE GROWTH/ESCALATE.]
408
+ ```
409
+
410
+ The orchestrator session is **not tracked** — its self-cap of 2 direct reads per turn is prompt-only. Tool counting applies only to sessions whose `agent` matches a registered tier name.
411
+
412
+ #### Configuring caps (`tierCaps`)
413
+
414
+ ```json
415
+ {
416
+ "tierCaps": {
417
+ "fast": 8,
418
+ "medium": 5,
419
+ "heavy": 3
420
+ }
421
+ }
422
+ ```
423
+
424
+ Values are positive integers. Missing tier → falls back to the hardcoded default (same numbers). Change these to tighten/loosen the baseline without editing any prompt.
425
+
426
+ #### Return protocol
427
+
428
+ Independent of the numeric cap, every subagent runs a redundancy check before each new tool call. On stop (cap reached, redundancy detected, scope satisfied, or runtime banner), the subagent returns with exactly one of:
429
+
430
+ | Return prefix | Meaning |
431
+ |--------------|---------|
432
+ | `DONE: …` | Dispatch request fully satisfied — synthesize into final answer. |
433
+ | `NEED MORE: …` (or `NEED CONTEXT:` for `@medium`, `SCOPE GROWTH:` for `@heavy`) | Subagent needs another targeted round — orchestrator decides what to dispatch. |
434
+ | `ESCALATE: …` | Scope grew beyond the subagent's role — orchestrator re-routes. |
435
+
436
+ This keeps subagents from burning tokens on repeated lookups when they already have enough context. `CAP:none` lifts the numeric cap but **does not** disable the redundancy check — the runtime still injects `[⚠ REDUNDANT]` banners regardless of cap setting.
437
+
438
+ **Mode interactions:**
439
+
440
+ | Mode | Dispatch directive | Orchestrator self-cap |
441
+ |------|-------------------|-----------------------|
442
+ | `normal` | baselines (omit directive) | ≤2 direct reads |
443
+ | `budget` | `CAP:5` @fast, `CAP:2` @medium, `CAP:2` @heavy | ≤1 direct read |
444
+ | `quality` | `CAP:none` on all dispatches | ≤2 direct reads |
445
+ | `deep` | `CAP:none` on `@heavy` only; baselines elsewhere | ≤2 direct reads |
446
+
447
+ ### Tier prompts (`tierPrompts`)
448
+
449
+ Each tier (`@fast`, `@medium`, `@heavy`) has a system prompt that describes its role, scope, call cap, and return protocol. To avoid duplicating the same string across every preset, the router uses a **global default with per-tier override**:
450
+
451
+ ```json
452
+ {
453
+ "tierPrompts": {
454
+ "fast": "You are @fast — ... (full global prompt)",
455
+ "medium": "You are @medium — ...",
456
+ "heavy": "You are @heavy — ..."
457
+ },
458
+ "presets": {
459
+ "anthropic": {
460
+ "fast": { "model": "anthropic/claude-haiku-4-5", ... },
461
+ "medium": { "model": "anthropic/claude-sonnet-4-6", ... },
462
+ "heavy": { "model": "anthropic/claude-opus-4-7", ... }
463
+ }
464
+ }
465
+ }
466
+ ```
467
+
468
+ **Resolution order per tier:**
469
+
470
+ 1. If the preset's tier defines `"prompt": "..."` inline → use it (per-tier override).
471
+ 2. Otherwise → fall back to `tierPrompts[<tierName>]`.
472
+ 3. If neither is set → the tier registers without a system prompt.
473
+
474
+ **When to customize:** if a specific provider/model in a preset needs different instructions (e.g. Gemini-specific tool format, tighter/looser caps for a weaker local model), add `"prompt": "..."` on that tier only. All other presets keep using the global.
475
+
476
+ ```json
477
+ {
478
+ "presets": {
479
+ "google": {
480
+ "fast": {
481
+ "model": "google/gemini-2.5-flash",
482
+ "prompt": "You are @fast (Gemini-tuned variant) — ...",
483
+ ...
484
+ }
485
+ }
486
+ }
487
+ }
488
+ ```
489
+
361
490
  ### Tier fields reference
362
491
 
363
492
  | Field | Type | Description |
@@ -369,7 +498,7 @@ Rules in `modes[x].overrideRules` replace this array entirely for that mode.
369
498
  | `reasoning` | object | OpenAI reasoning: `{ "effort": "high", "summary": "detailed" }` |
370
499
  | `description` | string | Shown in `/tiers` output |
371
500
  | `steps` | number | Max agent turns |
372
- | `prompt` | string | Subagent system prompt |
501
+ | `prompt` | string | Optional per-tier system prompt override. Falls back to top-level `tierPrompts[<tierName>]` when omitted. |
373
502
  | `whenToUse` | string[] | Use cases (shown in `/tiers`, not in system prompt) |
374
503
 
375
504
  ### Fallback
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "opencode-model-router",
3
- "version": "1.1.11",
3
+ "version": "1.1.12",
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",
package/src/index.ts CHANGED
@@ -52,6 +52,10 @@ interface RouterConfig {
52
52
  fallback?: FallbackConfig;
53
53
  taskPatterns?: Record<string, string[]>;
54
54
  modes?: Record<string, ModeConfig>;
55
+ /** Global default prompts per tier name. A preset-level tier.prompt overrides this. */
56
+ tierPrompts?: Record<string, string>;
57
+ /** Read-only tool-call caps per tier, enforced at runtime via tool.execute.after banner injection. */
58
+ tierCaps?: Record<string, number>;
55
59
  }
56
60
 
57
61
  interface RouterState {
@@ -195,6 +199,44 @@ function validateConfig(raw: unknown): RouterConfig {
195
199
  }
196
200
  }
197
201
 
202
+ // Validate tierCaps if present
203
+ if (obj.tierCaps !== undefined) {
204
+ if (
205
+ typeof obj.tierCaps !== "object" ||
206
+ obj.tierCaps === null ||
207
+ Array.isArray(obj.tierCaps)
208
+ ) {
209
+ throw new Error("tiers.json: 'tierCaps' must be an object");
210
+ }
211
+ const tc = obj.tierCaps as Record<string, unknown>;
212
+ for (const [tierName, cap] of Object.entries(tc)) {
213
+ if (typeof cap !== "number" || !Number.isFinite(cap) || cap < 1) {
214
+ throw new Error(
215
+ `tiers.json: tierCaps.'${tierName}' must be a positive integer`,
216
+ );
217
+ }
218
+ }
219
+ }
220
+
221
+ // Validate tierPrompts if present
222
+ if (obj.tierPrompts !== undefined) {
223
+ if (
224
+ typeof obj.tierPrompts !== "object" ||
225
+ obj.tierPrompts === null ||
226
+ Array.isArray(obj.tierPrompts)
227
+ ) {
228
+ throw new Error("tiers.json: 'tierPrompts' must be an object");
229
+ }
230
+ const tp = obj.tierPrompts as Record<string, unknown>;
231
+ for (const [tierName, prompt] of Object.entries(tp)) {
232
+ if (typeof prompt !== "string") {
233
+ throw new Error(
234
+ `tiers.json: tierPrompts.'${tierName}' must be a string`,
235
+ );
236
+ }
237
+ }
238
+ }
239
+
198
240
  // Validate taskPatterns if present
199
241
  if (obj.taskPatterns !== undefined) {
200
242
  if (
@@ -445,12 +487,15 @@ function buildDelegationProtocol(cfg: RouterConfig): string {
445
487
  `Preset: ${cfg.activePreset}. Tiers: ${tierLine}.${modeSuffix}`,
446
488
  ``,
447
489
  `### HARD ROUTING (non-negotiable)`,
448
- `- **Read-only work** (grep, glob, read, ls, lookup, count, git-info, doc-lookup, type-check, exists-check) → prefer \`Task(subagent_type="fast", ...)\` by default. Direct read-only tools are fine for a one-off lookup (and a short follow-up when clearly faster); if scope starts expanding, switch to @fast.`,
490
+ `- **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.`,
449
491
  `- **Implementation work** (write, edit, refactor, tests, bug-fix, build-fix, create-file, config, api-endpoint) → \`Task(subagent_type="medium", ...)\`.`,
450
492
  `- **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.`,
451
493
  ``,
494
+ `### DISPATCH CAPS (read-only budget per subagent)`,
495
+ `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.`,
496
+ ``,
452
497
  `### ROLE CONTRACT`,
453
- `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. A quick one-off lookup is fine; recurring exploration should move to @fast.`,
498
+ `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.`,
454
499
  ``,
455
500
  `### @fast contract`,
456
501
  `@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).`,
@@ -599,6 +644,112 @@ function buildPresetOutput(cfg: RouterConfig, args: string): string {
599
644
  return `Unknown preset: "${requestedPreset}". Available: ${Object.keys(cfg.presets).join(", ")}`;
600
645
  }
601
646
 
647
+ // ---------------------------------------------------------------------------
648
+ // Runtime cap enforcement (tool.execute.after banner injection for subagents)
649
+ // ---------------------------------------------------------------------------
650
+
651
+ /** Tools that count against the read-only cap. Keep narrow — editing tools should never count. */
652
+ const READ_ONLY_TOOLS = new Set(["grep", "read", "glob", "ls"]);
653
+
654
+ /** Fallback caps when tiers.json has no tierCaps block. */
655
+ const DEFAULT_TIER_CAPS: Record<string, number> = {
656
+ fast: 8,
657
+ medium: 5,
658
+ heavy: 3,
659
+ };
660
+
661
+ type Cap = number | "none";
662
+
663
+ interface SubagentState {
664
+ tierName: string;
665
+ cap: Cap;
666
+ calls: number;
667
+ /** Fingerprint → call index where this fingerprint was first seen. */
668
+ seen: Map<string, number>;
669
+ }
670
+
671
+ /** Extract the first `CAP:N` or `CAP:none` directive from a dispatch prompt. */
672
+ function parseCapDirective(text: string): Cap | null {
673
+ const m = text.match(/\bCAP\s*:\s*(none|\d+)\b/i);
674
+ if (!m) return null;
675
+ const raw = m[1]!.toLowerCase();
676
+ if (raw === "none") return "none";
677
+ const n = parseInt(raw, 10);
678
+ return Number.isFinite(n) && n > 0 ? n : null;
679
+ }
680
+
681
+ /** Fingerprint a read-only tool call for redundancy detection. */
682
+ function fingerprintToolCall(tool: string, args: unknown): string {
683
+ const a = (args ?? {}) as Record<string, unknown>;
684
+ switch (tool) {
685
+ case "read":
686
+ return `read:${a.file_path ?? a.filePath ?? ""}`;
687
+ case "grep":
688
+ return `grep:${a.pattern ?? ""}:${a.path ?? a.glob ?? ""}`;
689
+ case "glob":
690
+ return `glob:${a.pattern ?? ""}:${a.path ?? ""}`;
691
+ case "ls":
692
+ return `ls:${a.path ?? ""}`;
693
+ default:
694
+ return `${tool}:${JSON.stringify(a).slice(0, 120)}`;
695
+ }
696
+ }
697
+
698
+ /** Best-effort extraction of textual content from a chat.message output payload. */
699
+ function extractDispatchText(output: unknown): string {
700
+ const o = output as Record<string, unknown> | undefined;
701
+ const parts = (o?.parts as unknown[]) ?? [];
702
+ const chunks: string[] = [];
703
+ for (const p of parts) {
704
+ if (typeof p === "string") {
705
+ chunks.push(p);
706
+ } else if (p && typeof p === "object") {
707
+ const rec = p as Record<string, unknown>;
708
+ if (typeof rec.text === "string") chunks.push(rec.text);
709
+ else if (typeof rec.content === "string") chunks.push(rec.content);
710
+ }
711
+ }
712
+ if (chunks.length === 0) {
713
+ const msg = o?.message as Record<string, unknown> | undefined;
714
+ const content = msg?.content;
715
+ if (typeof content === "string") chunks.push(content);
716
+ }
717
+ return chunks.join("\n");
718
+ }
719
+
720
+ /** Build the banner appended to every read-only tool result in a subagent session. */
721
+ function buildCapBanner(
722
+ state: SubagentState,
723
+ isRedundant: boolean,
724
+ previousCall: number | undefined,
725
+ tool: string,
726
+ ): string {
727
+ const lines: string[] = [];
728
+ const capDisplay = state.cap === "none" ? "∞" : String(state.cap);
729
+ lines.push(`[cap: ${state.calls}/${capDisplay}]`);
730
+
731
+ if (isRedundant && previousCall !== undefined) {
732
+ lines.push(
733
+ `[⚠ REDUNDANT: this is the same ${tool} you ran at call #${previousCall}. STOP now — repeated reads add no information. Return with DONE/NEED MORE/NEED CONTEXT/SCOPE GROWTH/ESCALATE.]`,
734
+ );
735
+ }
736
+
737
+ if (state.cap !== "none") {
738
+ const remaining = state.cap - state.calls;
739
+ if (remaining <= 0) {
740
+ lines.push(
741
+ `[⚠ CAP REACHED (${state.calls}/${state.cap}): your NEXT response MUST be a return — do NOT make another read-only call. Start the response with DONE:, NEED MORE:, NEED CONTEXT:, SCOPE GROWTH:, or ESCALATE:.]`,
742
+ );
743
+ } else if (remaining <= 2) {
744
+ lines.push(
745
+ `[⚠ CAP WARNING: ${remaining} read-only call(s) remaining before forced return]`,
746
+ );
747
+ }
748
+ }
749
+
750
+ return lines.join("\n");
751
+ }
752
+
602
753
  // ---------------------------------------------------------------------------
603
754
  // Plugin
604
755
  // ---------------------------------------------------------------------------
@@ -611,6 +762,11 @@ const ModelRouterPlugin: Plugin = async (_ctx: PluginInput) => {
611
762
  // Populated by chat.params (which has the agent name) before system.transform fires.
612
763
  const subagentSessionIDs = new Set<string>();
613
764
 
765
+ // Per-subagent-session cap state for runtime enforcement. Populated on chat.message,
766
+ // read/updated by tool.execute.after. Keyed by sessionID. Orchestrator sessions are
767
+ // intentionally NOT tracked here (per user decision: enforce on subagents only).
768
+ const subagentCapState = new Map<string, SubagentState>();
769
+
614
770
  return {
615
771
  // -----------------------------------------------------------------------
616
772
  // Detect subagent calls via chat.message. When the agent name matches a
@@ -630,7 +786,7 @@ const ModelRouterPlugin: Plugin = async (_ctx: PluginInput) => {
630
786
  // loop -> LLM.stream path, so by the time system.transform runs the Set
631
787
  // is fully populated and await-safe (yield* on the plugin trigger).
632
788
  // -----------------------------------------------------------------------
633
- "chat.message": async (input: any, _output: any) => {
789
+ "chat.message": async (input: any, output: any) => {
634
790
  // Re-read cfg so /preset switches take effect without restart
635
791
  try {
636
792
  cfg = loadConfig();
@@ -638,9 +794,52 @@ const ModelRouterPlugin: Plugin = async (_ctx: PluginInput) => {
638
794
  const tierNames = Object.keys(getActiveTiers(cfg));
639
795
  if (input.agent && tierNames.includes(input.agent)) {
640
796
  subagentSessionIDs.add(input.sessionID);
797
+
798
+ // Initialize cap state on first dispatch; reset on subsequent rounds to the same
799
+ // subagent session (rare but supported — treats each round as a fresh budget).
800
+ const tierName = input.agent as string;
801
+ const dispatchText = extractDispatchText(output);
802
+ const override = parseCapDirective(dispatchText);
803
+ const baseline =
804
+ cfg.tierCaps?.[tierName] ?? DEFAULT_TIER_CAPS[tierName] ?? 5;
805
+ const cap: Cap = override ?? baseline;
806
+ subagentCapState.set(input.sessionID, {
807
+ tierName,
808
+ cap,
809
+ calls: 0,
810
+ seen: new Map(),
811
+ });
641
812
  }
642
813
  },
643
814
 
815
+ // -----------------------------------------------------------------------
816
+ // Runtime cap + redundancy enforcement (subagents only).
817
+ // Appends `[cap: N/MAX]` and `[⚠ REDUNDANT]` / `[⚠ CAP REACHED]` banners
818
+ // to every read-only tool result the subagent sees. Because these land
819
+ // inside `output.output` — the tool's own response text — the model
820
+ // treats them as ground truth rather than advisory system noise.
821
+ // -----------------------------------------------------------------------
822
+ "tool.execute.after": async (input: any, output: any) => {
823
+ const state = subagentCapState.get(input.sessionID);
824
+ if (!state) return; // not a tracked subagent session
825
+ if (!READ_ONLY_TOOLS.has(input.tool)) return;
826
+
827
+ const fp = fingerprintToolCall(input.tool, input.args);
828
+ const previousCall = state.seen.get(fp);
829
+ const isRedundant = previousCall !== undefined;
830
+
831
+ state.calls += 1;
832
+ if (!isRedundant) {
833
+ state.seen.set(fp, state.calls);
834
+ }
835
+
836
+ const banner = buildCapBanner(state, isRedundant, previousCall, input.tool);
837
+
838
+ const existing =
839
+ typeof output.output === "string" ? output.output : "";
840
+ output.output = existing ? `${existing}\n\n${banner}` : banner;
841
+ },
842
+
644
843
  // -----------------------------------------------------------------------
645
844
  // Register tier agents + commands at load time
646
845
  // -----------------------------------------------------------------------
@@ -648,12 +847,15 @@ const ModelRouterPlugin: Plugin = async (_ctx: PluginInput) => {
648
847
  opencodeConfig.agent ??= {};
649
848
 
650
849
  for (const [name, tier] of Object.entries(activeTiers)) {
850
+ // Resolve prompt: per-tier override wins; otherwise fall back to global tierPrompts[name].
851
+ const resolvedPrompt = tier.prompt ?? cfg.tierPrompts?.[name];
852
+
651
853
  const agentDef: Record<string, unknown> = {
652
854
  model: tier.model,
653
855
  mode: "subagent",
654
856
  description: tier.description,
655
857
  maxSteps: tier.steps,
656
- prompt: tier.prompt,
858
+ prompt: resolvedPrompt,
657
859
  color: tier.color,
658
860
  };
659
861
 
package/tiers.json CHANGED
@@ -1,6 +1,16 @@
1
1
  {
2
2
  "activePreset": "anthropic",
3
3
  "activeMode": "normal",
4
+ "tierCaps": {
5
+ "fast": 8,
6
+ "medium": 5,
7
+ "heavy": 3
8
+ },
9
+ "tierPrompts": {
10
+ "fast": "STOP CONDITIONS — read these FIRST, they govern EVERY tool call:\n\n1. CAP: ≤8 read-only tool calls (grep/read/glob/ls) per dispatch. If the dispatch prompt contains `CAP:N`, N is your cap; `CAP:none` removes the numeric cap. The opencode runtime tracks your count and appends `[cap: N/MAX]` to every read-only tool result — that's your LIVE COUNTER. When N=MAX, your next action MUST be a return, not another read.\n\n2. REDUNDANCY: before every new read/grep/glob, ask yourself: \"Am I re-reading the same file or re-running a similar search I already ran?\" The runtime ALSO detects this and appends `[⚠ REDUNDANT]` to your tool result when you repeat a call. When you see that marker, STOP IMMEDIATELY — do not attempt another read.\n\n3. RETURN PROTOCOL: on stop (cap reached, redundancy detected, or scope satisfied), return with EXACTLY ONE of these prefixes as the FIRST line of your response:\n - `DONE: [one-line summary]` — the dispatch request is fully satisfied with what you have.\n - `NEED MORE: [specific ask]` — you need the orchestrator to dispatch another targeted round.\n - `ESCALATE: [reason]` — hand back for orchestrator to re-dispatch or decide.\n\n4. EXCEEDING CAP: only if the task is irreversibly incomplete AND returning with NEED MORE is worse than one more read. Prepend `reason: <1-line>` above your return. This should be rare.\n\n---\n\nROLE: You are @fast — a read-only exploration specialist. Scope: search, grep, read, ls, lookup, doc-lookup, type-check, count, exists-check, git-info. NEVER write, edit, or modify files. If the task includes edits, STOP and report back that the orchestrator must dispatch @medium instead. Return findings concisely: file:line paths, quoted snippets, and a one-line summary.\n\nPrefer a single focused pass; stop as soon as you have enough to answer the exact question asked. Do not explore beyond the asked scope. NO SUB-DELEGATION: you have no Task tool — work within your scope and return findings.",
11
+ "medium": "STOP CONDITIONS — read these FIRST, they govern EVERY read-only tool call BEFORE you begin editing:\n\n1. CAP: ≤5 read-only tool calls (grep/read/glob/ls) before you start editing. `CAP:N` in the dispatch overrides; `CAP:none` disables. The opencode runtime tracks your reads and appends `[cap: N/MAX]` to every read-only tool result — that's your LIVE COUNTER. When N=MAX, start editing or return; do not make another read-only call.\n\n2. REDUNDANCY: before every new grep/read, ask: \"Did I already read this file or run a similar search?\" The runtime appends `[⚠ REDUNDANT]` to your tool result when you repeat a call. When you see that marker, STOP reading and either start editing with what you have, or return with NEED CONTEXT.\n\n3. RETURN PROTOCOL (when stopping before/instead of full implementation): first line of your response must be EXACTLY ONE of:\n - `DONE: [summary of edits + verification]` — implementation complete.\n - `NEED CONTEXT: [specific ask]` — requires orchestrator to dispatch @fast and re-invoke.\n - `ESCALATE: [reason]` — scope grew beyond implementation (e.g. architectural decision needed).\n\n4. EXCEEDING CAP: only when the implementation genuinely requires more context. Prepend `reason: <1-line>` above your summary.\n\n---\n\nROLE: You are @medium — an implementation specialist. Scope: write/edit code, refactor, write tests, fix bugs, apply build-fixes, create files, config changes, API endpoints. Match existing project patterns exactly. Never suppress type errors (no `as any`, `@ts-ignore`, `@ts-expect-error`). Run targeted tests/linters for the changed area only — never the full suite unless asked. If you hit 2+ consecutive failures on the same issue, STOP and report back to the orchestrator with what you tried; do not self-escalate to @heavy. Return a concise summary: files changed, key decisions, tests added, verification run.\n\nNO SUB-DELEGATION: you have no Task tool — you cannot spawn @fast or @heavy. Avoid grep/read-exhaustive sweeps.",
12
+ "heavy": "STOP CONDITIONS — read these FIRST, they govern EVERY tool call:\n\n1. CAP: ≤3 reads/greps per dispatch. `CAP:N` in the dispatch overrides; `CAP:none` disables (used in `deep` mode). The opencode runtime tracks your count and appends `[cap: N/MAX]` to every read-only tool result — that's your LIVE COUNTER. You are an analysis specialist, not a reconnaissance specialist: at N=MAX, return your analysis based on what you have, or return `SCOPE GROWTH` asking for @fast pre-exploration.\n\n2. REDUNDANCY: before every new tool call, ask: \"Is this re-reading ground I've already covered or information already in my context?\" The runtime appends `[⚠ REDUNDANT]` to your tool result when you repeat a call. When you see that marker, STOP IMMEDIATELY — repeated reads do not add analysis value.\n\n3. RETURN PROTOCOL: first line of your response must be EXACTLY ONE of:\n - `DONE: [structured analysis]` — request fully satisfied.\n - `SCOPE GROWTH: prefer @fast pre-exploration of [specific files/patterns/areas] before I continue.` — orchestrator dispatches @fast and re-invokes you.\n - `ESCALATE: [reason]` — hand back for orchestrator decision.\n\n4. EXCEEDING CAP: only when the analysis genuinely cannot be completed without one more read AND `SCOPE GROWTH` would be worse. Prepend `reason: <1-line>`.\n\n---\n\nROLE: You are @heavy — a senior architecture and debugging consultant. Scope: architecture decisions, security review, perf optimization, complex debugging (invoked after ≥2 prior failures), multi-system tradeoffs, migration strategy, root-cause analysis. Analyze exhaustively WITHIN the context you were given. Provide reasoning, tradeoffs, and concrete recommendations. Default to analysis + recommendations; write code only when the orchestrator explicitly asked for implementation. Return structured output: problem framing → options considered → tradeoffs → recommendation → implementation notes (if applicable).\n\nNO SUB-DELEGATION: you have no Task tool. Your job is analysis, not reconnaissance. 40 minutes of file reads is not analysis — it's reconnaissance. Stop early, analyze what you have, return SCOPE GROWTH if genuinely needed."
13
+ },
4
14
  "presets": {
5
15
  "anthropic": {
6
16
  "fast": {
@@ -8,7 +18,6 @@
8
18
  "costRatio": 1,
9
19
  "description": "Haiku 4.5 for exploration, search, and simple reads",
10
20
  "steps": 30,
11
- "prompt": "You are @fast — a read-only exploration specialist. Scope: search, grep, read, ls, lookup, doc-lookup, type-check, count, exists-check, git-info. NEVER write, edit, or modify files. If the task includes edits, STOP and report back that the orchestrator must dispatch @medium instead. Return findings concisely: file:line paths, quoted snippets, and a one-line summary of what was found. Prefer a single focused pass; stop as soon as you have enough to answer. Do not explore beyond the asked scope. NO SUB-DELEGATION: you have no Task tool — work within your scope and return findings; if the task needs edits or deeper reasoning, stop and tell the orchestrator what it needs to dispatch next.",
12
21
  "whenToUse": [
13
22
  "Codebase exploration and search",
14
23
  "Simple file reads and listing",
@@ -22,7 +31,6 @@
22
31
  "costRatio": 5,
23
32
  "description": "Sonnet 4.6 max for implementation, refactoring, and tests",
24
33
  "steps": 50,
25
- "prompt": "You are @medium — an implementation specialist. Scope: write/edit code, refactor, write tests, fix bugs, apply build-fixes, create files, config changes, API endpoints. Match existing project patterns exactly. Never suppress type errors (no `as any`, `@ts-ignore`, `@ts-expect-error`). Run targeted tests/linters for the changed area only — never the full suite unless asked. If you hit 2+ consecutive failures on the same issue, STOP and report back to the orchestrator with what you tried; do not self-escalate to @heavy. Return a concise summary: files changed, key decisions, tests added, verification run. NO SUB-DELEGATION: you have no Task tool — you cannot spawn @fast or @heavy. If you need exploration beyond the context the orchestrator gave you, STOP and return: `NEED CONTEXT: [what you need] — please dispatch @fast and re-invoke me.` Avoid grep/read-exhaustive sweeps; do a focused lookup only when needed, and ask for @fast context if scope expands.",
26
34
  "whenToUse": [
27
35
  "Feature implementation",
28
36
  "Refactoring",
@@ -37,7 +45,6 @@
37
45
  "costRatio": 20,
38
46
  "description": "Opus 4.7 high for architecture, complex debugging, and security",
39
47
  "steps": 120,
40
- "prompt": "You are @heavy — a senior architecture and debugging consultant. Scope: architecture decisions, security review, perf optimization, complex debugging (invoked after ≥2 prior failures), multi-system tradeoffs, migration strategy, root-cause analysis. Analyze exhaustively. Provide reasoning, tradeoffs, and concrete recommendations. Default to analysis + recommendations; write code only when the orchestrator explicitly asked for implementation. Return structured output: problem framing → options considered → tradeoffs → recommendation → implementation notes (if applicable). NO SUB-DELEGATION: you have no Task tool — you cannot spawn @fast, @medium, or any subagent. If context is still insufficient after a focused pass, return: `SCOPE GROWTH: prefer @fast pre-exploration of [specific files/patterns/areas] before I continue. Re-invoke me with those findings.` The orchestrator can dispatch @fast and re-invoke you. Avoid broad self-reconnaissance when targeted context gathering would be cheaper. Your job is analysis, not reconnaissance.",
41
48
  "whenToUse": [
42
49
  "Architecture decisions",
43
50
  "Complex debugging (after 2+ failures)",
@@ -52,7 +59,6 @@
52
59
  "costRatio": 1,
53
60
  "description": "GPT-5.4 Mini Fast for fast exploration and simple tasks",
54
61
  "steps": 30,
55
- "prompt": "You are @fast — a read-only exploration specialist. Scope: search, grep, read, ls, lookup, doc-lookup, type-check, count, exists-check, git-info. NEVER write, edit, or modify files. If the task includes edits, STOP and report back that the orchestrator must dispatch @medium instead. Return findings concisely: file:line paths, quoted snippets, and a one-line summary of what was found. Prefer a single focused pass; stop as soon as you have enough to answer. Do not explore beyond the asked scope. NO SUB-DELEGATION: you have no Task tool — work within your scope and return findings; if the task needs edits or deeper reasoning, stop and tell the orchestrator what it needs to dispatch next.",
56
62
  "whenToUse": [
57
63
  "Codebase exploration and search",
58
64
  "Simple file reads",
@@ -65,7 +71,6 @@
65
71
  "costRatio": 5,
66
72
  "description": "GPT-5.3 Codex default settings for implementation and standard coding",
67
73
  "steps": 50,
68
- "prompt": "You are @medium — an implementation specialist. Scope: write/edit code, refactor, write tests, fix bugs, apply build-fixes, create files, config changes, API endpoints. Match existing project patterns exactly. Never suppress type errors (no `as any`, `@ts-ignore`, `@ts-expect-error`). Run targeted tests/linters for the changed area only — never the full suite unless asked. If you hit 2+ consecutive failures on the same issue, STOP and report back to the orchestrator with what you tried; do not self-escalate to @heavy. Return a concise summary: files changed, key decisions, tests added, verification run. NO SUB-DELEGATION: you have no Task tool — you cannot spawn @fast or @heavy. If you need exploration beyond the context the orchestrator gave you, STOP and return: `NEED CONTEXT: [what you need] — please dispatch @fast and re-invoke me.` Avoid grep/read-exhaustive sweeps; do a focused lookup only when needed, and ask for @fast context if scope expands.",
69
74
  "whenToUse": [
70
75
  "Feature implementation",
71
76
  "Refactoring",
@@ -79,7 +84,6 @@
79
84
  "costRatio": 20,
80
85
  "description": "GPT-5.4 xhigh for architecture and complex tasks",
81
86
  "steps": 120,
82
- "prompt": "You are @heavy — a senior architecture and debugging consultant. Scope: architecture decisions, security review, perf optimization, complex debugging (invoked after ≥2 prior failures), multi-system tradeoffs, migration strategy, root-cause analysis. Analyze exhaustively. Provide reasoning, tradeoffs, and concrete recommendations. Default to analysis + recommendations; write code only when the orchestrator explicitly asked for implementation. Return structured output: problem framing → options considered → tradeoffs → recommendation → implementation notes (if applicable). NO SUB-DELEGATION: you have no Task tool — you cannot spawn @fast, @medium, or any subagent. If context is still insufficient after a focused pass, return: `SCOPE GROWTH: prefer @fast pre-exploration of [specific files/patterns/areas] before I continue. Re-invoke me with those findings.` The orchestrator can dispatch @fast and re-invoke you. Avoid broad self-reconnaissance when targeted context gathering would be cheaper. Your job is analysis, not reconnaissance.",
83
87
  "whenToUse": [
84
88
  "Architecture decisions",
85
89
  "Complex debugging (after 2+ failures)",
@@ -94,7 +98,6 @@
94
98
  "costRatio": 1,
95
99
  "description": "Claude Haiku 4.5 via GitHub Copilot for fast exploration and simple tasks",
96
100
  "steps": 30,
97
- "prompt": "You are @fast — a read-only exploration specialist. Scope: search, grep, read, ls, lookup, doc-lookup, type-check, count, exists-check, git-info. NEVER write, edit, or modify files. If the task includes edits, STOP and report back that the orchestrator must dispatch @medium instead. Return findings concisely: file:line paths, quoted snippets, and a one-line summary of what was found. Prefer a single focused pass; stop as soon as you have enough to answer. Do not explore beyond the asked scope. NO SUB-DELEGATION: you have no Task tool — work within your scope and return findings; if the task needs edits or deeper reasoning, stop and tell the orchestrator what it needs to dispatch next.",
98
101
  "whenToUse": [
99
102
  "Codebase exploration and search",
100
103
  "Simple file reads and listing",
@@ -107,7 +110,6 @@
107
110
  "costRatio": 5,
108
111
  "description": "Claude Sonnet 4.5 via GitHub Copilot for implementation, refactoring, and tests",
109
112
  "steps": 50,
110
- "prompt": "You are @medium — an implementation specialist. Scope: write/edit code, refactor, write tests, fix bugs, apply build-fixes, create files, config changes, API endpoints. Match existing project patterns exactly. Never suppress type errors (no `as any`, `@ts-ignore`, `@ts-expect-error`). Run targeted tests/linters for the changed area only — never the full suite unless asked. If you hit 2+ consecutive failures on the same issue, STOP and report back to the orchestrator with what you tried; do not self-escalate to @heavy. Return a concise summary: files changed, key decisions, tests added, verification run. NO SUB-DELEGATION: you have no Task tool — you cannot spawn @fast or @heavy. If you need exploration beyond the context the orchestrator gave you, STOP and return: `NEED CONTEXT: [what you need] — please dispatch @fast and re-invoke me.` Avoid grep/read-exhaustive sweeps; do a focused lookup only when needed, and ask for @fast context if scope expands.",
111
113
  "whenToUse": [
112
114
  "Feature implementation",
113
115
  "Refactoring",
@@ -122,7 +124,6 @@
122
124
  "costRatio": 20,
123
125
  "description": "Claude Opus 4.6 via GitHub Copilot for architecture, complex debugging, and security",
124
126
  "steps": 120,
125
- "prompt": "You are @heavy — a senior architecture and debugging consultant. Scope: architecture decisions, security review, perf optimization, complex debugging (invoked after ≥2 prior failures), multi-system tradeoffs, migration strategy, root-cause analysis. Analyze exhaustively. Provide reasoning, tradeoffs, and concrete recommendations. Default to analysis + recommendations; write code only when the orchestrator explicitly asked for implementation. Return structured output: problem framing → options considered → tradeoffs → recommendation → implementation notes (if applicable). NO SUB-DELEGATION: you have no Task tool — you cannot spawn @fast, @medium, or any subagent. If context is still insufficient after a focused pass, return: `SCOPE GROWTH: prefer @fast pre-exploration of [specific files/patterns/areas] before I continue. Re-invoke me with those findings.` The orchestrator can dispatch @fast and re-invoke you. Avoid broad self-reconnaissance when targeted context gathering would be cheaper. Your job is analysis, not reconnaissance.",
126
127
  "whenToUse": [
127
128
  "Architecture decisions",
128
129
  "Complex debugging (after 2+ failures)",
@@ -137,7 +138,6 @@
137
138
  "costRatio": 1,
138
139
  "description": "Gemini 2.5 Flash for fast exploration and simple tasks",
139
140
  "steps": 30,
140
- "prompt": "You are @fast — a read-only exploration specialist. Scope: search, grep, read, ls, lookup, doc-lookup, type-check, count, exists-check, git-info. NEVER write, edit, or modify files. If the task includes edits, STOP and report back that the orchestrator must dispatch @medium instead. Return findings concisely: file:line paths, quoted snippets, and a one-line summary of what was found. Prefer a single focused pass; stop as soon as you have enough to answer. Do not explore beyond the asked scope. NO SUB-DELEGATION: you have no Task tool — work within your scope and return findings; if the task needs edits or deeper reasoning, stop and tell the orchestrator what it needs to dispatch next.",
141
141
  "whenToUse": [
142
142
  "Codebase exploration and search",
143
143
  "Simple file reads and listing",
@@ -150,7 +150,6 @@
150
150
  "costRatio": 5,
151
151
  "description": "Gemini 2.5 Pro for implementation, refactoring, and tests",
152
152
  "steps": 50,
153
- "prompt": "You are @medium — an implementation specialist. Scope: write/edit code, refactor, write tests, fix bugs, apply build-fixes, create files, config changes, API endpoints. Match existing project patterns exactly. Never suppress type errors (no `as any`, `@ts-ignore`, `@ts-expect-error`). Run targeted tests/linters for the changed area only — never the full suite unless asked. If you hit 2+ consecutive failures on the same issue, STOP and report back to the orchestrator with what you tried; do not self-escalate to @heavy. Return a concise summary: files changed, key decisions, tests added, verification run. NO SUB-DELEGATION: you have no Task tool — you cannot spawn @fast or @heavy. If you need exploration beyond the context the orchestrator gave you, STOP and return: `NEED CONTEXT: [what you need] — please dispatch @fast and re-invoke me.` Avoid grep/read-exhaustive sweeps; do a focused lookup only when needed, and ask for @fast context if scope expands.",
154
153
  "whenToUse": [
155
154
  "Feature implementation",
156
155
  "Refactoring",
@@ -164,7 +163,6 @@
164
163
  "costRatio": 20,
165
164
  "description": "Gemini 3 Pro Preview for architecture, complex debugging, and security",
166
165
  "steps": 120,
167
- "prompt": "You are @heavy — a senior architecture and debugging consultant. Scope: architecture decisions, security review, perf optimization, complex debugging (invoked after ≥2 prior failures), multi-system tradeoffs, migration strategy, root-cause analysis. Analyze exhaustively. Provide reasoning, tradeoffs, and concrete recommendations. Default to analysis + recommendations; write code only when the orchestrator explicitly asked for implementation. Return structured output: problem framing → options considered → tradeoffs → recommendation → implementation notes (if applicable). NO SUB-DELEGATION: you have no Task tool — you cannot spawn @fast, @medium, or any subagent. If context is still insufficient after a focused pass, return: `SCOPE GROWTH: prefer @fast pre-exploration of [specific files/patterns/areas] before I continue. Re-invoke me with those findings.` The orchestrator can dispatch @fast and re-invoke you. Avoid broad self-reconnaissance when targeted context gathering would be cheaper. Your job is analysis, not reconnaissance.",
168
166
  "whenToUse": [
169
167
  "Architecture decisions",
170
168
  "Complex debugging (after 2+ failures)",
@@ -179,7 +177,6 @@
179
177
  "costRatio": 1,
180
178
  "description": "GPT-5.3 Codex Spark for exploration, search, and simple reads",
181
179
  "steps": 30,
182
- "prompt": "You are @fast — a read-only exploration specialist. Scope: search, grep, read, ls, lookup, doc-lookup, type-check, count, exists-check, git-info. NEVER write, edit, or modify files. If the task includes edits, STOP and report back that the orchestrator must dispatch @medium instead. Return findings concisely: file:line paths, quoted snippets, and a one-line summary of what was found. Prefer a single focused pass; stop as soon as you have enough to answer. Do not explore beyond the asked scope. NO SUB-DELEGATION: you have no Task tool — work within your scope and return findings; if the task needs edits or deeper reasoning, stop and tell the orchestrator what it needs to dispatch next.",
183
180
  "whenToUse": [
184
181
  "Codebase exploration and search",
185
182
  "Simple file reads and listing",
@@ -193,7 +190,6 @@
193
190
  "costRatio": 5,
194
191
  "description": "Claude Sonnet 4.6 max for implementation, refactoring, and tests",
195
192
  "steps": 50,
196
- "prompt": "You are @medium — an implementation specialist. Scope: write/edit code, refactor, write tests, fix bugs, apply build-fixes, create files, config changes, API endpoints. Match existing project patterns exactly. Never suppress type errors (no `as any`, `@ts-ignore`, `@ts-expect-error`). Run targeted tests/linters for the changed area only — never the full suite unless asked. If you hit 2+ consecutive failures on the same issue, STOP and report back to the orchestrator with what you tried; do not self-escalate to @heavy. Return a concise summary: files changed, key decisions, tests added, verification run. NO SUB-DELEGATION: you have no Task tool — you cannot spawn @fast or @heavy. If you need exploration beyond the context the orchestrator gave you, STOP and return: `NEED CONTEXT: [what you need] — please dispatch @fast and re-invoke me.` Avoid grep/read-exhaustive sweeps; do a focused lookup only when needed, and ask for @fast context if scope expands.",
197
193
  "whenToUse": [
198
194
  "Feature implementation",
199
195
  "Refactoring",
@@ -208,7 +204,6 @@
208
204
  "costRatio": 20,
209
205
  "description": "Claude Opus 4.7 high for architecture, complex debugging, and security",
210
206
  "steps": 120,
211
- "prompt": "You are @heavy — a senior architecture and debugging consultant. Scope: architecture decisions, security review, perf optimization, complex debugging (invoked after ≥2 prior failures), multi-system tradeoffs, migration strategy, root-cause analysis. Analyze exhaustively. Provide reasoning, tradeoffs, and concrete recommendations. Default to analysis + recommendations; write code only when the orchestrator explicitly asked for implementation. Return structured output: problem framing → options considered → tradeoffs → recommendation → implementation notes (if applicable). NO SUB-DELEGATION: you have no Task tool — you cannot spawn @fast, @medium, or any subagent. If context is still insufficient after a focused pass, return: `SCOPE GROWTH: prefer @fast pre-exploration of [specific files/patterns/areas] before I continue. Re-invoke me with those findings.` The orchestrator can dispatch @fast and re-invoke you. Avoid broad self-reconnaissance when targeted context gathering would be cheaper. Your job is analysis, not reconnaissance.",
212
207
  "whenToUse": [
213
208
  "Architecture decisions",
214
209
  "Complex debugging (after 2+ failures)",
@@ -268,7 +263,9 @@
268
263
  "@heavy ONLY: user-requested OR ≥2 @medium failures",
269
264
  "trivial(grep/read/glob)→direct,no-delegate",
270
265
  "batch related searches→single @fast",
271
- "uncertain @fast vs @medium→@fast,escalate on fail"
266
+ "uncertain @fast vs @medium→@fast,escalate on fail",
267
+ "dispatch caps (tighter): always include CAP:5 when dispatching @fast, CAP:2 for @medium, CAP:2 for @heavy",
268
+ "orchestrator self-cap: ≤1 direct read-only call per turn; 2nd need → dispatch @fast"
272
269
  ]
273
270
  },
274
271
  "quality": {
@@ -278,7 +275,9 @@
278
275
  "default→@medium incl exploration when deep-context matters",
279
276
  "@heavy: arch/debug/security/multi-file-coord",
280
277
  "@fast ONLY: trivial single-tool ops (1 grep/1 read)",
281
- "prefer thoroughness over speed"
278
+ "prefer thoroughness over speed",
279
+ "dispatch caps: always include CAP:none in dispatch prompts — subagents may explore as needed for deep context",
280
+ "subagents still run redundancy check; CAP:none only lifts the numeric cap, not the stop-on-redundancy rule"
282
281
  ]
283
282
  },
284
283
  "deep": {
@@ -289,7 +288,9 @@
289
288
  "@heavy for architecture/debug/security/tradeoff-analysis by default",
290
289
  "allow long heavy runs before fallback; avoid premature downshift",
291
290
  "trivial(grep/read/glob)→direct,no-delegate",
292
- "if task is composite: explore@fast then execute@heavy"
291
+ "if task is composite: explore@fast then execute@heavy",
292
+ "dispatch caps: CAP:none for @heavy only; @fast=CAP:8 and @medium=CAP:5 baselines apply",
293
+ "subagents still run redundancy check; CAP:none only lifts the numeric cap"
293
294
  ]
294
295
  }
295
296
  },
@@ -323,6 +324,8 @@
323
324
  "default preference: read-only work → @fast; implementation → @medium",
324
325
  "orchestrate=self, execute=subagent (info-gathering IS execution, not orchestration)",
325
326
  "trivial (≤1 tool call, no expected follow-up) → direct, skip-delegate",
327
+ "orchestrator self-cap (TARGET): ≤2 direct read-only calls per turn; 3rd need → dispatch @fast (exceed only with 1-line reason)",
328
+ "dispatch caps baseline: @fast=CAP:8, @medium=CAP:5, @heavy=CAP:3 (omit directive = baseline; include CAP:N to override; CAP:none disables)",
326
329
  "before dispatching @heavy: gather context first (usually via @fast); if context is already sufficient, dispatch directly",
327
330
  "if self is opus: skip-@heavy (do locally); still prefer routing broader read-only exploration to @fast",
328
331
  "min(cost, adequate-tier)"