opencode-model-router 2.0.0 → 2.1.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +68 -0
- package/README.md +70 -4
- package/package.json +2 -2
- package/src/compat/child-session.ts +5 -0
- package/src/compat/v2-hooks.ts +47 -14
- package/src/escalate/effort-override.ts +165 -0
- package/src/escalate/ladder.ts +57 -7
- package/src/index.ts +180 -14
- package/src/router/agent-options.ts +43 -12
- package/src/router/config.ts +131 -20
- package/src/router/depth-guard.ts +152 -0
- package/src/router/depth.ts +826 -0
- package/src/v2.ts +1 -0
- package/src/verify/wiring.ts +16 -2
package/CHANGELOG.md
CHANGED
|
@@ -7,6 +7,74 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
|
|
|
7
7
|
|
|
8
8
|
## [Unreleased]
|
|
9
9
|
|
|
10
|
+
## [2.1.0] - 2026-10-05
|
|
11
|
+
|
|
12
|
+
Observations by @MetalbolicX in opencode-smart-router (#17); implementation written from scratch.
|
|
13
|
+
|
|
14
|
+
### Added
|
|
15
|
+
|
|
16
|
+
- Delegation depth guard (#66), configured by `enforcement.maxDelegationDepth`
|
|
17
|
+
(default `1`; `null` disables it).
|
|
18
|
+
- Effort bump before escalation (#67), configured by
|
|
19
|
+
`enforcement.escalate.effortBump` (default `true`) and
|
|
20
|
+
`enforcement.escalate.effortBumpMax` (default `"xhigh"`, further capped per model).
|
|
21
|
+
|
|
22
|
+
### Changed
|
|
23
|
+
|
|
24
|
+
- The automatic ladder's existing same-tier retry now runs one effort level higher
|
|
25
|
+
by default on eligible tiers: explicit valid `effort`, no `variant`, a recognised
|
|
26
|
+
Claude or OpenAI model family, no winning explicit provider setting, and room
|
|
27
|
+
below the effective ceiling. This adds no attempt and
|
|
28
|
+
still respects attempt and cost ceilings. It applies only to the optional
|
|
29
|
+
`delegate` tool's automatic ladder, not native `task`/`subagent` or manual retries.
|
|
30
|
+
Only `fable-effort` fast/medium are eligible among bundled presets; at the default
|
|
31
|
+
cost ceiling, a run starting at fast stops before medium's bump. Set
|
|
32
|
+
`enforcement.escalate.effortBump: false` to restore the previous retry behaviour.
|
|
33
|
+
- Dispatches past `enforcement.maxDelegationDepth` (default `1`) are warned in
|
|
34
|
+
`advisory` mode (the bundled default) with `[⚠ GUARD:delegation_depth]` and refused
|
|
35
|
+
in `enforced` mode. Set `enforcement.mode: "enforced"` to enforce it unless the
|
|
36
|
+
caller tier's `enforcement.perTier` entry overrides `mode`; `MODEL_ROUTER_ENFORCE=1`
|
|
37
|
+
overrides both and forces enforcement. Set `enforcement.maxDelegationDepth: null`
|
|
38
|
+
to opt out of the guard. Enforcement mode `off`, a caller-tier `perTier: "off"`
|
|
39
|
+
(unless the environment gate forces enforcement), and `/bypass on` also disable
|
|
40
|
+
the check. OpenCode 2's own
|
|
41
|
+
`experimental.subagent_depth` cap remains independent.
|
|
42
|
+
- On OpenCode 2, router-modified `subagent` results now keep the host's
|
|
43
|
+
`<subagent sessionID=…>` envelope part and append the router's text as a separate
|
|
44
|
+
part, preserving the resume handle instead of replacing the envelope with plain
|
|
45
|
+
text. This applies when host text exists and the router output starts with the
|
|
46
|
+
child's text after trimming trailing whitespace. Missing host text or a
|
|
47
|
+
non-suffix rewrite uses the full router output as one text part instead, retaining
|
|
48
|
+
non-text attachments without losing or duplicating the child's text. Structured
|
|
49
|
+
output and metadata handling are unchanged.
|
|
50
|
+
|
|
51
|
+
### Fixed
|
|
52
|
+
|
|
53
|
+
- **OpenCode v1 behaviour change:** tier `effort` (for OpenAI-family models),
|
|
54
|
+
`reasoning.*` and `thinking.budgetTokens` settings that v1 silently dropped now
|
|
55
|
+
reach requests through provider-native registered keys: `reasoningEffort`,
|
|
56
|
+
`reasoningSummary` and `thinking: { type: "enabled", budgetTokens }`. User config
|
|
57
|
+
keys and provider-specific precedence/gates are unchanged; Claude `effort` was
|
|
58
|
+
already registered with its native key.
|
|
59
|
+
- OpenAI-family detection is regex-based: Copilot/OpenRouter/Azure `gpt-*`,
|
|
60
|
+
`gpt-oss` through Ollama/Groq, and non-reasoning GPT models with configured
|
|
61
|
+
`effort` or explicit `reasoning.effort` now receive `reasoningEffort` (and
|
|
62
|
+
configured summaries use `reasoningSummary`). IDs containing `o1`/`o3`/`o4`
|
|
63
|
+
delimited by `/`, `-` or `_` (or the start/end of the ID), including bare IDs
|
|
64
|
+
and false positives such as `mistral/magistral-o1`, are also treated as OpenAI.
|
|
65
|
+
OpenAI-family tiers with a truthy `thinking.budgetTokens` now also send
|
|
66
|
+
`thinking: { type: "enabled", budgetTokens }`; non-Claude budgets are not gated.
|
|
67
|
+
Whether the SDK strips unsupported options for non-reasoning models is unverified.
|
|
68
|
+
- Claude tiers with an applicable `thinking.budgetTokens` now send `thinking`;
|
|
69
|
+
adaptive-only Claude still drops manual budgets. Unknown-family tiers (such
|
|
70
|
+
as Bedrock Claude or Gemini) with explicit `thinking.budgetTokens` or
|
|
71
|
+
`reasoning.*` also receive the native keys; their provider effect is unverified.
|
|
72
|
+
- Latency/cost may rise, or a provider may reject newly delivered settings.
|
|
73
|
+
To restore the previous behaviour, remove `effort`, `reasoning.*` or `thinking`
|
|
74
|
+
from the affected tier. **Bundled presets are unaffected by this registration
|
|
75
|
+
fix:** none sets `reasoning` or `thinking`, and their explicit `effort` settings
|
|
76
|
+
are Claude's already-native key.
|
|
77
|
+
|
|
10
78
|
## [2.0.0] - 2026-10-04
|
|
11
79
|
|
|
12
80
|
The router now runs on OpenCode v2 through a separate server entrypoint. **OpenCode v1
|
package/README.md
CHANGED
|
@@ -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`/`
|
|
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
|
|
@@ -480,7 +481,11 @@ highest first:
|
|
|
480
481
|
provider-specific setting always wins, and a one-time warning names the tier.
|
|
481
482
|
2. `effort`.
|
|
482
483
|
|
|
483
|
-
**Unset means unset**:
|
|
484
|
+
**Unset means unset**: without `effort` or an explicit `reasoning.effort`, neither
|
|
485
|
+
`effort` nor `reasoningEffort` is registered. User config keys remain
|
|
486
|
+
`reasoning.effort`, `reasoning.summary` and `thinking.budgetTokens`; registered
|
|
487
|
+
provider options use `reasoningEffort`, `reasoningSummary` and
|
|
488
|
+
`thinking: { type: "enabled", budgetTokens }` respectively.
|
|
484
489
|
|
|
485
490
|
Explicit fields are gated by model family: Claude drops `reasoning.effort`/`reasoning.summary`; adaptive-only Claude also ignores `thinking.budgetTokens`, leaving `effort` applicable.
|
|
486
491
|
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 +493,7 @@ Each drop warns once per tier; non-Claude explicit fields are unchanged. See the
|
|
|
488
493
|
| Model family | Registered as | Caveats |
|
|
489
494
|
|---|---|---|
|
|
490
495
|
| 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.
|
|
496
|
+
| OpenAI | `options.reasoningEffort` | Supports only `low`/`medium`/`high`; `xhigh` and `max` are downgraded to `high` with a warning. |
|
|
492
497
|
| 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
498
|
|
|
494
499
|
An out-of-set value in `tiers.json` fails validation at load; one that arrives any other
|
|
@@ -932,6 +937,67 @@ That deferral is the v1.15.0 default (`enforcement.verify.defaultVerify: "deferr
|
|
|
932
937
|
- **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
938
|
- **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
939
|
|
|
940
|
+
### Delegation depth guard
|
|
941
|
+
|
|
942
|
+
The guard checks model-initiated dispatches through native `task` (OpenCode v1),
|
|
943
|
+
`subagent` (OpenCode 2), and the router's optional `delegate` tool, including resumes.
|
|
944
|
+
`enforcement.maxDelegationDepth` defaults to `1`: the root orchestrator is depth 0,
|
|
945
|
+
so it may delegate, but its depth-1 children would exceed the limit by delegating again.
|
|
946
|
+
|
|
947
|
+
- **`advisory` (bundled default):** allows the dispatch and warns with
|
|
948
|
+
`[⚠ GUARD:delegation_depth]` in its result; it does not refuse it.
|
|
949
|
+
- **`enforced`:** refuses a dispatch past the limit before another subagent runs.
|
|
950
|
+
Set `enforcement.mode: "enforced"` or `MODEL_ROUTER_ENFORCE=1` to enforce it.
|
|
951
|
+
The caller tier's `enforcement.perTier` override applies unless the environment
|
|
952
|
+
gate overrides it.
|
|
953
|
+
- **`off`:** skips the check. Set `enforcement.maxDelegationDepth: null` to disable
|
|
954
|
+
just this guard, or use an integer from 1 to 32 to change the depth limit.
|
|
955
|
+
|
|
956
|
+
This is not a sandbox: shell-launched `opencode run` and other plugins' session
|
|
957
|
+
tools are outside its scope. `/bypass on` also disables the depth guard. If the
|
|
958
|
+
caller depth cannot be resolved, the guard fails open with a logged warning.
|
|
959
|
+
OpenCode 2 has its own independent `experimental.subagent_depth` cap (default 1):
|
|
960
|
+
raising or disabling the router limit does not lift that host cap. With both caps
|
|
961
|
+
enforced, the lower one wins. V2's `general` agent also needs explicit `subagent`
|
|
962
|
+
permission to dispatch. The Phase 2.3 host proof on OpenCode v1 1.18.19 likewise encountered
|
|
963
|
+
a host cap and used top-level `subagent_depth: 4` to lift it; its default and upstream
|
|
964
|
+
documentation are unverified. Raising only the router limit does not lift a host cap.
|
|
965
|
+
These are observations from the [host-proof fixtures](docs/qa/depth-and-effort/phase-2.3.md#handoffs),
|
|
966
|
+
not a documented cross-version default for v1.
|
|
967
|
+
|
|
968
|
+
See the [configuration reference](docs/CONFIG_REFERENCE.md) and
|
|
969
|
+
[design decisions and scope limits](docs/adr/0004-delegation-depth-and-effort-bump.md).
|
|
970
|
+
|
|
971
|
+
### Effort bump before escalation
|
|
972
|
+
|
|
973
|
+
The automatic escalation ladder uses its existing same-tier retry to try **one
|
|
974
|
+
effort level higher** before moving to a more expensive tier. It adds no attempt.
|
|
975
|
+
`enforcement.escalate.effortBump` defaults to `true`, and `effortBumpMax` defaults
|
|
976
|
+
to `"xhigh"`, further capped by model family (OpenAI: `high`; Claude: `max`). Set
|
|
977
|
+
`enforcement.escalate.effortBump: false` to restore the previous ladder behaviour.
|
|
978
|
+
|
|
979
|
+
An eligible tier must set an explicit valid `effort`, have no `variant`, belong to
|
|
980
|
+
a recognised Claude or OpenAI model family, and have room below the effective ceiling.
|
|
981
|
+
A winning explicit provider setting
|
|
982
|
+
(`reasoning.effort` or an applicable `thinking.budgetTokens`) prevents the bump.
|
|
983
|
+
It changes only that retry producer's options, not the preset, titles or graders.
|
|
984
|
+
The bump applies to the optional `delegate` tool's automatic ladder, not native
|
|
985
|
+
`task`/`subagent` calls or manual retries; deferred verification does not retry.
|
|
986
|
+
`/bypass` leaves the ladder and effort bump active; use `effortBump: false` to disable
|
|
987
|
+
the bump.
|
|
988
|
+
|
|
989
|
+
Among bundled presets, **only `fable-effort` fast and medium are eligible**
|
|
990
|
+
(`low → medium` and `high → xhigh`). Its heavy tier is already at the default
|
|
991
|
+
ceiling; all other presets either set a variant or omit `effort`. In particular,
|
|
992
|
+
the default `anthropic` preset has no bumpable tier. Attempt and cost ceilings
|
|
993
|
+
still apply: starting at fast with the default cost multiple of 4, `fable-effort`
|
|
994
|
+
runs `fast@low → fast@medium → medium@high`, then stops on cost; medium's bump
|
|
995
|
+
is not reached. Raise `enforcement.escalate.costCeiling.multiple` to allow it.
|
|
996
|
+
|
|
997
|
+
See the [configuration reference](docs/CONFIG_REFERENCE.md) for eligibility and
|
|
998
|
+
cost settings, and the [ADR](docs/adr/0004-delegation-depth-and-effort-bump.md) for
|
|
999
|
+
trade-offs and host evidence (real-provider acceptance of bumped values is unverified).
|
|
1000
|
+
|
|
935
1001
|
### Tuning enforcement
|
|
936
1002
|
|
|
937
1003
|
Advisory is the default. To change the level:
|
|
@@ -946,7 +1012,7 @@ Set `taskPromptRepair: false` to restore the previous behaviour; see [configurat
|
|
|
946
1012
|
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
1013
|
If every changed file is absolute and outside the verification base, deterministic checks return unverifiable instead of running in the wrong directory.
|
|
948
1014
|
|
|
949
|
-
**Modes:** `off` —
|
|
1015
|
+
**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
1016
|
|
|
951
1017
|
> Enforcement applies to subagent/delegate sessions only. The orchestrator session is never hard-blocked.
|
|
952
1018
|
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "opencode-model-router",
|
|
3
|
-
"version": "2.
|
|
3
|
+
"version": "2.1.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
|
};
|
package/src/compat/v2-hooks.ts
CHANGED
|
@@ -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> =>
|
|
@@ -126,12 +127,11 @@ export async function registerV2Hooks(
|
|
|
126
127
|
for (const [name, definition] of Object.entries(config.agent)) {
|
|
127
128
|
if (originals.get(name) === JSON.stringify(definition) || !definition.options) continue;
|
|
128
129
|
const { reasoning_effort, reasoning_summary, budget_tokens, ...options } = definition.options;
|
|
129
|
-
|
|
130
|
-
|
|
131
|
-
|
|
132
|
-
|
|
133
|
-
|
|
134
|
-
});
|
|
130
|
+
const normalized = { ...options };
|
|
131
|
+
if (reasoning_effort !== undefined && normalized.reasoningEffort === undefined) normalized.reasoningEffort = reasoning_effort;
|
|
132
|
+
if (reasoning_summary !== undefined && normalized.reasoningSummary === undefined) normalized.reasoningSummary = reasoning_summary;
|
|
133
|
+
if (budget_tokens !== undefined && normalized.thinking === undefined) normalized.thinking = { type: "enabled", budgetTokens: budget_tokens };
|
|
134
|
+
agentOptions.set(name, normalized);
|
|
135
135
|
}
|
|
136
136
|
registrations.push(await ctx.agent.transform((editor) => {
|
|
137
137
|
if (runtime) editor.update(V2_GRADER_AGENT, (agent) => {
|
|
@@ -289,6 +289,12 @@ export async function registerV2Hooks(
|
|
|
289
289
|
await legacy["tool.execute.before"]?.({ ...event, tool: legacyToolName(event.tool), callID: event.id }, output);
|
|
290
290
|
});
|
|
291
291
|
const verifying = (output as Record<PropertyKey, unknown>)[TASK_VERIFICATION] === true;
|
|
292
|
+
const banner = (output as Record<PropertyKey, unknown>)[DEPTH_BANNER];
|
|
293
|
+
if (typeof banner === "string") {
|
|
294
|
+
depthBanners.delete(event.id);
|
|
295
|
+
depthBanners.set(event.id, banner);
|
|
296
|
+
while (depthBanners.size > 1000) depthBanners.delete(depthBanners.keys().next().value!);
|
|
297
|
+
}
|
|
292
298
|
if (verifying) {
|
|
293
299
|
verifyingCalls.add(event.id);
|
|
294
300
|
while (verifyingCalls.size > 1000) verifyingCalls.delete(verifyingCalls.values().next().value!);
|
|
@@ -300,14 +306,20 @@ export async function registerV2Hooks(
|
|
|
300
306
|
event.input = nativeArgs(event.tool, output.args, original, verifying);
|
|
301
307
|
}));
|
|
302
308
|
registrations.push(await ctx.tool.hook("execute.after", async (event) => {
|
|
309
|
+
const banner = depthBanners.get(event.id);
|
|
310
|
+
depthBanners.delete(event.id);
|
|
303
311
|
const verifying = verifyingCalls.delete(event.id);
|
|
304
312
|
if (event.status !== "completed") return;
|
|
305
313
|
const structured = event.result.output;
|
|
306
314
|
// A user can background a foreground subagent while it is running. That
|
|
307
315
|
// acknowledgement is not a final result and must never enter acceptance.
|
|
308
316
|
if (event.tool === "subagent" && structured?.status === "running") {
|
|
309
|
-
|
|
310
|
-
|
|
317
|
+
const notices = [
|
|
318
|
+
...(verifying ? ["[router] This subagent is still running. Its result has not been verified; automatic acceptance requires a completed foreground return."] : []),
|
|
319
|
+
...(banner === undefined ? [] : [banner]),
|
|
320
|
+
];
|
|
321
|
+
if (!notices.length) return;
|
|
322
|
+
const notice = notices.join("\n\n");
|
|
311
323
|
const content = Array.isArray(event.result.content) ? [...event.result.content]
|
|
312
324
|
: typeof event.result.content === "string" ? [{ type: "text" as const, text: event.result.content }] : [];
|
|
313
325
|
event.result = {
|
|
@@ -326,15 +338,36 @@ export async function registerV2Hooks(
|
|
|
326
338
|
callID: event.id, args: await scopedArgs(event),
|
|
327
339
|
}, output);
|
|
328
340
|
});
|
|
329
|
-
|
|
330
|
-
|
|
341
|
+
const changed = output.output !== text;
|
|
342
|
+
if (!changed && banner === undefined) return;
|
|
343
|
+
const routed = changed ? translateAdded(text, output.output) : text;
|
|
344
|
+
const final = banner === undefined ? routed : [routed.trimEnd(), banner].filter(Boolean).join("\n\n");
|
|
345
|
+
const content = Array.isArray(event.result.content) ? [...event.result.content]
|
|
346
|
+
: typeof event.result.content === "string" ? [{ type: "text" as const, text: event.result.content }] : [];
|
|
347
|
+
const childText = text.trimEnd();
|
|
348
|
+
const routedText = routed.trimEnd();
|
|
349
|
+
let visible;
|
|
350
|
+
if (event.tool === "subagent" && structured && typeof structured === "object" && typeof structured.output === "string"
|
|
351
|
+
&& content.some((part) => part.type === "text") && routedText.startsWith(childText)) {
|
|
352
|
+
// The host's visible text owns the session envelope (and resume handle).
|
|
353
|
+
// Footer helpers trim the bare output. Compare trimmed tails before taking
|
|
354
|
+
// only the router's suffix; other rewrites must replace, not repeat, it.
|
|
355
|
+
const suffix = changed ? routedText.slice(childText.length) : "";
|
|
356
|
+
const notices = [suffix, banner].filter((part) => part !== undefined && part !== "").join("\n\n");
|
|
357
|
+
visible = [
|
|
358
|
+
...content,
|
|
359
|
+
...(notices ? [{ type: "text" as const, text: notices }] : []),
|
|
360
|
+
];
|
|
361
|
+
} else {
|
|
362
|
+
visible = [{ type: "text" as const, text: final }, ...content.filter((part) => part.type !== "text")];
|
|
363
|
+
}
|
|
331
364
|
event.result = {
|
|
332
365
|
...event.result,
|
|
333
|
-
content:
|
|
366
|
+
content: visible,
|
|
334
367
|
metadata: output.metadata,
|
|
335
|
-
...(typeof structured === "string" ? { output:
|
|
368
|
+
...(typeof structured === "string" ? { output: final }
|
|
336
369
|
: structured && typeof structured === "object" && typeof structured.output === "string"
|
|
337
|
-
? { output: { ...structured, output:
|
|
370
|
+
? { output: { ...structured, output: final } } : {}),
|
|
338
371
|
};
|
|
339
372
|
}));
|
|
340
373
|
|
|
@@ -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
|
+
}
|
package/src/escalate/ladder.ts
CHANGED
|
@@ -1,15 +1,22 @@
|
|
|
1
|
-
import
|
|
1
|
+
import { effortCeilingFor, effortRank, minEffort, nextEffort } from "../router/agent-options";
|
|
2
|
+
import { resolveEffortBump, type EffortLevel, type RouterConfig } from "../router/config";
|
|
3
|
+
import { getActiveTiers } from "../router/protocol";
|
|
2
4
|
|
|
3
5
|
// ---------------------------------------------------------------------------
|
|
4
6
|
// Types
|
|
5
7
|
// ---------------------------------------------------------------------------
|
|
6
8
|
|
|
9
|
+
export interface EffortBumpPolicy {
|
|
10
|
+
perTier: Record<string, { base: EffortLevel; bound: EffortLevel }>;
|
|
11
|
+
}
|
|
12
|
+
|
|
7
13
|
export interface EscalatePolicy {
|
|
8
14
|
ladder: string[];
|
|
9
15
|
floorTier?: string | null;
|
|
10
16
|
maxAttemptsPerTier: number;
|
|
11
17
|
maxTotalAttempts: number;
|
|
12
18
|
costMultiple?: number | null;
|
|
19
|
+
effortBump?: EffortBumpPolicy | null;
|
|
13
20
|
}
|
|
14
21
|
|
|
15
22
|
export interface LadderState {
|
|
@@ -19,6 +26,7 @@ export interface LadderState {
|
|
|
19
26
|
escalations: number;
|
|
20
27
|
firstAttemptCost: number | null;
|
|
21
28
|
cumulativeCost: number;
|
|
29
|
+
currentEffort?: EffortLevel | null;
|
|
22
30
|
}
|
|
23
31
|
|
|
24
32
|
export type LadderActionKind = "accept" | "retry" | "escalate" | "give_up";
|
|
@@ -28,6 +36,7 @@ export interface LadderAction {
|
|
|
28
36
|
tier?: string;
|
|
29
37
|
forcingMessage?: string;
|
|
30
38
|
reason?: string;
|
|
39
|
+
effort?: EffortLevel;
|
|
31
40
|
}
|
|
32
41
|
|
|
33
42
|
export interface LadderVerdict {
|
|
@@ -59,7 +68,7 @@ export function newLadderState(
|
|
|
59
68
|
producerTier: string,
|
|
60
69
|
policy: EscalatePolicy,
|
|
61
70
|
): LadderState {
|
|
62
|
-
|
|
71
|
+
const state: LadderState = {
|
|
63
72
|
currentTier: resolveStartTier(producerTier, policy),
|
|
64
73
|
attemptsThisTier: 0,
|
|
65
74
|
totalAttempts: 0,
|
|
@@ -67,6 +76,8 @@ export function newLadderState(
|
|
|
67
76
|
firstAttemptCost: null,
|
|
68
77
|
cumulativeCost: 0,
|
|
69
78
|
};
|
|
79
|
+
if (policy.effortBump) state.currentEffort = null;
|
|
80
|
+
return state;
|
|
70
81
|
}
|
|
71
82
|
|
|
72
83
|
export function recordAttempt(
|
|
@@ -141,11 +152,25 @@ export function nextAction(
|
|
|
141
152
|
|
|
142
153
|
// (5) retry within tier
|
|
143
154
|
if (state.attemptsThisTier < policy.maxAttemptsPerTier) {
|
|
144
|
-
|
|
155
|
+
const action: LadderAction = {
|
|
145
156
|
action: "retry",
|
|
146
157
|
tier: state.currentTier,
|
|
147
158
|
forcingMessage: buildLadderForcingMessage(verdict?.reasons ?? []),
|
|
148
159
|
};
|
|
160
|
+
const perTier = policy.effortBump?.perTier;
|
|
161
|
+
const bump = perTier && Object.prototype.hasOwnProperty.call(perTier, state.currentTier)
|
|
162
|
+
? perTier[state.currentTier] : undefined;
|
|
163
|
+
if (bump) {
|
|
164
|
+
const current = state.currentEffort ?? bump.base;
|
|
165
|
+
const startingEffort = minEffort(
|
|
166
|
+
effortRank(current) < effortRank(bump.base) ? bump.base : current,
|
|
167
|
+
bump.bound,
|
|
168
|
+
);
|
|
169
|
+
const effort = nextEffort(startingEffort, bump.bound)
|
|
170
|
+
?? (state.currentEffort == null ? undefined : startingEffort);
|
|
171
|
+
if (effort !== undefined) action.effort = effort;
|
|
172
|
+
}
|
|
173
|
+
return action;
|
|
149
174
|
}
|
|
150
175
|
|
|
151
176
|
// (6) escalate or give_up
|
|
@@ -165,15 +190,19 @@ export function nextAction(
|
|
|
165
190
|
|
|
166
191
|
export function advance(state: LadderState, action: LadderAction): LadderState {
|
|
167
192
|
if (action.action === "retry") {
|
|
168
|
-
|
|
193
|
+
const next = { ...state, attemptsThisTier: state.attemptsThisTier + 1 };
|
|
194
|
+
if (action.effort !== undefined) next.currentEffort = action.effort;
|
|
195
|
+
return next;
|
|
169
196
|
}
|
|
170
197
|
if (action.action === "escalate") {
|
|
171
|
-
|
|
198
|
+
const next = {
|
|
172
199
|
...state,
|
|
173
200
|
currentTier: action.tier!,
|
|
174
201
|
attemptsThisTier: 0,
|
|
175
202
|
escalations: state.escalations + 1,
|
|
176
203
|
};
|
|
204
|
+
if (next.currentEffort !== undefined) next.currentEffort = null;
|
|
205
|
+
return next;
|
|
177
206
|
}
|
|
178
207
|
// accept / give_up — terminal, return unchanged
|
|
179
208
|
return state;
|
|
@@ -181,13 +210,34 @@ export function advance(state: LadderState, action: LadderAction): LadderState {
|
|
|
181
210
|
|
|
182
211
|
export function buildEscalatePolicy(cfg: RouterConfig): EscalatePolicy {
|
|
183
212
|
const esc = cfg.enforcement?.escalate;
|
|
184
|
-
|
|
213
|
+
const policy: EscalatePolicy = {
|
|
185
214
|
ladder: esc?.ladder ?? ["fast", "medium", "heavy"],
|
|
186
215
|
floorTier: esc?.floorTier ?? null,
|
|
187
216
|
maxAttemptsPerTier: esc?.maxAttemptsPerTier ?? 1,
|
|
188
217
|
maxTotalAttempts: esc?.maxTotalAttempts ?? 4,
|
|
189
218
|
costMultiple: esc?.costCeiling?.multiple ?? 4,
|
|
190
219
|
};
|
|
220
|
+
const effortBump = buildEffortBump(cfg);
|
|
221
|
+
// Keep bump-off policies byte-identical to the original golden fixture.
|
|
222
|
+
if (effortBump) policy.effortBump = effortBump;
|
|
223
|
+
return policy;
|
|
224
|
+
}
|
|
225
|
+
|
|
226
|
+
function buildEffortBump(cfg: RouterConfig): EffortBumpPolicy | null {
|
|
227
|
+
const { enabled, max } = resolveEffortBump(cfg);
|
|
228
|
+
if (!enabled) return null;
|
|
229
|
+
const entries: Array<[string, { base: EffortLevel; bound: EffortLevel }]> = [];
|
|
230
|
+
for (const [name, tier] of Object.entries(getActiveTiers(cfg) ?? {})) {
|
|
231
|
+
if (typeof tier?.model !== "string") continue;
|
|
232
|
+
const ceiling = effortCeilingFor(tier);
|
|
233
|
+
// A non-null ceiling also validates the configured effort (D7).
|
|
234
|
+
if (ceiling === null || tier.effort === undefined) continue;
|
|
235
|
+
const base = tier.effort;
|
|
236
|
+
const bound = minEffort(ceiling, max);
|
|
237
|
+
if (effortRank(bound) <= effortRank(base)) continue;
|
|
238
|
+
entries.push([name, { base, bound }]);
|
|
239
|
+
}
|
|
240
|
+
return entries.length > 0 ? { perTier: Object.fromEntries(entries) } : null;
|
|
191
241
|
}
|
|
192
242
|
|
|
193
243
|
/**
|
|
@@ -199,7 +249,7 @@ export function formatLadderScorecard(
|
|
|
199
249
|
method: string,
|
|
200
250
|
): string {
|
|
201
251
|
return (
|
|
202
|
-
`[router delegate scorecard | final_tier=${state.currentTier} | ` +
|
|
252
|
+
`[router delegate scorecard | final_tier=${state.currentTier}${state.currentEffort ? `@${state.currentEffort}` : ""} | ` +
|
|
203
253
|
`attempts=${state.totalAttempts} | escalations=${state.escalations} | ` +
|
|
204
254
|
`cost=${state.cumulativeCost} | verdict=${accepted ? "PASS" : "UNMET"} | ` +
|
|
205
255
|
`method=${method}]`
|