Adaptive, self-learning subagent routing for OpenCode V2. Simple subagent tasks run on faster, cheaper models; hard work stays on the parent — and when a cheap model struggles on a class of task, the router remembers locally and automatically steps up a rung next time.
By default, OpenCode subagents inherit the calling agent's model unless you pin a specific model. Running a frontier reasoning model such as Astra or Fable for a grep search or a documentation lookup increases cost and latency. Pinning one cheap model to every subagent does not work either because agents like @general handle both simple lookups and complex tasks.
Static routing rules also have a limit: some tasks look simple from the prompt alone, yet a smaller model fails or thrashes on them.
This plugin solves both problems without a third-party router or extra API keys:
- In each root session, the plugin builds a capability-labeled downgrade ladder from your enabled OpenCode models. It writes that ladder to the session with OpenCode V2's keyed
session.instructionsAPI so the parent model can select a cheaper rung directly at zero added latency. - If the parent model omits
model, a stateless fallback evaluator runs on the cheapest rung through OpenCode's nativeexperimental.generate.textAPI. - The plugin records each routing decision and post-execution outcome (
ok,thrash,error,interrupted,retried) in a local SQLite database. - When vector escalation is enabled, the plugin embeds each prompt locally in pure TypeScript. If a cheap model has failed on similar past tasks for the same agent, the plugin steps the request up one rung or back to the parent model.
The plugin never upgrades above the parent model, never overrides an explicit valid model or variant outside the ladder, and never routes nested subagents. If a timeout or provider error occurs, the plugin fails open to the parent model; if a Model2Vec download fails, the vector check is disabled and ordinary routing continues without vector escalation.
Requires OpenCode V2 and Node.js 20 or newer:
npx @jacobwolf/opencode-subagent-router@latest install
The installer detects opencode --version and adds the package to plugins. It reads OPENCODE_CONFIG if set; otherwise it uses $XDG_CONFIG_HOME/opencode (default ~/.config/opencode). It prefers an existing opencode.jsonc file over opencode.json. The installer preserves comments and unrelated settings, creates a backup before editing, and skips duplicate entries. OpenCode downloads the plugin directly and links nothing into npx's temporary cache.
npx @jacobwolf/opencode-subagent-router@latest install --project
npx @jacobwolf/opencode-subagent-router@latest install --dry-run
npx @jacobwolf/opencode-subagent-router@latest install --config ./opencode.jsonc --opencode-version 2
OpenCode reloads configuration automatically. Run /reload if the plugin does not appear.
To install manually, add the package to opencode.json:
{
"$schema": "https://opencode.ai/config.json",
"plugins": ["@jacobwolf/opencode-subagent-router"]
}
The plugin needs no separate API key or external classifier service. It writes all routing and escalation logs under the subagent-router service in the OpenCode server log.
Before a child session starts, the plugin sets model on the subagent tool (or target.model and variant on T3 delegate_task). It skips follow-ups to existing subagents and tasks that pin a model outside the downgrade ladder.
Telemetry is enabled by default and writes to $XDG_DATA_HOME/opencode/subagent-router.db (default ~/.local/share/opencode/subagent-router.db). When you enable vectors, the plugin stores prompt embeddings alongside those runs as SQLite BLOBs. It runs in pure TypeScript and requires no ONNX runtime, WASM binary, or native addon.
The escalation guard only steps up. It never uses vectors to downgrade a task, so a familiar topic does not force a hard task onto a small model. Escalation triggers only when all of these conditions are true:
- At least 2 settled runs exist for the same
agent, canonical model, and#variant. - Those runs have cosine similarity
>= 0.85to the current prompt. - At least 50% of those matching runs ended with a confirmed failure outcome (
thrash,error, orinterrupted).
The plugin normalizes each model to its canonical identity while preserving #variant, so history transfers across providers. For example, openrouter/openai/gpt-6-luna#low matches openai/gpt-6-luna#low. Likewise, claude-agent/haiku#low, openrouter/anthropic/claude-haiku-4.5#low, and anthropic/claude-haiku-4-5#low share the same history.
Model weights load asynchronously in the background when the plugin starts. If a subagent runs before the weights finish , the plugin skips the vector check with zero delay and embeds the queued run after the weights load. Once loaded, embedding takes under 0.2ms per prompt, and scanning local SQLite history takes a few milliseconds.
Because Model2Vec runs in pure TypeScript on your CPU, choose a model based on available RAM and disk space:
| Backend / Model | Dimensions | Disk cache | Steady heap RAM | Peak load RSS | SQLite per 10k runs | Recommended hardware |
|---|---|---|---|---|---|---|
model2vec /minishlab/potion-base-2M (default) |
64d | ~7.9 MB | ~12–15 MB (~7.2 MB weights) | ~35–40 MB | ~2.5 MB | 8 GB+ RAM (most laptops, desktops, and VMs). |
model2vec /minishlab/potion-base-8M |
256d | ~29.5 MB | ~33–40 MB (~28.8 MB weights) | ~60–75 MB | ~10 MB | 16 GB+ RAM desktops and workstations that need higher accuracy on paraphrased prompts. |
ngram |
256d | 0 MB | <1 MB | <1 MB | ~10 MB | Air-gapped networks, CI, or low-RAM containers. Downloads nothing and hashes tokens and character trigrams with Bun.hash.murmur32v3 . |
Use minishlab/potion-base-2M by default. Switch to minishlab/potion-base-8M if you have extra RAM and want 256-dimensional vectors. Use ngram if you need offline operation with zero downloads.
Add this block to opencode.json to enable vector escalation:
{
"$schema": "https://opencode.ai/config.json",
"plugins": [
{
"package": "@jacobwolf/opencode-subagent-router",
"options": {
"vectors": {
"enabled": true,
"backend": "model2vec",
"model": "minishlab/potion-base-2M"
}
}
}
]
}
When backend is model2vec, the plugin downloads tokenizer.json and model.safetensors once into $XDG_CACHE_HOME/opencode/subagent-router/models/. The plugin enforces these checks on every download and cache read:
- Pinned manifest : The plugin accepts only
minishlab/potion-base-2Mandminishlab/potion-base-8M. Each entry pins an immutable 40-character Hugging Face commit SHA and SHA-256 digest. The plugin rejects arbitrary repos and mutable refs such asmain. - Restricted HTTP transport : Downloads use Effect's
FetchHttpClientover HTTPS only, withredirect: "manual",credentials: "omit", and trace propagation disabled. The plugin allows at most 5 redirects and requires every hop to stay onhuggingface.co,*.hf.co, or*.huggingface.co. - Bounded streams and atomic cache writes : Response streams fail if they exceed the artifact's byte limit. The plugin validates the cache path against path traversal and writes files atomically with
0700directory and0600file permissions. - Digest verification on every load : The plugin computes the SHA-256 digest with
Bun.CryptoHasherbefore caching and again on every cache read. If a cached file changes or truncates, the plugin discards it and downloads a verified copy.
The router builds the downgrade ladder from OpenCode's enabled provider catalog in this order:
- The last matching route override, if it changes the model or lowers reasoning effort.
- Every compatible, strictly cheaper model in the same lab generation, ordered cheapest first. Models that cannot be ordered by price are skipped.
- The same model at
loweffort (parent#low) when the parent useshigh,xhigh, ormax, appended as the topfocusedrung. - The cheapest eligible exact-family sibling.
Cross-model selection stays on the same enabled OpenCode provider. The router infers lab, lineage, and major version from Models.dev metadata. It reads OpenCode's local models.json cache first, then falls back to live Models.dev, then to the bundled snapshot.
A candidate model must meet all of these requirements:
- Input and output prices are no higher than the parent at every compared context tier, with at least one price strictly lower.
- The model preserves the parent's tool-calling support, modalities, and output token limit.
- The context window is at least
min(parent.context, 200_000)tokens.
The router excludes service-tier variants (-fast, -flex, -ultrafast) and collapses same-price aliases into one candidate. Subscription or non-list prices fall back to Models.dev list prices. If identity or cost metadata is ambiguous, the router skips only the cross-model step.
The fallback evaluator runs only when the parent omits model and a fast target exists. Search, read-only research, mechanical edits, review, and bounded implementation can downgrade to a matching rung. Architecture, diagnosis, low-confidence results, and tasks that need deep reasoning stay on the parent model.
OpenCode's Claude Agent provider (claude-agent) uses a Claude subscription through the Agent SDK and works like any other provider. The plugin matches its models (opus, sonnet, haiku, fable, and full IDs such as claude-sonnet-5) to Anthropic entries on Models.dev by ID or display name. Because subscriptions report no price, the plugin compares Anthropic list prices instead. For example, claude-agent/fable routes simple work to claude-agent/haiku#low or claude-agent/opus#low.
All options are optional. Use route overrides when catalog metadata is incomplete:
{
"$schema": "https://opencode.ai/config.json",
"plugins": [
{
"package": "@jacobwolf/opencode-subagent-router",
"options": {
"mode": "hybrid",
"evaluator": "lowest",
"timeoutMs": 3000,
"confidenceMin": 0.6,
"telemetry": true,
"vectors": {
"enabled": true,
"backend": "model2vec",
"model": "minishlab/potion-base-2M"
},
"routes": [
{
"parent": {
"model": "anthropic/claude-fable-5.1",
"variant": ["high", "max"]
},
"fast": [{ "model": "anthropic/claude-haiku-5-5" }, { "model": "anthropic/claude-opus-5-5" }]
}
]
}
}
]
}
mode:"hybrid"(default; parent instructions and fallback evaluator),"parent"(instructions and validation only), or"classifier"(fallback evaluator only).evaluator:"lowest"(default; uses the cheapest rung on the ladder),"none"(disables the fallback evaluator), or an explicit model spec such as"openai/gpt-6-luna#low".timeoutMs: Timeout in milliseconds for the fallback evaluator and catalog load (default3000).confidenceMin: Minimum confidence from0to1(default0.6) required for the fallback evaluator to downgrade.telemetry:true(default). Records routing decisions and outcomes in local SQLite ($XDG_DATA_HOME/opencode/subagent-router.db, ortelemetryPathif set).vectors:{ "enabled": false, "backend": "model2vec", "model": "minishlab/potion-base-2M" }(default). Enables local prompt embeddings and history-based escalation whentelemetryistrue.routes: Explicitprovider/modeloverrides. Setfastto one target or a cheapest-first ladder. The last matching route wins. Omitparent.variantto match every variant of that parent model.
Issues and PRs are welcome. For user-facing changes, run bun run changeset and commit the generated release note with your PR. See the release guide for choosing a version bump and preparing a release through the tag-triggered npm publishing workflow.
CI runs these checks:
bun install
bun run fmt:check
bun run lint
bun run lint:ts
bun run typecheck
bun run test:coverage