Memory, routing, orchestration, cost — every piece in daily use, with the measurements attached.
← all explainers
· Yasaswy Nagavolu

Model-Routing: Keep Claude Subagents on Sonnet 5.5 and Haiku 5.5

Subagents silently ran on my most expensive Claude model. Model-Routing fixes that with one config file, a PreToolUse guard, an agent.spawn mod and an audit command that says out loud when a dispatch ran on the wrong model.

developer-toolscliautomationai-agentscost-optimization

I hand most of my coding to subagents: small Claude workers that my main chat spawns to read code, run checks and edit files. The main chat runs on a flagship model that I pick by hand. The workers were supposed to run on cheaper ones. They often did not, and nothing told me. A subagent with no model of its own inherits the main chat’s model. An opus alias resolves to the same Opus the main chat is on. An old model name in an agent file keeps running long after a newer model replaced it. Nothing fails and the work gets done, but it wastes money: in my config the input price per million tokens is 10 for the flagship, 4 for Opus, 2 for Sonnet and 0.1 for Haiku. A chore on the flagship costs five times what the same chore costs on the Sonnet worker. I also had no record of which model ran which task, so I could not even measure the waste. This post is the fix, built one broken attempt at a time.

Architecture: Model-Routing, in one loop

The name is Model-Routing. One file, models.json, holds every model id. Two hooks read it on every dispatch: a PreToolUse guard that sets names, effort and a scope header, and an agent.spawn mod that is the last writer of the final model id. The subagent starts on that model. A stop hook catches a hand-off, a ledger records the decision, and an audit command checks the records. Click through the loop. It starts and ends in the chat, and the dashed line marks what one npx command installs:

Model-Routing
Hook + Mod Stack (npx bundle)npx '@yasaswy.nagavolu/agents' install --bundle subagent-model-routing
STEP 1/9▸type
Σ 0 tok·$0.00Claude Sonnet 5.5, input price
Model-Routing · one npx install
dispatch
check
spawn
run
stop
log
audit
report

Three roles carry the policy. The main chat is whatever you choose with /model, and it is never dispatched. Everything else runs on one of two roles:

RoleModelUsed forInput price per million tokens
main chatyour /model choice (Opus 5.5 or Fable 5.1)decisions, planning, review4 or 10
worker (default)claude-sonnet-5-5 with the 1M-context suffixauthoring code and docs, debugging, every escalation2
assistantclaude-haiku-5-5narrow jobs with a checkable result: reading, running checks, drafts0.1 (0.5 above 100K tokens)

Each layer owns one job, so a failure in one layer does not hide a failure in another:

LayerOwnsDoes not own
models.jsonids, role names, effort, scope text, escalation signalany behaviour
PreToolUse guardnames, effort, scope header, dispatch log, denials, alias fallbackthe final id
agent.spawn modthe final full model id, read live at every spawnnames and logs
SubagentStop and Stop hooksthe hand-off signalthe model
Ledger and auditthe record and the checkany decision

The rollback is one line. Change the id under roles.worker, then run models apply. The mod reads the file at the next spawn, so a running session picks the change up without a restart.

How it got here: seven attempts

Each stage below has what I tried, what broke, and what it taught me. Click a number. Nothing in the final design came first, and the order matters:

Stage 0 — The silent bill
Tried

Spawned helper subagents from a main chat that runs on a flagship model I pick by hand.

Broke

A subagent with no model of its own inherits the main chat's model. Nothing errors. The work gets done on the most expensive model, and no log says which model ran which task.

Learned

Input prices in my config are 10, 4, 2 and 0.1 USD per million tokens for the four models. A chore on the flagship costs 5 times the worker price. I needed a rule, a number, and proof.

The pattern under the stages is simple. A rule written in prose drifts. A rule written in a hook runs on every dispatch. And a rule that runs is only trusted once something records that it ran.

Try the spawn rules

The mod picks a model with a first-match-wins table. Pick a spawn and watch which rule fires. The spawns are invented examples. The rule order is the one the shipped mod documents:

Pick a spawn
Caller passes the opus alias.
model setclaude-sonnet-5-5[1m]

A main-chat family is never dispatched. The worker id carries the 1M-context suffix an alias cannot.

1Fork whose parent runs a main-chat modeldenied
2Any other fork, or a workflow-script agentunchanged
3Registered agent that declares a worker rolethat role's id
4Registered agent with its own model, no roleunchanged (main-chat model becomes worker)
5Requested model is a main-chat familyworker
6Requested model is a worker-role alias or idthat role's id
7Type listed in typeRoles (Explore, ...)assistant
8Anything elseworker

Here is the shape of the config, trimmed to the keys that matter, and a clean-room sketch of the resolver. The sketch is not the shipped code. It shows the idea in a few lines:

