← Catalog

@underactive/pi-topping-routesense

LiteLLM-style Jev auto-router provider for pi (routesense)

Extension

Install

Install with PiG

pig install npm:@underactive/pi-topping-routesense

Install with Pi

pi install npm:@underactive/pi-topping-routesense
Review before installing

Packages run code with your permissions and influence agent behavior. Catalog inclusion is not a security audit. Review the source before installing a third-party package.

Pi manifest JSON

The pi field of package.json.

{
  "extensions": [
    "./index.ts"
  ]
}

README

Written by the package's publisher, shown as published in version 0.2.0 (README.md). PiG does not review it.

pi-topping-routesense

RouteSense is a pi extension that adds routesense/default and independently configured named routesense/<id> virtual models: a TypeScript port of LiteLLM's Auto Router v2, with the Jev classifier deciding which tier serves each request. Named profiles may also be random pools that skip classification and pick a physical model by weight each user turn.

The extension is built entirely on virtual models. pi's virtual-model API lets an extension register a selectable catalog entry whose route() function picks a physical model for each request. Every routesense/<id> is such an entry and route() is the router: there is no proxy provider, no pi.setModel() call, and no stream wrapper. See How the extension uses virtual models.

Select a routesense/<id> in /model. The built-in default and named classifier profiles route through their own tier candidates and default model; named random profiles choose from their own weighted pool and skip classification. default is always a classifier profile. Classifier, heuristic, and other routing settings are shared. pi dispatches to the chosen physical model itself, so any provider pi can talk to is a valid target, including bridge providers such as claude-bridge, openai-codex, and cursor. Detailed decision logs identify the selected virtual model, while /session attributes cost per physical model.

Install

pi install npm:@underactive/pi-topping-routesense
# inside pi:
/routesense init          # creates/updates the built-in default profile
/routesense models create Fast
/routesense settings      # tiers, defaults, and named classifier or random models with their pools
/model                    # pick routesense/default or routesense/fast

For development: pi -e ./index.ts --model routesense/default.

Classifier profiles send each user ask, and up to three prior user turns, to a Jev classifier. With no jevClassifierConfig pin, the first credentialed provider among typesafe, openrouter, cloudflare-workers-ai, vercel-ai-gateway and opencode is used. Pin jevClassifierConfig.provider/.model (or the Classifier model row in /routesense settings, which lists every classifier model pi has credentials for), or set classifierType: "heuristic", to control or prevent this. Without any of these credentials, classifier routing uses the heuristic scorer and warns once. Random profiles do not require Jev credentials because they skip classification.

How the extension uses virtual models

A pi virtual model is selectable like any other model but never reaches a provider. Before every request pi asks the entry's route() function for a physical model and thinking level, and everything below that step sees only the physical model. The selection (ctx.model, model_change entries) names routesense/<id>; each assistant message records the physical model that answered. This extension is that route() function plus the registration, state, and bookkeeping around it. pi documents the API in docs/virtual-models.md in its package.

pi virtual-model featureHow the extension uses it
pi.registerVirtualModel / unregisterVirtualModelOne virtual model per profile under provider routesense: the built-in default plus every named profile. Registrations follow the config: they are replaced when profiles or enabled change and removed by /routesense off, --no-routesense, or deleting a profile. A selected model that is unregistered falls back to the physical model that answered last.
route() and reasonOne shared router serves every profile and reads its type-specific config from request.model.id: classifier profiles use tiers/defaults, random profiles use a weighted pool and skip classification. Each of the four reasons is handled differently (How a request is routed). A fresh random continuation makes a new pool pick; a fresh classifier continuation is classified like a user turn.
Router state{ v: 1, last, compaction?, turn?, hold? }: the physical model, thinking level, and resolved/served tier of the last user or retry decision. hold separately stores the committed requested-complexity tier for hysteresis. Optional tool-signal markers record a handled compaction or one mid-turn switch. pi stores state on the session branch, so it follows forks and survives compaction. It is the fallback target when a continuation's previous model is unavailable and the starting point for a retry. Normal continuations leave it unchanged; direct requests carry none. v remains 1.
thinkingLevelsNot advertised, so pi offers only off for the selection. The session level therefore carries no routing meaning: every tier or pool entry states the level it runs at.
contextWindow, maxTokensAdvertised as the largest values among the active profile's credentialed tier/default models or positive-weight pool members. pi shows them until the first response, then uses the limits of the model that answered.
inputNot set, so pi's default (text and images) applies.
ctx.modelRegistrygetAvailable() supplies the physical models a tier or random pool can name; virtual models are filtered out because a virtual model cannot route to another. findOfType("classifier", …) and classify() are used only by classifier profiles; random profiles skip them. getModelsOfType("classifier") fills the settings TUI's Classifier model picker.

Three pieces sit on top of the API:

  • Routing announcements. An assistant message names the physical model only once it streams, so the router emits each decision on pi's event bus first (Announcing the routed model).
  • Outcome stats. message_end pairs each assistant message with the latest decision by its provider/model key, which attributes cost, latency, and savings to the recorded virtual-model type and its configured tier or random pool (Stats).
  • Usage leases. pi keeps no cross-process record of which sessions have a virtual model selected, so each live pi or subagent session leases the named profile it uses, which blocks rename and delete while it is in use (Virtual models).

How a request is routed

pi calls the router before every request made with the virtual model and tells it why:

ReasonWhat the router does
user (a turn the user wrote)Classifier profile: classify and pick a tier model (pipeline below). Random profile: make one weighted pool pick; classification is skipped.
continuation (tool results, follow-ups inside the turn)Stay on the model that handled the turn, keeping prompt caches and thinking signatures valid. With opt-in toolSignals.midTurn: "escalate", a hard E1/E2 signal may switch once to a different capable-tier deployment. If there is no sticky target, a random profile picks from its pool; a classifier profile classifies the fresh turn.
retry (pi retries a failed request)Classifier profile: context overflow prefers a larger-window tier/model; other errors cool the failed deployment and follow the tier fallback chain. Random profile: cool and exclude the failed pool member, then re-pick; for context overflow prefer a positive-weight pool member with a larger known window, otherwise stay on the failed model. Retries retain the failed request's thinking level.
direct (compaction summaries and other requests outside the agent loop)Classifier profile: the default model. Random profile: a fresh weighted pool pick, with no router state.

Random-profile picks use weight / sum(eligible positive weights) among credentialed, positive-weight members not cooled for that draw. Zero weight is never a standby; if every positive member is cooled, cooldowns are bypassed among those positive members. A selected model stays sticky across tool steps. Random routes do not invoke the Jev classifier, heuristic scorer, keyword rules, or escalation pipeline.

Tip: Include PI ESCALATE in your prompt to raise the served tier by one step. The phrase is exact and case-sensitive; configure alternatives with escalationKeywords.

