opencode-auto-shift
v0.5.1
Published
An automatic gearbox for your OpenCode models — eco/normal/sport drive modes, auto-shift reasoning effort per message, zero extra LLM cost
Maintainers
Readme
opencode-auto-shift
An automatic gearbox for your OpenCode models.
Every message gets the right drive mode and the right gear — automatically. Routine work
stays in eco, heavy lifting shifts into sport, and a normal middle tier slots in when
you have three models. The shifting is done by a zero-cost keyword heuristic: no extra LLM call, no
system-prompt overhead, just the right reasoning effort dialed in before the model starts. When you
need more power you can switch drive modes (switch_mode), force a gear (set_gear), or pull into
the pits to swap MCP servers (mcp_toggle).
Built for OpenCode today; the classifier core is agent-agnostic and portable — see Backlog for Claude Code, Cursor, Windsurf, OpenClaw, Grok, and more.
The metaphor
Drive modes are model tiers — each mode is a concrete model. Gears are the reasoning effort the model spends on a message. The automatic gearbox (the heuristic classifier) shifts the gears for you; the drive-mode selector lets you pick the model yourself.
| In a car | In opencode-auto-shift |
|---|---|
| Drive modes: eco / normal / sport | Model tiers: fast / medium / heavy — each mode maps to whatever model you configure (e.g. haiku / sonnet / opus, or flash / pro) |
| Gears: 1st, 2nd, 3rd… | Numbered effort positions — each maps to a reasoning-effort string your provider accepts (e.g. DeepSeek: low/high/max; Claude: low/medium/high/xhigh/max) |
| Automatic transmission | The heuristic classifier + shifts program — picks a gear (effort) for you, every message |
| Manual/paddle mode | The set_gear tool — force a gear on demand, or resume automatic shifting |
| Text directives | Type !sport, go eco, !gear 3, stay on normal, or back to auto at the start of a message — force a mode/gear per-message, or sticky until it self-expires |
| Drive-mode selector | The switch_mode tool — change drive mode (model) on demand |
| Pit stop | mcp_toggle — swap MCP servers at runtime |
Modes and gears are independent axes: any model can run at any gear. The classifier output (eco/normal/sport), the gear table, and the shift program are all configured separately — you can run your sport model at 1st gear if you want to (not recommended, but fully allowed).
Why this exists
I built my first serious project with the OpenCode agent. The result was great — but the token counter wasn't. Even with optimizers, prompt tweaks, and every performance trick I could find, a huge share of the spend went to messages that simply didn't need a strong model: a one-line edit, a "run the tests", a rename.
The pattern was hard to miss. Most of my messages were city driving — routine, low-stakes, done in seconds. A small minority — architecture, debugging, migrations, anything touching multiple files — were genuinely hard and deserved full compute. The rest were burning capable-model tokens for busywork, like cruising the highway in first gear.
So I went looking for a tool that would route each message to the right model automatically. There wasn't one. So I built it.
That's the core idea behind opencode-auto-shift: classify every message, shift the reasoning effort (and, where OpenCode allows, the model itself) so cheap work stays cheap and hard work gets the capability it needs. The default classifier is a zero-cost keyword heuristic on purpose — spending tokens to save tokens would defeat the entire point.
What it does
| Capability | Mechanism | Automatic? | Cost |
|---|---|---|---|
| Gear shifting (reasoning effort) | chat.params hook → options.reasoningEffort, via the shifts program | ✅ per message | zero |
| Model routing (drive mode) | chat.message hook → message-level model override, persisted before the message is processed | ✅ per message (opt-in, auto_route_models) | zero |
| Manual gear override | set_gear tool → forces a gear until cleared | 🔧 on demand | zero |
| MCP enable/disable | client.mcp.connect / disconnect tool | 🔧 on demand | zero |
| Drive-mode switch (model) | switch_mode tool → client.session.prompt model override | 🔧 on demand | zero |
| Text directives (mode + gear) | Type !sport, go pro, !gear 3, stay on normal, back to auto at the start of a message → per-message, or sticky until it self-expires | 🔧 on demand | zero |
| LLM classifier | optional tiny classification call | ✅ when enabled | ~1 small call/message |
Model routing is automatic when you opt in
With auto_route_models: true, every user message is classified and its model
field is set to the configured drive-mode model before the message is processed
(routine → modes.eco, complex → modes.sport, three-tier setups → modes.normal).
This works through the chat.message hook: opencode persists the hook's message
mutation and uses the saved message's model to resolve the LLM request
(getModel(lastUser.model.providerID, lastUser.model.modelID)), so the routed
model is what actually answers. Messages that belong to subagents are left
untouched — a subagent keeps its own configured model.
This requires an opencode version whose chat.message hook persists the message
mutation (verified on 1.18.x). The switch_mode tool remains as the manual,
on-demand way to force a model for a prompt.
Install
Add the plugin to your
opencode.json:{ "$schema": "https://opencode.ai/config.json", "plugin": [ ["opencode-auto-shift", { "modes": { "eco": "provider/eco-model", "normal": "provider/normal-model", "sport": "provider/sport-model" }, "gears": { "1": "low", "2": "high", "3": "max" }, "shifts": { "eco": 1, "normal": 2, "sport": 3 } }] ] }The three blocks are independent:
modesmap drive modes to models,gearsmap numbered positions to effort strings, andshiftsmap classifier output to a gear position. Any model can run at any gear.For example, a DeepSeek Flash/Pro split (eco and normal both run on Flash; effort differentiates them — see gear values):
["opencode-auto-shift", { "modes": { "eco": "deepseek/deepseek-v4-flash", "normal": "deepseek/deepseek-v4-flash", "sport": "deepseek/deepseek-v4-pro" }, "gears": { "1": "low", "2": "high", "3": "max" }, "shifts": { "eco": 1, "normal": 2, "sport": 3 } }]The same shape works for any provider — a three-model Claude setup:
["opencode-auto-shift", { "modes": { "eco": "anthropic/claude-haiku-4-5", "normal": "anthropic/claude-sonnet-4-5", "sport": "anthropic/claude-opus-4-6" }, "gears": { "1": "low", "2": "medium", "3": "high" }, "shifts": { "eco": 1, "normal": 2, "sport": 3 } }]Two-model OpenAI and Google setups (drop the
normalmode and third gear):["opencode-auto-shift", { "modes": { "eco": "openai/gpt-5-nano", "sport": "openai/gpt-5" }, "gears": { "1": "low", "2": "high" }, "shifts": { "eco": 1, "sport": 2 } }]["opencode-auto-shift", { "modes": { "eco": "google/gemini-2.5-flash", "sport": "google/gemini-2.5-pro" }, "gears": { "1": "low", "2": "high" }, "shifts": { "eco": 1, "sport": 2 } }]These are just examples — the plugin never constrains which models or providers you run.
Restart OpenCode (or run
/pluginto load it). The plugin injects effort only when agearstable is configured and/or you use its tools.
Configuration
["opencode-auto-shift", {
// Master kill switch. false = complete no-op.
"enabled": true,
// Drive modes = model tiers. Each mode is a concrete model (provider/model).
// Used by the `switch_mode` tool. Independent of gears — any model can run
// at any gear.
"modes": {
"eco": "provider/eco-model",
"normal": "provider/normal-model", // optional — 3-mode setups only
"sport": "provider/sport-model"
},
// Numbered gears = reasoning-effort positions. Each maps to a provider
// effort string, passed through verbatim. No default table — effort values
// are provider-specific. `key` overrides the options key used to set effort
// (defaults to a built-in per-provider map). Set the whole block to `false`
// to disable gear routing entirely.
"gears": {
"1": "low",
"2": "medium",
"3": "high",
"key": "reasoningEffort"
},
// The automatic shift program: classifier complexity -> gear position.
// The KEYS (eco/normal/sport) are the classifier's output tiers. Each VALUE
// is a gear NUMBER — an index into the `gears` table above, NOT the effort
// itself. The effort that actually gets injected is whatever `gears[number]`
// holds. Any tier may point at any gear. Defaults to { eco: 1, normal: 2,
// sport: 3 } — but only for tiers you leave out; yours always wins.
// Example: set "sport": 2 to run sport at gear 2 instead of 3, skipping the
// max-effort gear to save cost.
"shifts": { "eco": 1, "normal": 2, "sport": 3 },
// Text-directive layer: force a mode/gear by typing at the start of a
// message (`!sport`, `go eco`, `!gear 3`, `stay on normal`, `back to auto`).
"directives": {
"enabled": true, // kill switch for the directive layer
"sticky_turns": 10, // user messages a sticky override survives
"aliases": { "pro": "sport" } // extra word -> eco|normal|sport (highest precedence)
},
// Extra sport-mode escalation keywords (merged with the built-in defaults).
"sport_keywords": ["architecture", "refactor", "custom-signal"],
// Normal-mode keywords (merged with the populated defaults). The normal tier
// is always available now — add entries to tune feature-work detection.
"normal_keywords": ["feature", "refine", "write tests"],
// Eco/baseline keywords (merged with the populated defaults). Eco is the
// fallback tier; these tune the trivial-signal detection.
"eco_keywords": ["stub", "placeholder"],
// Optional LLM classifier (off by default — see cost note below).
"use_llm_classifier": false,
"llm_classifier": {
"baseUrl": "https://your-provider.example/v1", // any OpenAI-compatible endpoint
"model": "your-small-model",
"apiKeyEnv": "YOUR_API_KEY_ENV"
},
// Automatic model routing: classify every user message and set its model to
// the configured drive-mode model (eco/normal/sport -> `modes` slots) before
// it is processed. Requires an opencode that persists the `chat.message`
// message mutation (verified on 1.18.x). Subagent messages are never routed.
"auto_route_models": true,
// Log routing decisions to stderr.
"debug": false
}]Gear values are provider-specific — examples
The plugin is model- and provider-agnostic: gear values are passed through verbatim to the active provider, never validated or rewritten. Pick values your provider supports. The table below is illustrative, not a contract — check your provider's docs:
| Provider | Example effort levels |
|---|---|
| DeepSeek (thinking mode) | low, high, max — see DeepSeek effort control |
| Claude / Anthropic | low, medium, high, xhigh, max — see Claude effort levels |
| xAI (Grok) | low, medium, high — supported values vary per Grok model |
| OpenAI (reasoning models) | none through max (e.g. low, medium, high) |
There is no universal default gear table because the vocabulary differs per provider. A
provider like DeepSeek has no medium — so a three-gear DeepSeek table is
{ "1": "low", "2": "high", "3": "max" }, while Claude can use
{ "1": "low", "2": "medium", "3": "high" }. Configure the gear table (and shifts) to
match the models you actually run.
Provider compatibility
Effort injection depends on two independent things — the injection key (does the plugin know
where to put the value?) and the gear values (what your provider accepts). The injection key is
resolved from the AI SDK package your provider uses (model.api.npm), via the map in
src/effort.ts:
| Provider | AI SDK package | Effort key | Status |
|---|---|---|---|
| OpenAI | @ai-sdk/openai | reasoningEffort | ✅ auto |
| Anthropic (Claude) | @ai-sdk/anthropic | reasoningEffort | ✅ auto |
| DeepSeek | @ai-sdk/deepseek | reasoningEffort | ✅ auto |
| xAI (Grok) | @ai-sdk/xai | reasoningEffort | ✅ auto |
| Groq | @ai-sdk/groq | reasoningEffort | ✅ auto |
| Mistral | @ai-sdk/mistral | reasoningEffort | ✅ auto |
| Perplexity | @ai-sdk/perplexity | reasoningEffort | ✅ auto |
| OpenRouter | @ai-sdk/openrouter | reasoningEffort | ✅ auto |
| Fireworks | @ai-sdk/fireworks | reasoningEffort | ✅ auto |
| Cerebras | @ai-sdk/cerebras | reasoningEffort | ✅ auto |
| DeepInfra | @ai-sdk/deepinfra | reasoningEffort | ✅ auto |
| Together AI | @ai-sdk/togetherai | reasoningEffort | ✅ auto |
| Azure OpenAI | @ai-sdk/azure | reasoningEffort | ✅ auto |
| OpenAI-compatible (any) | @ai-sdk/openai-compatible | reasoningEffort | ✅ auto |
| Google (Gemini) | @ai-sdk/google | thinkingConfig.thinkingLevel | ⚠️ not mapped |
| Google Vertex | @ai-sdk/google-vertex | thinkingConfig.thinkingLevel | ⚠️ not mapped |
| Amazon Bedrock | @ai-sdk/amazon-bedrock | reasoningConfig.budgetTokens | ⚠️ not mapped |
The ⚠️ providers use a different reasoning mechanism — a nested object or a numeric token budget,
not a flat effort string — so the plugin's string-based reasoningEffort injection would be a
silent no-op for them. gears.key cannot fix this (it only renames the flat key, not reshape the
value); supporting them would mean extending effort.ts and the injection shape in index.ts.
This mapping is enforced by test/effort.test.ts, which asserts reasoningEffort for every ✅
package and undefined for the ⚠️ ones — so the table cannot drift from the code without a test
failing.
Built-in keyword lists
All three tiers ship with a populated default vocabulary, and all three are tunable via
sport_keywords / normal_keywords / eco_keywords (each option merges with its built-in
defaults).
Sport (heavy signals — the raw-capability work that wants the strong model) — architecture,
rearchitect, restructure, rewrite, rebuild, migrate, migration, refactor, "from scratch", "2+ files",
"multiple files", non-trivial, "non trivial", algorithm, schema, debug, "root cause", concurrency,
"race condition", deadlock, threading, distributed, scalability, throughput, transaction,
consistency, "fault tolerance", idempotent, performance, optimize, profiling, incident, outage,
"data loss", security, cryptography, authentication, authorization, encryption, "technical debt"
Normal (moderate work — features, design, planning, review, explanations, ops) — feature,
implement, endpoint, component, handler, module, integration, api, database, query, validation,
validate, form, route, router, controller, service, repository, middleware, config, configure,
settings, workflow, install, setup, scaffold, boilerplate, crud, pagination, serializer,
"error handling", logging, design, spec, specification, plan, review, "why does", "how does",
"how should", "explain how", analyze, analysis, investigate, investigation, benchmark,
observability, telemetry, orchestration, infrastructure, regression, latency
Eco (trivial/cheap signals) — typo, one-liner, "one liner", whitespace, formatting, comment,
comma, semicolon, "string literal", label, wording, copy, rename, quick, simple, small, tiny,
trivial, minor, just, readme, docs, "what is", "what's", "what does", "where is", "how do i",
"how do you", explain, syntax, hello, thanks, "thank you"
Single-word keywords match their stem (debug → debugging, refactor → refactoring). Phrase
keywords match as case-insensitive substrings. Add entries via sport_keywords,
normal_keywords, or eco_keywords to tune the heuristic for your workflow.
How shifting decides
- The user message text is extracted from the incoming message.
- If
use_llm_classifieris on and configured, a tiny model call classifies it assport/eco; if that call fails or is unavailable, the heuristic runs instead. - Otherwise the heuristic scores the message against all three keyword lists and applies a
sport-favoring rule: a heavy (sport) signal wins by default; it drops to eco only when
cheap/trivial (eco) signals clearly dominate (
eco > sport + normal). With no sport signal, a normal (feature-work) signal wins, dropping to eco only wheneco > normal. With no signal at all, the message is eco. - Unless a gear was manually forced via
set_gear, the classifier tier maps to a gear position via theshiftsprogram (defaults:eco→ 1,normal→ 2,sport→ 3). - The gear position maps to an effort string via the
gearstable. If the position has no entry, no effort is injected for that message.
The effort value is injected only when the active model is reasoning-capable and its provider
uses a known reasoningEffort key (all OpenAI-compatible providers, and several others). This
mirrors the same options path OpenCode's own variant computation uses.
How shifts + gears resolve (worked example)
The classifier tier is not the effort, and the gear number is not the effort either.
A message resolves in two hops: tier → gear (via shifts), then gear → effort (via gears).
Given:
"gears": { "1": "low", "2": "high", "3": "max" },
"shifts": { "eco": 1, "normal": 2, "sport": 3 }| Classifier tier | shifts → gear | gears[gear] → effort |
|---|---|---|
| eco | 1 | low |
| normal | 2 | high |
| sport | 3 | max |
To run sport cheaper — skipping the max-effort gear — point it at gear 2 instead:
"shifts": { "eco": 1, "normal": 2, "sport": 2 }Now sport resolves to gear 2 → high, not max. The classifier still says "sport"; only the
gear it engages changed. The two maps are independent: edit gears to redefine what a gear
means (e.g. "2": "medium"), or edit shifts to redefine which gear a tier engages — neither
edit touches the other, and neither forces sport onto max.
Manual gear override
set_gear moves the gearbox into manual mode: it forces a gear for all subsequent messages
until you clear it. This is independent of switch_mode (which changes the model) — you can
force a gear, switch drive mode, or both, in any combination.
set_gear(gear=3) // force gear 3 (max effort) for subsequent messages
set_gear(auto=true) // back to automatic shiftingManual control: directives
You can also drive the gearbox by typing — a text directive at the very start of a message
overrides the automatic routing for that message (or longer, if you ask). Directives are
provider-agnostic: they resolve to abstract mode slots (eco/normal/sport) and gear
numbers, never to concrete model names — the same directive works no matter which provider's
models you have configured.
Two forms are recognized, both case-insensitive and anchored to the start of the message (leading whitespace is fine; mid-message words never trigger):
- Sigil — starts with
!:!sport,!gear 3,!stay sport,!lock gear 2,!auto. - Natural language — starts with a verb:
go sport,use gear 2,switch to normal,stay on heavy,back to auto.
| Input | Effect |
|---|---|
| go sport | mode sport, this message only |
| !pro (alias pro → sport) | mode sport, this message only |
| use the heavy model | mode sport, this message only |
| !gear 3 | gear 3, this message only |
| use gear 2 do the thing | gear 2, this message only |
| stay on normal | mode normal, sticky |
| !lock gear 1 | gear 1, sticky |
| back to auto / !auto | clear all sticky overrides |
Per-message by default, sticky on request. A plain !sport or go eco affects only that
message. Prefix with stay / lock / hold (or the !stay sigil) to make it stick, and the
override survives for directives.sticky_turns user messages (default 10) before it expires
back to automatic. back to auto (or !auto) clears every sticky override immediately.
Mode words are layered (lowest precedence first; later wins on conflict):
- Built-in —
eco/fast/lite→ eco,normal/balanced→ normal,sport/heavy→ sport. - Auto-derived from your configured model IDs — the token after the last
/, split on-and., keeping alphabetic tokens (version bits likev4are dropped). A token that maps to more than one distinct model is dropped; one shared by several modes maps to the lowest tier. directives.aliases— your explicitword -> tieroverrides (highest precedence).
Because they resolve to slots and gear numbers, your directives keep working when you swap models or providers — only the config (or the auto-derived aliases) changes, never your muscle memory.
Cost tradeoff of the LLM classifier
use_llm_classifier: false (default) costs nothing — the heuristic is pure string matching.
Enabling it makes one small classification call per message (typically a few tokens on a cheap
model). It buys higher precision on ambiguous inputs at a tiny per-message cost. For most routing
decisions the keyword heuristic is sufficient.
MCP note
The enabled flag on an MCP server in opencode.json is startup-only. To toggle a server at
runtime, the plugin exposes the mcp_toggle tool:
mcp_toggle(name="my-server", action="connect")
mcp_toggle(name="my-server", action="disconnect")Alternatively, flip the config flag and restart:
"mcp": { "my-server": { "enabled": false, "type": "local", "command": ["..."] } }Limitations
- Automatic model routing needs a recent opencode: it relies on the
chat.messagehook's message mutation being persisted and honored at request time (verified on 1.18.x). On older versions the hook still fires but the model override is ignored — useswitch_modethere. - Subagent messages are skipped by both routing and gear injection: a subagent keeps the model its agent config pins, and its reasoning effort is never overridden by a sticky gear or the automatic shift program.
switch_modeand/modeloverrides are honored: theswitch_moderelay is exempt from auto-routing (the hook skips the exact message it sends), so an explicit drive-mode switch sticks instead of being re-classified back. A manualF2//modelchoice on your next typed message is still overridden by the classifier whileauto_route_modelsis on — that is the feature.- Gear routing needs a
gearstable: with no configured gear table, the plugin injects no effort (there is no universal default, since effort vocabulary is provider-specific). Set"gears": falseto disable gear routing explicitly if you only want the tools. - Provider-specific effort keys: the built-in map (
src/effort.ts) resolvesreasoningEffortfor OpenAI, Anthropic, DeepSeek, xAI/Grok, Groq, Mistral, Perplexity, OpenRouter, and the OpenAI-compatible providers. Providers with a different reasoning mechanism (Google/Vertex usesthinkingConfig.thinkingLevel; Amazon Bedrock usesreasoningConfig) are not mapped — override withgears.keyfor those, or extend the map insrc/effort.ts. set_gearis sticky, in-memory: a forced gear applies for the rest of the session until cleared (set_gear(auto=true)); it does not persist across restarts. It shares the same manual state as text directives, soset_gear(auto=true)andback to autoboth clear mode and gear together.- Sticky overrides are per-session: a forced mode/gear set in one session (via
set_gearor a sticky text directive) does not leak into another — each session owns its own override and turn counter. - Directives are recognized only at the start of a message:
!sport,go eco, etc. must be the first thing you type (leading whitespace is fine). A word mid-message ("refactor auth and go sport") never triggers a directive. - Heuristic false positives/negatives: keyword matching is cheap, not perfect. Tune
sport_keywordsor enable the LLM classifier for higher precision. switch_mode/set_gear/mcp_toggleare agent-facing tools, not user-facing slash commands — they are invoked by the model (or via an agent that calls them), not typed by you directly.- The LLM classifier is binary (
sport/eco); thenormaltier is heuristic-only. use_llm_classifiersends message text to your endpoint: enabling it posts the user message text to the configuredllm_classifier.baseUrl(using the configured API key) for classification. Classification is cached once per distinct message text, so a message that reaches both model routing and gear injection triggers only a single classification call.
Backlog
Ideas for the future — not implemented yet.
- Agent-agnostic support — the classifier (
src/classifier.ts) is already dependency-free and portable. A future version could extract it into a shared core package with thin per-agent adapters — Claude Code, Cursor, Windsurf, OpenClaw, Grok, or any agent with an extension API — so the same routing logic works across agents. Each adapter would plug into that agent's own extension API, so capabilities would vary per agent.
Development
npm install
npm test # unit tests for the classifier + config
npm run typecheck # tsc --noEmitAuthor
- Renzo S. — mr-wolf-rsh
Contributing
All sorts of suggestions and pull requests are welcome.