{
  "roles": { "worker": "claude-sonnet-5-5", "assistant": "claude-haiku-5-5" },
  "mainChat": { "opus": "claude-opus-5-5", "fable": "claude-fable-5-1" },
  "typeRoles": { "Explore": "assistant" },
  "agentSuffix": { "worker": "[1m]" },
  "effort": "high",
  "escalationSignal": "NEEDS_WORKER:"
}
# pick_model.py - first match wins; sketch only
def pick_model(spawn, cfg):
    if spawn.is_fork:
        if spawn.parent_model in cfg.main_chat:
            return deny("fork would run on a main-chat model")
        return keep()
    if spawn.agent_role in cfg.worker_roles:
        return with_suffix(cfg.roles[spawn.agent_role])
    if spawn.own_model and spawn.own_model not in cfg.main_chat:
        return keep()
    if spawn.requested in cfg.main_chat:
        return with_suffix(cfg.roles["worker"])
    if spawn.requested in cfg.worker_aliases_and_ids:
        return with_suffix(cfg.role_of(spawn.requested))
    if spawn.type in cfg.type_roles:
        return with_suffix(cfg.roles[cfg.type_roles[spawn.type]])
    return with_suffix(cfg.roles["worker"])

The sketch has no model id in the code. The ids live in the file, so a rename is one edit. The real package also has a test that fails when a model id appears in its hook source.

Install it and verify it works

You need Claude Code 2.1.289 or later for the mod (mods are early access), Node for npx, and python3 on your path for the hooks. The package page is @yasaswy.nagavolu/agents on npm.

One command installs the whole pipeline. The dashed boundary in the diagram is exactly what it puts on your machine:

npx '@yasaswy.nagavolu/agents' install --bundle subagent-model-routing --yes

It installs these files and wires these hooks:

PartWhat lands in ~/.claude
Configmodels.json and its reader
Agentsthe worker and assistant subagent definitions, with the role model and effort stamped in
PreToolUse guardagent_model_guard.py and the small modules it imports, wired on the Agent tool
Modmods/model-routing, wired through CLAUDE_CODE_PLUGIN_DIRS
Hooks and auditthe post-dispatch hook, the escalation hooks (SubagentStop and Stop), the ledger hook and routing_audit.py

It carries no router, scheduled task, proxy autostart or secret prompt. It also runs models apply, which stamps the role models into the agent files and the model env vars of settings.json. Three limits are worth knowing:

  • Without the mod (older Claude Code), the guard still routes by alias. It cannot set the full id or the 1M-context suffix, which is the gap the mod closes.
  • The mod loads when the Claude Code process starts. After the install, restart the process. /clear keeps the same process and does not load mods.
  • If you already wire a model guard into settings.json by hand, do not add this bundle on top. The guard would run twice.

I ran it against a throwaway target directory using version 0.26.12 from the registry. The install wired six hooks, models apply --dry-run was in sync, and doctor came back green. Then a headless Claude Code run with that directory’s settings dispatched a general-purpose subagent and an Explore subagent. They ran on claude-sonnet-5-5 with the 1M suffix and on claude-haiku-5-5, both at effort high with the scope header, and routing_audit.py exited 0 with no discrepancies.

Check the install with two commands:

npx '@yasaswy.nagavolu/agents' models apply --dry-run
npx '@yasaswy.nagavolu/agents' doctor

The first prints Already in sync with models.json. when every agent file and settings key matches the file. The second prints a Model routing: block. A healthy block reads routing mod: installed, matches the repo copy, wired, no unhandled dispatches.

Check what ran: usage, audit and slash commands

Every command below is one I ran or one I checked in the installed build. The / commands are Claude Code built-ins. There is no custom /routing command; the routing checks are CLI commands.

CommandWhat it showsHow to read it
npx '@yasaswy.nagavolu/agents' models usage --days 7dispatches per role, from the guard’s logthe share column is your cheap-role share. --json gives raw data. Read-only
npx '@yasaswy.nagavolu/agents' doctorthe Model routing: blockred when the mod copy differs, the wiring is missing, or an unhandled-dispatch flag is set
python "$HOME/.claude/proxy/routing_audit.py" --session latestone line per discrepancy in a sessionexit 0 clean, exit 1 has discrepancies, exit 2 usage error. Add --json for data
claude --debug-file routing.logmodel-routing: <type> <requested> -> <id> (<rule>) per rewriteproof the mod ran. A load error reads failed to load
/usage (aliases /cost, /stats)session cost, plan usage, activity statsuse it for spend; use models usage for the role split
/model <model>sets the main chat modelthe one choice the router never touches
/statusversion, model, account, connectivityconfirm the Claude Code version is 2.1.289 or later
/contexta grid of context usecheck how full a long session is
/effortsets the effort levelsession level; subagents get their own from the file
/hooksthe configured hooks per eventconfirm the PreToolUse, SubagentStop and Stop hooks are wired

