← Catalog

@kylebrodeur/pi-model-router

Intelligent per-turn model router extension for the pi coding agent (Enhanced Fork)

Extension

Install

Install with PiG

pig install npm:@kylebrodeur/pi-model-router

Install with Pi

pi install npm:@kylebrodeur/pi-model-router
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": [
    "./extensions/index.ts"
  ]
}

README

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

pi-model-router

npm version License: MIT Pi Version

Intelligent per-turn model router extension for the pi coding agent. Automatically selects between high, medium, and low-tier LLMs based on task intent, session budget, context size, and custom rules — with automatic fallbacks, phase awareness, and transparent rate-limit recovery.

✨ Features

FeatureDescription
Logical Router ProviderRegisters a router provider that exposes stable profiles (e.g., router/auto) as models.
Per-Turn RoutingIntelligently chooses between high, medium, and low tiers for every turn based on task intent and complexity.
Task-Aware HeuristicsDetects planning vs. implementation vs. lightweight tasks using keyword analysis, word count, and conversation history.
LLM Intent ClassifierOptionally use a fast model to categorize intent (overrides heuristics).
Custom RulesDefine keyword-based tier overrides for specific patterns (e.g., deploy → high).
Context TriggerAutomatically upgrade to high-tier when token usage exceeds a threshold.
Cost BudgetingSet a session spend limit; high tier downgrades to medium once exceeded.
Fallback ChainsAutomatic retry with alternative models if the primary choice fails.
Phase MemoryBiased stickiness to keep you in the same tier during multi-turn planning or implementation work.
Thinking ControlFull control over reasoning/thinking levels per tier and profile.
Persistent StatePins, profiles, costs, and debug history are remembered across agent restarts and conversation branches.
Rate-Limit FallbackDetect HTTP 402/429/503/529 and transparently fall back to local models.
Feature TogglesEnable/disable features at user or project level.
Optional Agent Bus IntegrationDetects agent-bus when installed and integrates conditionally.

📦 Installation

From npm

pi install npm:@kylebrodeur/pi-model-router

From source

git clone https://github.com/kylebrodeur/pi-model-router.git
cd pi-model-router
pi install .

Quick test

pi -e ./extensions/index.ts

🚀 Quick Start

# 1. Install the extension
pi install npm:@kylebrodeur/pi-model-router

# 2. Create default config
/router init

# 3. Reload to apply
/reload

# 4. Check status
/router status

⚙️ Configuration

Copy the example config to one of:

  • ~/.pi/agent/model-router.json (Global)
  • .pi/model-router.json (Project-specific)

Basic Config Shape

{
  "defaultProfile": "auto",
  "classifierModel": "google/gemini-flash-latest",
  "maxSessionBudget": 1.0,
  "profiles": {
    "auto": {
      "high": { "model": "openai/gpt-5.4-pro", "thinking": "high" },
      "medium": { "model": "google/gemini-flash-latest", "thinking": "medium" },
      "low": { "model": "openai/gpt-5.4-nano", "thinking": "low" }
    }
  }
}

Configuration Fields

FieldDescription
defaultProfileThe profile to use when starting a new session.
classifierModel(Optional) Model used to categorize intent. If omitted, fast heuristics are used.
maxSessionBudget(Optional) USD budget for the session. Forces medium tier once exceeded.
largeContextThreshold(Optional) Token count trigger to force high tier for large contexts.
phaseBias(0.0 - 1.0) Stickiness of the current phase. Higher = more stable. Default 0.5.
rulesList of custom keyword rules (e.g. { "matches": "deploy", "tier": "high" }).
profilesMap of profile definitions, each containing high, medium, and low tiers.

Feature Toggles

{
  "features": {
    "rateLimitFallback": true,
    "scopeShim": true,
    "perTurnRouting": true,
    "intentClassifier": false,
    "costBudgeting": true,
    "phaseMemory": true,
    "contextCompression": true,
    "agentBusIntegration": false
  }
}

Priority: Project config .pi/model-router.json overrides user config ~/.pi/agent/model-router.json. Both override defaults.

Model Discovery

Install @kylebrodeur/pi-model-discovery with:

pi install npm:@kylebrodeur/pi-model-discovery

Run /providers sync to discover Ollama models. /router ollama-sync only delegates to /providers sync. The router no longer writes ~/.pi/agent/models.json.

Rate Limit Interception & Fallback

The router can gracefully handle 429 Rate Limit and Quota errors. If the error specifies a wait time (e.g., "reset after 58s"), the router will pause and automatically retry the prompt if the wait time is under your threshold. If it exceeds the threshold or is unparseable, it fails over to the next available model in your fallback sequence.

{
  "rateLimitFallback": {
    "enabled": true,
    "shortDelayThreshold": 60,
    "autoFallback": true,
    "autoRestore": true,
    "restoreCheckInterval": 300,
    "fallbackSequence": ["anthropic/claude-3-haiku-20240307", "ollama/*"]
  }
}
FieldDescription
shortDelayThresholdMaximum time (in seconds) the router will pause and wait to retry when encountering a rate limit. If the cooldown is longer than this, it triggers a fallback.
fallbackSequenceArray of model IDs (or wildcards like ollama/*) to try if the primary model fails or the wait time is too long.
autoFallback(Optional) Automatically switch session to the fallback model globally after a hard failure.
autoRestore(Optional) If fallback was triggered, automatically try to restore the original cloud model after restoreCheckInterval seconds.

Progressive Enhancement Configs

After installing optional extensions, copy one of these to .pi/model-router.json:

FileFeature
model-router.agent-bus.jsonPublish model changes to agent-bus
model-router.essential.jsonRate-limit fallback, scope sync, and agent-bus integration

⌨️ Commands

Core Router Commands

CommandDescription
/routerShow detailed status, current profile, spend, and settings.
/router statusAlias for /router (show current status).
/router profile [name]Switch to a profile or list available ones (enables router if off).
/router pin [prof] <t|a>Pin a tier (high/medium/low/auto) for the current or specified profile.
/router fix <tier>Correct the last decision and pin that tier for the current profile.
/router thinking ...Override thinking levels (e.g., /router thinking low xhigh).
/router disableDisable the router and switch back to the last non-router model.
/router widget <on|off>Toggle the persistent state widget (supports toggle).
/router debug <on|off>Toggle turn-by-turn routing notifications (supports toggle, clear, show).
/router reloadHot-reload the configuration JSON.
/router helpShow usage help for all subcommands.

Fork-Added Commands

CommandFeatureDescription
/router ollama-syncDelegates to /providers sync from pi-model-discovery
/router fallbackrateLimitFallbackSwitch to fallback model sequence
/router restorerateLimitFallbackRestore cloud model
/router initScaffold default config file
/router scope applyscopeShimSync router profiles to Pi enabled models
/router scope resetscopeShimClear router profiles from Pi enabled list
/router scope showscopeShimShow current Pi scoped models settings

🔒 Requirements

  • Pi >= 0.70.2 — Required for after_provider_response event (rate limit detection)
  • Ollama — Optional and only needed for local fallback models; install pi-model-discovery for Ollama model registration.
  • Node.js >= 18 — For TypeScript compilation

📚 Documentation

🤝 Contributing

See CONTRIBUTING.md for:

  • How to split changes into upstream-friendly PRs
  • Commit message conventions
  • Testing requirements
  • What to say in PR descriptions

📜 License

MIT — See LICENSE.

🙏 Acknowledgements