Skip to main content
Glama
README.md
<div align="center">

<img src="assets/banner_header.png" width="100%"/>

<br/>

[![Tests](https://img.shields.io/badge/Tests-33%20Passed-00C853?style=for-the-badge&logo=pytest&logoColor=white)](#-benchmarks--ast-compaction-matrix)
[![Python](https://img.shields.io/badge/Python-3.10+-7000FF?style=for-the-badge&logo=python&logoColor=white)](https://www.python.org/)
[![Dependencies](https://img.shields.io/badge/Runtime%20Deps-Zero%20(Stdlib)-00F0FF?style=for-the-badge&logo=python&logoColor=white)](pyproject.toml)
[![Anthropic Proxy](https://img.shields.io/badge/Anthropic%20API-Drop--In-10A37F?style=for-the-badge&logo=anthropic&logoColor=white)](#-drop-in-anthropic-proxy--mcp-server)
[![MCP](https://img.shields.io/badge/MCP-JSON--RPC%202.0-7000FF?style=for-the-badge)](docs/ARCHITECTURE.md)
[![License: MIT](https://img.shields.io/badge/License-MIT-00C853?style=for-the-badge&logo=opensourceinitiative&logoColor=white)](LICENSE)
[![Benni OS](https://img.shields.io/badge/Benni%20OS-benni--os.net-0D0D0D?style=for-the-badge)](https://benni-os.net)

<br/>

> **Zero-Dependency Hybrid Local-Cloud Model Router, AST Context Compactor & Semantic Prefix Cache for Claude Code.**  
> Cut Claude Code API spend by routing trivial turns to local GPUs (`BIE` / `Ollama`), compacting bloated code & logs via Python AST, and deduplicating repeated tool payloads in SQLite3 WAL — with **zero runtime dependencies**.

<br/>

<img src="assets/demo.gif" alt="claude-code-router Hybrid Routing & AST Compaction Demo" width="100%"/>

</div>

---

## ⚡ Why claude-code-router?

Running every Claude Code turn — typo fixes, file reads, log inspection, and boilerplate edits — through frontier cloud models burns tokens and budget unnecessarily.

**`claude-code-router`** sits transparently between Claude Code (`ANTHROPIC_BASE_URL`) and your inference backends using pure Python stdlib (`http.server`, `sqlite3`, `ast`, `json`):

- **Sub-Millisecond Complexity Scorer** — Deterministically classifies every turn (`trivial`, `standard`, `frontier`) in `< 0.5 ms` based on prompt length, conversation depth, tool-call weight (`Edit`/`Bash` vs `Read`/`Grep`), extended thinking, and architectural/security signals.
- **AST-Aware Code & Log Compactor** — Uses Python's `ast` module to collapse long function bodies while preserving imports, signatures, decorators, and line anchors (`# [L...-L...]`), and strips ANSI/repeated log noise while keeping every traceback frame.
- **SQLite3 WAL Semantic Prefix Cache** — Deduplicates repeated `Read`/`Grep`/`Bash` turns and identical prompts using deterministic SHA-256 keys, `PRAGMA journal_mode=WAL`, and configurable TTLs (`~0.015 ms` cache hits).
- **Bidirectional Wire Translator** — Translates Anthropic `/v1/messages` (including `tool_use`, `tool_result`, and SSE streams) <-> OpenAI `/v1/chat/completions` for local `benni-inference-engine` (`BIE`) or `Ollama` servers, plus `/v1/messages/count_tokens`.
- **Automatic `429`/`529` Circuit Breaker** — Smoothly fails over between local GPU (`127.0.0.1:8080` / `11434`) and Anthropic Cloud on rate limits or connection errors.
- **One-Command Claude Code Injection (`claude-router init`)** — Idempotently configures `.claude/settings.json`, `.mcp.json`, and `/router-status` + `/router-stats` slash commands without clobbering existing settings.

---

## 🏗️ Architecture

```text
  Claude Code CLI / IDE / MCP Clients
         │
         ├──► HTTP  POST /v1/messages, /v1/messages/count_tokens
         └──► STDIO JSON-RPC 2.0 (claude-router mcp)
                       │
                       ▼
  ┌─────────────────────────────────────────────────────────────────────┐
  │                         claude-code-router                          │
  │                                                                     │
  │  ┌───────────────────┐  ┌───────────────────┐  ┌─────────────────┐  │
  │  │ Complexity Scorer │  │ AST & Log         │  │ SQLite3 WAL     │  │
  │  │ • Trivial (<0.32) │─►│ Compactor         │─►│ Semantic Cache  │  │
  │  │ • Standard        │  │ • Keep signatures │  │ • SHA-256 keys  │  │
  │  │ • Frontier (>=.68)│  │ • Keep tracebacks │  │ • TTL + hits    │  │
  │  └───────────────────┘  └───────────────────┘  └─────────────────┘  │
  │                                                         │           │
  │  ┌───────────────────┐  ┌───────────────────┐           ▼           │
  │  │ Rolling Telemetry │  │ Wire Translator   │  ┌─────────────────┐  │
  │  │ • P50/P90/P99 ms  │◄─│ • Anthropic<->OAI │◄─│ Circuit Breaker │  │
  │  │ • USD Saved       │  │ • SSE Stream      │  │ • 429/529 Trip  │  │
  │  └───────────────────┘  └───────────────────┘  └─────────────────┘  │
  └─────────────────────────────────────────────────────────────────────┘
         │                                         │
         ▼                                         ▼
   Local GPU (BIE / Ollama)                 Anthropic Cloud API
   127.0.0.1:8080 / :11434                  Haiku / Sonnet / Opus
```

---

## 🚀 60-Second Quickstart

```bash
# 1. Clone and install (zero runtime dependencies)
git clone https://github.com/Benni-OS/claude-code-router
cd claude-code-router
pip install -e .

# 2. Verify environment, SQLite3 WAL, and routing pipeline
claude-router doctor

# 3. Run the multi-scale complexity, AST compaction & cache matrix
claude-router matrix

# 4. Inject .claude/settings.json, .mcp.json, and slash commands
claude-router init --project-dir .

# 5. Start the Anthropic-compatible proxy server
claude-router serve --port 4100
```

### Key CLI Commands

```bash
claude-router doctor                         # Full environment, SQLite WAL & backend probe
claude-router matrix                         # Multi-scale scorer, AST compaction & cache benchmark
claude-router init --project-dir .           # Idempotent .claude/settings.json & .mcp.json setup
claude-router serve --port 4100              # Start threaded HTTP /v1/messages proxy
claude-router serve --port 4100 --dry-run    # Offline deterministic dry-run proxy mode
claude-router route "Fix typo in README"     # Inspect routing tier, model & USD saved
claude-router compact src/my_module.py       # Preview AST-aware compaction savings
claude-router cache --stats                  # Inspect SQLite3 WAL cache entries & hits
claude-router mcp                            # Launch native JSON-RPC 2.0 stdio MCP server
```

---

## 📊 Benchmarks & AST Compaction Matrix

Measured with `claude-router matrix` (Python 3.11.0, Windows, 5 repetitions per scale):

| Functions | Orig Chars | Compact Chars | Context Savings | Assigned Tier | Score Latency | Compact Latency | Cache Hit Latency |
|---:|---:|---:|---:|---|---:|---:|---:|
| **2** | 847 | 202 | **76.1%** | `trivial` | `0.1197 ms` | `0.1801 ms` | `0.0176 ms` |
| **8** | 3,235 | 665 | **79.4%** | `trivial` | `0.3853 ms` | `0.6463 ms` | `0.0150 ms` |
| **24** | 9,617 | 1,927 | **80.0%** | `standard` | `1.1139 ms` | `1.9881 ms` | `0.0128 ms` |

---

## 🌐 Drop-In Anthropic Proxy & MCP Server

### REST Endpoints

| Method | Endpoint | Purpose |
|---|---|---|
| `POST` | `/v1/messages` | Complexity routing, AST compaction, semantic cache, and local/cloud dispatch |
| `POST` | `/v1/messages/count_tokens` | Fast deterministic token estimation for Claude Code |
| `GET` | `/health` | Proxy, SQLite3 WAL cache, circuit breaker, and local BIE/Ollama health |
| `GET` | `/v1/router/metrics` | Rolling P50/P90/P99 latency, local offload ratio, cache hit rate, and USD saved |

### Native MCP Tools (`claude-router mcp`)

- `router_classify_turn` — Classify a prompt + tool list into `trivial` / `standard` / `frontier`.
- `router_compact_context` — Compact Python code blocks and log/traceback outputs via AST.
- `router_cache_stats` — Query SQLite3 WAL semantic cache hits and tokens saved.
- `router_estimate_savings` — Compute USD saved vs Claude Opus baseline.

---

## 🗂️ Project Structure

```text
claude-code-router/
├── src/
│   └── claude_code_router/
│       ├── cli.py                    # CLI entrypoint (init, serve, route, compact, cache, mcp, doctor, matrix)
│       ├── core/
│       │   ├── circuit_breaker.py    # Automatic 429/529 & connection-error failover breaker
│       │   ├── complexity_scorer.py  # Sub-ms prompt & tool-context complexity classifier
│       │   ├── context_compactor.py  # AST-aware Python code & log/traceback compactor
│       │   ├── injector.py           # Idempotent .claude/settings.json, .mcp.json & slash command injector
│       │   ├── semantic_cache.py     # Thread-safe SQLite3 WAL prefix & tool-result cache
│       │   └── wire_translator.py    # Bidirectional Anthropic <-> OpenAI payload & SSE translator
│       ├── serve/
│       │   ├── health_monitor.py     # Local BIE/Ollama reachability & WAL cache monitor
│       │   ├── mcp_server.py         # Zero-dependency JSON-RPC 2.0 stdio MCP server
│       │   ├── proxy_server.py       # Threaded HTTP proxy (/v1/messages, /health, /v1/router/metrics)
│       │   └── telemetry.py          # Rolling P50/P90/P99 latency & FinOps USD saved telemetry
│       └── tools/
│           ├── bench_matrix.py       # Multi-scale complexity, AST compaction & cache benchmark matrix
│           └── doctor.py             # Environment & routing pipeline diagnostic (claude-router doctor)
├── examples/
│   ├── quickstart_anthropic_proxy.py # Dry-run /v1/messages proxy quickstart
│   └── quickstart_context_compaction.py # AST code & log compaction example
├── scripts/
│   ├── benchmark_router_latency.py   # Latency & compaction benchmark runner
│   └── gate_router_integrity.py      # End-to-end zero-dependency integrity gate
├── docs/
│   └── ARCHITECTURE.md               # Detailed request pipeline architecture
└── tests/                            # Full pytest suite (33 tests)
```

---

## 🌍 Part of the Benni OS Ecosystem

`claude-code-router` is part of the coordinated **Benni Master OS v9.4** open-source infrastructure suite:

| Repository | Focus & Architecture | Stars |
| :--- | :--- | :---: |
| **[`benni-inference-engine`](https://github.com/Benni-OS/benni-inference-engine)** | High-Throughput Sovereign Local Inference for 8GB–16GB Consumer GPUs | [![GitHub Stars](https://img.shields.io/github/stars/Benni-OS/benni-inference-engine?style=flat)](https://github.com/Benni-OS/benni-inference-engine) |
| **[`claude-code-router`](https://github.com/Benni-OS/claude-code-router)** | Hybrid Local-Cloud Model Router, AST Context Compactor & Semantic Cache | [![GitHub Stars](https://img.shields.io/github/stars/Benni-OS/claude-code-router?style=flat)](https://github.com/Benni-OS/claude-code-router) |
| **[`conductor-sdd`](https://github.com/Benni-OS/conductor-sdd)** | Zero-Dependency Spec-Driven Development, Static AST Drift Detector & MCP Guardrail | [![GitHub Stars](https://img.shields.io/github/stars/Benni-OS/conductor-sdd?style=flat)](https://github.com/Benni-OS/conductor-sdd) |
| **[`agent-eval-harness`](https://github.com/BenniAlencar/agent-eval-harness)** | Deterministic Zero-Cloud Agent Evaluation, Red-Teaming & Benchmark Harness | [![GitHub Stars](https://img.shields.io/github/stars/BenniAlencar/agent-eval-harness?style=flat)](https://github.com/BenniAlencar/agent-eval-harness) |

---

## 🏛️ Commercial & Sovereign Architecture

Need autonomous multi-agent swarm orchestration, private datacenter infrastructure, or enterprise governance?

- **Official Website:** [https://benni-os.net](https://benni-os.net)
- **Operator Mode Playbook:** [https://benni-os.net/blog/academy.html](https://benni-os.net/blog/academy.html)
- **GitHub Organization:** [https://github.com/Benni-OS](https://github.com/Benni-OS)
- **Maintainer:** [Benni Alencar](https://github.com/BenniAlencar)

---

## 📄 License & Provenance

- **License:** [MIT License](LICENSE)
- **Author:** Benni Alencar (`bennialencar@benni-os.net`)
- **Architecture:** Benni Master OS v9.4 Tier-0 Governance Standard

<div align="center">

<img src="assets/banner_footer.png" width="100%"/>

**claude-code-router** — *Hybrid Local-Cloud Model Router & AST Context Compactor for Claude Code* • [benni-os.net](https://benni-os.net) • `MIT License`

</div>