A sample of the usage output looks like this. The numbers are invented; the layout is real:

Dispatches in the last 7 day(s): 200
role         count   share
worker         140   70.0%
assistant       60   30.0%

Rows named unknown are older log lines from before roles were recorded. The audit names nine kinds of discrepancy, one plain line each:

KindMeaning
no_ledger_eventa dispatch with no routing event in the ledger
no_mod_recordthe mod did not handle this dispatch
role_model_mismatchthe model set is not the model of the dispatch’s role
role_mismatchan unregistered dispatch ran as a role the shared table does not allow
engine_model_mismatchthe engine resolved a different model than the mod set
fork_main_chata fork on a main-chat parent was tried, and the mod denied it
no_headera role that has a scope brief got none
bad_efforteffort is missing or outside the allowed levels
escalatedan assistant returned NEEDS_WORKER: and needs a worker re-dispatch

What changed along the way

  • One install. A single public bundle ships the whole pipeline, with no router or secret in it.
  • One home for ids. No hook holds a model id, and a test fails if one appears.
  • A full id at spawn. The worker gets its 1M-context suffix, which an alias cannot carry.
  • Main-chat models are never dispatched. A request for Opus or Fable becomes the worker.
  • Effort high on every subagent. It is one config value, with an optional override per role.
  • A scope header and an escape hatch. The assistant role gets four lines on what is in and out of scope, and returns NEEDS_WORKER: <reason> as its first line for anything else. A security or pentest request is re-routed to the worker by code.
  • A ledger and an audit. Each dispatch leaves a routing event. A drift test makes the guard and the mod resolve the same role from one shared table.
  • Hardening from daily use. A fork on a main-chat parent is denied, a repeated dispatch name gets a -2 suffix, informal hand-offs such as “this task needs a worker” count as escalations, and the stale-process notice is per session.

Does it work?

I checked it against 630 real dispatches made since the first config went live (after removing test scratch runs and shutdown shells). Method: join the guard log, the mod record and the ledger for each dispatch, label each one by its task description, then check the labels against the subagent transcripts.

MeasureResultKind
Headered dispatches on a model other than their role’s0 of 193measured
Mix after the last routing fix (417 dispatches)Haiku 142 (34%), Sonnet 275 (66%)measured
Haiku dispatches that returned NEEDS_WORKER:3 of 142 (2.1%), all from one docs agentmeasured
Sonnet dispatches that were truly trivialabout 6%estimate from a small sample
Their share of Sonnet tokensabout 0.4%estimate
Follow-up fix passes after docs authoring on Haiku, against Sonnet coding agentsabout 37% against about 14%estimate

The routing was correct wherever it could be checked: no headered dispatch ran on the wrong model.

Counts alone mislead, so here is the less flattering part. Only about 6% of the Sonnet dispatches were jobs that Haiku could have done, and they used about 0.4% of the tokens. Many small jobs do not add up to many tokens, so a bigger cheap-role share would not have saved much. The one place the cheap role was asked to do too much was docs authoring, which belongs to the worker. One stray dispatch ran on Opus, most likely from an agent definition cached before the fix (an estimate, not proven).

Two lessons were worth more than the numbers. First, a scary “mod not active” notice came from a /clear inside a process that started before the install. Restart the process before you debug the mod. Second, never add a new row shape to a log that another tool already reads.

Technicals

The real stack behind this build, on record:

  • Agentic harness: Claude Code (2.1.295 when this was written; the mod needs 2.1.289 or later).
  • Skill: Model-Routing, made of the PreToolUse guard, the model-routing agent.spawn mod, the post-dispatch and escalation hooks, and the audit script. The worker and assistant roles run through the generic-purpose-subagent and assistant-subagent definitions.
  • Memory/RAG system: one-brain, a local memory MCP that recalls past decisions at session start. The routing hooks themselves use no memory system.
  • Source: ships inside the published package @yasaswy.nagavolu/agents (the content/ folder of the tarball).

For the model docs this builds on, see the Claude Code sub-agents guide. For earlier work on the same family of problems, read Route-Lock and Model-Router, part 1.

The cheat sheet

  • Install it: npx '@yasaswy.nagavolu/agents' install --bundle subagent-model-routing --yes.
  • Edit one line to switch a model: change roles.worker in ~/.claude/models.json, then models apply.
  • Restart the process after installing the mod. /clear does not load it.
  • Check the install: models apply --dry-run, then doctor.
  • Check a session: routing_audit.py --session latest and read the exit code.
  • Check the split: models usage --days 7.
  • Never trust a prose rule for routing. Put it in the file, enforce it in a hook, and audit it.