opencode-model-router 2.0.0 → 2.2.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/CHANGELOG.md CHANGED
@@ -7,6 +7,95 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
7
7
 
8
8
  ## [Unreleased]
9
9
 
10
+ ## [2.2.0] - 2026-10-05
11
+
12
+ ### Added
13
+
14
+ - Config hot reload: the router re-reads `tiers.json`, the global and project
15
+ overrides files and the state file when their mtime/ctime/size fingerprint changes,
16
+ with no restart. A source that turns invalid or unreachable keeps the last valid
17
+ config (the reason is surfaced by `getConfigReloadError()`); only ENOENT/ENOTDIR
18
+ count as a removed file. `/router-reload` forces a reload, and on OpenCode 2 the
19
+ agent and command registry is refreshed on reload and after `/preset`.
20
+ - `hybrid-2` preset: `@fast` → `openai/gpt-6-luna-fast` (medium), `@medium` →
21
+ `anthropic/claude-sonnet-5-5` (xhigh), `@heavy` → `anthropic/claude-opus-5-5`
22
+ (xhigh).
23
+
24
+ ### Fixed
25
+
26
+ - Project overrides are found again on opencode v2 service mode (#70): the override
27
+ lookup and the config cache are now keyed by the host-provided project directory
28
+ instead of `process.cwd()` (which the v2 server moves to `$HOME`), so several
29
+ projects in one process each keep their own config, reload state and error.
30
+
31
+ ## [2.1.0] - 2026-10-05
32
+
33
+ Observations by @MetalbolicX in opencode-smart-router (#17); implementation written from scratch.
34
+
35
+ ### Added
36
+
37
+ - Delegation depth guard (#66), configured by `enforcement.maxDelegationDepth`
38
+ (default `1`; `null` disables it).
39
+ - Effort bump before escalation (#67), configured by
40
+ `enforcement.escalate.effortBump` (default `true`) and
41
+ `enforcement.escalate.effortBumpMax` (default `"xhigh"`, further capped per model).
42
+
43
+ ### Changed
44
+
45
+ - The automatic ladder's existing same-tier retry now runs one effort level higher
46
+ by default on eligible tiers: explicit valid `effort`, no `variant`, a recognised
47
+ Claude or OpenAI model family, no winning explicit provider setting, and room
48
+ below the effective ceiling. This adds no attempt and
49
+ still respects attempt and cost ceilings. It applies only to the optional
50
+ `delegate` tool's automatic ladder, not native `task`/`subagent` or manual retries.
51
+ Only `fable-effort` fast/medium are eligible among bundled presets; at the default
52
+ cost ceiling, a run starting at fast stops before medium's bump. Set
53
+ `enforcement.escalate.effortBump: false` to restore the previous retry behaviour.
54
+ - Dispatches past `enforcement.maxDelegationDepth` (default `1`) are warned in
55
+ `advisory` mode (the bundled default) with `[⚠ GUARD:delegation_depth]` and refused
56
+ in `enforced` mode. Set `enforcement.mode: "enforced"` to enforce it unless the
57
+ caller tier's `enforcement.perTier` entry overrides `mode`; `MODEL_ROUTER_ENFORCE=1`
58
+ overrides both and forces enforcement. Set `enforcement.maxDelegationDepth: null`
59
+ to opt out of the guard. Enforcement mode `off`, a caller-tier `perTier: "off"`
60
+ (unless the environment gate forces enforcement), and `/bypass on` also disable
61
+ the check. OpenCode 2's own
62
+ `experimental.subagent_depth` cap remains independent.
63
+ - On OpenCode 2, router-modified `subagent` results now keep the host's
64
+ `<subagent sessionID=…>` envelope part and append the router's text as a separate
65
+ part, preserving the resume handle instead of replacing the envelope with plain
66
+ text. This applies when host text exists and the router output starts with the
67
+ child's text after trimming trailing whitespace. Missing host text or a
68
+ non-suffix rewrite uses the full router output as one text part instead, retaining
69
+ non-text attachments without losing or duplicating the child's text. Structured
70
+ output and metadata handling are unchanged.
71
+
72
+ ### Fixed
73
+
74
+ - **OpenCode v1 behaviour change:** tier `effort` (for OpenAI-family models),
75
+ `reasoning.*` and `thinking.budgetTokens` settings that v1 silently dropped now
76
+ reach requests through provider-native registered keys: `reasoningEffort`,
77
+ `reasoningSummary` and `thinking: { type: "enabled", budgetTokens }`. User config
78
+ keys and provider-specific precedence/gates are unchanged; Claude `effort` was
79
+ already registered with its native key.
80
+ - OpenAI-family detection is regex-based: Copilot/OpenRouter/Azure `gpt-*`,
81
+ `gpt-oss` through Ollama/Groq, and non-reasoning GPT models with configured
82
+ `effort` or explicit `reasoning.effort` now receive `reasoningEffort` (and
83
+ configured summaries use `reasoningSummary`). IDs containing `o1`/`o3`/`o4`
84
+ delimited by `/`, `-` or `_` (or the start/end of the ID), including bare IDs
85
+ and false positives such as `mistral/magistral-o1`, are also treated as OpenAI.
86
+ OpenAI-family tiers with a truthy `thinking.budgetTokens` now also send
87
+ `thinking: { type: "enabled", budgetTokens }`; non-Claude budgets are not gated.
88
+ Whether the SDK strips unsupported options for non-reasoning models is unverified.
89
+ - Claude tiers with an applicable `thinking.budgetTokens` now send `thinking`;
90
+ adaptive-only Claude still drops manual budgets. Unknown-family tiers (such
91
+ as Bedrock Claude or Gemini) with explicit `thinking.budgetTokens` or
92
+ `reasoning.*` also receive the native keys; their provider effect is unverified.
93
+ - Latency/cost may rise, or a provider may reject newly delivered settings.
94
+ To restore the previous behaviour, remove `effort`, `reasoning.*` or `thinking`
95
+ from the affected tier. **Bundled presets are unaffected by this registration
96
+ fix:** none sets `reasoning` or `thinking`, and their explicit `effort` settings
97
+ are Claude's already-native key.
98
+
10
99
  ## [2.0.0] - 2026-10-04
11
100
 
12
101
  The router now runs on OpenCode v2 through a separate server entrypoint. **OpenCode v1
package/README.md CHANGED
@@ -35,7 +35,7 @@ Every tier carries its `costRatio` (fast=1x, medium=5x, heavy=20x) injected into
35
35
  If the orchestrator is already running on Opus, the rule `self∈opus→never→@heavy` fires — it does the heavy work itself rather than delegating to another Opus instance.
36
36
 
37
37
  **Multi-provider support with automatic fallback.**
38
- Seven presets out of the box: Anthropic, OpenAI, GitHub Copilot, Google, hybrid, fable-effort, and Zai (GLM). Switch with `/preset`. If a provider fails, the fallback chain tries the next one automatically.
38
+ Eight presets out of the box: Anthropic, OpenAI, GitHub Copilot, Google, hybrid, hybrid-2, fable-effort, and Zai (GLM). Switch with `/preset`. If a provider fails, the fallback chain tries the next one automatically.
39
39
 
40
40
  **Plan annotation for long tasks.**
41
41
  `/annotate-plan` reads a markdown plan and tags each step with `[tier:fast]`, `[tier:medium]`, or `[tier:heavy]` — removing all routing ambiguity from multi-step workflows.
@@ -279,9 +279,10 @@ host's permissions and cancellation. There are a few host differences:
279
279
  ([details](docs/OPENCODE_V2.md#grader-temperature-on-v2)).
280
280
  - Anti-narration warnings appear as separate synthetic transcript entries, because
281
281
  completed v2 text events cannot be rewritten.
282
- - Tier options (`effort`/`variant`/`reasoning_effort`, `budget_tokens`, etc.) are
282
+ - Tier options (`effort`/`reasoningEffort`/`reasoningSummary`/`thinking`) are
283
283
  applied per turn through the v2 `session` context hook, filling only keys not
284
284
  already present, because v2 does not read `Agent.Info.request.settings`.
285
+ A tier's `variant` is applied through its agent model reference at registration.
285
286
 
286
287
  **Smoke tests:** Set `OPENCODE_V2_BIN` to the absolute path of an OpenCode v2
287
288
  executable. `npm run smoke:v2` checks loading and registration without provider
@@ -414,7 +415,7 @@ For an npm install, `tiers.json` is **inside the cached package directory**, not
414
415
 
415
416
  ### Presets
416
417
 
417
- The plugin ships with seven presets (switch with `/preset <name>`):
418
+ The plugin ships with eight presets (switch with `/preset <name>`):
418
419
 
419
420
  **anthropic** (default):
420
421
  | Tier | Model | Cost ratio |
@@ -451,6 +452,13 @@ The plugin ships with seven presets (switch with `/preset <name>`):
451
452
  | @medium | `openai/gpt-6-astra-fast` (high) | 5x |
452
453
  | @heavy | `anthropic/claude-opus-5-5` (variant/effort: xhigh) | 20x |
453
454
 
455
+ **hybrid-2** — OpenAI for exploration, Anthropic for implementation and heavy analysis:
456
+ | Tier | Model | Cost ratio |
457
+ |------|-------|-----------|
458
+ | @fast | `openai/gpt-6-luna-fast` (medium) | 1x |
459
+ | @medium | `anthropic/claude-sonnet-5-5` (variant/effort: xhigh) | 5x |
460
+ | @heavy | `anthropic/claude-opus-5-5` (variant/effort: xhigh) | 20x |
461
+
454
462
  **fable-effort** — one model, three reasoning depths (see [per-tier `effort`](#per-tier-effort)):
455
463
  | Tier | Model | Effort | Cost ratio |
456
464
  |------|-------|--------|-----------|
@@ -480,7 +488,11 @@ highest first:
480
488
  provider-specific setting always wins, and a one-time warning names the tier.
481
489
  2. `effort`.
482
490
 
483
- **Unset means unset**: no `effort` (and no `reasoning_effort`) key is registered at all.
491
+ **Unset means unset**: without `effort` or an explicit `reasoning.effort`, neither
492
+ `effort` nor `reasoningEffort` is registered. User config keys remain
493
+ `reasoning.effort`, `reasoning.summary` and `thinking.budgetTokens`; registered
494
+ provider options use `reasoningEffort`, `reasoningSummary` and
495
+ `thinking: { type: "enabled", budgetTokens }` respectively.
484
496
 
485
497
  Explicit fields are gated by model family: Claude drops `reasoning.effort`/`reasoning.summary`; adaptive-only Claude also ignores `thinking.budgetTokens`, leaving `effort` applicable.
486
498
  Each drop warns once per tier; non-Claude explicit fields are unchanged. See the [provider gate](docs/CONFIG_REFERENCE.md#provider-gate-for-explicit-thinking-and-reasoning-fields).
@@ -488,7 +500,7 @@ Each drop warns once per tier; non-Claude explicit fields are unchanged. See the
488
500
  | Model family | Registered as | Caveats |
489
501
  |---|---|---|
490
502
  | Anthropic | `options.effort`, incl. `xhigh`/`max` | Requires the `opencode-anthropic-fix` plugin (commit `307aea9`+ for fable/mythos). Non-adaptive Claude models (e.g. haiku) silently strip `effort` at the API layer, and without the plugin a top-level `effort` can break Claude-Code billing fingerprinting. |
491
- | OpenAI | `options.reasoning_effort` | Supports only `low`/`medium`/`high`; `xhigh` and `max` are downgraded to `high` with a warning. |
503
+ | OpenAI | `options.reasoningEffort` | Supports only `low`/`medium`/`high`; `xhigh` and `max` are downgraded to `high` with a warning. |
492
504
  | Other (Google, …) | nothing | Dropped with a warning — no known mapping. Detection is by model family, not provider prefix, so Copilot-proxied ids (`github-copilot/gpt-4o`, `github-copilot/claude-sonnet-4`) take their family's knob above. |
493
505
 
494
506
  An out-of-set value in `tiers.json` fails validation at load; one that arrives any other
@@ -932,6 +944,67 @@ That deferral is the v1.15.0 default (`enforcement.verify.defaultVerify: "deferr
932
944
  - **Mode A — on-the-fly.** The orchestrator delegates through the native `Task()` tool — observed by the enforcement pipeline, verified according to the settings above, and rendered inline in the TUI. (An optional, independently-verified `delegate` tool can be enabled via `experimental.verifiedDelegateTool` in `tiers.json` or `MODEL_ROUTER_VERIFIED_DELEGATE=1`; it is hidden by default so delegation stays visible.)
933
945
  - **Mode B — plan-annotated.** `/annotate-plan` emits `[tier:X]` plus an `[acceptance]` block per task; the enforcement loop is wired up at execution time based on those annotations.
934
946
 
947
+ ### Delegation depth guard
948
+
949
+ The guard checks model-initiated dispatches through native `task` (OpenCode v1),
950
+ `subagent` (OpenCode 2), and the router's optional `delegate` tool, including resumes.
951
+ `enforcement.maxDelegationDepth` defaults to `1`: the root orchestrator is depth 0,
952
+ so it may delegate, but its depth-1 children would exceed the limit by delegating again.
953
+
954
+ - **`advisory` (bundled default):** allows the dispatch and warns with
955
+ `[⚠ GUARD:delegation_depth]` in its result; it does not refuse it.
956
+ - **`enforced`:** refuses a dispatch past the limit before another subagent runs.
957
+ Set `enforcement.mode: "enforced"` or `MODEL_ROUTER_ENFORCE=1` to enforce it.
958
+ The caller tier's `enforcement.perTier` override applies unless the environment
959
+ gate overrides it.
960
+ - **`off`:** skips the check. Set `enforcement.maxDelegationDepth: null` to disable
961
+ just this guard, or use an integer from 1 to 32 to change the depth limit.
962
+
963
+ This is not a sandbox: shell-launched `opencode run` and other plugins' session
964
+ tools are outside its scope. `/bypass on` also disables the depth guard. If the
965
+ caller depth cannot be resolved, the guard fails open with a logged warning.
966
+ OpenCode 2 has its own independent `experimental.subagent_depth` cap (default 1):
967
+ raising or disabling the router limit does not lift that host cap. With both caps
968
+ enforced, the lower one wins. V2's `general` agent also needs explicit `subagent`
969
+ permission to dispatch. The Phase 2.3 host proof on OpenCode v1 1.18.19 likewise encountered
970
+ a host cap and used top-level `subagent_depth: 4` to lift it; its default and upstream
971
+ documentation are unverified. Raising only the router limit does not lift a host cap.
972
+ These are observations from the [host-proof fixtures](docs/qa/depth-and-effort/phase-2.3.md#handoffs),
973
+ not a documented cross-version default for v1.
974
+
975
+ See the [configuration reference](docs/CONFIG_REFERENCE.md) and
976
+ [design decisions and scope limits](docs/adr/0004-delegation-depth-and-effort-bump.md).
977
+
978
+ ### Effort bump before escalation
979
+
980
+ The automatic escalation ladder uses its existing same-tier retry to try **one
981
+ effort level higher** before moving to a more expensive tier. It adds no attempt.
982
+ `enforcement.escalate.effortBump` defaults to `true`, and `effortBumpMax` defaults
983
+ to `"xhigh"`, further capped by model family (OpenAI: `high`; Claude: `max`). Set
984
+ `enforcement.escalate.effortBump: false` to restore the previous ladder behaviour.
985
+
986
+ An eligible tier must set an explicit valid `effort`, have no `variant`, belong to
987
+ a recognised Claude or OpenAI model family, and have room below the effective ceiling.
988
+ A winning explicit provider setting
989
+ (`reasoning.effort` or an applicable `thinking.budgetTokens`) prevents the bump.
990
+ It changes only that retry producer's options, not the preset, titles or graders.
991
+ The bump applies to the optional `delegate` tool's automatic ladder, not native
992
+ `task`/`subagent` calls or manual retries; deferred verification does not retry.
993
+ `/bypass` leaves the ladder and effort bump active; use `effortBump: false` to disable
994
+ the bump.
995
+
996
+ Among bundled presets, **only `fable-effort` fast and medium are eligible**
997
+ (`low → medium` and `high → xhigh`). Its heavy tier is already at the default
998
+ ceiling; all other presets either set a variant or omit `effort`. In particular,
999
+ the default `anthropic` preset has no bumpable tier. Attempt and cost ceilings
1000
+ still apply: starting at fast with the default cost multiple of 4, `fable-effort`
1001
+ runs `fast@low → fast@medium → medium@high`, then stops on cost; medium's bump
1002
+ is not reached. Raise `enforcement.escalate.costCeiling.multiple` to allow it.
1003
+
1004
+ See the [configuration reference](docs/CONFIG_REFERENCE.md) for eligibility and
1005
+ cost settings, and the [ADR](docs/adr/0004-delegation-depth-and-effort-bump.md) for
1006
+ trade-offs and host evidence (real-provider acceptance of bumped values is unverified).
1007
+
935
1008
  ### Tuning enforcement
936
1009
 
937
1010
  Advisory is the default. To change the level:
@@ -946,7 +1019,7 @@ Set `taskPromptRepair: false` to restore the previous behaviour; see [configurat
946
1019
  For work outside the router directory (e.g. a git worktree), add `cwd: <dir>` inside the task's `[acceptance]` block; a non-empty tool `args.cwd` takes precedence.
947
1020
  If every changed file is absolute and outside the verification base, deterministic checks return unverifiable instead of running in the wrong directory.
948
1021
 
949
- **Modes:** `off` — no-op, byte-for-byte-unchanged routing (must now be set explicitly, since `advisory` is the default); `advisory` (default) — evaluates and surfaces guidance, never blocks; `enforced` — hard-blocks active, full produce → verify → accept/escalate pipeline.
1022
+ **Modes:** `off` — disables enforcement guards and skips native `task`/`subagent` verification (must be set explicitly, since `advisory` is the default); `advisory` (default) — warns on guard violations without blocking; `enforced` — blocks guard violations. Native-task verification annotates completed results in both advisory and enforced modes, subject to verification policy. Whenever the opt-in `delegate` tool is enabled, its produce → verify → accept/escalate pipeline runs in **every mode**, including retries and eligible effort bumps, subject to its verification policy and attempt/cost limits.
950
1023
 
951
1024
  > Enforcement applies to subagent/delegate sessions only. The orchestrator session is never hard-blocked.
952
1025
 
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "opencode-model-router",
3
- "version": "2.0.0",
3
+ "version": "2.2.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",
@@ -9,7 +9,7 @@
9
9
  "test:watch": "vitest",
10
10
  "test:coverage": "vitest run --coverage",
11
11
  "smoke": "cross-env RUN_OC_SMOKE=1 vitest run --config vitest.smoke.config.ts test/smoke",
12
- "smoke:keyless": "cross-env RUN_OC_SMOKE_KEYLESS=1 vitest run --config vitest.smoke.config.ts test/smoke/registration.smoke.test.ts test/smoke/subagent-tiers.smoke.test.ts test/smoke/deferred-catalog.smoke.test.ts",
12
+ "smoke:keyless": "cross-env RUN_OC_SMOKE_KEYLESS=1 vitest run --config vitest.smoke.config.ts test/smoke/registration.smoke.test.ts test/smoke/subagent-tiers.smoke.test.ts test/smoke/deferred-catalog.smoke.test.ts test/smoke/depth-effort.smoke.test.ts test/smoke/helpers/scripted-provider.test.ts",
13
13
  "smoke:v2": "cross-env RUN_OC_SMOKE_V2=1 vitest run --config vitest.smoke.config.ts test/smoke/v2-registration.smoke.test.ts",
14
14
  "smoke:v2:e2e": "cross-env RUN_OC_SMOKE_V2_E2E=1 vitest run --config vitest.smoke.config.ts test/smoke/v2-provider-e2e.smoke.test.ts",
15
15
  "typecheck": "tsc --noEmit"
@@ -4,6 +4,9 @@ import type { PluginInput } from "@opencode-ai/plugin";
4
4
  * that task call. V1 hosts read only output.args, so this symbol is invisible. */
5
5
  export const TASK_VERIFICATION = Symbol.for("opencode-model-router.task-verification");
6
6
 
7
+ /** An advisory depth banner for this call; the v2 bridge delivers it. */
8
+ export const DEPTH_BANNER = Symbol.for("opencode-model-router.depth-banner");
9
+
7
10
  /** A host-owned child lifecycle, so v2 never fabricates REST sessions or IDs. */
8
11
  export interface ChildSessionRequest {
9
12
  parentSessionID?: string;
@@ -24,4 +27,6 @@ export interface ChildSessionRunner {
24
27
 
25
28
  export type RouterPluginInput = PluginInput & {
26
29
  routerChildRunner?: ChildSessionRunner;
30
+ /** Set only by src/v2.ts; absent = v1 host (A3). */
31
+ routerHost?: "v2";
27
32
  };
@@ -5,7 +5,7 @@ import type { ToolContext } from "@opencode/plugin/promise/tool";
5
5
  import type { SystemPart } from "@opencode/ai";
6
6
  import type { V2Runtime } from "./v2-client";
7
7
  import { V2_GRADER_AGENT } from "./v2-client";
8
- import { TASK_VERIFICATION } from "./child-session";
8
+ import { DEPTH_BANNER, TASK_VERIFICATION } from "./child-session";
9
9
  import { isAbsolute, resolve } from "node:path";
10
10
  import { loadConfig } from "../router/config";
11
11
  import { getActiveTiers } from "../router/protocol";
@@ -87,6 +87,7 @@ export async function registerV2Hooks(
87
87
  const registrations: Array<{ dispose(): Promise<void> }> = [];
88
88
  const abort = new AbortController();
89
89
  const verifyingCalls = new Set<string>();
90
+ const depthBanners = new Map<string, string>();
90
91
  let eventTask: Promise<void> | undefined;
91
92
  let disposed = false;
92
93
  const within = <T>(context: ToolContext, operation: () => Promise<T>): Promise<T> =>
@@ -113,26 +114,55 @@ export async function registerV2Hooks(
113
114
  };
114
115
 
115
116
  try {
117
+ // Captured once: after our own transform, ctx.agent.list() returns
118
+ // router-modified agents, which would defeat the originals diff on refresh.
116
119
  const agents = await ctx.agent.list();
117
- const config: LegacyConfig = { agent: {}, command: {} };
118
- for (const agent of agents.data) config.agent[agent.id] = {
120
+ const baseSeed: Record<string, LegacyAgent> = {};
121
+ for (const agent of agents.data) baseSeed[agent.id] = {
119
122
  mode: agent.mode,
120
123
  model: agent.model && `${agent.model.providerID}/${agent.model.id}`,
121
124
  variant: agent.model?.variant,
122
125
  };
123
- const originals = new Map(Object.entries(config.agent).map(([id, agent]) => [id, JSON.stringify(agent)]));
124
- await hooks.config?.(config);
125
- const agentOptions = new Map<string, Record<string, unknown>>();
126
- for (const [name, definition] of Object.entries(config.agent)) {
127
- if (originals.get(name) === JSON.stringify(definition) || !definition.options) continue;
128
- const { reasoning_effort, reasoning_summary, budget_tokens, ...options } = definition.options;
129
- agentOptions.set(name, {
130
- ...options,
131
- ...(reasoning_effort === undefined ? {} : { reasoningEffort: reasoning_effort }),
132
- ...(reasoning_summary === undefined ? {} : { reasoningSummary: reasoning_summary }),
133
- ...(budget_tokens === undefined ? {} : { thinking: { type: "enabled", budgetTokens: budget_tokens } }),
126
+ let config: LegacyConfig = { agent: {}, command: {} };
127
+ let originals = new Map<string, string>();
128
+ let agentOptions = new Map<string, Record<string, unknown>>();
129
+ let lastConfig: unknown;
130
+ // Returns the router config the registry state was built from; the caller
131
+ // advances `lastConfig` only once the host registries have reloaded from it.
132
+ const buildConfig = async (): Promise<unknown> => {
133
+ const next: LegacyConfig = { agent: JSON.parse(JSON.stringify(baseSeed)), command: {} };
134
+ const nextOriginals = new Map(Object.entries(next.agent).map(([id, agent]) => [id, JSON.stringify(agent)]));
135
+ await hooks.config?.(next);
136
+ const nextOptions = new Map<string, Record<string, unknown>>();
137
+ for (const [name, definition] of Object.entries(next.agent)) {
138
+ if (nextOriginals.get(name) === JSON.stringify(definition) || !definition.options) continue;
139
+ const { reasoning_effort, reasoning_summary, budget_tokens, ...options } = definition.options;
140
+ const normalized = { ...options };
141
+ if (reasoning_effort !== undefined && normalized.reasoningEffort === undefined) normalized.reasoningEffort = reasoning_effort;
142
+ if (reasoning_summary !== undefined && normalized.reasoningSummary === undefined) normalized.reasoningSummary = reasoning_summary;
143
+ if (budget_tokens !== undefined && normalized.thinking === undefined) normalized.thinking = { type: "enabled", budgetTokens: budget_tokens };
144
+ nextOptions.set(name, normalized);
145
+ }
146
+ config = next;
147
+ originals = nextOriginals;
148
+ agentOptions = nextOptions;
149
+ return loadConfig(ctx.location.directory);
150
+ };
151
+ lastConfig = await buildConfig();
152
+ let refreshChain: Promise<void> = Promise.resolve();
153
+ const refresh = (): Promise<void> => {
154
+ const run = refreshChain.then(async () => {
155
+ if (disposed) return;
156
+ const built = await buildConfig();
157
+ await ctx.agent.reload();
158
+ await ctx.command.reload();
159
+ // Only after both registries reloaded: a rejected reload leaves
160
+ // `lastConfig` stale so the next prompt retries the refresh.
161
+ lastConfig = built;
134
162
  });
135
- }
163
+ refreshChain = run.catch(() => {});
164
+ return run;
165
+ };
136
166
  registrations.push(await ctx.agent.transform((editor) => {
137
167
  if (runtime) editor.update(V2_GRADER_AGENT, (agent) => {
138
168
  agent.mode = "subagent";
@@ -163,6 +193,15 @@ export async function registerV2Hooks(
163
193
  await legacy["command.execute.before"]?.({
164
194
  command: name, arguments: invocation.prompt.text, sessionID: invocation.sessionID,
165
195
  }, output);
196
+ if (name === "router-reload") {
197
+ const reloadText = output.parts.map((part) => v2Instructions(part.text)).join("\n\n");
198
+ await refresh();
199
+ await ctx.session.synthetic({
200
+ sessionID: invocation.sessionID, text: reloadText, description: "Model router config reload", resume: false,
201
+ });
202
+ return;
203
+ }
204
+ if (name === "preset") await refresh();
166
205
  await ctx.session.prompt({
167
206
  ...invocation.prompt,
168
207
  sessionID: invocation.sessionID,
@@ -207,6 +246,7 @@ export async function registerV2Hooks(
207
246
  const output = { message: { agent: session.agent }, parts: [{ type: "text", text: event.prompt.text }] };
208
247
  await legacy["chat.message"]?.({ sessionID: event.sessionID, agent: session.agent }, output);
209
248
  event.prompt.text = output.parts.map((part) => part.text).join("\n\n");
249
+ if (loadConfig(ctx.location.directory) !== lastConfig) await refresh();
210
250
  }));
211
251
  registrations.push(await ctx.session.hook("context", async (event) => {
212
252
  const input = { sessionID: event.sessionID, agent: event.agent, model: { ...event.model, modelID: event.model.id } };
@@ -215,7 +255,7 @@ export async function registerV2Hooks(
215
255
  if (!(key in event.options)) event.options[key] = value;
216
256
  }
217
257
  await legacy["chat.params"]?.(input, event.options);
218
- const verify = loadConfig().enforcement?.verify;
258
+ const verify = loadConfig(ctx.location.directory).enforcement?.verify;
219
259
  if (event.agent === V2_GRADER_AGENT
220
260
  && (verify?.graderTemperature === null
221
261
  || !(verify?.graderTemperatureModels ?? []).includes(`${event.model.providerID}/${event.model.id}`))) {
@@ -256,7 +296,7 @@ export async function registerV2Hooks(
256
296
  const source = message.id ? attributed.get(message.id) : undefined;
257
297
  if (!source || source.type !== "synthetic") continue;
258
298
  const filtered = { system: [source.text] };
259
- stripDelegateInstructions(filtered, loadConfig(), session.location?.directory ?? ctx.location.directory);
299
+ stripDelegateInstructions(filtered, loadConfig(ctx.location.directory), session.location?.directory ?? ctx.location.directory);
260
300
  const retained = filtered.system.join("");
261
301
  if (retained === source.text) continue;
262
302
  const index = event.messages.indexOf(message);
@@ -274,7 +314,7 @@ export async function registerV2Hooks(
274
314
  const original = args && typeof args === "object" ? { ...args } : args;
275
315
  const output = { args };
276
316
  if (event.tool === "subagent" && args && typeof args.agent === "string" && args.model === undefined) {
277
- const cfg = loadConfig();
317
+ const cfg = loadConfig(ctx.location.directory);
278
318
  if (cfg.subagentTiers?.[args.agent]) {
279
319
  const actual = await ctx.agent.list();
280
320
  const overrides = actual.data.some((agent) => agent.id === args.agent) ? resolveSubagentOverrides({
@@ -289,6 +329,12 @@ export async function registerV2Hooks(
289
329
  await legacy["tool.execute.before"]?.({ ...event, tool: legacyToolName(event.tool), callID: event.id }, output);
290
330
  });
291
331
  const verifying = (output as Record<PropertyKey, unknown>)[TASK_VERIFICATION] === true;
332
+ const banner = (output as Record<PropertyKey, unknown>)[DEPTH_BANNER];
333
+ if (typeof banner === "string") {
334
+ depthBanners.delete(event.id);
335
+ depthBanners.set(event.id, banner);
336
+ while (depthBanners.size > 1000) depthBanners.delete(depthBanners.keys().next().value!);
337
+ }
292
338
  if (verifying) {
293
339
  verifyingCalls.add(event.id);
294
340
  while (verifyingCalls.size > 1000) verifyingCalls.delete(verifyingCalls.values().next().value!);
@@ -300,14 +346,20 @@ export async function registerV2Hooks(
300
346
  event.input = nativeArgs(event.tool, output.args, original, verifying);
301
347
  }));
302
348
  registrations.push(await ctx.tool.hook("execute.after", async (event) => {
349
+ const banner = depthBanners.get(event.id);
350
+ depthBanners.delete(event.id);
303
351
  const verifying = verifyingCalls.delete(event.id);
304
352
  if (event.status !== "completed") return;
305
353
  const structured = event.result.output;
306
354
  // A user can background a foreground subagent while it is running. That
307
355
  // acknowledgement is not a final result and must never enter acceptance.
308
356
  if (event.tool === "subagent" && structured?.status === "running") {
309
- if (!verifying) return;
310
- const notice = "[router] This subagent is still running. Its result has not been verified; automatic acceptance requires a completed foreground return.";
357
+ const notices = [
358
+ ...(verifying ? ["[router] This subagent is still running. Its result has not been verified; automatic acceptance requires a completed foreground return."] : []),
359
+ ...(banner === undefined ? [] : [banner]),
360
+ ];
361
+ if (!notices.length) return;
362
+ const notice = notices.join("\n\n");
311
363
  const content = Array.isArray(event.result.content) ? [...event.result.content]
312
364
  : typeof event.result.content === "string" ? [{ type: "text" as const, text: event.result.content }] : [];
313
365
  event.result = {
@@ -326,15 +378,36 @@ export async function registerV2Hooks(
326
378
  callID: event.id, args: await scopedArgs(event),
327
379
  }, output);
328
380
  });
329
- if (output.output === text) return;
330
- const content = Array.isArray(event.result.content) ? event.result.content.filter((part) => part.type !== "text") : [];
381
+ const changed = output.output !== text;
382
+ if (!changed && banner === undefined) return;
383
+ const routed = changed ? translateAdded(text, output.output) : text;
384
+ const final = banner === undefined ? routed : [routed.trimEnd(), banner].filter(Boolean).join("\n\n");
385
+ const content = Array.isArray(event.result.content) ? [...event.result.content]
386
+ : typeof event.result.content === "string" ? [{ type: "text" as const, text: event.result.content }] : [];
387
+ const childText = text.trimEnd();
388
+ const routedText = routed.trimEnd();
389
+ let visible;
390
+ if (event.tool === "subagent" && structured && typeof structured === "object" && typeof structured.output === "string"
391
+ && content.some((part) => part.type === "text") && routedText.startsWith(childText)) {
392
+ // The host's visible text owns the session envelope (and resume handle).
393
+ // Footer helpers trim the bare output. Compare trimmed tails before taking
394
+ // only the router's suffix; other rewrites must replace, not repeat, it.
395
+ const suffix = changed ? routedText.slice(childText.length) : "";
396
+ const notices = [suffix, banner].filter((part) => part !== undefined && part !== "").join("\n\n");
397
+ visible = [
398
+ ...content,
399
+ ...(notices ? [{ type: "text" as const, text: notices }] : []),
400
+ ];
401
+ } else {
402
+ visible = [{ type: "text" as const, text: final }, ...content.filter((part) => part.type !== "text")];
403
+ }
331
404
  event.result = {
332
405
  ...event.result,
333
- content: [{ type: "text", text: translateAdded(text, output.output) }, ...content],
406
+ content: visible,
334
407
  metadata: output.metadata,
335
- ...(typeof structured === "string" ? { output: translateAdded(text, output.output) }
408
+ ...(typeof structured === "string" ? { output: final }
336
409
  : structured && typeof structured === "object" && typeof structured.output === "string"
337
- ? { output: { ...structured, output: translateAdded(text, output.output) } } : {}),
410
+ ? { output: { ...structured, output: final } } : {}),
338
411
  };
339
412
  }));
340
413
 
@@ -0,0 +1,165 @@
1
+ import { buildAgentOptions, effortCeilingFor, effortRank } from "../router/agent-options";
2
+ import { EFFORT_LEVELS, type EffortLevel, type TierConfig } from "../router/config";
3
+
4
+ export const EFFORT_OVERRIDE_KEYS = ["effort", "reasoningEffort"] as const;
5
+
6
+ type Logger = { warn(msg: string): void };
7
+ type Entry = {
8
+ tierName: string;
9
+ model: string;
10
+ keys: Partial<Record<(typeof EFFORT_OVERRIDE_KEYS)[number], unknown>>;
11
+ warnedMissingTarget: boolean;
12
+ warnedApplyFailure: boolean;
13
+ warnedAliasDeletion: boolean;
14
+ };
15
+
16
+ export interface EffortOverrideStore {
17
+ set(sessionID: string, tierName: string, tier: TierConfig, effort: EffortLevel): void;
18
+ clear(sessionID: string): void;
19
+ has(sessionID: string): boolean;
20
+ size(): number;
21
+ }
22
+
23
+ // Keep the public store API small and prevent callers from mutating saved keys.
24
+ const entriesByStore = new WeakMap<EffortOverrideStore, Map<string, Entry>>();
25
+
26
+ function warn(logger: Logger, message: string): void {
27
+ try {
28
+ logger.warn(message);
29
+ } catch {
30
+ // A failing logger must not turn a best-effort override into a hook failure.
31
+ return;
32
+ }
33
+ }
34
+
35
+ function nonempty(value: unknown): value is string {
36
+ return typeof value === "string" && value.trim().length > 0;
37
+ }
38
+
39
+ export function createEffortOverrideStore(
40
+ opts: { maxEntries?: number; logger?: Logger } = {},
41
+ ): EffortOverrideStore {
42
+ const logger = opts.logger ?? { warn: (message: string) => console.warn(`[model-router] ${message}`) };
43
+ const builderLogger = {
44
+ warn: (message: string) => warn(logger, message),
45
+ flush: () => Promise.resolve(),
46
+ };
47
+ const requestedMax = opts.maxEntries ?? 1_000;
48
+ const maxEntries = Number.isSafeInteger(requestedMax) && requestedMax > 0 ? requestedMax : 1_000;
49
+ if (maxEntries !== requestedMax) warn(logger, "Invalid effort override maxEntries; using 1000");
50
+ const entries = new Map<string, Entry>();
51
+ const store: EffortOverrideStore = {
52
+ set(sessionID, tierName, tier, effort) {
53
+ try {
54
+ entries.delete(sessionID);
55
+ if (!nonempty(sessionID) || !nonempty(tierName) || !tier || typeof tier !== "object") {
56
+ warn(logger, "Invalid effort override arguments; override refused");
57
+ return;
58
+ }
59
+ // Ordinary reads preserve inherited/non-enumerable fields, once per field.
60
+ // Validation, ceiling and builder all share this snapshot.
61
+ const model = tier.model;
62
+ const tierEffort = tier.effort;
63
+ const variant = tier.variant;
64
+ const thinking = tier.thinking;
65
+ const reasoning = tier.reasoning;
66
+ const snapshot = { model, effort: tierEffort, variant, thinking, reasoning };
67
+ if (!nonempty(model) || !EFFORT_LEVELS.includes(effort)) {
68
+ warn(logger, "Invalid effort override arguments; override refused");
69
+ return;
70
+ }
71
+ const separator = model.indexOf("/");
72
+ if (separator <= 0 || separator === model.length - 1) {
73
+ warn(logger, "Effort override requires a provider/model identity; override refused");
74
+ return;
75
+ }
76
+ const ceiling = effortCeilingFor(snapshot);
77
+ if (ceiling === null || effortRank(effort) > effortRank(ceiling)) {
78
+ warn(logger, `Effort override for ${sessionID} exceeds the tier ceiling; override refused`);
79
+ return;
80
+ }
81
+ const options = buildAgentOptions({ ...snapshot, effort }, tierName, builderLogger);
82
+ const keys: Entry["keys"] = {};
83
+ for (const key of EFFORT_OVERRIDE_KEYS) {
84
+ if (Object.hasOwn(options, key)) keys[key] = options[key];
85
+ }
86
+ if (Object.keys(keys).length === 0) {
87
+ warn(logger, `Effort override for ${sessionID} has no effort keys; override refused`);
88
+ return;
89
+ }
90
+ entries.set(sessionID, {
91
+ tierName, model, keys, warnedMissingTarget: false,
92
+ warnedApplyFailure: false, warnedAliasDeletion: false,
93
+ });
94
+ if (entries.size > maxEntries) {
95
+ // A positive capacity and overflow guarantee a first entry.
96
+ const oldest = entries.keys().next().value!;
97
+ entries.delete(oldest);
98
+ warn(logger, `Evicted oldest effort override for ${oldest}`);
99
+ }
100
+ } catch {
101
+ entries.delete(sessionID);
102
+ warn(logger, "Failed to register effort override");
103
+ }
104
+ },
105
+ clear(sessionID) { entries.delete(sessionID); },
106
+ has(sessionID) { return entries.has(sessionID); },
107
+ size() { return entries.size; },
108
+ };
109
+ entriesByStore.set(store, entries);
110
+ return store;
111
+ }
112
+
113
+ /** Apply only to the producer's provider-options object, chosen by the host adapter. */
114
+ export function applyEffortOverride(
115
+ store: EffortOverrideStore,
116
+ input: { sessionID?: unknown; agent?: unknown; model?: unknown },
117
+ target: unknown,
118
+ logger: Logger,
119
+ ): void {
120
+ let entry: Entry | undefined;
121
+ try {
122
+ const sessionID = input.sessionID;
123
+ if (typeof sessionID !== "string") return;
124
+ entry = entriesByStore.get(store)?.get(sessionID);
125
+ if (!entry || input.agent !== entry.tierName) return;
126
+ if (input.model === null || typeof input.model !== "object") return;
127
+ const model = input.model as { providerID?: unknown; modelID?: unknown; id?: unknown };
128
+ const providerID = model.providerID;
129
+ const modelID = model.modelID ?? model.id;
130
+ const separator = entry.model.indexOf("/");
131
+ if (typeof providerID !== "string" || typeof modelID !== "string"
132
+ || providerID.toLowerCase() !== entry.model.slice(0, separator).toLowerCase()
133
+ || modelID.toLowerCase() !== entry.model.slice(separator + 1).toLowerCase()) return;
134
+ if (target === null || typeof target !== "object") {
135
+ // Warning state lives with the bounded entry and is removed on clear/eviction.
136
+ if (!entry.warnedMissingTarget) {
137
+ entry.warnedMissingTarget = true;
138
+ warn(logger, `Missing provider-options target for effort override ${sessionID}`);
139
+ }
140
+ return;
141
+ }
142
+ const options = target as Record<string, unknown>;
143
+ for (const key of EFFORT_OVERRIDE_KEYS) {
144
+ if (Object.hasOwn(entry.keys, key)) {
145
+ options[key] = entry.keys[key];
146
+ if (key === "reasoningEffort") {
147
+ try {
148
+ delete options.reasoning_effort;
149
+ } catch {
150
+ if (!entry.warnedAliasDeletion) {
151
+ entry.warnedAliasDeletion = true;
152
+ warn(logger, `Applied native effort override for ${sessionID}, but failed to remove reasoning_effort alias`);
153
+ }
154
+ }
155
+ }
156
+ }
157
+ }
158
+ } catch {
159
+ // Session failure latches share the entry's capacity and clear/eviction lifetime.
160
+ if (!entry || !entry.warnedApplyFailure) {
161
+ if (entry) entry.warnedApplyFailure = true;
162
+ warn(logger, "Failed to apply effort override");
163
+ }
164
+ }
165
+ }