The classification pipeline below applies only to classifier profiles:

  1. Extract the ask. Complete harness reminder blocks (<system-reminder>...</system-reminder>, configurable with reminderMarkers) are stripped; a turn that strips to nothing is skipped in favour of the previous real ask, and a request with no ask at all goes to the default model (cause=empty_ask).

  2. Keyword rules. The first keywordTierRules entry whose keyword appears in the ask (word-bounded, case-insensitive) picks the tier (cause=literal_keyword_match).

  3. Tool signals (optional). When toolSignals.enabled is true, completed tool results from the recent branch transcript can adjust the classifier tier or choose a tier directly. Keyword rules always win; the default is off. See Tool-signal routing.

  4. Classify. In adjust mode, classifierOrder controls which classifier runs first when classifierType is "jev":

    • "jev_first" (default) asks Jev on every turn. Jev receives one System One choice question (tier) whose criteria describe the four tiers, with the ask, up to three prior user turns within an 8,000-character budget, and a conversation-depth line as state (cause=jev_classifier).
    • "heuristic_first" runs the local LiteLLM scorer first. A conclusive verdict is used immediately (cause=heuristic_scorer); an inconclusive verdict is sent to Jev with the same request context.

    Jev times out after 3 s by default. A recognised timeout opens a circuit breaker for 30 s; one probe is allowed afterwards. When Jev is unavailable, times out, errors, or returns an unknown tier, classifierFallback decides: heuristic (default) uses the already-computed result in heuristic-first mode, while default_model uses the default model (cause=default_model_fallback).

    A heuristic verdict is conclusive when the reasoning override fired or a content dimension crossed LiteLLM's match threshold and has a positive configured weight. tokenCount never counts as content evidence because it fires on content-free requests at both short and long extremes; a zero-weight dimension contributed nothing and does not count either. A short request with retained prior turns is also inconclusive, so context-dependent follow-ups reach Jev. This follow-up guard depends on classifierContextWindowSize > 0 and a non-empty retained context window.

  5. Hysteresis (optional). For classifier profiles, when enabled, a lower verdict must repeat for confirmations consecutive user turns before the committed tier drops. Upgrades are immediate; keyword rules and verified D1 de-escalation are explicit and immediate. This step is off by default and is described in Turn-to-turn hysteresis.

  6. Escalation keyword. An exact, case-sensitive escalationKeywords phrase in the ask bumps the served tier by one (PI ESCALATE by default), including a tier held by hysteresis; the bumped tier is committed. It suppresses a tool-signal de-escalation.

  7. Context-window escalation. When enabled, a tier whose models provably cannot hold the prompt (estimated tokens above contextWindowEscalationBuffer of the window) hands the request to the lowest higher tier that fits. Unknown windows are never escalated from or onto; this capacity move does not change the committed hysteresis tier.

  8. Resolve the tier. For classifier profiles, a tier naming one model pins it. A pool with a weight on every member is sampled by those percentages after context-fit and cooldown filters; percentages are renormalized over the surviving members. A 0% tier member is standby: it is picked only when no positive-weight member remains usable and warm. When at least one tier-pool member has no weight, that pool is sampled uniformly. Models whose provider has no credentials or that are cooling down after a failure are skipped. A tier with nothing usable falls through to more capable tiers, then cheaper ones, then the default model. Cooldowns are ignored only when everything is cooled. /routesense tier replaces the entire tier pool with a single entry and drops its weights; use /routesense settings or edit the config to change tier shares. Random-profile weights have different semantics: they are relative nonnegative weights with no upper bound, and zero is never picked.

  9. Thinking level. Each tier or pool entry runs at its own thinkingLevel, chosen in the settings picker or written in the config. The virtual model advertises no levels, so the session selection is always off and never reaches a routed model; an entry with no thinkingLevel runs at off on a fresh user turn. Continuations keep the level already serving the turn; a mid-turn escalation runs at the target entry's level, or the serving level when the entry has none; retries keep the failed request's level. The level is not used for Jev classification or tier selection. pi clamps it to what the physical model supports.

Tool-signal routing

Tool-signal routing is an opt-in extension feature inspired by Switchyard's stage router; it is not part of LiteLLM. It reads completed tool-call/result pairs from request.messages, which is already scoped to the current session branch. No global tool-event buffer is used, so forks and resumed branches evaluate their own history. The default toolSignals.enabled: false leaves existing routing, state, logs, announcements, and stats unchanged.

For classifier profiles, the router scans up to windowSteps recent assistant tool-call steps (default 6), crossing user-turn boundaries and stopping at compaction. Mid-turn evaluation uses only the current user turn. Unfinished tool calls are ignored.

