@dev-ahmed/ai-router
v0.3.0
Published
Local intelligent router that classifies AI coding tasks with Ollama and routes them to the best external coding agent, model, and effort level.
Readme
ai-router
Local intelligent router that uses Ollama as a "task judge" to classify AI coding tasks, then deterministically routes them to the best external AI coding agent, model, and effort level.
Full design spec:
SPEC.md— architecture, routing algorithm, escalation semantics, config reference, security model.
TASK → CLASSIFY (Ollama) → AGENT → MODEL → EFFORT → EXECUTION → ESCALATION- Ollama only answers "what does this task require?" — it never picks commercial models.
- A deterministic routing engine compares task requirements against a user-editable capability registry.
- External agents (OpenCode, Claude Code) keep full ownership of authentication, tools, and execution. ai-router never touches provider credentials.
Install
npm install -g @dev-ahmed/ai-routerOr use it programmatically:
npm install @dev-ahmed/ai-routerQuick start
# 1. Make sure Ollama is running, then fetch the classifier model:
ai-router ollama sync
# 2. Check your environment:
ai-router doctor
# 3. Route your first task (dry run — nothing is executed):
ai-router --dry-run "Refactor the authentication system to support OAuth"
# 4. Execute for real:
ai-router "Fix the login bug where sessions are lost after refresh"Terminal input modes
Like opencode and claude, tasks can be provided three ways:
ai-router "Fix this bug" # argument
cat diff.patch | ai-router "review" # piped stdin (multi-line safe)
ai-router # interactive promptOr run the interactive TUI (type a task, watch it classify → route → execute, repeat):
ai-router tui # or the standalone binary: ai-router-tui, or bare `ai-router`The TUI renders the routing pipeline live: task line → route band (model, agent
command, effort) → fit card (green demand / dim spare / red shortfall blocks with
margin) → execute blocks (per-attempt status with diff stats like +34 −8) → agent
output. The right panel shows the judge's six requirement scores plus a
demand-vs-capability overlay against the selected model.
TUI keys and slash commands:
tabcollapse/expand the requirements panel ·escclear the queue, else interrupt the running agent ·eforce escalation to a stronger model ·⏎send- Type while a task runs to queue the next prompt; queued prompts run in order.
/help,/profile <name>,/models,/judge [model],/queue [clear],/new,/thread,/keys,/keys <NAME>(masked secret entry),/quit
CLI
| Command | Description |
|---|---|
| ai-router [prompt...] | Prompt given: classify + route + execute. No args (TTY): launches the TUI |
| ai-router tui | Interactive terminal UI |
| ai-router keys add <NAME> [-v] | Store an API key in ~/.config/ai-router/env, wire shell rc sourcing |
| ai-router keys list [--json] | List stored key names (values masked) |
| ai-router setup | Choose the local judge model (runs automatically on first interactive use) |
| ai-router judge [list] | Show judge models, marking the current default |
| ai-router judge use <model> | Switch judge, downloading only if the model is missing |
| ai-router doctor | Environment health checks (Ollama, agents, config) |
| ai-router models [--discover] | Show configured models; optionally ask agents for their live model lists |
| ai-router agents | Installed agents, versions, status |
| ai-router config | Print resolved configuration |
| ai-router ollama sync [models...] | Pull missing Ollama models with live progress (configured classifier model by default) |
| ai-router benchmark [--suite LOW\|MEDIUM\|HIGH] | Benchmark classification accuracy/latency against bundled suites |
| ai-router serve | Optional localhost HTTP API |
Default command flags
ai-router --dry-run "Refactor auth" # everything except execution
ai-router --agent claude-code "..." # require a specific agent
ai-router --profile fast "Fix typo" # fast | balanced | quality | custom
ai-router --json "Analyze this task" # machine-readable output (incl. metrics)
ai-router --quiet "Fix typo" # single-line decisionHow routing works
- Collect — lightweight project metadata only (language, framework, changed file count, recent filenames). No source code leaves your machine except tiny metadata.
- Classify — Ollama returns strict JSON scores (0–10) for reasoning, coding, planning, context, risk, complexity plus a confidence value. Invalid JSON is retried once with a stricter prompt, then fails safely.
- Route — deterministic engine adjusts requirements upward for high risk / low
confidence, then selects the fastest, cheapest sufficient candidate of
agent + model + effort. Profiles (
fast,balanced,quality) reweight the trade-off. - Execute — the selected agent runs the task through its supported non-interactive
interface (
opencode run,claude -p) with structured output parsing where available. - Escalate — on failure, escalate to a strictly stronger configured model. Sessions are preserved when the agent supports continuation; otherwise a new context is created and clearly announced — never faked.
Configuration
Create ai-router.config.yaml in your project or
~/.config/ai-router/config.yaml globally. Everything is optional; defaults work out
of the box. See examples/ai-router.config.yaml.
Key sections:
classifier: # any Ollama-compatible model
model: llama3.2:3b
temperature: 0
timeout_ms: 1500
profile: balanced
escalation:
enabled: true
confidence_threshold: 0.65
max_retries: 1
profiles:
fast: { speed_weight: 1, cost_weight: 1, quality_weight: 0.5 }
balanced: { speed_weight: 0.7, cost_weight: 0.7, quality_weight: 1 }
quality: { speed_weight: 0.3, cost_weight: 0.2, quality_weight: 1 }
agents:
opencode: { enabled: true, command: opencode }
claude-code: { enabled: true, command: claude }
models: # add/edit freely — no source changes needed
my-fast-model:
agent: opencode
model: openai/gpt-5.4-mini
capabilities: { reasoning: 7, coding: 8, planning: 6, context: 8, speed: 9, cost: 8 }Capability semantics: all scores 0–10; cost means economy (10 = cheapest).
The registry ships with Claude Haiku/Sonnet/Opus entries for both agents as sensible
defaults — edit them to match your actual access.
Claude subscription auth
Nothing to configure — ai-router shells out to the claude binary, so it uses whatever
login you already have. ai-router doctor reports it:
✓ Auth: claude-code: claude.ai · proDo not store ANTHROPIC_API_KEY via keys add or the env: block. Every stored key
is injected into agent subprocesses, and Claude Code prefers an API key over a
subscription login — so it would silently bill API credits instead of your plan. Doctor
flags this if it detects the variable, whether it comes from ai-router's keystore or
your shell.
Preferences and portable instructions
Agent memory is agent-specific — claude reads CLAUDE.md, opencode reads
AGENTS.md — so it does not follow a task that gets routed elsewhere. ai-router keeps
both kinds of preference at the router level instead:
# Prepended to every task prompt, whichever agent routing picks.
instructions: |
Use pnpm. Match the surrounding code style.
preferences:
- label: security work
when: { matches: "auth|oauth|crypto" }
then: { min_reasoning: 9, profile: quality }
- when: { risk_above: 8 }
then: { model: claude-opus }
- when: { matches: "migration" }
then: { instructions: "Never drop a table without an explicit backup step." }when supports matches (regex on the task), risk_above and complexity_above, and
every declared condition must hold. then can raise requirement floors (min_*), pin
agent/model/effort/profile, or add instructions. Floors only ever raise a
requirement, so a rule cannot route a hard task to a weaker model. Matches are listed in
the decision rationale.
API keys for routed models
Routed execution goes through your installed agents, which authenticate with their own credentials. To make any LLM API key available to agent subprocesses, store it once:
ai-router keys add OPENROUTER_API_KEY # prompted privately; value never echoed
ai-router keys list # names only — values always maskedKeys live in ~/.config/ai-router/env (mode 0600) and ai-router:
- loads that file itself and injects every entry into agent subprocess env on each run;
- appends a marker block to
~/.zshrc(and~/.bashrcif present) so other tools in new terminals see them too.
Alternatively declare keys per project in config (${VAR} refs are expanded from your
environment at runtime, empty results are dropped):
env:
OPENROUTER_API_KEY: ${OPENROUTER_API_KEY}
ANTHROPIC_API_KEY: sk-ant-literal-values-also-workChoosing a judge model
The classifier only produces requirement scores — bigger is more accurate, smaller is
faster. Measured on the bundled benchmark suites (ai-router benchmark):
| Judge | Accuracy | False LOW | Mean latency |
|---|---|---|---|
| llama3.2:3b (default) | 77.8% | 0% | ~1.9s |
| qwen3:1.7b | 16.7% | 0% | ~1.6s |
False LOW = routing a hard task to a weak model (the dangerous direction). Any
Ollama-compatible model works; tune classifier.model to your hardware.
Package API
import { AIRouter } from "@dev-ahmed/ai-router";
const router = new AIRouter();
const decision = await router.route({ prompt: "Fix the auth bug" });
// => { agent, model, effort, requirements, confidence, escalatable, ... }
const decision2 = await router.route({
prompt: "Design the architecture",
profile: "quality",
});
await router.execute({ decision, prompt: "Fix the auth bug" });Lower-level building blocks are exported too:
import {
OllamaClassifier, // classify()
RoutingEngine, // selectModel()
ModelRegistry, // capability registry
EscalationManager, // escalate()
ExecutionEngine, // execute()
} from "@dev-ahmed/ai-router";Optional HTTP API
ai-router serve --port 4477POST /route, POST /execute, POST /escalate, GET /health, GET /agents,
GET /models, GET /config, GET /metrics
Security
- Never sends secrets to Ollama — classification payloads contain only the task text and lightweight metadata.
- Agents authenticate with their own existing credentials.
- API keys you explicitly store via
keys add/ the TUI/keyscommand orenv:config are forwarded only to agent subprocesses — never printed, logged, or included in API responses (ai-router configandGET /configmask all values).
Development
pnpm install
pnpm build # tsc -> dist/
pnpm test # vitest
pnpm typecheck
node dist/cli/index.js --helpLicense
MIT
