Stage Router
Execution routing uses the stage router to choose a model from tool results
and agent progress. Configure it with type = "stage_router".
Stage-router routing sends each request to either a capable model or a
typically cheaper efficient one, depending on where the agent is in its run.
The goal is to spend the capable model on turns that need exploration or error
recovery and let the efficient model carry routine, mechanical work. Choose a
required picker for ambiguous turns, tune the split with
confidence_threshold, and optionally add an LLM classifier.
Model-call fallback happens after the routing decision. Eligible context-window or availability failures can try the route’s other completion target. See Context-Window Handling.
How it works
A tool-using agent’s run moves through stages that call for different amounts of model capability. The built-in vocabulary is calibrated for coding agents: it recognizes file observation, mutation, planning, shell activity, and test results.
For each LLM call without an active hold, stage-router estimates the agent’s state from the conversation’s tool-result history, scoring signals in two directions:
- RECOVERY → capable:
severity(windowed error severity),spinning(deep churn with no reads or writes), andexploring(reading or planning without producing) push toward the capable tier. - PROGRESS → efficient:
production_intensity(the share of recent recognized operations that are writes or edits) pushes toward the efficient tier with 1.5 times the weight of one signal. Production with no error in the recent window adds 1.2 more signals toward efficient, so clean production resolves a turn to the efficient tier on its own, even when writes are a small share of recent operations.
The axes are corroborative: the signed score is tanh-squashed to a
confidence in [0, 1]. One maxed scoring dimension produces about 0.46;
corroborating evidence pushes confidence decisively past a 0.5 threshold.
Repeated failures, critical-error severity, and context compaction are hard
overrides to the capable tier. Set compaction_override = false to disable the
compaction override in either picker. Active holds bypass signal extraction and scoring.
Severity and test results come from tool output that ran something. The contents
returned by the built-in read and search tools do not count, unless the tool
reports a failure. Reading a missing file does not add error severity, even
when the tool marks the result as an error.
confidence_threshold sets how sure that estimate must be before the router acts
on the signal alone. Scores inside the ambiguous band go to the optional
classifier and then, if it cannot decide, to the picker’s default tier. A turn
with no tool-result history follows the same fallback path.
The routing decision for one turn:
Both pickers support capable_hold_turns (default 2) and
efficient_hold_turns (default 0 on standalone routes; composite’s
capable-first policy defaults to -1). A positive value holds that tier for the
specified number of requests after a switch, excluding the switch request.
Held requests do not restart the counter. A finite capable hold also starts or
restarts on a signal-driven capable decision. Active holds return the selected
tier at confidence 1.0 before extracting tool signals or scoring. The existing
cascade then skips the fallback judge. Passing tests and errors do not end holds
early, and held requests receive no handoff notes.
Set either value to 0 to disable that hold, or -1 to pin to that tier after
switching into it. The initial selection does not activate a pin. Pins override
later signals, including passing tests and critical errors, and skip the fallback
judge. If both values are -1, the first tier switch pins its destination.
Switches chosen by signals, the fallback judge, or the picker default all count.
Holds use the existing session state and are separate for each agent ID. Supply
a stable session ID across requests. A pin ends when that session state is cleared
(including session completion, expiry, or a server restart). Values below -1 or
above 4294967295 are rejected.
Pickers
The picker name says which tier is the default: the tier used when the signals are ambiguous and no classifier verdict is available.
efficient_first: efficient is the default; escalate to capable only when the signals (or the classifier) clearly say so. Cost-first.capable_first(experimental): capable is the default; drop to efficient only when the signals (or the classifier) clearly say so. Quality-first.
Both pickers read the same signals; only the default tier differs.
capable_first is experimental
The SWE-Atlas-QnA results report accuracy and cost
savings for capable_first. It has no calibrated threshold. The server logs a
warning at startup when a route selects it. Use efficient_first unless you
are running your own calibration. See
Reachable scores per picker for what a
threshold can and cannot do with each picker.
Tuning confidence_threshold
The tool-signal scorer gives each turn a signed score in (-1, 1): negative
scores point to the efficient tier, positive scores point to the capable tier,
and the absolute value is the confidence. confidence_threshold creates a
closed ambiguous band from -threshold to +threshold. Scores outside the
band make a signal-based decision; scores inside it go to the optional
classifier or fall back to the picker’s default tier.
The TOML schema requires you to choose picker explicitly; there is no implicit
default.
Set 0.5 explicitly. confidence_threshold is required by the TOML schema;
0.5 is the recommended starting point, derived from many coding benchmarks,
and what the example below uses.
Reachable scores
The scorer adds a few signals from the recent tool results. Error severity and stalls count toward the capable tier. Writes count toward the efficient tier. Each signal is bounded, so a turn’s confidence can only reach a few values. These are the ones that matter when you choose a threshold:
Production turns the stall signals off, so with any production in the window
the capable side stays below 0.46. An error in the window removes the
clean-production bonus, so with a hard error the efficient side reaches at most
0.24. The unit test scorer_ceilings_match_the_documented_values in
crates/libsy/src/algorithms/util/stage.rs
pins these values, so a change to the scorer fails CI until this table is
updated.
Reachable scores per picker
Both pickers use the same score. The picker only sets which direction the signals must prove.
Lower the threshold to let the signals decide more turns. Raise it to keep more
turns on the picker’s default tier. Hard overrides, capable holds, and the
classifier do not use the threshold. The server warns at startup that
capable_first has no calibrated threshold.
What 0.5 means with efficient_first
With picker = "efficient_first", no classifier, and a threshold of 0.5:
- scores below
-0.5route to efficient from the tool signals; - scores from
-0.5through+0.5are ambiguous and fall back to efficient; - scores above
+0.5route to capable from the tool signals.
Hard overrides and capable-hold state can still select capable independently of this score. Lowering the threshold narrows the ambiguous band, so more turns are decided directly by the scorer. Raising it widens the band, so more turns use the picker default (or the classifier, when configured). That movement changes the efficient/capable routing split.
A route with a 1.0 threshold remains valid without a classifier. In that case,
ordinary sub-threshold turns fall back to the picker’s default tier; hard
overrides and capable-hold behavior still apply.
The signal-vs-classifier split is dataset-dependent. Measure it in production:
/v1/stats reports decision counts by source and selected target, plus aggregate
scorer metrics. Response headers and structured decision logs explain individual
selections.
Calibrating the threshold from run data
Use about 10% of your representative tasks. Replay their agent histories through the Stage tool-signal scorer and collect the unthresholded signed score for each ordinary turn. Track hard overrides and capable holds separately because changing the threshold does not affect them. Plot the score distribution, then overlay candidate ambiguous bands.
For efficient_first, count how many turns fall below the band, inside it, and
above it. Without a classifier, those regions map to signal-selected efficient,
default-efficient, and signal-selected capable decisions. Choose the threshold
that gives the routing split you want, then validate it on the same sample before
running the full task set.
Cache-aware switches
A model can reuse the part of a prompt that it has already processed. It reports those tokens as cache reads. The rest is the prefill: the prompt tokens that the model has to process again. When Stage moves an agent to the other model, that model often holds little of the conversation, so the move makes it process most of a long prompt again.
Set cache_aware = true on a Stage route to check proposed switches. The
check runs after Stage picks a model and before the route binds the pick. It
reads the session’s routing history, which records the target that served every
completed call with the call’s agent ID and turn ID.
The agent’s latest call names the current target. The check estimates the cost
of the next call on that target and on the proposed destination.
The limit ranges from 0 to 1 and defaults to 0.10. At the limit, Stage follows its pick. If staying costs 9¢ and switching costs 10¢, overhead is 10% and the switch goes through at the default limit. A cheaper or free destination always passes the cost check.
Stage binds its handoff note and its capable hold to the final pick. When the check keeps the agent on the efficient model, the escalation note does not reach that model and no capable hold starts.
The Switchyard cost API estimates usage for both targets from the session’s completed calls. Stage compares the two quotes:
- Prompt tokens. For each target, the check multiplies the incoming prompt’s byte count by the median tokens per byte from that target’s 32 most recent measured prompts in the session.
- Output tokens. The check uses the median of the 32 most recent output counts reported for the target in the session, with at least three samples.
- Cache reads and writes. The check estimates each as a token-weighted share of the prompt on the agent’s earlier calls of the same kind. For the current model, those are the calls that stayed on it. For the destination, those are the calls that returned to it after another model had served the agent. The check reads the eight most recent of them.
- Estimated cost. The cost API prices fresh input, cache reads, observed cache
writes, and output at each provider model’s rates. The server uses bundled
prices or the table supplied with
--pricing-file.
The pick stands when either candidate lacks a usage estimate or applicable rates. The check needs three measured prompts per target, two earlier stays on the current target, and two earlier returns to the destination. If either target has too few output samples, the check compares input cost for both targets.
The cache-aware check log carries both predictions, the estimated costs,
the signed overhead, and the decision. It logs a veto at info level and an
allowed switch at debug level.
/metrics counts vetoes in
switchyard_cache_aware_decisions_total, by decision and by the target_name
that the agent went to. Stage’s own decision_source counts Stage’s pick before
the check.
The check has these limits:
- Use a stable session ID and distinct IDs for distinct sessions. The check reads only the calls of the current session, so each session starts with no history.
- The history lives in the memory of one Switchyard process, with the session’s other routing state. It is gone after the session’s final request, after an hour without a request, after a config reload, and after a restart. Each replica sees only the calls that it served.
- The session keeps one record per completed call, with its IDs, serving target, usage (if reported), and measured prompt size (if available). It keeps no prompt text or request headers. The 32- and 8-sample windows limit each estimate, not memory use: the history can grow as long as the session stays active.
- A successful call without usage still identifies the last model that served the agent. It counts when distinguishing a stay from a return, but supplies no token sample.
- The check uses the same incoming instructions, messages and tools for both estimates. It assumes the instructions and handoff notes added during routing are small relative to the incoming prompt. Call history records the prepared prompt’s byte count at dispatch.
- The check has no clock. A provider drops its cache after a time without use, and the check assumes the reuse that earlier calls of the same kind measured.
- While one model keeps the agent, the conversation grows, and the other model has cached none of the growth. The check applies the reuse that earlier returns measured, whatever the length of the stay.
- Switchyard records a call when it makes the model call itself, as the server
does. A host that makes the calls through
run_stream, such as the Python bindings, records none, so the check has no effect there.
Route configuration
Knob reference
Every key a stage_router route accepts. The handoff_notes and classifier
tables are optional. The
TOML schema has the full table with
required columns.
classifier.response_schema, classifier.policy, and any classifier.mode
other than capability belong to
composite routes and are rejected
here. classifier.mode = "capability" is accepted and changes nothing.
Minimal route
Save as routes.toml and start the server:
This is the recommended default: routing on tool signals alone, no classifier.
Plan and execute
To start with the capable model and keep using the efficient model after a switch, add this route to the minimal configuration:
With no tool history, Stage selects capable and adds the planning prompt. After successful writes, Stage can select efficient; critical failures can keep capable selected. A switch from capable to efficient starts a hold that keeps selecting efficient while the session state remains. Later tool errors do not end it. Only capable requests receive the planning prompt. See How it works for scoring and hold behavior.
Send requests to switchyard/plan-execute with the same
x-switchyard-session-id from the first planning request onward. Include the
full conversation, including the plan, tool calls, and results. For the Responses
API, send that history in input and omit both previous_response_id and
conversation. Known continuation IDs bypass Stage even with full input
history. Send x-switchyard-session-final: true when the shared session ends to
clear all of its agents’ state.
When migrating from the removed plan_execute type, use this recipe and replace
planning_prompt with capable_system_prompt. Stage has no exact equivalent
for the old judged handoff or reasoning-to-text conversion; keep the plan in
ordinary conversation text so the executor receives it.
Optional: custom tool semantics
Extend the built-in coding vocabulary when an agent uses domain-specific tool names. Mappings are route-scoped, additive, and matched by exact name without regard to ASCII case:
The categories affect existing stage signals:
observecounts as investigation, like the built-in read and search tools.mutatecounts as production, like the built-in write and edit tools.plancounts as investigation, like the built-in planning tools.newrecords forward activity that suppresses falsespinningandexploringsignals, but does not otherwise favor either tier.- Unmatched tools remain
unknown; there is nounknownconfiguration key.
Configuration cannot reclassify a built-in tool. Empty names, duplicate names across categories, and unknown category keys are rejected when the route is loaded. Argument-aware wrapper tools, inferred semantics, and learned routing rules are outside this exact-name configuration.
MCP tools match by their bare tool name or by their full name. Claude Code sends
an MCP tool as mcp__<server>__<tool>, and Codex sends it with a separate
namespace. For both, send_payment_request matches the send_payment_request
tool on the billing MCP server, and so does
mcp__billing__send_payment_request. A server name that contains __ needs the
full name.
Optional: handoff notes
Add a [routes.stage.handoff_notes] section to append contextual guidance to a
request when tool signals decide its tier. Notes exist only in the forwarded
request; they do not accumulate in the caller’s conversation. The escalation
note accompanies a signal-driven capable decision, and the optional de-escalation
note accompanies a signal-driven efficient decision.
Classifier and picker-default decisions do not add handoff notes.
Optional: LLM classifier fallback
The block is optional. Without it, an ambiguous turn goes directly to the
picker tier.
To judge ambiguous turns with a model call, add the block. The classifier runs when the scorer has no tool history or produces a score inside the closed ambiguous band:
prompt replaces the packaged capability-classifier prompt. In the default
json_schema mode, Switchyard sends the verdict schema through the
structured-output request. Set response_format_type = "json_object" for
providers that only support JSON Object mode; Switchyard then adds the schema to
the judge prompt and validates the returned object locally. The verdict schema
and routing thresholds remain unchanged.
The nested stage table in Composite Routing does not
accept a classifier block. Its outer classifier supplies the tier used when
the stage signals are ambiguous.
Give the classifier its own LLM client or quota bucket where possible. Sharing one provider bucket with the efficient tier adds a request per classified turn and can cause sustained 429s at scale.
Observability
When a model serves the request, the response identifies it with this routing header:
Decision sources
The router labels each resolved turn with a decision_source. /v1/stats
counts turns by it under algorithm_stats.stage_router.routing_decisions, and
the stage router override log line carries it for overrides. With
cache_aware, the label is Stage’s pick before the
cache-aware check, which reports its own decisions:
When not to use stage-router
- Single-model deployments. Use a
passthroughroute instead. - Probabilistic A/B splits. Use
Random Routing (
type = "random"). The stage-router’s signals are wasted on a fixed traffic ratio. - No tool-result history. Stage-router needs meaningful tool-call traffic to populate its signals. For pure chat-completion workloads, the signal scorer abstains; the optional classifier decides, or the request uses the picker default when no classifier is configured.
Related
- Model Selection: choose and check the two models before tuning the threshold.
- Mechanics of Libsy: the execution model and host responsibilities.
- TOML Schema: the complete configuration reference.
- Tuning: check your current route and compare candidate settings on your workload.