Transcript evidenceInterpretation
Tool name matched by readTools, writeTools, or shellToolsRead, write, or shell activity; * matches tool-name sequences such as mcp__*__read. Unmatched tools are other.
isError plus Pi's shell status textexit, timeout, and non-shell errors are hard errors; Command aborted is ignored; blocked, not-found, and unrecognized shell errors are uncertain.
Successful write-kind resultProgress evidence for E2 and D1. Writes performed through bash are not visible as write tools.
Recognized shell test commandA successful result is a pass; exit/timeout is a fail. A pipe without pipefail, `
Compaction summary user messageFires E3 once per summary timestamp, persisted in branch state.

Rules run in this order:

  • E1, hard-error streak: escalate after errorStreak counted hard errors in a row (default 3). Pi's exit, timeout, and non-shell tool errors count; aborted and uncertain/blocked results do not. Uncertain errors contribute half weight only to the score.
  • E2, repeated failure: escalate when an identical tool call fails again with no successful write between failures and both failures are newer than the latest passing test run.
  • E3, compaction: user-turn evaluation escalates once per new compaction summary in the signal window. A small marker in branch state prevents re-triggering while the summary remains in the transcript.
  • D1, verified progress: de-escalate to the configured efficient tier when a recognized test command passes after at least one successful write and the later transcript tail is clean (no errors or unverified writes). testCommandPatterns are anchored regexes matched against normalized shell-command segments. Piped commands without pipefail, || commands, and ambiguous results do not qualify.
  • Weighted activity score: after minToolResults (default 3), errorRate = (exit + timeout + tool + 0.5 × uncertain) / results; spinning = 1 for a full window without reads or writes; exploring = reads / results when there are no writes; and writing = writes / (reads + writes) when errorRate < 0.25. The score is clamp(errorsWeight × errorRate + spinningWeight × spinning + exploringWeight × exploring − writingWeight × writing, −1, 1). Scores at or above confidenceThreshold (default 0.5) give an up verdict; scores at or below its negative give a down verdict. Set all weights to zero to disable scoring while keeping the hard rules.

In mode: "adjust" (default), the classifier still runs: an up verdict raises the base tier to at least capableTier (default COMPLEX), and a down verdict lowers it to at most efficientTier (default MEDIUM). This is monotone and leaves the classifier's cause intact. In mode: "decide", conclusive signals choose a tier without a classifier call; absent, inconclusive, and escalation- keyword-suppressed verdicts use fallOpen (classifier by default, or a fixed efficient/capable tier). Keyword-tier rules always win and skip signal evaluation.

midTurn: "escalate" optionally permits one E1/E2 switch during a user turn when the capable tier resolves to a different physical model. It is off by default because switching mid-turn can cause a prompt-cache miss. It never de-escalates or scores mid-turn; a branch marker prevents another switch on later tool steps. Retry, direct, and random-profile routes ignore tool signals.

Pi exposes error status text rather than a structured exit code, so error and test detection depend on its wording. Blocked calls are conservatively marked uncertain; bash-based writes are invisible; provider failures are handled by the retry path; nested tool calls are not counted. When the selected virtual model is first enabled mid-session, recent activity already on that branch can count until it ages out of the step window. /routesense test remains prompt-only and reports that it did not inspect tool signals when the feature is enabled.

Turn-to-turn hysteresis

Hysteresis is opt-in for classifier profiles and disabled by default. It dampens only ordinary downgrades between user turns; it never chooses a physical deployment, so normal tier-chain and default-model fallthrough still handle unavailable models. Random profiles skip it.

"hysteresis": { "enabled": false, "confirmations": 2 }

hold.tier (H) is the committed requested-complexity tier, before context-window escalation and deployment fallback. With no hold, the first tiered verdict commits immediately. Upgrades and equal verdicts commit immediately and clear a pending lower streak. An ordinary lower verdict is held at H until there are confirmations consecutive lower verdicts; the confirming turn counts, and the release target is the highest tier seen during that streak. Any verdict at or above H resets the streak. The default is 2 confirmations; valid values are 1–10, with 1 releasing on the first lower verdict.

For example, with N=2, candidate tiers MEDIUM, COMPLEX, MEDIUM, COMPLEX, MEDIUM, MEDIUM serve as MEDIUM, COMPLEX, COMPLEX, COMPLEX, COMPLEX, MEDIUM. The first COMPLEX verdict upgrades immediately. The MEDIUM turns at positions 3 and 5 are held at COMPLEX; the equal COMPLEX verdict at position 4 resets the first streak. The final MEDIUM verdict releases the two-turn streak. held=COMPLEX 1/2 and released=COMPLEX 2/2 explain the transitions.

VerdictBehavior
Jev, heuristic, heuristic fallback (including open circuit), heuristic-first, and scored tool-signal resultsOrdinary votes; lower tiers wait for consecutive confirmations.
Keyword tier rules and verified D1 tool-signal de-escalationExplicit transitions in either direction; immediate.
Escalation keywordApplied after hysteresis to the served tier, then commits the bumped tier.
Tierless verdict (empty_ask, classifierFallback: "default_model")Does not vote and leaves the hold unchanged.
Context-window escalation, cooldown/chain fallthroughMay serve a different deployment/tier for this request; the pre-resolution verdict still votes normally, but the capacity/fallback tier is not committed.
Overflow retryMay serve a larger-window tier/model; carries the hold unchanged and never votes.
Mid-turn E1/E2 hard-error escalationMay raise the hold to toolSignals.capableTier and clears pending downgrades; otherwise carries it.
Retry, sticky continuation, direct request, random profileDoes not vote. Retries and continuations carry state; direct and random routes do not use a classifier hold.

The streak counts consecutive user turns that reach classification, including steering and follow-up messages. Tierless turns do not count as confirmations. The newest non-compaction user-message timestamp is stored as a best-effort anchor so the same turn routed twice cannot vote twice. Pi writes branch state before dispatch, so a request that later fails has already recorded its vote; the retry itself does not add another vote.

hold is optional in the existing RoutingState v1 and is written only when enabled. It follows the selected routesense/<id> branch across forks, resume/restart, and compaction; each profile has independent state. Disabling hysteresis drops the hold on the next user turn. The classifier-context window and character budgets above still bound what each verdict sees; there are no additional hysteresis window settings. /routesense status shows the committed tier and pending count, and /routesense test notes that prompt-only classification does not evaluate hysteresis.

Heuristic scorer

src/classifier/heuristic.ts ports LiteLLM's rule-based scorer: seven weighted dimensions (tokenCount, codePresence, reasoningMarkers, technicalTerms, simpleIndicators, multiStepPatterns, questionComplexity) summed and mapped to tiers with tierBoundaries (0.15 / 0.35 / 0.60 by default). Tokens are estimated as characters divided by four, as in LiteLLM, so tokenThresholds keep the meaning LiteLLM tuned them for. Two or more reasoning markers promote a request to REASONING when its score reaches reasoningOverrideMinScore (the simpleMedium boundary unless set). customTechnicalKeywords extends the built-in technical term list. The scorer reads only the stripped human ask. Set classifierType: "heuristic" to route with it alone.

With classifierType: "jev" and classifierOrder: "heuristic_first", the scorer decides on its own only when it has positively weighted content evidence or the reasoning override. Content-free verdicts and short contextual follow-ups defer to Jev.

Configuration

~/.pi/agent/pi-topping-routesense/config.json (honours PI_CODING_AGENT_DIR). The built-in default profile is always classifier-type. A named profile is classifier-type by default and has its own LiteLLM-shaped tiers and defaultModel; set "type": "random" to instead give it a pool and skip classification. Both kinds can be created and edited in /routesense settings without touching the file. Classifier, heuristic, and other router settings remain global. Model references are provider/model-id exactly as /model shows them. A tier value is a string, an object { "model", "thinkingLevel", "weight" }, or an array of those (a tier pool); tier weights are percentages from 0 to 100. thinkingLevel is the level that entry runs at, and omitting it means off. Random-pool weights are nonnegative relative weights without a maximum and are normalized over the positive-weight members.

{
  "version": 2,
  "enabled": true,
  "profiles": {
    "default": {
      "defaultModel": { "model": "anthropic/claude-sonnet-5", "thinkingLevel": "medium" },
      "tiers": {
        "SIMPLE": "anthropic/claude-haiku-4-5",
        "MEDIUM": "anthropic/claude-sonnet-5",
        "COMPLEX": [
          { "model": "anthropic/claude-sonnet-5", "weight": 60 },
          { "model": "openai-codex/gpt-5.6-sol", "weight": 40 }
        ],
        "REASONING": { "model": "claude-bridge/claude-opus-5-5", "thinkingLevel": "high" }
      }
    },
    "fast": {
      "name": "Fast",
      "tiers": { "SIMPLE": "anthropic/claude-haiku-4-5", "MEDIUM": "anthropic/claude-sonnet-5" }
    },
    "mix": {
      "name": "Mix",
      "type": "random",
      "pool": [
        { "model": "anthropic/claude-haiku-4-5", "weight": 5 },
        { "model": "openai-codex/gpt-5.6-sol", "weight": 3, "thinkingLevel": "high" },
        { "model": "claude-bridge/claude-opus-5-5", "weight": 2 }
      ]
    }
  },
  "classifierType": "jev",
  "classifierOrder": "jev_first",
  "jevClassifierConfig": {
    "provider": "typesafe",
    "model": "jev-latest",
    "timeoutMs": 3000,
    "circuitBreakerEnabled": true,
    "circuitBreakerCooldownSeconds": 30
  },
  "classifierFallback": "heuristic",
  "classifierContextWindowSize": 3,
  "classifierContextBudgetChars": 8000,
  "classifierContextPerTurnChars": null,
  "classifierContextIncludeAssistantTurns": false,
  "reminderMarkers": [{ "open": "<system-reminder>", "close": "</system-reminder>" }],
  "keywordTierRules": [{ "keywords": ["migration", "security review"], "tier": "REASONING" }],
  "escalationKeywords": ["PI ESCALATE"],
  "enableContextWindowEscalation": true,
  "contextWindowEscalationBuffer": 0.95,
  "tierBoundaries": { "simpleMedium": 0.15, "mediumComplex": 0.35, "complexReasoning": 0.6 },
  "tokenThresholds": { "simple": 15, "complex": 400 },
  "dimensionWeights": { "tokenCount": 0.1, "codePresence": 0.3, "reasoningMarkers": 0.25, "technicalTerms": 0.25, "simpleIndicators": 0.05, "multiStepPatterns": 0.03, "questionComplexity": 0.02 },
  "customTechnicalKeywords": [],
  "cooldownSeconds": 60,
  "decisionLog": true,
  "toolSignals": {
    "enabled": false,
    "mode": "adjust",
    "fallOpen": "classifier",
    "midTurn": "off",
    "windowSteps": 6,
    "minToolResults": 3,
    "confidenceThreshold": 0.5,
    "errorStreak": 3,
    "escalateOnCompaction": true,
    "capableTier": "COMPLEX",
    "efficientTier": "MEDIUM",
    "weights": { "errors": 0.8, "spinning": 0.3, "exploring": 0.2, "writing": 0.5 },
    "testCommandPatterns": [
      "^(npm|pnpm|yarn|bun)\\s+(run\\s+)?test\\b",
      "^node\\s+--test\\b",
      "^(vitest|jest|mocha|pytest|rspec|phpunit)\\b",
      "^go\\s+test\\b",
      "^cargo\\s+(test|nextest)\\b",
      "^make\\s+test\\b",
      "^(mvn|gradle|\\./gradlew)\\b.*\\btest\\b",
      "^dotnet\\s+test\\b",
      "^mix\\s+test\\b"
    ],
    "readTools": ["read", "grep", "find", "ls"],
    "writeTools": ["edit", "write"],
    "shellTools": ["bash", "powershell"]
  },
  "hysteresis": { "enabled": false, "confirmations": 2 }
}
KeyDefaultPurpose
enabledtrueRegister all profiles. /routesense on and off toggle and persist it.
profiles.default.defaultModel / profiles.default.tiersunset / {}The built-in model's direct/default fallback and tier pools. Missing tiers fall through the chain.
profiles.<id>.namederived from idDisplay name for a named model. Classifier profiles have defaultModel and tiers; random profiles have pool.
profiles.<id>.typeclassifier (default)"random" selects a weighted pool. Invalid or unknown type values fall back to classifier; default is always classifier.
profiles.<id>.pool[]Random only: an array of { "model", "weight", "thinkingLevel?" } objects, edited in /routesense settings or in the file. An empty pool is valid but routes nothing (no config) until a model is added.
pool[].weightrequiredRandom only: finite, nonnegative relative weight, with no upper bound. After credential and cooldown filtering, probability is weight / sum(eligible positive weights); 0 is never picked, even as a fallback. At least one weight must be positive and the sum must be finite.
pool[].thinkingLeveloffRandom only: level (off, minimal, low, medium, high, xhigh, max) used when this member is picked. Omitting it means off; the settings picker always writes one.
tier-entry.weightunsetClassifier tier pools only: optional 0–100 percentage share. A 0% tier member is standby; an unweighted or partly weighted tier pool stays uniform.
classifierType"jev""jev" or "heuristic".
classifierOrder"jev_first"With the Jev classifier, "jev_first" asks Jev every turn; "heuristic_first" uses conclusive local verdicts and asks Jev for content-free or short contextual follow-ups. Ignored in heuristic-only mode.
jevClassifierConfig.provider / .modelfirst configured known Jev modelAny classifier model in pi's catalog; /routesense settings lists those with credentials. Known Jev models: typesafe/jev-latest, openrouter/typesafe/jev-1.13, cloudflare-workers-ai/typesafe/jev, vercel-ai-gateway/typesafe-ai/jev, opencode/jev-1.13.
jevClassifierConfig.timeoutMs3000Classifier deadline.
jevClassifierConfig.circuitBreakerEnabled / .circuitBreakerCooldownSecondstrue / 30Skip Jev for the cooldown after a timeout; one probe afterwards.
classifierFallback"heuristic""heuristic" or "default_model".
classifierContextWindowSize3Prior user turns sent to the classifier. 0 sends the ask alone.
classifierContextBudgetChars8000Total prior-turn characters; the oldest turns are dropped first.
classifierContextPerTurnCharsnullOptional per-turn clip.
classifierContextIncludeAssistantTurnsfalseCount assistant replies in the window and label turns by role.
reminderMarkers<system-reminder> pairHarness block delimiters stripped before classification. Replaces the default list.
keywordTierRules[]{ keywords, tier } rules, first match wins.
escalationKeywords["PI ESCALATE"]Exact phrases that raise the tier by one.
enableContextWindowEscalation / contextWindowEscalationBuffertrue / 0.95Move oversized prompts to a higher tier with capacity.
tierBoundaries, tokenThresholds, dimensionWeights, customTechnicalKeywords, reasoningOverrideMinScoreLiteLLM defaultsHeuristic scorer knobs.
cooldownSeconds60How long a deployment that failed a request is skipped (per pi process).
decisionLogtrueShow detailed decision entries in the TUI or write decision lines to stderr (pi -p, RPC). When disabled, routing decisions are not written to the transcript or stderr.
toolSignals.enabledfalseEnable transcript-derived signals for classifier profiles. Off means unchanged routing.
hysteresis.enabledfalseHold a classifier profile's committed tier between turns when a lower verdict arrives; off preserves per-turn routing.
hysteresis.confirmations2Consecutive lower verdicts before downgrade (integer 1–10); release goes to the highest tier seen in that streak.
toolSignals.mode / .fallOpenadjust / classifierAdjust the classifier tier, or decide directly; in decide mode, inconclusive signals fall back to the classifier or a configured fixed tier.
toolSignals.midTurnoff"off" or "escalate"; opt into one hard-error switch per user turn.
toolSignals.windowSteps, .minToolResults, .confidenceThreshold, .errorStreak6, 3, 0.5, 3Recent step window, minimum scored results, score threshold, and hard-error streak length. The window is 1–50 steps; error streak is at least 2.
toolSignals.escalateOnCompactiontrueEscalate once for a new in-window compaction summary.
toolSignals.capableTier / .efficientTierCOMPLEX / MEDIUMFixed up/down targets; capable must be above efficient.
toolSignals.weights0.8 / 0.3 / 0.2 / 0.5Nonnegative { errors, spinning, exploring, writing } score weights. All zero disables scoring.
toolSignals.testCommandPatternsanchored test-command regexesShell commands recognized by D1. Invalid regexes are dropped; [] disables test detection.
toolSignals.readTools, .writeTools, .shellToolsread/grep/find/ls, edit/write, bash/powershellComma-separated tool-name globs; * matches any sequence.

Invalid global values fall back to their defaults individually; the file is rewritten atomically. Random pools are validated as arrays of model/weight objects: each model must be provider/model-id, each weight must be finite and nonnegative, an optional thinkingLevel must be recognized, and a non-empty pool must have a finite, positive weight sum with at least one positive member. An empty array is an unconfigured pool, not an error. The first validation error is shown verbatim in routing errors, warnings, status, models list, and the settings-menu pool row. Exact validation messages:

Invalid inputMessage
Missing or non-array poolpool must be an array of { "model", "weight" } entries
Entry is not an objectpool[i] must be an object with "model" and "weight"
Invalid model referencepool[i].model must be "provider/model-id"
Missing or non-finite weightpool[i].weight must be a finite number
Negative weightpool[i].weight must be 0 or greater
Invalid thinkingLevelpool[i].thinkingLevel must be one of off, minimal, low, medium, high, xhigh, max
Weight sum is non-finitepool weights must add up to a finite number
Weight sum is zeropool weights add up to 0; give at least one model a positive weight

An invalid pool remains listed but cannot route; the original raw pool value is preserved verbatim when unrelated settings are saved, and adding a model to it in the settings menu replaces the invalid entries on Save. If no positive-weight pool member has credentials, routing fails rather than selecting a zero-weight entry.

Version 1 files migrate to profiles.default on read and are rewritten as version 2 on the next settings update; the first such update saves the original file once as config.v1.json. Unknown type values fall back to classifier, so a typo can cause the random pool to be lost on a later save. Older extension builds that do not understand random profiles can rewrite a random profile as an empty classifier profile, and builds predating tool signals or hysteresis can drop those settings blocks on save. Back up or downgrade only after checking the new schema. Restart every pi process that might touch the config after upgrading; mixed-version processes can overwrite newer profile data.

Routing, status, advertised limits, the savings baseline, the settings TUI model picker, and /routesense init all read one catalog: every physical chat model whose provider has credentials. pi's --models / enabledModels session scope does not constrain it. A model you pick in the settings TUI or name in a classifier tier or positive-weight random pool stays a routing target even when it sits outside the current session's scope. A virtual model advertises limits from the configured classifier deployments or credentialed positive-weight random-pool members. /routesense init ranks the same unscoped catalog, so its generated ladder covers every credentialed model for the provider you choose. Candidate edits made in another pi process are re-read at the next routing request; the physical model already selected for an in-flight request or sticky continuation is not changed.

Virtual models

The built-in default model always remains classifier-type and available when routing is enabled. Create named classifier profiles with /routesense models create Fast or in the settings menu; the id is the lower-case slug, so Fast becomes fast and appears in /model as routesense/fast. Create random profiles with New random virtual model in the settings menu and add pool models and weights there (Settings TUI), or write them in config.json. Names are 1–40 characters, default is reserved, and renaming changes the id. /routesense init, /routesense tier, and /routesense default continue to edit only default; models tier and models default edit classifier profiles and refuse random profiles with a message directing you to /routesense settings.

Select a model with /model routesense/fast, --model routesense/fast, pi's session settings model picker, resume when the saved model is still registered, a scoped enabledModels entry, or a subagent's model: option when that child loads extensions. Each selected classifier model uses its own tiers/default; a random model uses its own weighted pool. Classifier, heuristic, cooldown, and enabled settings are shared, but random profiles skip classification. Candidate changes take effect on the next request; a continuation keeps its current physical model.

A named model is in use while any live pi or background subagent session has it selected, not just while a request is streaming. Rename and delete are refused until all such sessions switch away or exit; /routesense models leases <id> shows the holders. Lease files live under ~/.pi/agent/pi-topping-routesense/usage/<id>/ and are removed on switch, shutdown, or process exit. Reloads hand the lease to the replacement extension instance. There is no lease for default.

This protection coordinates extension writes on a local filesystem; manually editing config.json bypasses it, and leases from another host are conservatively treated as live. A foreground pi-subagents child that inherits only providers does not load this extension and cannot select routesense/*; background runner children load it in their own process. A rename or delete does not automatically switch a session that still has the old id selected: choose another model with /model.

Export and import

/routesense models export [path] exports every virtual model's type, name, classifier defaultModel and tiers, or random pool, including thinking levels and weights. For example, profile entries have these fields:

{
  "format": "routesense-models",
  "version": 1,
  "exportedAt": "2026-10-15T12:00:00.000Z",
  "virtualModels": {
    "default": {
      "type": "classifier",
      "name": "default",
      "defaultModel": { "model": "anthropic/claude-haiku-4-5" },
      "tiers": {
        "SIMPLE": [
          { "model": "anthropic/claude-haiku-4-5", "weight": 60 },
          { "model": "openai/gpt-5-mini", "thinkingLevel": "low", "weight": 40 }
        ],
        "MEDIUM": [{ "model": "anthropic/claude-sonnet-5" }],
        "COMPLEX": [],
        "REASONING": [{ "model": "anthropic/claude-opus-5", "thinkingLevel": "high" }]
      }
    },
    "mix": {
      "type": "random",
      "name": "Mix",
      "pool": [{ "model": "anthropic/claude-sonnet-5", "thinkingLevel": "high", "weight": 3 }]
    }
  }
}

The default file is ./routesense-models.json in the project directory. In the TUI, export asks before overwriting; outside the TUI, it refuses to overwrite an existing file. Import is TUI-only and uses the same default file. Its picker starts new profiles checked and existing profiles unchecked; invalid entries and profiles whose type would change are disabled. Global settings are not exported or imported. Import replaces each selected profile whole. The built-in default remains classifier-type and keeps its name; type changes are refused. Unavailable models are kept and warned about, not rejected. Invalid random pools are exported as-is but refused on import. Paths resolve against the project directory and a leading ~ expands. The command parser splits arguments on whitespace, so paths containing spaces are not reliably supported.

Local or alternative Jev-compatible classifiers

The classifier call goes through pi's model registry, so any model that speaks the System One protocol (POST <baseUrl>/systemone) works. Point the built-in TypeSafe provider at a local server with pi's models.json:

{ "providers": { "typesafe": { "baseUrl": "http://127.0.0.1:8000/v1/" } } }

or select another provider's Jev model with jevClassifierConfig.provider and .model. Other classifiers pi serves, such as llama.cpp decision models, Cloudflare Clef, and GPT-6 Luna, appear in the Classifier model picker of /routesense settings once their provider has credentials; a drop-in endpoint behind an existing provider still needs the models.json redirect above. /routesense test <prompt> classifies without routing, so you can check which classifier answered (it may spend one classifier call).

Commands

CommandPurpose
/routesense or /routesense statusSelected model's enabled state, classifier and credential source, circuit state or random pool, active cooldowns, last decision, and summaries of other profiles. When tool signals are enabled on a classifier profile, status shows their mode, window, tier targets, and mid-turn setting; enabled hysteresis adds its confirmation count, committed tier, and pending count.
/routesense init [provider]Rank the models pi can reach by price and write a starter config for default: cheapest to SIMPLE, most expensive to REASONING (with thinkingLevel: "high" when it reasons). Named profiles are preserved. Price is only a proxy for capability; review the result.
/routesense models [list]List profile ids, display names, per-tier candidate counts or random pool size/invalid status, and live lease counts.
/routesense models create <name…>Create an empty named classifier profile; its id is derived from the name. Random profiles are created in /routesense settings.
/routesense models rename <id> <new name…> / delete <id>Rename or delete a named profile. Both are blocked while it is in use.
/routesense models tier <id> <TIER> <provider/model> [thinking]Replace one classifier profile's tier pool with one candidate. Candidate edits remain allowed while in use; random profiles refuse tier edits and direct you to /routesense settings.
/routesense models default <id> <provider/model> [thinking]Set a named classifier profile's default model. Random profiles refuse this edit and direct you to /routesense settings.
/routesense models leases <id>Show live lease pid, host, kind, session id, and age.
/routesense models export [path]Export every virtual model's profile data, including thinking levels and weights, to ./routesense-models.json in the project directory by default. TUI export asks before overwrite; outside the TUI an existing file is refused.
/routesense models import [path]TUI-only import from ./routesense-models.json in the project directory by default. The picker defaults new profiles to checked and existing profiles to unchecked; invalid entries and type changes are disabled.
/routesense explainThe last decision as a rail breakdown: reason, cause, tier with Jev's confidence bar, classifier, probabilities or heuristic signals, tool-signal action, and the route.
/routesense log [n]The last n decision lines (default 10, max 50), colored by field in the TUI.
/routesense statsThe stats TUI (below).
/routesense test <prompt>Run the classification pipeline on a prompt without routing. When tool signals or hysteresis are enabled, the output says they were not evaluated.
/routesense settings (/routesense config)Open the interactive settings editor.
/routesense tier <TIER> <provider/model> [thinking]Replace the default tier pool with a single model and save.
/routesense default <provider/model> [thinking]Set the default default model and save.
/routesense on / offRegister or unregister every virtual model and persist enabled. Selected virtual models fall back to their last physical model when unregistered.
--no-routesenseCLI flag: do not offer any routesense/* virtual model for this launch.

The settings, stats and import dialogs take their full size where the terminal has room (settings 108 columns by 32 rows, stats 112 by 33, import 104 columns and as tall as its list) and lay themselves out in a smaller one down to 80 columns by 24 rows: panes and lists lose rows and scroll, tables leave out their least-needed columns, and the key legend drops its least-needed keys. On a terminal smaller than that a dialog keeps the 80x24 layout and is cut. An open dialog follows a resize.

Settings TUI

/routesense settings (also /routesense config) edits every setting except the schema version in a dialog with a section sidebar: pick a section on the left and its rows fill the pane beside it. Rows show on/off, ‹ value › for cycles, › for rows that open a picker, and ● for a value changed since the last Save; a section holding a row that cannot be saved is marked !. The hint area explains the focused row, including validation errors, and Ctrl+R reverts it.

Choose a profile with Virtual model; classifier profiles show editable default and tier rows, random profiles show their pool. Create a classifier profile with New classifier virtual model or a random profile with New random virtual model, then add candidates or pool models and Save. Rename applies immediately from the name row; delete applies immediately after the armed second Enter. Both are disabled for the built-in model and while the profile is in use. Candidate and pool edits are still allowed while in use and are saved with Save. Cancel discards unsaved candidate, pool, and global-setting edits, but does not undo a rename or delete already applied. Classifier, heuristic, and tool-signal settings remain global. The Tool signals section is off by default; its mode, fall-open behavior, mid-turn option, tier targets, score thresholds/weights, and tool/test patterns are editable there. The Turn hysteresis section is also off by default; it controls consecutive lower verdicts before a classifier profile downgrades, and its confirmations row is dimmed while hysteresis is off. Fall-open is dimmed unless mode is decide.

Enter on the default model, a tier member or a pool member opens the model/thinking picker; its thinking pane lists only the levels the picked model supports, and the level you confirm is saved on that entry. Enter or → opens a tier to show its members. Tier and pool members show a share bar: ←→ (⇧ for 5) moves a share or pool weight in place, Backspace removes a member, and w (or Set weights…) opens the weight editor, which takes a percentage per model to two decimals. Tier shares must total 100%; a 0% tier member stays on standby, and a tier left with one model drops its shares. + Add model appends a member: at 0% to a weighted tier, with weight 1 to a pool. Pool weights are relative and need not total anything, but at least one must be positive; members show their share of the positive weights, and a weight of 0 is never picked. An empty pool saves as an unconfigured profile (no config). When config.json holds an invalid pool, adding a model replaces the invalid entries on Save, while saving other settings leaves them as they are.

The Classifier model row opens a filterable list of auto and every classifier model pi has credentials for, each with its API; Backspace on the row resets it to auto, and a pinned model that is no longer available is marked unavailable. The Classifier order row selects decision-model-first or heuristic-first routing and is dimmed when the classifier is heuristic-only.

Enter on a text row opens its inline editor; Enter commits the edit, and Esc reverts it. Save (Ctrl+S, or the Save button) validates, writes, and applies the draft, then closes the dialog; it is refused, with the reason in the hint area, while a tier's shares are off 100%, every pool weight is 0, a keyword rule or reminder marker is empty, or a value breaks a range. Esc from the sections, or Cancel, discards the draft, asking once more when there are unsaved changes. /routesense tier still replaces that tier's pool with one entry and clears its pool shares.

Decision log

With decisionLog enabled, each routed user turn and retry gets a detailed entry in the shape of LiteLLM's decision log, so cause= searches work the same way. Named profiles append virtual_model=<id>:

routesense: routing decision cause=jev_classifier, tier=COMPLEX, score=0.910, signals=[jev:COMPLEX 0.91], routed_model=anthropic/claude-sonnet-5, thinking=high
routesense: routing decision cause=heuristic_scorer, tier=MEDIUM, score=0.300, signals=[code (function, async, endpoint), heuristic:conclusive], routed_model=anthropic/claude-sonnet-5, thinking=low
routesense: routing decision cause=jev_classifier, tier=COMPLEX, score=0.910, signals=[heuristic:inconclusive (short follow-up), jev:COMPLEX 0.91], routed_model=anthropic/claude-sonnet-5, thinking=low
routesense: routing decision cause=jev_classifier, tier=COMPLEX, score=0.910, signals=[jev:COMPLEX 0.91, tool:error_streak 3 (bash)], routed_model=anthropic/claude-sonnet-5, thinking=high, tool_signal=escalate
routesense: routing decision cause=jev_classifier, tier=COMPLEX, score=0.620, signals=[jev:MEDIUM 0.62], routed_model=anthropic/claude-sonnet-5, thinking=low, held=COMPLEX 1/2
routesense: routing decision cause=jev_classifier, tier=MEDIUM, score=0.620, signals=[jev:MEDIUM 0.62], routed_model=anthropic/claude-sonnet-5, thinking=low, released=COMPLEX 2/2
routesense: routing decision cause=literal_keyword_match, tier=REASONING, signals=[keyword:migration], routed_model=claude-bridge/claude-opus-5-5, thinking=high, keyword="migration"
routesense: routing decision cause=heuristic_scorer, tier=MEDIUM, score=0.300, signals=[code (implement, endpoint, database)], routed_model=anthropic/claude-sonnet-5, thinking=medium, classifier_failure="jev:timeout: request timed out"
routesense: routing decision cause=retry_fallback, tier=REASONING, signals=[context overflow on anthropic/claude-sonnet-5], routed_model=claude-bridge/claude-opus-5-5, thinking=high, fallback=context_overflow
routesense: routing decision cause=jev_classifier, tier=COMPLEX, routed_model=anthropic/claude-sonnet-5, thinking=low, virtual_model=fast
routesense: routing decision cause=weighted_random, signals=[weight 3 of 10], routed_model=openai-codex/gpt-5.6-sol, thinking=high, virtual_model=mix

That line is what pi -p and RPC sessions print on stderr, what the event log stores, and what /routesense log shows, colored by field in the TUI. The detailed TUI chat entry above the routed prompt shows Jev decisions as a probability tree: each row shows a tier's probability, and the selected row includes the routed model and thinking level. Non-Jev decisions use the pipeline line instead; additional fields hang below either view.

routesense: typesafe/jev-latest: fast (420ms)
├─ SIMPLE     ▋░░░░░░░░░  5%
├─ MEDIUM     ▋▋▋▋▋▋▋▋░░  80%  ✓ openai-codex/gpt-5.6-terra · thinking medium
├─ COMPLEX    ▋░░░░░░░░░  12%
└─ REASONING  ░░░░░░░░░░  3%

A held or released decision adds held=COMPLEX 1/2 or released=COMPLEX 2/2 after tool_signal in the decision line. /routesense explain adds a hold rail row, and the tier row identifies the classified candidate when it differs from the served tier. When hysteresis does not act, the decision line omits these fields.

Press the tool-output expand key, or run /routesense explain, for the breakdown:

● routesense/fast · routing decision
│ reason         user
│ cause          jev_classifier
│ tier           COMPLEX (classified MEDIUM)  ██████░░░░ 0.620
│ classifier     typesafe/jev-latest in 420ms ($0.000100)
│ probabilities  MEDIUM 62%, COMPLEX 25%, SIMPLE 8%, REASONING 5%
│ signals        jev:MEDIUM 0.62
│ hold           held at COMPLEX: 1 of 2 lower verdicts
╰ routed         anthropic/claude-sonnet-5 · thinking low

Tiers take pi's thinking colors from SIMPLE to REASONING, the thinking level its own thinking color, and the routed model the accent color. Jev's confidence is drawn as a bar; the heuristic's weighted score is a number only. When a tool signal moves or selects a tier, the log adds tool_signal= and /routesense explain adds a tools row; adjusted classifier decisions include the tool adjustment in their detailed explanation.

Stats

Disk-backed stats use one JSON Lines (JSONL) file for each local calendar day: ~/.pi/agent/pi-topping-routesense/routing-events/YYYY-MM-DD.jsonl. The event timestamp selects the file. Each append is one write, safe across concurrent pi processes. /routesense stats opens a dialog with group and mode tabs (Tab switches Overview / Routing log, s sorts the model table, r re-reads the log, which also happens every 5 s) and:

  • Classifier / Random groups: the overview headings are CLASSIFIER VIRTUAL MODELS and RANDOM VIRTUAL MODELS. Use ←/→ to switch; navigation clamps at both ends. The defaults can be rebound with routesense.stats.previousGroup and routesense.stats.nextGroup in keybindings.json, and the legend names the keys in use. Requests, decisions, errors, tokens, cost, savings, models, fallbacks, causes, and the routing-log tab are scoped to the active type. Older events without virtualModelType (and unknown type values) count as classifier. Random omits the Tiers and Classifier sections.
  • Tiers (Classifier only): how often each tier served.
  • Models: calls, errors, share, tokens, cache hit rate, cost, p50 latency per physical model; req% is within the active type.
  • Classifier (Classifier only): Jev calls, failures, timeouts, circuit opens, latency percentiles, cost.
  • Decision models (Classifier only): one row per decision (classifier) provider/model, sorted by calls: calls, failures, fail%, avg/p50/p95 latency of successful calls only, total cost, and cost per priced call. A cost counts only when it is positive; otherwise it shows unknown, and * marks totals that leave out unknown-cost calls. Cancelled calls and circuit-open skips are not counted, so call totals can be lower than the Classifier line. Saved decisions within the retention window are included.
  • Tool signals (Classifier only, hidden at zero): escalations, de-escalations, decide-mode choices, and mid-turn switches.
  • Hysteresis (Classifier only, hidden at zero): held lower verdicts and released downgrades.
  • Fallbacks: context-window escalations, unavailable models/tiers, retries, cooldown bypasses, and causes; the classifier-fallback count appears only in the Classifier group.
  • Routing log tab: the last 200 decisions for the active group. /routesense log remains global.
  • Based on: the number of distinct local days with events in the active group. The overview shows based on N days of data, or no data yet.

The Stats retention setting defaults to forever. never (session only) keeps stats in memory for the current pi process. It does not read, write, migrate, or prune saved files. Saved files stay on disk, and the overview shows their directory. 1 day keeps today. 1 week, 1 month, 3 months, and 1 year keep 7, 30, 90, and 365 local days, counting today. forever keeps daily files and never deletes them.

The store checks retention at session start, at the first event of each new local day, after a successful settings Save, and before the stats dialog opens. It runs at most one maintenance pass for each retention value and local day. The first pass splits an existing routing-events.jsonl file into daily files by event timestamp, then removes the old file. A corrupt line follows the prior parsed event's day. Leading corrupt lines use the first parsed event's day. If no event parses, corrupt lines use the current local day. If migration is interrupted, maintenance reports the .migrating claim file and stops pruning. Some claimed lines may already be in their matching daily files, so append only missing lines to those files, then delete the claim file to resume pruning; blindly replaying the whole claim can duplicate lines already migrated.

Savings follow LiteLLM's reference request of 20k prompt tokens and 1k completion: the baseline is the most expensive configured classifier deployment or positive-weight random-pool member, minus what the routed model and classifier actually cost. Switching models leaves caches cold, so the number can go negative. R in the dialog asks before it deletes every stats day file. In session-only mode, it clears only the current process's in-memory stats; saved files stay on disk.

Announcing the routed model

pi names the physical model on every assistant message (message.provider, message.model), but only once the response starts streaming, and responseModel is reserved for the model name a provider reports back. So the router announces each decision itself, before pi sends the routed request, on pi's extension event bus:

import { CHANNELS, subscribe } from "@underactive/pi-topping-primitives/contracts";
import type { ParsedRoutedModel, RoutedModelAnnouncementV1 } from "@underactive/pi-topping-primitives/contracts";

const unsubscribe = subscribe(pi.events, CHANNELS.routedModel, (announcement) => {
  // `announcement` is a validated ParsedRoutedModel.
});

Routesense emits the RoutedModelAnnouncementV1 wire shape. parseRoutedModel validates that shape when a consumer handles raw data; subscribe applies it automatically and filters malformed messages. Both are exported by @underactive/pi-topping-primitives/contracts.

{
  "version": 1,
  "provider": "openai-codex",
  "modelId": "gpt-5.6-sol",
  "model": "openai-codex/gpt-5.6-sol",
  "name": "GPT-5.6 Sol",
  "thinkingLevel": "high",
  "reason": "user",
  "cause": "jev_classifier",
  "tier": "COMPLEX",
  "toolSignal": "escalate",
  "hold": "held",
  "ts": 1790000000000
}

toolSignal is optional and appears only when a signal moved or directly selected a tier; hold is optional and appears only on a held or released hysteresis decision. The tool_signals cause identifies decide-mode or mid-turn routing. reason is pi's route reason (user, continuation, retry, direct) and cause is the decision log's cause. Random routes use cause: "weighted_random" and omit tier; classifier routes may omit tier when the default model serves. Every decision is announced, including sticky continuations, so a working loader can show the model behind the response from the moment it is chosen until the next decision. direct routes serve compaction summaries and other extensions' requests, not the chat response, so a loader for the chat response should ignore them. /routesense test classifies without routing and announces nothing. This is the hook for pi-topping's working loader and similar displays.

Differences from LiteLLM

  • Optional tool-signal routing is an extension-specific feature inspired by Switchyard's stage router; it derives signals from Pi's branch transcript and is not LiteLLM behavior.
  • Turn-to-turn hysteresis is an extension-specific, opt-in layer; it stores a branch-local committed tier and delays ordinary lower verdicts, unlike LiteLLM's per-turn classification.
  • pi's own system prompt is not sent to the classifier and does not feed the heuristic scorer. It is the same on every turn of a coding session and would dominate both.
  • The heuristic scorer reads only the stripped human ask, not prior turns or assistant text.
  • classifierOrder and the heuristic-first conclusiveness rule are additions in this port, not LiteLLM behavior. Short asks with retained prior turns defer to Jev because only Jev sees classifier context; with no retained context, the heuristic verdict stands alone.
  • pi's getAvailable() catalog includes virtual models. Routing targets are filtered to physical models: entries with api === "pi-virtual" (an internal pi id) or provider === "routesense" are excluded, so tiers, random pools, and /routesense init cannot target another virtual model or route back into this router. Classifier profiles use their own tier/default config and random profiles their own pool; classifier settings are shared, but random profiles skip classification.
  • Routing state (last tier and model, plus the optional hysteresis hold) is stored by pi on the session branch, so it follows forks and survives compaction. Cooldowns and the circuit breaker are in-memory and per pi process.
  • A missing TypeSafe key does not stop the router from loading; it degrades to the heuristic scorer with a warning.
  • Session affinity, adaptive (Thompson-sampled) pools, and tier labels are not implemented.

Development

npm install
npm run typecheck
npm test
TYPESAFE_API_KEY=... node --test test/live.test.ts   # real Jev calls, skipped without a key

The dialogs under src/ui/generated are generated from the mockups in the sibling repository pi-topping-mockups; never edit them by hand. Change the mockup, then:

npm run port:ui     # convert the files listed in opentui-port.json
npm run parity:ui   # replay the key scripts and compare every cell with the recorded frames
npm run port:check  # fail when a generated file is stale (--offline: hand edits only, as CI runs it)

The hand-written adapters beside them (src/ui/*-dialog.ts) feed the dialogs and act on what they return; src/ui/dialog-fit.ts holds each dialog's full size.

Smoke checklist with PI_CODING_AGENT_DIR=$(mktemp -d) pi -e ./index.ts:

  1. Create two profiles in /routesense settings, assign different tier candidates, save, restart, and verify /model lists both.
  2. Select each profile in separate terminals and confirm its decision log shows the correct virtual_model= and candidates.
  3. Start a background pi-subagents runner child, or pi -p --model routesense/fast, with fast selected; verify /routesense models delete fast is refused until that process exits, then succeeds.
  4. Try renaming a profile from one terminal while it is selected in another; verify the operation is refused, then switch away or quit and retry.
  5. Edit candidates while a profile is selected; verify the next request sees the change.
  6. Verify /routesense init, tier, and default still modify only default, and on/off affect every profile.
  7. Create a random profile with New random virtual model, add two pool models with different weights, save, restart, select it in /model, and verify /routesense status shows the pool shares and decision lines read cause=weighted_random.
  8. Enable tool signals in /routesense settings, trigger an error streak, and verify the next user-turn decision includes a tool_signal=escalate field and tool:error_streak note.
  9. Make a successful edit, run a recognized passing test command, and verify the next decision can de-escalate; compact once and verify tool:compacted appears only once for that summary.
  10. Enable hysteresis and alternate one COMPLEX verdict with lower MEDIUM verdicts; confirm held= appears, two consecutive lower verdicts release, and /routesense status shows the pending count.
  11. Disable hysteresis and confirm the next user turn drops the hold annotation from detailed decision entries.
  12. Disable tool signals and confirm detailed decision entries no longer show tool annotations, state returns to its defaults, and /routesense status reflects the setting.

Tested against pi 1.6.0 on Node v24.22.1 and npm 11.19.1: npm run typecheck and npm test pass, and the pi host lists routesense/default. The only runtime dependency is @underactive/pi-topping-primitives; pi packages are peer dependencies.