# 9RouterX README ![9RouterX — Local AI Router, LLM Gateway, and Token Saver Single Binary](docs/9routerx-readme-hero-motion.gif) # 9RouterX — FREE AI Router & Token Saver (Single Binary) **High-performance local AI gateway and OpenAI/Anthropic-compatible LLM router compiled into a single Go binary.** Cut tool-output token consumption by **20–40%**, automate multi-tier failover (**Subscription → Cheap → Free**), and route across **394 AI providers** and **245 free models** with zero Node.js runtime overhead. **9RouterX is the self-hosted 9Router & LiteLLM alternative** — one native Go binary you own: per-key financial governance, semantic cache, and 245 free models (24 keyless) running locally on port `20128`. If 9RouterX helps your workflow, please give the repository a star — it helps other developers discover the project. [![CI](https://github.com/yanstd888/9routerx/actions/workflows/ci.yml/badge.svg)](https://github.com/yanstd888/9routerx/actions/workflows/ci.yml) [![Release CI](https://github.com/yanstd888/9routerx/actions/workflows/release.yml/badge.svg)](https://github.com/yanstd888/9routerx/actions/workflows/release.yml) [![npm version](https://img.shields.io/npm/v/9routerx.svg?style=flat-square&logo=npm)](https://www.npmjs.com/package/9routerx) [![npm downloads](https://img.shields.io/npm/dm/9routerx.svg?style=flat-square&label=downloads&color=22c55e)](https://www.npmjs.com/package/9routerx) [![GHCR Container](https://img.shields.io/badge/GHCR-yanstd888%2F9routerx-2496ED?style=flat-square&logo=github&logoColor=white)](https://github.com/yanstd888/9routerx/pkgs/container/9routerx) [![Container & Binary Pulls](https://img.shields.io/github/downloads/yanstd888/9routerx/total?style=flat-square&logo=docker&logoColor=blue&label=Docker%20pulls&color=0ea5e9)](https://github.com/yanstd888/9routerx/pkgs/container/9routerx) [![Telegram Community](https://img.shields.io/badge/Telegram-%40aiclub__id-26A5E4?style=flat-square&logo=telegram)](https://t.me/aiclub_id) [Quick Start](#quick-start) • [Why 9RouterX?](#why-9routerx) • [Comparison](#9routerx-vs-9router-vs-omniroute) • [Key Features](#key-features) • [Supported Clients](#supported-ai-coding-clients) • [Free Providers](#free-ai-providers-and-keyless-models-catalog) • [Database Sharing](#sharing-a-database-with-9router) • [Screenshots](#screenshots) • [Setup Guide](#setup-guide-summary-and-wiki-documentation) • [Architecture Matrix](#architecture-comparison) • [FAQ](#frequently-asked-questions-faq) • [Docs](#docs) • [Wiki](https://yanstd888.github.io/9routerx/) **394** Built-in Providers · **35** OAuth-category Entries · **31** Free-category Entries · **245** Cataloged Free Models (**24** Keyless) · **5** Build Targets · **1** Binary --- > **What is 9RouterX?** > > **9RouterX** is an open-source, self-hosted LLM gateway written in Go with an embedded Svelte 5 + Vite + Tailwind 4 dashboard, listening on loopback port `20128` by default. It exposes Chat Completions, Anthropic Messages, Responses, embeddings, model catalogs, Ollama-compatible chat, MCP, and A2A routes. The registry contains **394 built-in provider entries** grouped as **317 API-key**, **35 OAuth**, **31 free**, and **11 web-cookie** entries. These are catalog categories, not guaranteed authentication-flow counts: auth modes vary by provider. The static free catalog lists **245 models across 37 providers**, including **24 keyless models**; Antigravity still requires Google OAuth. See [Providers](https://yanstd888.github.io/9routerx/providers.html) for actual browser-login and credential support. ## Why 9RouterX? AI-assisted software engineering workflows suffer from fragmented monthly subscriptions, sudden upstream rate limits, runaway token billing, and bloated CLI tool context windows. 9RouterX resolves these operational bottlenecks locally at the gateway layer before requests leave your machine: * **Unused Monthly Quotas & Rate-Limit Interruptions → Smart 3-Tier Cascade (`Subscription → Cheap → Free`):** Stop losing unused monthly subscription credits or hitting `429 Too Many Requests` in the middle of a complex multi-file refactor. 9RouterX prioritizes your active **Subscription** tier first (via connected OAuth accounts or web-cookie sessions), overflows seamlessly to **Cheap API** providers (such as DeepSeek, Groq, Fireworks, or Nebius), and automatically falls back to **Free-Tier / Keyless** models (`245 free models across 37 providers`, including `24 keyless models`) when primary limits are exhausted. * **Verbose CLI & Tool-Call Outputs → 20–40% Token Saver Suite:** Autonomous coding agents regularly burn tens of thousands of input tokens reading raw terminal logs, directory trees, build outputs, and repetitive JSON responses. Built-in RTK compression (`internal/tokensaver`, `internal/compression`), **50+ ready-made per-tool output filters** (`git diff`, `git log`, `grep`, `ripgrep`, `docker logs`, `npm install`, `pnpm`, `cargo build`, `go test`, `terraform plan`, `kubectl`, `pytest`, and friends), GCF/tabular headroom compression (`internal/compression/gcf`, `internal/headroom`), context squeezing, and output style directives (`Caveman`, `Ponytail`, `ADHD`, and `Anti-Slop` modes) strip redundant noise before forwarding requests upstream. * **Uncontrolled API Spend → Per-Key Financial Governance & Guardrails:** Enforce strict daily USD spending ceilings with hard cutoffs checked when each request starts (`internal/budget`), per-key request rate limits, CIDR/IP whitelists, per-key system prompt injection, and scoped endpoint permissions (`internal/policy`, `internal/guardrails`, `internal/keikey`) before distributing local gateway keys (`sk-...`) to autonomous agents, CI pipelines, or team members. * **Silent Endpoint Failures & Broken Tool Calls → Active Health Probing & Auto-Repair:** Upstream LLM providers frequently return malformed JSON tool-call arguments, truncated schemas, or suffer silent latency degradation. 9RouterX repairs broken tool-call structures in transit (`tool-call repair fallback`), guards against SSRF dispatch and leaks via PII masking, and continuously tracks live endpoint health (`internal/modelhealth`, `internal/resilience`) with a 3-tier circuit breaker to bypass degraded nodes automatically. * **Redundant Repeated Prompts → Semantic, Prompt & Sticky TTL Caching:** Reduce round-trip latency and API token billing through local vector-similarity semantic caching (`internal/semanticcache`), automatic upstream prompt cache header passthrough (`internal/promptcache`), **cache-aware sticky TTL routing** (saving up to ~90% on cached input reads), and zero-allocation FastJSON parsing (`internal/fastjson`). * **Heavy Runtime Dependencies → Single Self-Contained Go Binary:** No Node.js runtime memory bloat, no Python virtual environments, and no external PostgreSQL or Redis containers required. Everything—including the reactive Svelte 5 dashboard, SQLite storage engine, MCP server, and MITM inspector—runs from a single native binary across Linux (`x64`/`arm64`), macOS (`x64`/`arm64`), and Windows (`x64`). ## 9RouterX vs 9Router vs OmniRoute 9RouterX is an independent Go + Svelte 5 evolution of 9Router (`decolua/9router` and `luqman-v1/9router-go`) that expanded its own enterprise governance and token-saving architecture, sitting in the same self-hosted gateway space as OmniRoute (`cheaper-inference/OmniRoute`). Every row in the table below states a verifiable fact—where an architectural trait has no standardized public benchmark behind it, it is explicitly labeled *On paper* rather than given a synthetic number. Star counts were checked live on **Nov 14, 2026**; evaluate each gateway by its operational requirements and feature rows. | Metric / Capability | **9RouterX** (This Repo) | **9Router** (`decolua`) | **OmniRoute** (`cheaper-inference`) | | :--- | :--- | :--- | :--- | | **GitHub Stars (Nov 14, 2026)** | 68 | 32,422 | 87,366 | | **Language / Runtime** | **Go, single native binary + Svelte 5 dashboard** | JavaScript / Node.js + Next.js | TypeScript / Node.js | | **Installation Footprint** | **One native binary (~48 MB linux-amd64), zero runtime dependencies** | `npm i -g 9router` (6 deps, requires Node.js runtime) | npm (~105 deps) / Docker / pnpm | | **Supported Providers** | **394** (`317 API` · `35 OAuth` · `31 free` · `11 cookie`) | 40+ | 375–380 (150+ free) | | **Cataloged Free Models** | **245 across 37 providers (24 keyless)** | 100+ | 1,400+ models (~1.62B free tokens/mo) | | **Embedded Dashboard** | **Svelte 5 + Vite + Tailwind 4, embedded in binary** | Next.js React web app | Desktop / PWA | | **Database Engine** | **Embedded SQLite, drop-in schema-compatible** | Same SQLite schema | SQLite | | **Behavior Under Heavy Traffic** | *On paper:* a compiled native Go process—one process for the gateway, dashboard, and SQLite engine, with no V8 heap or GC pauses growing with the request queue. Measure on your own workload. | *On paper:* Node.js runtime (V8 + single-threaded event loop); sustained throughput depends on Node version and warm-up state. | *On paper:* Node.js runtime, same event-loop and V8 heap considerations. | | **Latency Profile** | *On paper:* zero cold-start tax after boot; hot request paths use allocation-conscious Go routines and FastJSON. | *On paper:* first-request warm-up on the Node/Next.js side. | *On paper:* first-request warm-up on the Node side. | ### What 9RouterX Adds on Top of 9Router 9RouterX preserves 100% SQLite database compatibility with upstream 9Router while adding a dedicated optimization and security stack: * **Full Per-Key Governance:** Daily USD hard cutoffs checked at request start, per-key rate limits, IP whitelists, reusable plan templates, SSRF dispatch protection, and PII masking (versus basic key authentication). * **Token Saver Suite:** 20–40% RTK compression, 50+ per-tool CLI output filters, GCF/tabular headroom compression, context squeezer, output style directives (`Caveman`, `Ponytail`, `ADHD`, `Anti-Slop`), and automated tool-call repair fallback. * **Multi-Layer Caching & Resilience:** Semantic cache + prompt cache passthrough + cache-aware sticky TTL routing, windowed-LRU rotation, auto-prune for dead credentials, and burn-in account recovery. * **Expanded Free & Keyless Catalog:** 245 free models across 37 providers (including 24 keyless models). * **Advanced Protocols & Ops Modules:** Built-in MCP Server, A2A protocol, TLS stealth fingerprinting, MITM traffic inspector, multi-target webhooks, Telegram bot alerts, encrypted credential Vault, and one-command service migration (`9routerx service take-over`). ### Where OmniRoute is Bigger OmniRoute's upstream catalog is larger, stated plainly: roughly 375–380 providers (150+ of them free), 1,400+ models, a pooled ~1.62B free tokens/month allowance, 20 routing strategies, and quota-aware fallback. That catalog breadth is their core strength. Where **9RouterX** differs: it ships as **one compiled Go binary with zero runtime dependencies** (versus an npm installation pulling ~105 packages), stays lightweight enough for **small self-hosted VPS instances or edge hardware**, enforces **granular per-key financial governance and RTK/GCF tool compression**, and embeds the **Svelte 5 dashboard directly inside the binary**. Compare features against your infrastructure requirements—neither replaces the other. ### Go + Svelte 5 vs a Node.js Stack The architectural difference manifests in day-to-day operations (*on paper throughout — measure on your own workload*): * **Single-File Distribution:** One native executable per platform (`linux-x64`, `linux-arm64`, `win32-x64`, `darwin-x64`, `darwin-arm64`) versus `npm install` pulling a Node.js runtime dependency tree and `node_modules`. * **Instant Cold Start:** The compiled Go gateway serves its first completion request immediately upon process boot without waiting for JIT/module graph warm-up. * **Predictable Memory Footprint:** Compiled Go services of comparable scope typically idle with a smaller resident memory footprint than Node.js/Next.js servers. * **Concurrency Under Load:** Concurrent streaming connections are multiplexed across lightweight Go goroutines rather than competing on a single-threaded V8 event loop. * **Atomic Self-Updates:** Updating swaps a single binary (`9routerx update` or container image pull) without rebuilding local package trees. ## System Architecture ```text AI Coding Clients (Claude Code, Cursor, Codex, Cline, OpenCode, Gemini CLI, OpenClaw) │ http://localhost:20128/v1 (OpenAI / Anthropic / MCP / A2A) ▼ ┌─────────────────────────────────────────────────────────────────────────────────────┐ │ 9RouterX Single Go Binary │ │ ┌────────────────────────┐ ┌────────────────────────┐ ┌───────────────────────┐ │ │ │ Governance & Policy │→ │ Token Saver Suite │→ │ Semantic & Prompt │ │ │ │ • Daily Cost Cutoff │ │ • RTK Compression │ │ Caching │ │ │ │ • Rate Limit / IP WL │ │ • 50+ Tool Filters │ │ • Vector Similarity │ │ │ │ • Guardrails & Vault │ │ • GCF / Headroom │ │ • Sticky TTL (~90%) │ │ │ │ • PII Mask / SSRF Grd │ │ • Tool-Call Repair │ │ • FastJSON Engine │ │ │ └────────────────────────┘ └────────────────────────┘ └───────────────────────┘ │ │ │ │ │ ▼ │ │ ┌───────────────────────────────────────────────────────────────────────────────┐ │ │ │ Smart Combo Router & Resilience Engine (Model Health Probes) │ │ │ │ Strategies: Fallback │ Round-Robin │ Sticky TTL │ Capacity │ Fusion │ Auto │ │ │ └───────────────┬────────────────────────┬────────────────────────┬─────────────┘ │ └──────────────────┼────────────────────────┼────────────────────────┼────────────────┘ ▼ ▼ ▼ [Tier 1: Subscription] [Tier 2: Cheap API] [Tier 3: Free / Keyless] 35 OAuth-category Entries 317 API-category Entries 245 Free Models across 11 Web Cookie Providers (DeepSeek, Groq...) 37 Providers (24 Keyless) ``` ## Key Features | Feature Group | Capabilities & Internal Modules | | :--- | :--- | | **Routing & Fallback** | **Auto 3-Tier Fallback** (`Subscription → Cheap → Free`), **Combo Routing** (`fallback`, `round-robin`, `sticky`, `capacity`, `fusion`, `cache-optimized`, `auto`, `quota-weighted`, `reset-aware` via `internal/routing`, `internal/combos` & `internal/combopresets`), multi-account round-robin load balancing, active **Model Health** probing (`internal/modelhealth`), and 3-stage circuit-breaker resilience (`internal/resilience`). | | **Token Saver Suite** | **20–40% tool-output token savings** (`internal/tokensaver`, `internal/compression`), **RTK Compression**, **50+ ready-made per-tool output filters** (for `git diff`, `grep`, `docker logs`, `npm install`, `terraform plan`, and friends), **GCF/Tabular Headroom** (`internal/compression/gcf`, `internal/headroom`), **Context Squeezer** for long histories, **Output Style Directives** (`Caveman`, `Ponytail`, `ADHD`), **Anti-Slop Injector** (`internal/tokensaver/antislop`), and automated **Tool-Call Repair Fallback**. | | **Governance per Key** | **Daily Cost Ceiling + Hard Cutoff** (`internal/budget`, checked per request), per-key request rate limits, **IP Whitelist**, per-key custom system prompts, granular endpoint permissions, reusable **Plan Templates** (`internal/policy`, `internal/guardrails`, `internal/keikey`), SSRF dispatch protection, PII masking, encrypted credential storage (`internal/vault`, `internal/sessionvault`), and audit logs (`internal/securitylog`). | | **Providers & Auth** | **394 built-in entries**, grouped as 317 API-key, 35 OAuth, 31 free, and 11 web-cookie. Categories are not auth-flow counts. Custom endpoints, custom headers, Kiro JSON import, cookie paste, and supported browser capture/import are available; persistent profiles and Xvfb apply only to the generic runner. See the [provider support matrix](https://yanstd888.github.io/9routerx/providers.html#browser-based-login). | ### MCP Server 9RouterX includes a built-in MCP server (`internal/mcpserver`) speaking JSON-RPC 2.0 over stdio and HTTP POST at `http://localhost:20128/api/mcp`. Set `ROUTERX_MCP_TOKEN` to enable it; an empty token keeps the server disabled. Authenticate with `Authorization: Bearer ` or `X-MCP-Token`. Fourteen tools cover keys, health, models, combos, cache, usage, security log, notifications, resilience, team usage, backups, quota, providers and settings. See the [MCP guide](https://yanstd888.github.io/9routerx/mcp.html) for client config and JSON-RPC examples. | **Free Tier & Keyless** | **31 free-tier providers** (22 `CategoryFreeTier` + 9 `CategoryFree`) and **245 free models cataloged across 37 providers**, including **24 cataloged keyless models** without a user-supplied upstream API key (`antigravity`, `opencode`, `blackbox`); Antigravity requires Google OAuth login once. Tracks daily, monthly, credit, one-time, and uncapped quota regimes automatically. | | **Cache & Performance** | **Semantic Cache** (`internal/semanticcache`) for vector-matched query deduplication, upstream **Prompt Cache** optimization (`internal/promptcache`), **Cache-Aware Sticky TTL** (reduces cached input costs by up to ~90%), and high-throughput **FastJSON** serialization (`internal/fastjson`). | | **Observability** | **Extended Logging + Payload Inspector**, custom usage analytics windows (`12h`, `14d`, custom date ranges), Tremor-inspired data visualizations (`bits-ui` + `layerchart`), distributed **Tracing** (`internal/tracing`, `internal/observ`), **Uptime** monitoring (`internal/uptime`), **Security Log**, multi-target **Webhooks + Notifications** (`internal/notifications`), and **Telegram Bot** alerts (`internal/telegram`). | | **Infra & Extras** | **Single Go Binary** across 5 OS/arch targets, background daemon CLI (`start`/`stop`/`restart`/`status`/`logs`), one-command migration (`9routerx service take-over`), Docker container (`ghcr.io`), desktop **Tray App**, built-in **Tunnel** (`internal/tunnel`), self-**Updater** (`internal/updater`), encrypted **Sync Bundle** backup/restore (`internal/syncbundle`), **TLS Stealth** (`internal/tlsstealth`), **MITM Traffic Inspection** (`internal/mitm`), **MCP Server** (`internal/mcpserver`), **A2A Protocol** (`internal/a2a`), and **Media TTS/STT**. | ### Current routing and management additions - [Combos](https://yanstd888.github.io/9routerx/combos.html): `lkgp` usage-based ranking, combo budgets, derived family warnings, and a limited direct API-key arena. Multi-member fusion does not use the combo-budget gate. - [Security](https://yanstd888.github.io/9routerx/security.html) and [Token Saver](https://yanstd888.github.io/9routerx/token-saver.html): scoped dashboard tokens, opt-in reversible PII placeholders, and tool-loop watch. Coverage is protocol-dependent; masking is not guaranteed anonymization. - [Operations](https://yanstd888.github.io/9routerx/operations.html): automatic SQLite snapshots, partial/sensitive remote JSON backups, and user-supplied proxy harvest batches. Browser profiles are excluded from built-in DB backups. - [Dashboard](https://yanstd888.github.io/9routerx/dashboard.html) and [Analytics](https://yanstd888.github.io/9routerx/usage-analytics.html): local doctor/onboarding status, mixed-window cache metrics, estimated savings, and rough gateway-wide burn-rate projections. These are not live upstream readiness or financial forecasts. These pages describe the reviewed source. Check `9routerx version` and the release history before assuming every change is in an older binary. ### v1.2 Cost & Resilience Controls (Conservative Opt-In Defaults) All advanced v1.2 cost-reduction and account-protection mechanisms ship **disabled (`OFF`) by default** to guarantee predictable baseline behavior until explicitly enabled by the operator: | Control Feature | Environment / Config Flag | Default | Operational Impact | | :--- | :--- | :---: | :--- | | **Cache-Aware Sticky TTL** | Combo strategy `ttl` mode (`5m` Claude default, up to `60m` Gemini) | `OFF` | Pins consecutive requests to the same warm upstream account within the vendor's prompt-cache window so cached prefixes are reused instead of re-billed—delivering **up to ~90% input-cost reduction on cache hits** (e.g., Anthropic bills cached reads at ~10% of standard input pricing). | | **Windowed-LRU Rotation** | `ROTATION_WINDOW=N` | `OFF` | Restricts round-robin selection to the top `N` active candidate connections to prevent pool-wide rate-limit burn-in across large account pools. | | **Dead-Credential Auto-Prune** | `AUTOPRUNE_ENABLED` (supports dry-run mode) | `OFF` | Automatically deactivates upstream connections after consecutive permanent credential failures (`401 Unauthorized`, `403 Banned`, `402 Payment Required`). | | **Account Burn-In Protection** | `BURNIN_ENABLED` | `OFF` | Guides degraded accounts through an automated **Suspect → Heal (1-in-5 request throttle) → Rescue (temporary rotation quarantine)** recovery cycle. | ## Quick Start Install 9RouterX, create your local gateway API key in the dashboard on port `20128`, and execute your first routed completion in 3 steps. ### 1. Install 9RouterX > **Upgrading from 9Router?** Your existing SQLite data carries over automatically. Run `9routerx service take-over` to replace the legacy gateway process and its system autostart service in a single step (see the [Installation & Migration Guide](https://yanstd888.github.io/9routerx/installation.html)). **Option A — Via npm (Recommended for Linux, macOS, and Windows; requires Node.js >= 18 for wrapper install only):** ```bash npm install -g 9routerx ``` **Option B — Via Official Installer Script (Linux / macOS / Windows):** ```bash # Linux & macOS curl -fsSL https://raw.githubusercontent.com/yanstd888/9routerx/main/install.sh | bash ``` ```powershell # Windows (PowerShell) irm https://raw.githubusercontent.com/yanstd888/9routerx/main/install.ps1 | iex ``` **Option C — Prebuilt Standalone Binaries:** Download `9routerx-linux-amd64`, `9routerx-linux-arm64`, `9routerx-darwin-amd64`, `9routerx-darwin-arm64`, or `9routerx-windows-amd64.exe` from [GitHub Releases](https://github.com/yanstd888/9routerx/releases). These are executable assets, not archives; verify them against `SHA256SUMS.txt`. ### 2. Start & Create API Key ```bash 9routerx # Dashboard: http://localhost:20128 (Default password: 123456 — change in Settings → Profile) # Next: Settings → API Keys → Create Key → copy your key (sk-...) ``` * **Default Login:** First login uses the default compatibility password `123456`. Change it immediately in **Settings → Profile**. * **Gateway Auth Note:** `RequireApiKey` (`internal/middleware/auth.go`) validates client keys against your local SQLite database (`0 keys configured = 401 Authentication required`). Always create at least one gateway API key (`sk-...`) in **Settings → API Keys** before sending requests. ### 3. Send Your First Request (OpenCode Keyless, Zero Upstream Login) Once you have created your local gateway key (`sk-YOUR-KEY`), test immediately with `oc/big-pickle` from OpenCode Free without any upstream login. To test `antigravity/gemini-3.7-flash-medium`, sign in with Google through Antigravity once first (free); no user-supplied upstream API key is needed. ```bash curl http://127.0.0.1:20128/v1/chat/completions \ -H "Content-Type: application/json" \ -H "Authorization: Bearer sk-YOUR-KEY" \ -d '{ "model": "oc/big-pickle", "messages": [ {"role": "user", "content": "Verify 9RouterX local gateway on port 20128 in one sentence."} ] }' ``` ### Keep the Terminal Free (Background Mode) Run 9RouterX as a background daemon without tying up an active terminal session: ```bash 9routerx start # launch in background (writes DATA_DIR/run/gateway.pid) 9routerx status # check running PID and active port 9routerx restart # restart background instance 9routerx logs -n 100 # tail the last 100 lines of DATA_DIR/run/gateway.log 9routerx stop # stop the background daemon 9routerx service take-over # migrate from legacy 9Router service & take over autostart 9routerx version # print running binary version & build metadata ``` * **PID & Logs:** Background state is stored in `DATA_DIR/run/gateway.pid` and daemon output is written to `DATA_DIR/run/gateway.log`. * **Windows Note:** On Windows, `9routerx stop` uses `TerminateProcess` (which skips graceful in-flight drain). For a graceful drain on Windows, trigger **Shutdown** from the web dashboard or use `9routerx restart`. ### Running with Docker (GHCR) Run 9RouterX in a container with persistent SQLite storage. The explicit host setting makes the published port reachable; replace the password placeholder and keep authentication enabled: ```bash docker run -d \ --name 9routerx \ --restart unless-stopped \ -p 20128:20128 \ -v ~/.9router:/data \ -e DATA_DIR=/data \ -e HOST=0.0.0.0 \ -e INITIAL_PASSWORD=your-secure-password \ ghcr.io/yanstd888/9routerx:latest ``` * **Experimental Builds:** To test bleeding-edge commits from the experimental branch, pull `ghcr.io/yanstd888/9routerx:exp` (`docker pull ghcr.io/yanstd888/9routerx:exp`). Experimental workflow builds only publish to the `exp` tag and never overwrite `latest`. ### Install Alternatives & Build from Source **Release binary:** download from [GitHub Releases](https://github.com/yanstd888/9routerx/releases/latest) and verify against `SHA256SUMS.txt`. **Experimental builds:** unpublished work ships as experimental builds — GitHub Releases marks them **Pre-release** (so `9routerx update` keeps pointing at stable), and GHCR tags them `exp` (`ghcr.io/yanstd888/9routerx:exp`), never `latest`. Opt in only to help shake out bugs. **Build from source:** prerequisites Go 1.27 and Bun 1.x (dashboard is embedded into the binary, so build web first) — then `make build`. Full flags and steps: [wiki — installation](https://yanstd888.github.io/9routerx/installation.html). **Start on boot:** autostart/service installation is documented in the wiki — [installation](https://yanstd888.github.io/9routerx/installation.html). ## Sharing a Database with 9Router 9RouterX is engineered as a drop-in compatible upgrade for existing **9Router** and **9router-go** installations. It listens on the exact same default port (`20128`) and opens the same `DATA_DIR/db/data.sqlite` database—meaning your configured **providers, OAuth connections, combos, client API keys, and usage history carry over automatically without migration**. | Deployment Mode | Default `DATA_DIR` / SQLite Database Path | | :--- | :--- | | **Linux / macOS (Native)** | `~/.9router` (opens `~/.9router/db/data.sqlite`) | | **Windows (Native)** | `%APPDATA%\9router` (opens `%APPDATA%\9router\db\data.sqlite`) | | **Docker Container** | Mount host `~/.9router:/data` with `-e DATA_DIR=/data` | * **Caveat:** Do not run both 9Router and 9RouterX against the same SQLite file simultaneously. Stop the old process first (or run `9routerx service take-over` / back up `data.sqlite` before switching) so only one binary holds the SQLite write lock. ### Optional runtime environment | Variable | Effect | | :--- | :--- | | `9ROUTERX_GOMEMLIMIT` | Optional soft Go heap limit in byte syntax (`512MiB`, `1.5GiB`). Unset keeps the Go default. Invalid values are logged and ignored at startup. | | `SEMANTIC_CACHE_MAX_BYTES` | Soft ceiling on the semantic cache store in bytes (`64MiB` default). Trims the oldest entries past it. | | `SEMANTIC_CACHE_MAX_ENTRY_BYTES` | Per-entry ceiling on the semantic cache (`512KiB` default). Larger entries are not stored. | | `STREAM_STALL_TIMEOUT_MS` | Idle budget for an SSE stream before it is closed as stalled (`360000` = 6m default). Free-tier models instead stop after the 120s free-tier budget. `9ROUTERX_STREAM_STALL_TIMEOUT_MS` / `NINEROUTER_STREAM_STALL_TIMEOUT_MS` are legacy spellings of the same knob; the first one set wins. | | `SEAT_ATTEMPT_BUDGET_MS` | Overall budget in milliseconds for seat-attempt retries (`0` = policy default). `9ROUTERX_SEAT_ATTEMPT_BUDGET_MS` is the `9ROUTERX_`-prefixed spelling. | | `ROUTE_HEADERS` | Optional extra headers attached to every upstream route call (JSON object). | | `URL` | Optional override of the URL a CLI tool points at in the CLI-tools panel. | | `SERVICE_BACKEND` | Optional backend selector for the systemone lane. | ## Screenshots Every screen ships in dark and light themes, at desktop and mobile widths. The full gallery — with per-page commentary — lives on the wiki's [**Screenshots**](https://yanstd888.github.io/9routerx/screenshots.html) page. | | Dark | Light | |---|---|---| | **Providers** — connect AI providers and manage custom OpenAI/Anthropic-compatible endpoints | ![Providers view, dark theme — the provider catalog and connection list in the 9RouterX dashboard](docs/screenshots/providers.png) | ![Providers view, light theme — the same provider catalog and connection list in light mode](docs/screenshots/providers-light.png) | ## Supported AI Coding Clients 9RouterX works out of the box with any OpenAI-compatible, Anthropic-compatible, Responses API, Ollama-compatible, MCP, or A2A client: Claude Code OpenAI Codex CLI OpenCode Cursor Antigravity Gemini CLI Cline Roo Code Droid Continue Amp OpenClaw GitHub Copilot Claude Cowork Kilo Code Kiro Hermes Agent DeepSeek TUI Grok Build jcode Pi Oh My Pi (omp) Crush Forge Smelt CodeWhale Qwen Code OpenDesign > **IPv6 Resolution Note (`localhost` vs `127.0.0.1`):** Some CLI tools (upstream documentation specifically notes **OpenClaw** and certain Node/Go CLIs) may resolve `localhost` to IPv6 `::1` first and fail to connect. If a client refuses to connect via `localhost`, use explicit IPv4 **`http://127.0.0.1:20128`** instead. ### Example 1: Claude Code Setup Route Claude Code through `http://localhost:20128` to enable 20–40% tool-output token compression, 50+ per-tool filters, and multi-provider failover: ```bash export ANTHROPIC_BASE_URL="http://localhost:20128" export ANTHROPIC_API_KEY="sk-YOUR-KEY" claude ``` ### Example 2: Codex / OpenCode / OpenClaw (Explicit IPv4 `127.0.0.1`) ```bash export OPENAI_BASE_URL="http://127.0.0.1:20128/v1" export OPENAI_API_KEY="sk-YOUR-KEY" ``` ### Example 3: Cline / Cursor JSON Configuration ```json { "apiProvider": "openai-compatible", "openAiBaseUrl": "http://127.0.0.1:20128/v1", "openAiApiKey": "sk-YOUR-KEY", "openAiModelId": "oc/big-pickle" } ``` ### Example 4: Gemini CLI / Custom Anthropic-Compatible Clients ```bash export GEMINI_API_BASE_URL="http://127.0.0.1:20128/v1" export GEMINI_API_KEY="sk-YOUR-KEY" ``` ## Free AI Providers and Keyless Models Catalog 9RouterX includes a built-in catalog of **245 free models across 37 providers** (verified in `freemodels.go`), featuring **24 cataloged keyless models** (`antigravity`, `opencode`, `blackbox`) without a user-supplied upstream API key. Antigravity requires Google OAuth login once (free); OpenCode offers zero-login access. Gemini Web requires a browser login/session cookie. ### Supported Free Quota Regimes * **`keyless`**: No user-supplied upstream provider API key (`antigravity`, `opencode`, `blackbox`). Antigravity requires Google OAuth login once; OpenCode and the cataloged Blackbox free endpoint do not require an upstream login. * **`recurring-daily`**: Free request or token allowance resets automatically every 24 hours. * **`recurring-monthly`**: Free quota refreshes each calendar or billing month. * **`recurring-credit`**: Periodic free credit grants replenished by the provider. * **`recurring-uncapped`**: Rate-limited free endpoints without hard lifetime exhaustion caps. * **`one-time-initial`**: Initial trial credit pool granted upon account creation. ### Complete Free Provider Directory (37 Providers · 245 Free Models) | Provider | Model free | Keyless | Quota / Access Regime | | :--- | :---: | :---: | :--- | | `agnes` | 3 | — | Source-backed Go free catalog (`regimeRecurringUncapped`) | | `antigravity` | 9 | 9 | Source-backed Go free catalog (`regimeKeyless`) | | `api-airforce` | 7 | — | Source-backed Go free catalog (`regimeRecurringDaily`) | | `baidu` | 1 | — | Source-backed Go free catalog (`regimeRecurringUncapped`) | | `bazaarlink` | 32 | — | Source-backed Go free catalog (`regimeRecurringDaily`) | | `blackbox` | 6 | 6 | Source-backed Go free catalog (`regimeKeyless`) | | `bluesminds` | 22 | — | Source-backed Go free catalog (`regimeRecurringDaily`) | | `cerebras` | 2 | — | Source-backed Go free catalog (`regimeOneTimeInitial`) | | `cloudflare-ai` | 9 | — | Source-backed Go free catalog (`regimeRecurringDaily`) | | `cohere` | 6 | — | Source-backed Go free catalog (`regimeRecurringMonthly`) | | `deepseek` | 2 | — | Source-backed Go free catalog (`regimeOneTimeInitial`) | | `fireworks` | 10 | — | Source-backed Go free catalog (`regimeOneTimeInitial`) | | `fish-audio` | 1 | — | Source-backed Go free catalog (`regimeRecurringUncapped`) | | `gemini` | 4 | — | Source-backed Go free catalog (`regimeRecurringDaily`) | | `glm` | 2 | — | Source-backed Go free catalog (`regimeRecurringUncapped`) | | `glm-cn` | 4 | — | Source-backed Go free catalog (`regimeOneTimeInitial, regimeRecurringUncapped`) | | `groq` | 5 | — | Source-backed Go free catalog (`regimeRecurringDaily`) | | `huggingface` | 6 | — | Source-backed Go free catalog (`regimeRecurringMonthly`) | | `hyperbolic` | 8 | — | Source-backed Go free catalog (`regimeOneTimeInitial`) | | `kilo-gateway` | 12 | — | Source-backed Go free catalog (`regimeRecurringUncapped`) | | `kiro` | 7 | — | Source-backed Go free catalog (`regimeRecurringMonthly`) | | `llm7` | 4 | — | Source-backed Go free catalog (`regimeRecurringDaily`) | | `mistral` | 5 | — | Source-backed Go free catalog (`regimeRecurringMonthly`) | | `morph` | 2 | — | Source-backed Go free catalog (`regimeRecurringMonthly`) | | `nebius` | 1 | — | Source-backed Go free catalog (`regimeOneTimeInitial`) | | `nous` | 7 | — | Source-backed Go free catalog (`regimeRecurringDaily`) | | `nvidia` | 4 | — | Source-backed Go free catalog (`regimeRecurringCredit, regimeRecurringUncapped`) | | `ollama` | 8 | — | Source-backed Go free catalog (`regimeRecurringDaily`) | | `opencode` | 17 | 9 | Source-backed Go free catalog (`regimeKeyless, regimeRecurringUncapped`) | | `opencode-zen` | 16 | — | Source-backed Go free catalog (`regimeRecurringUncapped`) | | `openrouter` | 3 | — | Source-backed Go free catalog (`regimeRecurringDaily`) | | `qoder` | 9 | — | Source-backed Go free catalog (`regimeRecurringDaily`) | | `sambanova` | 5 | — | Source-backed Go free catalog (`regimeRecurringDaily`) | | `sensenova` | 1 | — | Source-backed Go free catalog (`regimeOneTimeInitial`) | | `tencent` | 1 | — | Source-backed Go free catalog (`regimeRecurringUncapped`) | | `tokenharbor` | 2 | — | Source-backed Go free catalog (`regimeRecurringUncapped`) | | `tokenrouter` | 2 | — | Source-backed Go free catalog (`regimeRecurringUncapped`) | | **Total (37 Providers)** | **245** | **24** | **Verified in `freemodels.go`** | ## Provider Categories Breakdown 9RouterX groups **394 built-in entries** into four catalog categories. These are not four mutually exclusive authentication architectures; follow each provider's credential form: 1. **317 API-key category entries:** Includes OpenAI, Anthropic, Gemini, DeepSeek, and other API services. Header requirements vary by upstream. 2. **35 OAuth-category entries:** Includes browser, device-code, token-import, and API-key forms. For example, `muse` uses API-key auth despite its category; this is not a promise of 35 one-click flows. 3. **31 free-category entries:** 22 `CategoryFreeTier` and 9 `CategoryFree`. Free quota and eligibility belong to the upstream service and can change. 4. **11 web-cookie entries:** `claude-web`, `deepseek-web`, `gemini-web`, `grok-web`, `muse-web` (Baidu Yiyan/ERNIE, not Meta Muse), and `perplexity-web`. Generic Grok/Perplexity/Yiyan capture uses persistent profiles; dedicated Gemini/DeepSeek/Claude login uses temporary profiles. Import/reset support is not universal. See [Providers](https://yanstd888.github.io/9routerx/providers.html#browser-based-login). ### Adding a Custom Provider You can register any custom OpenAI-compatible or Anthropic-compatible upstream server directly in the dashboard (`http://localhost:20128` → **Providers** → **Add Custom**): * Set custom base URLs for local or private inference servers (vLLM, Ollama, llama.cpp, LM Studio, LiteLLM, or enterprise gateways). * Inject custom HTTP authentication or routing headers per provider. * Attach dedicated per-key outbound HTTP/SOCKS5 proxy pools and configure SSRF dispatch guard rules. ## Embedded Dashboard Overview 9RouterX compiles a reactive **Svelte 5 + Vite + Tailwind 4** management interface (built with `shadcn-svelte`, `bits-ui`, and `layerchart`) directly into the Go binary at `http://localhost:20128` (default password: `123456`): * **Token Saver & Compression Analytics:** Monitor real-time 20–40% token reduction ratios, RTK compression metrics, **50+ ready-made per-tool output filters**, GCF/tabular headroom stats, output style directives (`Caveman`, `Ponytail`, `ADHD`, `Anti-Slop`), context squeezer activity, and semantic cache hit rates. * **Connections & Authentication:** Configure catalog entries with their supported credential forms, including Kiro JSON import, cookie paste, and provider-specific browser capture/import. Persistent-profile support is limited to the generic runner. Inspect model health and build combos with the [documented strategies and budgets](https://yanstd888.github.io/9routerx/combos.html). * **Per-Key Governance & Custom Usage Ranges:** Issue client API keys (`sk-...`) with daily USD cutoffs enforced at request start, request rate limits, IP whitelists, and custom system prompts; inspect Tremor-style usage charts across `12h`, `14d`, or custom date ranges; and inspect full request/response JSON payloads in the Extended Logging & Payload Inspector. ## Setup Guide Summary and Wiki Documentation For advanced deployment and module configuration, refer to the [**Official 9RouterX Documentation & Wiki**](https://yanstd888.github.io/9routerx/): * [**Installation, Background CLI & Docker Guide**](https://yanstd888.github.io/9routerx/installation.html) — Custom port configuration (default `20128`), daemon commands (`start`/`stop`/`restart`/`status`/`logs`), one-step `9routerx service take-over`, autostart on boot, desktop tray mode, and GHCR containers. * [**Client Setup Guide**](https://yanstd888.github.io/9routerx/client-setup.html) — Ready-to-copy snippets for Claude Code, Cursor, Codex CLI, Cline, OpenCode, and OpenClaw. * [Combo Routing & Budgets](https://yanstd888.github.io/9routerx/combos.html): fallback chains, strategy IDs, timeout/grace, family warnings, and arena limitations. * [Token Saver & Tool-Loop Watch](https://yanstd888.github.io/9routerx/token-saver.html): RTK filters, compression, output styles, and protocol-specific loop detection. * [Key Governance](https://yanstd888.github.io/9routerx/governance.html) and [Security](https://yanstd888.github.io/9routerx/security.html): per-key budgets, scheduling hints, dashboard scopes, PII and TLS boundaries. * [Operations & Backups](https://yanstd888.github.io/9routerx/operations.html): automatic snapshots, sensitive remote JSON artifacts, proxy harvest, and runtime maintenance. * [API Reference](https://yanstd888.github.io/9routerx/api.html): mounted endpoint groups, including MCP/A2A and the recent management routes. ## Architecture Comparison Factual capability matrix comparing **9RouterX**, upstream **9router-go**, and the original **9Router (Next.js)**: | Capability / Metric | **9RouterX** (This Repository) | **9router-go** (Upstream Port) | **9Router** (Original Next.js) | | :--- | :--- | :--- | :--- | | **Runtime Binary** | **Single Native Go Binary** | Single Native Go Binary | Node.js + Next.js Runtime | | **Default Port** | **`20128`** | `20128` | `20128` | | **Database Compatibility** | **Drop-in `DATA_DIR/db/data.sqlite` sharing** | `DATA_DIR/db/data.sqlite` | `~/.9router/db/data.sqlite` | | **Embedded Dashboard** | **Svelte 5 + Vite + Tailwind 4 (`shadcn-svelte` + `layerchart`)** | Embedded Web UI | Next.js React Web App | | **Supported Providers** | **394 Providers (`317 API` · `35 OAuth` · `31 Free` · `11 Cookie`)** | Core Provider Subset | Core JS Providers | | **Cataloged Free Models** | **245 Free Models across 37 Providers (24 Keyless)** | Static Subset | Manual Configuration | | **Token Saver Suite** | **20–40% RTK Compression, 50+ Tool Filters, GCF Headroom, Context Squeezer, Tool Repair** | Not Included | Not Included | | **Per-Key Governance** | **Daily Cost Cutoff, Request Limits, IP Whitelist, Plan Templates, PII Masking** | Basic Key Auth | Basic Key Auth | | **Caching Layer** | **Semantic Cache + Prompt Cache + Sticky TTL (~90% Read Savings) + FastJSON** | Passthrough | Passthrough | | **Resilience Controls** | **3-Tier Circuit Breaker, Windowed-LRU, Auto-Prune, Burn-In Protection** | Basic Failover | Basic Failover | | **Advanced Modules** | **MCP Server, A2A, TLS Stealth, MITM Inspector, Multi-Target Webhooks, Telegram Bot, Vault** | Core Proxy Routing | Core Proxy Routing | | **Supported Platforms** | **5 Platforms** (`linux-x64`, `linux-arm64`, `win32-x64`, `darwin-x64`, `darwin-arm64`) | Go Target Builds | Requires Node.js Environment | ## Credential encryption The "Credential encryption: OFF" banner means provider credentials and browser sessions are stored unencrypted. An absent or invalid `ROUTER_MASTER_KEY` disables sealing. 1. Generate **32 random bytes** on your own machine and encode them with standard padded Base64 (for example, `openssl rand -base64 32`). Keep the result private; never paste it into chat or logs. 2. Set `ROUTER_MASTER_KEY` in the environment of the **gateway process**. On Linux/macOS, use `export ROUTER_MASTER_KEY=''`; in PowerShell, use `$env:ROUTER_MASTER_KEY=''`. These are placeholders, not usable keys. 3. Persist the value in your protected service/container environment or secret store, then restart the gateway. A shell export does not change an already running service. 4. Check Dashboard → Security → Credential Vault: sealing must show enabled. Keep the same key on later restarts and protect a separate backup of it alongside your database recovery plan. Do not replace the key casually. Losing it can make sealed credentials unrecoverable. The vault supports re-wrapping and an optional `ROUTER_MASTER_KEY_PREVIOUS`; preserve the old key during a planned rotation and persist the new current key before restarting. Without a usable old key, affected credentials must be re-entered. See [Security](https://yanstd888.github.io/9routerx/security.html) for the vault boundaries. ## Claude Web (Unofficial, Opt-in) 9RouterX can also drive claude.ai's web interface with the `sessionKey` browser cookie through a provider named `claude-web`. **It is disabled by default and it is not part of the free-tier catalog.** Enable it with `CLAUDE_WEB_ENABLED=true` or the toggle in Dashboard → Web Cookie Providers; `CLAUDE_WEB_ENABLED=false` is the operator kill-switch that always wins. Be clear about what this lane is before enabling it: - It violates [Anthropic's terms of service](https://www.anthropic.com/legal/consumer-terms) — the account you paste the cookie from risks restriction or ban. - It is unofficial and unverified against a live session: claude.ai can change or remove the endpoints at any time, and when it breaks there is no support and no fix on any schedule. - The session key is a full-account credential: it never leaves the gateway except inside the Cookie header, but anyone with dashboard access can read the stored connection, so treat it like a password. - Usage is estimated locally (characters per token); claude.ai reports no counts on this lane. If you enable it anyway: paste the `sessionKey` cookie from a logged-in claude.ai browser into the connection's API-key field, keep the toggle on, and point your client's model at `claude-web`. ## Frequently Asked Questions (FAQ) 1. Does 9RouterX support Claude Code, Cursor, Codex, and Cline? Yes. 9RouterX exposes Anthropic-compatible (`http://localhost:20128`), OpenAI-compatible (`http://localhost:20128/v1`), Responses API, and Ollama-compatible endpoints, alongside built-in MCP Server and A2A protocol support. You can connect Claude Code, Cursor, OpenAI Codex CLI, Cline, Roo Code, OpenCode, OpenClaw (use explicit IPv4 `http://127.0.0.1:20128`), Antigravity, and Gemini CLI directly to port `20128`. 2. Is 9RouterX free, and how do the 24 keyless models work? Yes. 9RouterX is free and open-source software (MIT License) that runs locally as a single binary with no proxy markup fees. It ships with **31 free-tier providers** and **245 cataloged free models across 37 providers**, including **24 cataloged keyless models** (`antigravity`, `opencode`, `blackbox`) without a user-supplied upstream API key. Antigravity (for example `antigravity/gemini-3.7-flash-medium`) requires a Google OAuth login once, which is free. Use `oc/big-pickle` from OpenCode for a zero-login test. Create a local 9RouterX gateway key in Settings → API Keys → Create Key (`http://localhost:20128`, default password `123456`) before making API requests; 0 keys returns `401 Authentication required`. 3. How is 9RouterX different from LiteLLM or OpenRouter? * **Versus OpenRouter:** OpenRouter is a cloud intermediary that adds per-token markup fees and routes prompts through external third-party servers. 9RouterX runs **100% locally on your machine** as a single binary with zero markup. * **Versus LiteLLM:** LiteLLM requires a Python environment; advanced budget/usage tracking needs external databases (PostgreSQL/Redis). **9RouterX** compiles a full AI gateway, **Svelte 5 dashboard**, **20–40% Token Saver suite (with 50+ per-tool filters)**, **semantic cache**, **per-key USD budget cutoffs checked at request start**, and **provider-specific authentication forms** into a **single zero-dependency Go binary** backed by an embedded SQLite file. 4. How does the 20–40% Token Saver work without breaking code generation? AI coding agents consume massive context windows when reading CLI outputs, directory listings, and tool responses. 9RouterX's `tokensaver` and `compression` modules apply RTK compression, **50+ ready-made per-tool output filters** (`git diff`, `grep`, `docker logs`, `npm install`, `terraform plan`), GCF tabular headroom compression, context squeezing, output style directives (`Caveman`, `Ponytail`, `ADHD`), and anti-slop rules to tool outputs in transit—cutting 20–40% of token volume while repairing malformed JSON tool calls automatically. 5. Can I migrate from 9Router or 9router-go without losing my keys and combos? Yes. 9RouterX shares the exact same default port (`20128`) and SQLite database schema (`DATA_DIR/db/data.sqlite`). Run `9routerx service take-over` (or stop your existing 9Router instance and start 9RouterX)—all providers, OAuth connections, combos, client API keys, and usage statistics carry over immediately without migration scripts. 6. What happens when my primary AI subscription hits a rate limit? When a request hits a `429` rate limit, quota exhaustion, or upstream `5xx` error, 9RouterX's `resilience` circuit breaker and `modelhealth` probes automatically cascade the request through your configured combo tier (**Subscription OAuth → Cheap API Key → Free-Tier / Keyless**) without dropping your active coding session. 7. How do I run 9RouterX in the background or update to the latest release? Use the built-in daemon commands: `9routerx start`, `9routerx status`, `9routerx restart`, `9routerx logs -n 100`, and `9routerx stop`. To update, run `npm install -g 9routerx@latest`, `9routerx update`, or pull the latest GHCR container (`ghcr.io/yanstd888/9routerx:latest`). ## Contributing Issues and pull requests use templates, so pick the right one rather than opening a blank report: - **Bug report** — something behaves incorrectly. Include a reproduction, `9routerx version`, OS, and the log excerpt around the failure. - **Feature request** — the problem you cannot solve today, the surface it touches, and whether upstream already has it. - **Question** — configuration and usage help. PRs follow the checks CI runs: `go vet ./...`, `go test -count=1 ./...`, `make test-integration`, plus `cd web && bun test` and `make vet-svelte` for anything touching the dashboard. Before writing code, skim [`AGENTS.md`](AGENTS.md) — provider isolation and the Go/Svelte conventions keep reviews fast. ## Docs **Full documentation, searchable:** [**9routerx Wiki**](https://yanstd888.github.io/9routerx/) — installation, usage, API reference, dashboard, providers, governance, architecture, database, CLI, and a screenshot gallery. Every page supports `?q=` search and `#section` deep links. Repository references: - [`ARCHITECTURE.md`](ARCHITECTURE.md) — routing, providers, runtime layout - [`DATABASE.md`](DATABASE.md) — SQLite schema & operator contract - [`CHANGELOG.md`](CHANGELOG.md) — release history. Work merged since the last tag lives in `.changes/` fragments and is folded in at the next release; the dashboard's changelog modal shows both. Check what you are running with `9routerx version`. ## Acknowledgments | Repository | Stars | Contribution to 9RouterX | |---|---|---| | [decolua/9router](https://github.com/decolua/9router) | ![stars](https://img.shields.io/github/stars/decolua/9router?style=social) | the original Next.js gateway & dashboard that 9RouterX preserves compatibility with (same SQLite data dir, no-migration upgrade path) | | [luqman-v1/9router-go](https://github.com/luqman-v1/9router-go) | ![stars](https://img.shields.io/github/stars/luqman-v1/9router-go?style=social) | the Go + Svelte port 9RouterX continues from; gateway core, provider lanes, CLI | | [serenhope/9router](https://github.com/serenhope/9router) | ![stars](https://img.shields.io/github/stars/serenhope/9router?style=social) | per-key governance, token-saver suite, security log, web executors, dashboard features ported into 9RouterX | | [cheaper-inference/OmniRoute](https://github.com/cheaper-inference/OmniRoute) | ![stars](https://img.shields.io/github/stars/cheaper-inference/OmniRoute?style=social) | SSRF dispatch guard + PII masking, routing strategies, circuit breaker, multi-target webhooks, Tremor-style data-viz patterns | | [router-for-me/CLIProxyAPI](https://github.com/router-for-me/CLIProxyAPI) | ![stars](https://img.shields.io/github/stars/router-for-me/CLIProxyAPI?style=social) | Kiro `external_idp` auth JSON importer (port of their auth format, see `internal/handlers/oauth/kiro_external_idp.go`) | | [rtk-ai/rtk](https://github.com/rtk-ai/rtk) | ![stars](https://img.shields.io/github/stars/rtk-ai/rtk?style=social) | the request-side token-compression concept behind the RTK Token Saver (20-40% input savings) | | [headroomlabs-ai/headroom](https://github.com/headroomlabs-ai/headroom) | ![stars](https://img.shields.io/github/stars/headroomlabs-ai/headroom?style=social) | GCF/tabular compression concepts ported into `internal/compression/gcf` and `internal/headroom` | | [JuliusBrussee/caveman](https://github.com/JuliusBrussee/caveman) | ![stars](https://img.shields.io/github/stars/JuliusBrussee/caveman?style=social) | the terse-output style directive (Caveman mode, `internal/tokensaver/caveman.go`) | | [DietrichGebert/ponytail](https://github.com/DietrichGebert/ponytail) | ![stars](https://img.shields.io/github/stars/DietrichGebert/ponytail?style=social) | the structured-output style directive (Ponytail mode) | | [ayghri/i-have-adhd](https://github.com/ayghri/i-have-adhd) | ![stars](https://img.shields.io/github/stars/ayghri/i-have-adhd?style=social) | the scannable/bulleted output style (ADHD mode) | | [miqdadbadjuber/anti-slop](https://github.com/miqdadbadjuber/anti-slop) | ![stars](https://img.shields.io/github/stars/miqdadbadjuber/anti-slop?style=social) | antislop injector rules bundled in `internal/tokensaver/antislop` with their original text and attribution preserved | | [huntabyte/shadcn-svelte](https://github.com/huntabyte/shadcn-svelte) | ![stars](https://img.shields.io/github/stars/huntabyte/shadcn-svelte?style=social) | the dashboard component layer (chart, table, tooltip, separator via bits-ui + layerchart) | 9RouterX stands on this lineage — thank you to the upstream maintainers and their communities for the gateway, the port, and the ideas this project builds on. The complete three-layer ownership inventory (inherited / ported / original) lives in [ATTRIBUTION.md](ATTRIBUTION.md), and everyone whose commit landed in the repository is credited on the wiki's [**Owner & Contributors**](https://yanstd888.github.io/9routerx/team.html) page. ## Contributors 9RouterX stands on the work of its maintainers and every contributor whose commit landed here. Thank you. [![Contributors](https://contrib.rocks/image?repo=yanstd888/9routerx&max=150&columns=15&anon=1)](https://github.com/yanstd888/9routerx/graphs/contributors) ## Star History [![Star History Chart](https://api.star-history.com/chart?repos=yanstd888/9routerx&type=date&legend=top-left)](https://www.star-history.com/?repos=yanstd888%2F9routerx&type=date&legend=top-left) ## License MIT License — see [`LICENSE`](https://github.com/yanstd888/9routerx/blob/main/LICENSE). --- ## Attribution **9RouterX — all source code port and modification by [yanstd888](https://github.com/yanstd888/) — [t.me/aiclub_id](https://t.me/aiclub_id).** This repository is an independent Go + Svelte port of [9Router](https://github.com/decolua/9router) (MIT); all port and modification work is by Muhammad Dian (yanstd888). Re-hosting this code without the LICENSE copyright notice and this attribution violates the MIT license terms. For the full file-by-file ownership breakdown, see [`ATTRIBUTION.md`](ATTRIBUTION.md). # Home (wiki source home) # 9RouterX **Never stop coding. Save 20-40% tokens with RTK + auto-fallback to FREE & cheap AI models.** 9routerx is a single Go binary that serves both the proxy APIs and the dashboard — no Node.js at runtime. This page is the entry point to the whole wiki. ## Start here | You want to… | Open | |---|---| | Install and run | [Installation](installation.html) | | Use it from a CLI tool (Claude Code, Codex, Cursor…) | [Client Setup](client-setup.html) | | Browse the main endpoint groups | [API](api.html) | | Get to know the dashboard | [Dashboard](dashboard.html) | | Connect AI providers | [Providers](providers.html) | | Build fallback chains | [Combos](combos.html) | | Cut token spend | [Token Saver](token-saver.html) | | See what RTK actually saved | [Usage & Analytics](usage-analytics.html) | | Limit who spends what | [Governance](governance.html) | | Protect credentials and prompts | [Security](security.html) | | Understand routing internals | [Architecture](architecture.html) | | See how data is stored | [Database](database.html) | | Run it in production | [Operations](operations.html) | | Configure everything in the dashboard | [Settings](settings.html) | | Compare with upstream 9Router | [Parity](parity.html) | | See what was ported, and from where | [Advanced Features](advanced-features.html) | | Every CLI command and env var | [CLI](cli.html) | | Contribute | [Contributing](contributing.html) | | Browse screenshots | [Screenshots](screenshots.html) | ## Running in 30 seconds ```bash 9routerx # Dashboard: http://localhost:20128 (initial password: 123456) ``` Dashboard → Providers → connect a supported provider, then create a local engine API key in Settings → API Keys before pointing your client at `http://127.0.0.1:20128/v1`. OpenCode Free is cataloged as a no-upstream-login lane; Kiro still requires a supported credential flow. ## Which version am I on? ```bash 9routerx version ``` Some features on this site arrived in a specific release. Where that matters, the page says so — for example the [Advanced Features](advanced-features.html) page lists which release each port landed in, and flags the ones that are still on a branch rather than in a release you can download. ## What is in the box | Area | What you get | |---|---| | Proxy APIs | OpenAI Chat, Claude Messages, Responses, embeddings, images, video, audio, search, batches | | Routing | [Combo strategies](combos.html), including `lkgp`, budgets and family warnings; arena uses a limited direct path | | Token savers | RTK and compression/output styles; opt-in [tool-loop watch](token-saver.md#tool-loop-watch) with protocol-dependent coverage | | Governance | Per-key rate limits, budgets, plans, allowlists, and a [fair-share scheduling hint](governance.md#fair-share-scheduling), not a reserved quota | | Security | Credential vault, key hashing, dashboard-token scopes, reversible PII placeholders, guardrails, and audit records with documented limits | | Providers | 394 built-in entries (317 API category, 35 OAuth category, 31 free, 11 web-cookie); auth modes vary. 245 static free models across 37 providers, including 24 keyless; custom endpoint templates are separate | | Agents | MCP server endpoint (see [MCP guide](mcp)), A2A endpoints, multi-target webhooks, team cost centers | | Operations | Docker, tunnels, updates, automatic snapshots, sensitive remote JSON backups, supplied proxy harvest, and local doctor/onboarding status | ## Search The search box at the top left searches **titles, headings, and endpoints** across every wiki page. Results are also shareable: the URL becomes `?q=...` (query) and `#...` (a specific section inside a page), so whoever you send it to opens exactly the part you meant. # Installation # Installation ## npm (primary) ```bash npm install -g 9routerx ``` The launcher installs the right binary for your OS automatically (Windows, macOS Intel/Apple Silicon, Linux x64/ARM64). Requires Node.js **>= 18**; the gateway binary itself is a single Go executable with no runtime dependencies. ## Alternative — script installer (same binaries) ```bash # macOS / Linux curl -fsSL https://raw.githubusercontent.com/yanstd888/9routerx/main/install.sh | bash ``` ```powershell # Windows (PowerShell) — writes to %LOCALAPPDATA% + user PATH, no admin needed irm https://raw.githubusercontent.com/yanstd888/9routerx/main/install.ps1 | iex ``` ## Defaults No flags required: | | Default | |---|---| | Port | `20128` | | Listener | `127.0.0.1` (loopback); explicit `HOST=0.0.0.0` or `HOST=*` enables all interfaces | | Data | `~/.9router` (`%APPDATA%/9router` on Windows) | | Dashboard | `http://localhost:20128` | | Initial password | `123456` (localhost only) | ## Running ```bash 9routerx # run in the foreground curl http://localhost:20128/health 9routerx version ``` Override only when you need something different (`PORT`, `DATA_DIR`/`DB_PATH` — there are no `--port` flags): ```bash PORT=20129 9routerx DATA_DIR=/srv/9router 9routerx DB_PATH=/srv/9router/data.sqlite 9routerx HOST=127.0.0.1 9routerx ``` ## Background mode ```bash 9routerx start # same as: 9RouterX --background (or -d) 9routerx status # pid, dashboard, log 9routerx restart 9routerx logs -n 100 9routerx stop ``` The detached process records itself in `DATA_DIR/run/gateway.pid` and writes its output to `DATA_DIR/run/gateway.log`. A second `start` while one is running refuses instead of fighting over the port. > Windows stops the process with `TerminateProcess` instead of `SIGTERM`, so > `stop` skips the graceful drain; use the dashboard's Shutdown button or > `9routerx restart` when you want in-flight streams to finish first. ## Start on boot ```bash 9routerx service install # systemd user unit, launchd agent, OpenRC/runit service, cron @reboot, or Windows logon task 9routerx service status 9routerx service start 9routerx service restart 9routerx service stop 9routerx service uninstall ``` `install` picks the native backend for the host. systemd, launchd, and cron all install into the **user** scope and need no root; runit's `~/service` path too. Two exceptions: OpenRC is a system service and needs root (run with `sudo`, or pick `--backend cron`), and on Windows install registers a scheduled task via `schtasks`, which requires an Administrator console. Force a backend with `--backend systemd|launchd|openrc|runit|cron`. ## Docker For container port publishing, explicitly set `HOST=0.0.0.0` inside the container; the default loopback listener is not reachable through a published port. Require strong dashboard authentication before allowing network access. ```bash docker run -d --name 9routerx --restart unless-stopped \ -p 20128:20128 -v "$HOME/.9router:/data" \ -e PORT=20128 -e DATA_DIR=/data -e HOST=0.0.0.0 \ -e INITIAL_PASSWORD=your-secure-password \ ghcr.io/yanstd888/9routerx:latest ``` Experimental releases are marked **Pre-release** and are not selected by the stable updater. GHCR uses `ghcr.io/yanstd888/9routerx:exp` for experimental containers, separate from `latest`. ## Building from source Prerequisites: Go 1.27 and Bun 1.x (the dashboard is embedded into the binary, so build web first). ```bash git clone https://github.com/yanstd888/9routerx.git cd 9routerx make web-build # bun install --frozen-lockfile && bun run build make build # embeds VERSION into the Go binary ``` ## First login - **Localhost (`localhost` / `127.0.0.1`)**: the initial compatibility password is `123456`. Once logged in, change it in **Settings → Profile**. - **Remote / VPS / Docker / LAN**: for security (preventing public takeover of fresh installs with known defaults), remote access blocks the default `123456` password. Either: 1. Set `INITIAL_PASSWORD` on launch (recommended): ```bash INITIAL_PASSWORD="your-secure-password" 9routerx ``` 2. Or access via SSH port-forwarding first: ```bash ssh -L 20128:127.0.0.1:20128 user@remote-host # open http://localhost:20128, log in with 123456, then change the password ``` # Client Setup # Client Setup ## From a CLI tool ``` Claude Code / Codex / OpenClaw / Cursor / Cline Settings: Endpoint: http://localhost:20128/v1 API Key: [Settings → API Keys in the dashboard] Model: kr/claude-sonnet-4.5 ``` For Claude Messages clients: `ANTHROPIC_BASE_URL=http://localhost:20128/v1`. ## curl example ```bash curl http://localhost:20128/v1/chat/completions \ -H 'Content-Type: application/json' \ -H 'Authorization: Bearer sk-your-api-key' \ -d '{"model":"ag/gemini-3.8-flash-high","messages":[{"role":"user","content":"Hello"}],"stream":true}' ``` ## Environment | Variable | Default | Purpose | |---|---|---| | `PORT` | `20128` | HTTP port | | `HOST` / `BIND_ADDR` | `127.0.0.1` (loopback) | Listener address; explicit `0.0.0.0` or `*` allows all interfaces | | `DATA_DIR` | `~/.9router` (`%APPDATA%/9router` on Windows) | Data root | | `DB_PATH` | `$DATA_DIR/db/data.sqlite` | SQLite file | | `INITIAL_PASSWORD` | unset (fallback `123456` locally) | First dashboard password | | `RTK_ENABLED` | `true` | RTK input compression | | `CAVEMAN_ENABLED` / `PONYTAIL_ENABLED` | `false` | Output style savers | | `AUTO_UPDATE` | `false` | Background self-update | | `HTTP_PROXY` / `HTTPS_PROXY` | Go defaults | Upstream egress proxy | | `PPROF_ENABLED` | `false` | Expose `/debug/pprof/*` | | `TRUST_PROXY` / `TRUST_CLOUDFLARE` | unset | Trust forwarded client-IP headers | | `TRUSTED_PROXIES` | unset | CIDR list of trusted reverse proxies | | `GEMINI_WEB_ROTATION` | `on` | Renew the Gemini Web session cookie in the background | `.env.example` documents the security-sensitive subset and OAuth overrides. ## Authentication - **Public**: `/health`, dashboard HTML/assets, `/login`, OAuth callbacks. - **Proxy routes** require an active client API key (`Authorization: Bearer` / `X-API-Key`). - **Dashboard management APIs** require an operator session cookie or CLI token. Engine keys only grant the explicitly allowlisted catalog/capability GETs. Login disabled remains an open anonymous dashboard, not tenant isolation. - The API server defaults to loopback (`127.0.0.1`). Access from other machines requires explicit `HOST=0.0.0.0` or `HOST=*`; protect that port with strong dashboard authentication and trusted network controls. ## Trusting a proxy A forwarded client-IP header is only read when the TCP peer is inside the trusted set — otherwise a client could rotate `X-Forwarded-For` and give every login attempt its own rate-limit bucket. `TRUST_PROXY=true` trusts loopback and the RFC1918/link-local ranges; `TRUSTED_PROXIES` takes a comma-separated list of CIDRs or single IPs and **replaces** those defaults. Behind a proxy that is *not* in the trusted set, every request is bucketed by the proxy's own socket address, so all users of that proxy share one login bucket: five failed attempts lock them all out. ## Gemini Web session renewal The `gemini-web` provider reaches `gemini.google.com` with a session cookie, and Google rotates the session's timestamp cookie (`__Secure-1PSIDTS`) every few minutes. The router renews it in the background, so a signed-in account keeps reaching the models it pays for instead of falling back to one model after a few minutes. There are three ways to get a session, and the dashboard offers two of them as a button: 1. **A throwaway browser** — the safest. The button opens a browser with a profile of its own, waits for the Google sign-in, reads the session out of it, then closes the browser and deletes the profile. 2. **A browser that is already signed in** — the convenient one. The button opens the browser's own cookie database, takes the key that seals it from the platform's secret store, and unseals the cookies. **A browser that is still open keeps rotating the same session** and the router renews it from the other side, and the two cancel each other out — which signs the account out. Close the browser first, or use the throwaway browser above. 3. **A cookie you paste** — the fallback. Copy the cookie header from an Incognito window that you close right after, then paste it into the connection form. Set `GEMINI_WEB_ROTATION=off` to run the router without renewing anything at all — the right choice when the credential belongs to a browser you want to keep using. # API # API 9routerx speaks the OpenAI, Claude, Gemini and Ollama dialects, and adds media, batching, and a dashboard REST API. This is a grouped reference to the main mounted routes, not an exhaustive OpenAPI schema. Provider-specific support and operational limits are linked from each section. ## Authentication tiers | Tier | Protects | |---|---| | Public | `/health`, `/version`, `/api/hello`, `/changelog`, OAuth callbacks, dashboard assets | | Client API key (`Authorization: Bearer` / `X-API-Key`) | every `/v1/*` proxy route | | Dashboard session / CLI token / dashboard access token | Management APIs; dashboard-token scopes restrict methods and paths, engine keys get 403 | | Engine key, read-only dashboard allowlist | GET `/api/providers/catalog`, GET `/api/models/caps` | | Privileged dashboard access | Explicit method/path exclusions protect some APIs; `write` still allows vault rotation and auto-backup restore/delete | Dashboard access tokens use the `x-9r-access-token` header and are distinct from engine keys. Export with login required adds a handler-level password/session/CLI check that an admin access token alone does not satisfy. See [Security](security.md#dashboard-access-tokens) for scopes, revocation, and caching. ## Chat and models ```text POST /v1/chat/completions OpenAI Chat Completions POST /messages Claude Messages POST /messages/count_tokens Claude token counting POST /responses Responses API POST /responses/compact Compact a Responses conversation POST /api/chat Ollama-compatible chat GET /v1/models Model catalog GET /v1/models/{id} One model's detail GET /v1/models/{kind} Models by kind (llm, embedding, image, tts, stt, video) GET /api/models/catalog-sync Catalog sync status POST /api/models/catalog-sync Trigger a catalog sync ``` ## Media ```text POST /embeddings Embeddings POST /images/generations Text to image POST /images/edits Image editing POST /audio/speech Text to speech POST /audio/music Music generation POST /audio/sound-generation Sound effect generation POST /audio/transcriptions Speech to text GET /audio/voices Available voices GET /api/media-providers/tts/voices TTS voices GET /api/media-providers/tts/{provider}/voices Voices for one TTS provider POST /videos/generations Text to video POST /videos/edits Video editing POST /videos/extensions Video extension GET /videos/{id} Video job status POST /search Web search POST /scrape Page scraping POST /web/fetch Fetch a URL POST /systemone System One ``` ## Batching ```text POST /v1/batches Create a batch GET /v1/batches List batches GET /v1/batches/{batch_id} Batch status POST /v1/batches/{batch_id}/cancel Cancel a batch ``` The same four exist unprefixed under `/batches`. ## Dashboard REST Grouped by the dashboard page that drives them. ### Connections and providers ```text GET /api/connections POST /api/connections PUT /api/connections/{id} DELETE /api/connections/{id} POST /api/connections/{id}/test Probe a connection POST /api/connections/{id}/reorder Change rotation order GET /api/providers/{id}/models Models on a provider GET /api/providers/{id}/export-keys Export provider keys DELETE /api/providers/{id}/models Bulk model removal GET /api/providers/{id}/overrides Per-provider header overrides PUT /api/providers/{id}/overrides POST /api/providers/validate Validate an endpoint before saving POST /api/providers/{id}/browser-login Provider-specific browser capture POST /api/providers/{id}/import-chrome Supported Chromium profile import POST /api/providers/{id}/reset-profile Configured persistent profile reset POST /api/connections/{id}/renew-deepseek Persist a renewed DeepSeek session ``` These generic patterns do not imply every provider supports every operation. See the [browser support matrix](providers.md#browser-based-login) for dedicated overrides, temporary profiles, import limits, and credential handling. ### Custom provider nodes ```text GET /api/provider-nodes POST /api/provider-nodes PUT /api/provider-nodes/{id} DELETE /api/provider-nodes/{id} POST /api/provider-nodes/validate PUT /api/provider-nodes/{id}/limits Capacity limits POST /api/provider-nodes/{id}/quota/reset Lift a spent token quota ``` ### Combos ```text GET /api/combos POST /api/combos POST /api/combos/auto-free Build a free-tier chain POST /api/combos/auto-family Build per-family chains GET /api/combos/presets Cursor / Claude preset lists POST /api/combos/presets Create from presets PUT /api/combos/{id} DELETE /api/combos/{id} POST /api/combos/reconcile Apply every combo's smart rules POST /api/combos/{id}/smart/preview Dry-run one combo's rules POST /api/combos/{id}/smart/load Apply one combo's rules POST /api/arena/run Limited direct model comparison ``` Budget fields, strategy coverage, family warnings, and the arena's direct API-key-only path are described in [Combos](combos.html). ### API keys, plans, and model access ```text GET /api/keys POST /api/keys PUT /api/keys/{id} DELETE /api/keys/{id} PUT /api/keys/{id}/toggle POST /api/keys/{id}/rotate POST /api/keys/{id}/reset-quota GET /api/keys/{id}/models Per-key model allowlist PUT /api/keys/{id}/models GET /api/plans POST /api/plans GET /api/plans/{id} PUT /api/plans/{id} DELETE /api/plans/{id} GET /api/plans/{id}/keys Keys inheriting a plan ``` ### Models ```text GET /api/models/custom POST /api/models/custom DELETE /api/models/custom/{key} GET /api/models/caps Model capabilities and limits GET /api/models/meta GET /api/models/disabled PUT /api/models/disabled/{provider} POST /api/models/auto-disable GET /api/models/health PUT /api/models/health GET /api/models/alias PUT /api/models/alias DELETE /api/models/alias GET /api/models/deprecations POST /api/models/sync ``` ### Proxy pools ```text GET /api/proxy-pools POST /api/proxy-pools PUT /api/proxy-pools/{id} DELETE /api/proxy-pools/{id} POST /api/proxy-pools/{id}/test POST /api/proxy-pools/{id}/harvest Import/probe a supplied proxy batch POST /api/proxy-pools/vercel-deploy Deploy a relay POST /api/proxy-pools/deno-deploy POST /api/proxy-pools/cloudflare-deploy POST /api/proxy-pools/netlify-deploy ``` ### Usage, quota, and analytics ```text GET /api/usage/stream Live usage SSE GET /api/usage/stats GET /api/usage/chart GET /api/usage/dashboard GET /api/usage/request-details GET /api/usage/request-details/{id} GET /api/usage/providers GET /api/usage/{connectionId} GET /api/usage/{connectionId}/reset-credits Codex reset credits POST /api/usage/{connectionId}/reset-credits/consume GET /api/usage/{connectionId}/glm-reset-cards GLM reset cards POST /api/usage/{connectionId}/glm-reset-cards GET /api/analytics/compression Token-saver analytics GET /api/savings/summary Estimated savings by period GET /api/burn-rate Rough gateway-rate projections ``` See [Usage & Analytics](usage-analytics.html) for metric windows and estimates; see [Operations](operations.md#proxy-pool-harvest) for harvest limits. ### Cache ```text GET /api/cache Includes hitRates for prompt/semantic cache DELETE /api/cache GET /api/cache/entries DELETE /api/cache/entries ``` ### Settings and maintenance ```text GET /api/settings PUT /api/settings GET /api/settings/database Export the database POST /api/settings/database Import a database GET /api/settings/database/stats POST /api/settings/database/prune POST /api/settings/database/prune-usage POST /api/settings/database/vacuum POST /api/settings/proxy-test POST /api/settings/logo White-label logo upload POST /api/settings/currency/refresh Refresh exchange rates GET /api/tokensaver/rtk/filters POST /api/tokensaver/rtk/test POST /api/tokensaver/caveman/test GET /api/settings/history Best-effort top-level key history POST /api/settings/history/{id}/rollback GET /api/settings/auto-backup Sanitized config/status and local backups PATCH /api/settings/auto-backup Configure schedule and remote destination POST /api/settings/auto-backup Backup, restore, or delete GET /api/doctor Local diagnostic probes GET /api/onboarding/status Connection/key counts, not live validation POST /api/onboarding/complete Dismiss onboarding ``` Settings section replacement and history rollback caveats are in [Settings](settings.md#settings-api-and-history). Backup formats and sensitive remote artifacts are covered in [Operations](operations.md#automatic-and-remote-backups). Doctor/onboarding semantics are in [Dashboard](dashboard.md#onboarding-and-local-doctor). ### Tunnels ```text GET /api/tunnel/status POST /api/tunnel/enable POST /api/tunnel/disable GET /api/tunnel/tailscale-check POST /api/tunnel/tailscale-enable POST /api/tunnel/tailscale-disable ``` ### Security ```text GET /api/vault/status GET /api/dashboard-tokens Scoped dashboard-token metadata POST /api/dashboard-tokens Mint once-visible token DELETE /api/dashboard-tokens/{id} Revoke token POST /api/vault/rotate GET /api/guardrails/policies POST /api/guardrails/policies PUT /api/guardrails/policies/{id} DELETE /api/guardrails/policies/{id} GET /api/guardrails/logs GET /api/metrics Prometheus ``` ### Security log and audit log ```text GET /api/security-log Security events (login attempts, key changes, …) GET /api/security-logs Alias of the above DELETE /api/security-log Clear the security log GET /api/audit Audit trail of dashboard actions ``` See [Security](security.md#security-log-and-audit-log) for audit coverage and integrity limits. Internal verification helpers are not a mounted public API. ### Web executors Session health and switches for the browser-based provider executors: ```text GET /api/webexec Per-provider executor status PUT /api/webexec/{provider}/toggle Enable or disable one executor POST /api/webexec/{provider}/test Run the health probe for one provider ``` ### Webhooks Multi-target push notifications. Every configured target receives the same events; a per-target test ping proves delivery without waiting for a real one: ```text GET /api/webhooks POST /api/webhooks PUT /api/webhooks/{id} DELETE /api/webhooks/{id} POST /api/webhooks/{id}/test ``` ### Teams Team cost centers: keys belong to a team, and each team's spend is reported separately. ```text GET /api/teams POST /api/teams PUT /api/teams/{id} DELETE /api/teams/{id} Archive — history keeps its attribution GET /api/teams/{id}/usage ``` ### MCP and A2A Agent integrations served by the gateway itself: ```text POST /api/mcp Model Context Protocol server endpoint GET /.well-known/agent.json A2A agent card POST /api/a2a A2A JSON-RPC endpoint GET /api/a2a/status A2A status ``` ### OAuth Import and exchange endpoints per provider. Kiro, Codex, Grok CLI, Freebuff, Antigravity, Cline, PKCE, device-code, auth-code, Trae, Windsurf, Zed, Cursor, Kimchi, GitLab PAT, iFlow cookie, and Xiaomi MiMo all have their own authorize/exchange pair under `/api/oauth/{provider}/…`. Several providers add bulk-import and auto-import variants. ### Console log ```text GET /api/translator/console-logs DELETE /api/translator/console-logs GET /api/translator/console-logs/stream GET /api/translator/console-logs/level PUT /api/translator/console-logs/level ``` ### CLI tools and version ```text GET /api/cli-tools/all-statuses GET /api/cli-tools/{tool}-settings GET /version GET /api/version GET /api/version/status GET /api/version/check POST /api/version/update admin POST /api/version/auto-update admin ``` ### Headroom ```text POST /headroom/start | stop | restart GET /headroom/status GET /headroom/extras POST /headroom/extras DELETE /headroom/extras GET /headroom/proxy ``` The same set is also mounted under `/api/headroom/…`. ## Finding an endpoint Use the search box at the top left to jump straight to an endpoint. Shareable links you can build: - `?q=/v1/chat/completions` — every page mentioning that endpoint - `?q=RTK_ENABLED` — the environment page and any page using that variable - `api.html#batching` — a specific section inside this page ## Model response timeout in combos For sequential combo routing, set **Model response timeout** in seconds (decimals such as `5.3` are fine) in the combo's Edit dialog, or from the compact field on the combo card. Empty or `0` disables it. The timer covers each model candidate except the last, including connection selection and waiting for a usable response. If it expires before output is committed, the router cancels that candidate and tries the next. The last candidate keeps the gateway's normal deadline, so the setting never makes a combo fail sooner than it would without it. An active stream is not cut off by this setting. For non-streaming requests, the timer covers the wait for the complete response. Fusion panel timing is separate. A model that times out is left out of that combo for a grace period (default 5 minutes, set per combo under the timeout in the Edit dialog; `0` re-includes it on the next request) and then rejoins the chain. If every model in the chain is inside its grace period, the full chain is used. The pause is held in memory and resets on restart. Stored as `firstTokenGraceMs` next to the timeout. The dashboard shows seconds; the setting is stored in milliseconds as `comboStrategies[comboName].firstTokenTimeoutMs`. # Migrating from 9Router # Migrating from 9Router The SQLite data already carries over; replacing the running process and its hidden autostart is a separate step: ```sh 9routerx service take-over ``` The command uses the configured `PORT` (default 20128) and `DATA_DIR`. It reports the listener's fingerprint, PID, executable, command line and parent PID, asks before stopping it, waits for the port, inventories matching legacy autostart, asks before disabling each entry, and calls the **same service backend as `service install`**. It then checks `/health` and the 9RouterX root fingerprint and prints read-only counts of `providerConnections` and `apiKeys`, the database path, dashboard URL and login guidance. Zero rows warn about a different `DATA_DIR`; they do not mean migration erased anything. Every action is reported. Force-kill is attempted only after graceful stop fails, with an explicit warning and another confirmation. Without a terminal, confirmation fails instead of hanging. For reviewed unattended migrations: ```sh 9routerx service take-over --yes ``` `--yes` approves **all** reported actions, including the warned force fallback. It does not bypass process identity or legacy path matching. Take a database backup first; see [Database](database.md). Windows service installation may need an Administrator terminal; a failure is reported, not presented as success. ## The real problem this solves An operator installed 9RouterX while an autostarted Node.js/Next.js 9Router kept returning after every restart. Task Scheduler, the Startup folder, Task Manager Startup apps and Registry Run keys all appeared empty. There was no obvious process to stop or useful error: both gateways competed for port 20128, or the operator gave up. Data compatibility alone did not solve process migration. If no matching autostart is found, take-over prints the old command line and **parent PID**, warns that the parent may respawn it, and asks before continuing. Disable that parent and rerun take-over, or keep the old gateway and use the next port. A respawn occupying the port aborts installation instead of silently claiming success. HTTP fingerprints vary across upstream versions, redirects and custom themes; executable/command-line inspection is the fallback, not a claim that every Next.js page identifies 9Router. Upstream's shutdown endpoint can terminate multiple matching processes and `cloudflared`, so take-over deliberately does **not** call that broad legacy shutdown helper. It requests a stop of the verified listener PID only. For a 9RouterX daemon with a valid pidfile it reuses authenticated graceful HTTP shutdown. ## First run and side-by-side operation 9RouterX now listens on `127.0.0.1` by default. Existing LAN or container setups that relied on implicit all-interface binding must opt in with `HOST=0.0.0.0` (or `HOST=*`) and keep dashboard authentication enabled. When `9routerx start` has no pidfile in this `DATA_DIR` and the port is occupied, a terminal shows: 1. Take over the existing gateway (`service take-over`). 2. Use another free port (recommended default 20129). 3. Abort (default). With piped/non-TTY stdin it exits with an informative error; no automatic choice and no prompt. Identified 9Router/9RouterX conflicts name take-over; unrelated listeners only get the alternative-port hint. Later starts use the same conflict description, without repeating the first-run menu. ```sh # macOS / Linux PORT=20129 9routerx start PORT=20129 9routerx service install ``` ```powershell # Windows PowerShell $env:PORT = '20129' 9routerx start 9routerx service install ``` The service captures the effective port and absolute data/database paths in its command arguments so the next login does not depend on your shell's env. Log in with your existing dashboard password. For a new empty database use `INITIAL_PASSWORD` as described in [Installation](installation.md). ## Windows: where autostart can hide These are **read-only** inspections. Run them in PowerShell. Compare paths with the listener, not just the shared `node.exe` interpreter: ```powershell # Listener and its identity (replace 20128 if PORT differs) netstat -ano -p tcp | Select-String ':20128\s+.*LISTENING' # Substitute the PID from the final netstat column, not PowerShell's reserved $PID $gatewayPid = 1234 Get-CimInstance Win32_Process -Filter "ProcessId = $gatewayPid" | Select-Object ProcessId,ParentProcessId,Name,ExecutablePath,CommandLine # Task Scheduler: exact commands, including subfolders schtasks /query /fo LIST /v | Select-String '9router|node' -Context 3,3 Get-ScheduledTask | Select-Object TaskPath,TaskName,Actions # Registry Run keys (HKLM is inspection only; only migrate it with proven system scope) reg query 'HKCU\Software\Microsoft\Windows\CurrentVersion\Run' reg query 'HKLM\Software\Microsoft\Windows\CurrentVersion\Run' # Current user's Startup folder; inspect .lnk targets too Get-ChildItem ([Environment]::GetFolderPath('Startup')) $ws = New-Object -ComObject WScript.Shell Get-ChildItem ([Environment]::GetFolderPath('Startup')) -Filter *.lnk | ForEach-Object { $ws.CreateShortcut($_.FullName) } | Select-Object TargetPath,Arguments # Task Manager > Startup apps; services.msc for system services Get-CimInstance Win32_StartupCommand | Select-Object Name,Command,Location,User Get-CimInstance Win32_Service | Where-Object { $_.PathName -match '9router|node' } | Select-Object Name,ProcessId,StartMode,PathName # Only if installed: pm2 can resurrect apps from its saved process list pm2 jlist ``` Take-over inventories tasks via their XML/CIM actions (locale-independent), HKCU Run, Startup files/shortcut targets and Windows service paths. HKLM Run is considered only when the old listener was proven to be a Windows service. It disables matching tasks/services, removes confirmed Run values with a registry warning, and renames matching Startup files with `.9router-disabled`. It never matches generic `node.exe` alone or disables 9RouterX entries. An entry whose command changed since inspection is refused. Multi-action tasks and compound/multiline commands are left for manual inspection so another app is not disabled with the gateway. Wrappers with no exact legacy gateway path match are reported as unresolved rather than guessed. ## macOS: launchd and Login Items ```sh lsof -nP -iTCP:20128 -sTCP:LISTEN ps -p 1234 -o pid=,ppid=,comm=,args= launchctl list | grep -i router find "$HOME/Library/LaunchAgents" -name '*.plist' -print # Replace with a plist from that list; inspect Program/ProgramArguments plutil -p "$HOME/Library/LaunchAgents/com.example.9router.plist" # Login Items/background items (inspect System Settings > General > Login Items too) sfltool dumpbtm pm2 jlist ``` Take-over checks user LaunchAgents' parsed Program/ProgramArguments. Matching agents are unloaded and renamed `.9router-disabled`. Login Items managed by another app may require disabling that app manually. ## Linux: systemd user, cron, desktop autostart ```sh lsof -nP -iTCP:20128 -sTCP:LISTEN # Alternative when lsof is unavailable; PID visibility may need permission ss -ltnp 'sport = :20128' ps -p 1234 -o pid=,ppid=,comm=,args= systemctl --user list-unit-files --no-pager | grep -i router systemctl --user show 9router.service --property=ExecStart --value crontab -l | grep -E '^[[:space:]]*@reboot[[:space:]]' find "$HOME/.config/autostart" -name '*.desktop' -print # Inspect the listed files' Exec= lines before changing anything grep -H '^Exec=' "$HOME"/.config/autostart/*.desktop pm2 jlist ``` Take-over disables matching systemd user units, comments out matching `@reboot` lines while preserving the rest of crontab, and renames matching desktop entries. On every OS, matching pm2 apps are deleted by their numeric ID and `pm2 save` updates resurrection state. If pm2 is not installed, it is skipped. ## Nothing found, but the old process returns Inspect the reported parent before stopping anything else. Examples: ```powershell Get-CimInstance Win32_Process -Filter 'ProcessId = 5678' | Select-Object ProcessId,ParentProcessId,ExecutablePath,CommandLine ``` ```sh ps -p 5678 -o pid=,ppid=,comm=,args= ``` A terminal manager, npm wrapper, process manager, container or other parent can restart the gateway without a conventional Startup entry. Disable only the parent you identify, then rerun take-over. Otherwise choose another port; do not kill every Node.js process or delete unrelated autostart entries. # Dashboard # Dashboard The dashboard is native Svelte 5, embedded in the binary — no separate Node.js process at runtime. Every page below is a real sidebar entry. ## Sidebar entries The sidebar is organised into three groups: the main entries, an **Advanced Features** group, and a **System** group. Every entry can be hidden or reordered from Settings; a fresh install hides only **Plans** and **Persona**. | Entry | What it does | |---|---| | Endpoint & Key | Where to point your CLI tool, and the API keys it uses | | Providers | Connect providers, browse models, manage custom nodes | | Combo & Vision Adapter | Fallback chains, round-robin, sticky, fusion, capacity | | Usage | Live usage, history, per-request breakdown | | Quota Tracker | Per-provider quota and reset schedules | | Token Saver | RTK, Caveman, Ponytail, ADHD, and the test benches | | CLI Tools | Which installed CLI tools the gateway has written config for | | Security | Credential vault, guardrails, and the enforcement panel | | Security Log | The per-event security log the gateway records on | | Audit Log | Operational records of dashboard actions; not a complete tamper-evident ledger | | Persona | Agent prompt presets, per-model binding *(hidden by default)* | | Free Tier | Free-tier provider catalog with usage and cost tracking | | Web Executors | Browser-based provider executors and their session health | | Webhooks | Multi-target push notifications with per-target test pings | | Plans | Reusable policy templates *(hidden by default)* | | Media Providers | Accordion: Embedding, Text to Image, Text to Speech, Speech to Text, Video, System One, Web Fetch & Search | | Proxy Pools | Bind a proxy to each API key connection | | Skills | Operator skill blocks per scope | | Console Log | Live log with level filters and search | | Settings | Profile, display, savers, branding, sidebar layout | ## Usage views The Usage page switches between several views of the same ledger (`web/src/components/analytics/UsageDashboard.svelte`): | View | Component | |---|---| | Summary KPIs | `SummaryKpiCards.svelte` | | Chart | `UsageChart.svelte` | | Breakdown table | `UsageBreakdownTable.svelte` | | Provider topology | `ProviderTopologyCard.svelte` | | Activity heatmap | `ActivityHeatmap.svelte` | | Combo flow | `ComboFlowCard.svelte` | | Node health | `NodeHealthTable.svelte` | | Request details | `RequestDetailsTab.svelte` | ## Sidebar layout is yours The sidebar is not fixed. Three controls, all in Settings: - **Per-entry visibility** — show or hide any row without touching code (`web/src/lib/navVisibility.svelte.ts`). Settings itself can never be hidden. - **Arrangement** — reorder rows inside their container, up/down or drag-and-drop (`web/src/lib/orderList.ts`). A drop on a row from another container is refused rather than silently misplaced. - **Presets** — one click fills the hide list: | Preset | Hides | |---|---| | `default` | Plans, Persona | | `advanced` | nothing | | `simple` | media surfaces, CLI Tools, Skills, Console Log, Plans | | `super-lite` | everything except Endpoint & Key, Providers, Combos, Usage, Settings, Security | A preset writes the hide list only. The arrangement stays where you put it, because "what is on the sidebar" and "in which order" are different questions. ## Quota and model health - **Quota table** (`components/quota/QuotaTable.svelte`) shows per-provider remaining quota, with Codex reset credits and GLM reset cards where the provider has them. - **Auto-ping schedule** (`components/quota/AutoPingScheduleModal.svelte`) sets a background schedule that pings a provider through the real dispatch path, so OAuth refreshes and quota stays current without traffic. - **Model health** (`components/settings/ModelHealthPanel.svelte`) shows what the automatic health loop found, and lets you re-enable a model it disabled. ## Compression and cache analytics Two pages read the same ledger: - **Compression Analytics** (`CompressionAnalyticsView.svelte`) — tokens saved, savings ratio, mode breakdown (`rtk`, `caveman`, `adhd`, `ponytail`, `stacked`). - **Cache Analytics** (`CacheAnalyticsView.svelte`) — semantic cache hit rate and the entries behind it. ## Onboarding and local doctor `GET /api/onboarding/status` counts active connections and engine keys. Its `complete` result means both counts are positive, not that an upstream call has succeeded; read failures can appear as zero. `POST /api/onboarding/complete` stores the separate dismissal flag. Dismissing onboarding does not create credentials or prove readiness. `GET /api/doctor` runs five graded local checks, including a temporary `.doctor-probe` write/delete. It is not side-effect-free. Database ping and a quick-check attempt do not certify database integrity or WAL health; the quick-check result is not used as an integrity verdict. Use the response to locate local setup issues, not to certify upstream access or security. ## Keyboard and motion The dashboard includes a skip link, visible focus styles, named icon actions, and reduced-motion handling. Use Tab/Shift+Tab to move between native controls and Enter/Space to activate them. These mechanisms do not constitute a complete accessibility audit or certification of every control and theme. ## Appearance A theme toggle in the top bar switches between light and dark; the choice is stored per browser and applied again on the next visit. Both themes share one palette, so a visitor who opens the docs and then the dashboard sees one product, not two tools. ## Screenshots The [Screenshots](screenshots.html) page contains historical dashboard captures in both themes at desktop and mobile widths. They are not fresh captures of the current release. # Providers # Providers 9RouterX has 394 built-in provider entries: 317 in the API-key category, 35 in OAuth, 31 in the free categories, and 11 in web-cookie. These are catalog groups, not counts of guaranteed authentication flows; for example, `muse` is grouped under OAuth but uses API-key authentication. The grouped catalog also includes two custom endpoint templates, which are not built-in providers. The static catalog contains 245 free models across 37 providers, including 24 keyless models. Antigravity requires one Google OAuth login; OpenCode offers zero-login access. Catalog inclusion does not guarantee current upstream availability or quota. Provider-specific credentials and dispatch paths remain separate. ## Connecting Dashboard → Providers → pick a provider → Connect. OpenCode Free is cataloged as a no-upstream-auth lane. Kiro still needs a supported credential/login flow; free credits do not mean no signup or login. ## OAuth flows Different providers authenticate differently, and the dashboard offers the right one per provider: | Flow | Providers | |---|---| | Social / authorize-exchange | Kiro, Antigravity, Cline, Trae, Windsurf, Zed, Kimchi, Xiaomi MiMo | | Device code | Any provider exposing a device flow | | Local proxy callback | Codex | | Bulk import | Codex, Grok CLI | | API key paste | Kiro | | Cookie / PAT paste | iFlow (cookie), GitLab (PAT) | | Session polling | Freebuff — initiate, poll, inspect, and switch between sessions | Built-in public client credentials exist for antigravity, gemini-cli, xai, codex, iflow and others, so most operators never set an OAuth client ID. Override per provider with `{PROVIDER}_OAUTH_CLIENT_ID` / `{PROVIDER}_OAUTH_CLIENT_SECRET` when you run your own OAuth app. Tokens are refreshed automatically, and a request that fails with `401` is retried once after a refresh. ## Browser-based login Browser capture and import are management operations, not OAuth flows. Use `POST /api/providers/{id}/browser-login` to launch a browser, or `POST /api/providers/{id}/import-chrome` to read an existing Chromium profile. Support depends on the actual route: | Provider ID | Browser login | Import | Profile and reset | |---|---|---|---| | `grok-web` | Generic, captures `sso` | Domain cookies | Persistent; reset supported | | `perplexity-web` | Generic, captures `__Secure-next-auth.session-token` | Domain cookies | Persistent; reset supported | | `muse-web` | Generic Baidu Yiyan/ERNIE, captures `BDUSS` on `baidu.com` | Domain cookies | Persistent; reset supported | | `chatgpt-web` | Generic runtime lane | Domain cookies | Persistent; reset supported; not a seventh catalog entry | | `gemini-web` | Dedicated, captures `__Secure-1PSID` and `__Secure-1PSIDTS` | Dedicated | Temporary; reset returns `400` | | `deepseek-web` | Dedicated, captures user token and cookies | Dedicated | Temporary, including renewal; reset does not clear the profile used by this flow | | `claude-web` | Dedicated, captures `sessionKey` | Not configured (`404`) | Temporary; reset returns `400` | `muse-web` is a historical compatibility ID for **Baidu Yiyan/ERNIE**, not Meta Muse. `chatgpt-web` has runtime configuration and an executor, but no `ProviderRegistry` entry in the dashboard catalog. Claude Web is unofficial, opt-in, and unverified against a live session. ### Persistent profiles and Xvfb Generic persistent profiles live under `/browser-profiles//`. The runner requests `0700` permissions on Unix; Windows permissions follow the host ACLs. The built-in database export and remote backup do not include these directories. A manual filesystem backup can include them, so exclude them explicitly. Treat the profile as an account credential. `POST /api/providers/{id}/reset-profile` removes a configured persistent profile and returns `{provider,status:"reset"}`. Gemini and Claude have no such persistent profile. DeepSeek has a reference config, but its dedicated route still uses a temporary directory; resetting the generic directory does not reset that browser session. On Linux without `DISPLAY` or `WAYLAND_DISPLAY`, the generic persistent runner can use an installed Xvfb. It provides an invisible display for a profile that already has a usable session. It does not supply a visible login UI or solve MFA, CAPTCHA, or cookie decryption. Dedicated Gemini, DeepSeek, and Claude flows do not use this fallback. Repeated or concurrent Xvfb-backed sessions are not guaranteed by the current lifecycle implementation. ### Import and saving credentials Import supports Chromium-family browsers (Chrome, Chromium, Brave, Edge, Vivaldi, and Arc), not Firefox or Safari. An optional `{profile}` selector can choose a browser profile or path; the first `Default` profile may belong to a different account. Close the source browser to reduce locks and concurrent session changes; the returned warning is advisory, not a guarantee against logout or session invalidation. Windows App-Bound encryption is not bypassed. Supported legacy DPAPI/v10/v11 cookies can still be unavailable on a particular host; unavailable decryption or keyring support can return `501`. DeepSeek local-storage scanning reads `.ldb`/`.log` files rather than reconstructing every LevelDB state. Generic login returns `{provider,cookie,tokens,userAgent}`; generic import returns `{provider,cookie,tokens,warning}`. Gemini/Claude login returns `{cookie}`, while DeepSeek returns `{userToken,cookie}`. Dedicated imports add a `warning`. Capture/import reads credentials and leaves connection saving to the caller. A `200` response does not prove live upstream authentication; generic import can return partially decrypted cookies without the required token. Do not log or share these payloads. `POST /api/connections/{id}/renew-deepseek` is different: it persists renewed credentials and returns `{renewed,userToken,cookie}`. Browser capture does not enable an executor. Web executors use `ENABLE_WEB_EXECUTORS` / `enableWebExecutors`; Claude also has the separate `CLAUDE_WEB_ENABLED` / `claudeWebEnabled` gate. ## Custom providers One shared dialog adds an OpenAI- or Anthropic-compatible endpoint. One custom provider is one `providerNodes` row, and a node can have many connections; a connection points at its node through `provider = node.id`. | Field | Purpose | |---|---| | Name | Display name | | Prefix | Wire syntax prefix (`provider/model`) | | Base URL | Upstream endpoint | | Headers | Your own request headers | Validate an endpoint before saving with `POST /api/providers/validate`. ## Per-provider limits Each custom node can carry a capacity budget: | # | Limit | Unit | Meaning | |---|---|---|---| | L1 | RPM | requests/minute | Request rate this endpoint tolerates | | L2 | TPM | tokens/minute | Input (prompt) token rate this endpoint tolerates | | L3 | Concurrency | parallel requests | Number of simultaneous requests | | L4 | Lifetime quota | total tokens | Cumulative cap before the node is declared exhausted | | L5 | Queue timeout | ms | How long a request may wait in the FIFO queue for L1/L3 | | L6 | Contract expiry | RFC3339 UTC date | Validity period of the node's contract | `0` means unlimited; an empty string means no expiry — the same convention as API keys. **Behaviour when exceeded**: congestion (RPM/TPM/concurrency) marks the candidate as full for that attempt only, and the router tries the next candidate; `429` is returned only when every candidate is exhausted. Node state (quota exhausted, contract ended) skips all of that node's connections and returns a typed `403`. **A congestion burst writes no cooldown.** One request over a limit must not globally park a healthy node — only a debug trace is written. The `lastError` row the dashboard's node-health table reads is still written, so you can see the cause without the node being locked. Set limits with `PUT /api/provider-nodes/{id}/limits` and lift a spent quota with `POST /api/provider-nodes/{id}/quota/reset` (it moves the watermark, it does not delete history). ## Models Browse a provider's models with `GET /api/providers/{id}/models`, export keys with `GET /api/providers/{id}/export-keys`, and remove many at once with `DELETE /api/providers/{id}/models`. **Custom models** are stored in the `customModels` key-value scope, not as columns on `providerNodes`. Add one at a time or paste many (separated by spaces, commas or newlines) — one request, atomic, per-row results. **Aliases** (`/api/models/alias`) let a client write a short name for a long model id. **Deprecations** (`/api/models/deprecations`) surface models upstream has retired, and **auto-disable** (`/api/models/auto-disable`) turns off the ones that stopped working. ## Important notes - **No cross-provider aliasing.** `antigravity` is not `opencode`; a model belonging to one provider is never redirected to another. - **No substring-based model rewriting.** Routing decisions are driven by catalog registration, database aliases, custom node prefixes, or standard `provider/model` wire syntax — never by ad-hoc string inspection. - **The Import from /models button** only appears for providers that genuinely support dynamic catalog discovery upstream. # Combos # Combos A combo is a named chain of models the router walks when a request arrives. It is the mechanism behind "never stop coding": the first candidate is your subscription, the next is cheap, the last is free. ## Strategies | Strategy ID | Behaviour | |---|---| | `fallback` | Try candidates in order until one succeeds | | `round-robin` | Rotate across candidates | | `sticky` | Hold the same candidate while it succeeds | | `capacity` | Skip candidates that cannot serve the request's capabilities | | `fusion` | Query a multi-model panel and combine its results | | `cache-optimized` | Prefer candidates likely to retain prompt-cache locality | | `auto` | Choose an order using the available routing signals | | `quota-weighted` | Weight candidates using available quota information | | `reset-aware` | Score remaining quota with assumed windows; rotate leading-score ties, not actual provider reset timestamps | | `lkgp` | Stable ascending order by provider usage-row count over the prior hour | Despite its name, `lkgp` is a usage-based ranking, not a last-success health check: its query does not filter for successful responses. It is applied in the Chat Completions combo path, not explicitly in the separate Messages/Responses loop. `reset-aware` receives the same remaining-quota fraction for both windows and assumed reset distances of 5 hours/7 days, not provider reset timestamps. Other strategy effects depend on available signals; none guarantees an upstream quota or uninterrupted streaming. ## Combo budgets and model families A combo can carry `budgetLimitUsd`, `budgetPeriod` (`daily`, `weekly`, `monthly`, or `total`). Set the limit to `0` to clear it. The global `budget.breach_mode` (`reject` or `downgrade`) selects the exhausted-budget action. The request-start gate can reject with `402` or restrict the combo to its cheapest **priced** member, returning `X-Budget-Downgraded: combo:`. An unpriced member is not a reliable cheapest choice. This is not a universal spend reservation: in-flight requests can overshoot, budget read failures fail open, and multi-member fusion bypasses this gate. Per-key [governance](governance.html) is a separate control. Family classification and the `crossFamily` result provide a derived warning when members span model families. They do not enforce a strict family boundary or automatically make different protocols interchangeable. ## Model arena `POST /api/arena/run` accepts a prompt and 1–6 members. `maxTokens` defaults to 256 when outside the accepted 1–2048 range. Four workers share a 90-second context. The reported latency measures arrival of response headers, not full completion time. The arena selects the first active connection, then checks its credentials. If that connection is OAuth/cookie/unusable, it skips the member rather than searching later connections for an API key. Accepted connections receive a direct OpenAI-shaped request with Bearer authentication. It does not run the normal router's proxy pools, custom headers, governance, refresh protocols, or usage accounting. Use it for a limited comparison, not as proof that the same members work through every client or combo path. ## Creating a combo Dashboard → Combo & Vision Adapter → Create. Two shortcuts build a chain for you: - **Auto-free** (`POST /api/combos/auto-free`) — assembles a chain from the free tiers you have connected. - **Auto-family** (`POST /api/combos/auto-family`) — builds one chain per model family, so `claude`, `gpt`, and `gemini` each get their own fallback. **Presets** (`GET /api/combos/presets`) offer the Cursor and Claude default lists. Every preset is *derived*, never hard-coded: the Claude items are whatever the `cc` registry row currently holds plus the Claude Code aliases, so adding a model to the provider registry adds a preset with no second edit. ## Smart combos Smart combos keep a combo's membership in step with the models the gateway actually knows about. Instead of listing model ids by hand, you write **rules** and the router maintains the list. ### The two ideas a rule separates | Notion | Meaning | |---|---| | **Addable** | A model a rule may put *into* the combo. Gated by reachability (a provider with a connection, a node that still exists) and by kind. | | **Live** | A model that still *exists*. A member that is no longer live is pruned whatever the pattern says. | A provider that loses its connection keeps its members — they are live, just unreachable — but stops contributing new ones. Absence from a catalogue is weak evidence of death, so a member is never pruned for being unreachable. ### Rule shape | Field | Meaning | |---|---| | `pattern` | Glob, keyword, or regex (`re:` prefix required for regex) | | `mode` | `glob` (default), `keyword`, `regex` | | `effect` | `include` or `exclude` — an exclude rule always wins | | `maxMembers` | How many models one rule may contribute. Default 20. `0` = unlimited, an explicit choice. | | `allKinds` | Match non-LLM kinds too. Off by default: embedding, image, TTS and STT models cannot serve a chat turn. | | `enabled` | Rule on/off | Rules match against both spellings of a model — `alias/model` and bare `model` — the same way the per-key allowlist does. A second qualified spelling (`AltID`) means a member is never pruned for being spelled the other way round, and the membership it adds still lands under one id, so a rule cannot create two slots for one model. ### What survives a reconcile - **Excluded ids** — a model you removed by hand is recorded in the rule's `excluded` list, so a later reconcile never re-adds it. A manual removal is permanent. - **Managed members** — the picker never offers a model that is already a member, and the rules editor labels which members a rule owns. **Known limitation:** a model id you pinned by hand *and* a rule claims is owned by the rule, so editing the pattern removes it. The dashboard prevents the common path, but the API cannot tell a pin from a claim when both spell the same id. ### Working with rules ```text POST /api/combos/reconcile Apply every combo's rules POST /api/combos/{id}/smart/preview Dry-run one combo — nothing is written POST /api/combos/{id}/smart/load Apply one combo's rules ``` A preview reports what would change before anything is committed: ```json { "models": ["ag/gemini-3-flash", "oc/free-model"], "added": ["oc/free-model"], "removed": [], "rules": [{ "id": "r1", "matched": 41, "applied": 20, "capped": true }] } ``` `matched` is what the pattern selected; `applied` is what actually landed after the cap; `capped` tells you the cap bit. ## Timeout and grace period Set **Model response timeout** per combo in the Edit dialog (seconds, decimals such as `5.3` are allowed; empty or `0` disables), or from the compact field on the combo card. The timer covers each model candidate except the last, **including connection selection and waiting for a usable response**. The last candidate keeps the gateway's normal deadline, so the setting never makes a combo fail sooner than it would without it (#744). An active stream is not cut off by this setting; for non-streaming requests the timer covers the wait for the complete response. When it fires, the candidate is cancelled and the next is tried; the timed-out model is then left out of that combo for a grace period — default 5 minutes, set per combo under the timeout in the Edit dialog, `0` re-includes it on the next request — before rejoining the chain. Fusion panel timing is separate: a model that times out there is benched by the same grace logic, and if every model in the chain is inside its grace period, the full chain is used. The pause is held in memory and resets on restart. **Where the value is stored:** the dashboard shows seconds; the setting is stored in milliseconds as `comboStrategies[comboName].firstTokenTimeoutMs`, with the grace period next to it as `firstTokenGraceMs`. ## Where it lives - `internal/handlers/chat/combo.go` — dispatch, failover, and the two combo loops - `internal/combos/smart/smart.go` — the rule resolver (pure, no I/O) - `internal/combopresets/presets.go` — the derived Cursor/Claude presets - `web/src/components/combos/` — the dashboard UI # Security # Security 9routerx holds provider credentials, client API keys, and the prompts that pass through it. This page covers every control that protects them. ## Dashboard authentication | Access | Requirement | |---|---| | Public | `/health`, dashboard HTML/assets, `/login`, OAuth callbacks | | Proxy routes (`/v1/*`, `/api/chat`) | Active client API key (`Authorization: Bearer` / `X-API-Key`) | | Dashboard management APIs | Operator session, local CLI token, or a dashboard access token with a permitted scope; engine keys are forbidden | | Read-only metadata (`/api/providers/catalog`, `/api/models/caps`) | An active, unexpired engine API key is also accepted | | Shutdown, update, DB import | Session, local CLI token, or dashboard token with admin permission; never an engine API key | | DB export with login required | Additional handler check requires a valid session, local CLI token, or verified `x-9r-password`; an admin dashboard token alone is insufficient | | Vault rotation and automatic-backup restore/delete | Dashboard `write` or `admin` token can reach these routes; do not treat `write` as non-destructive | | Console log APIs | Full session, local CLI token, or permitted dashboard-token scope; engine API keys are rejected | ### Dashboard access tokens Dashboard tokens are separate from client/engine keys. `GET /api/dashboard-tokens` lists token metadata; `POST` accepts a name and scope (`admin`, `write`, or `read`). Creation shows the plaintext `9rdt_` token once. Send it in the `x-9r-access-token` header, not as an assumed Bearer token. Do not put it in URLs or logs. `read` and `write` permissions are restricted by HTTP method and explicit path exclusions. Shutdown, update, and DB import are privileged. DB export adds a handler-level password/session/CLI check when login is required; an admin access token alone does not satisfy it. Vault rotation and automatic-backup restore/delete are still in scope for `write`. Do not equate `write` with safe or non-destructive access. These scopes do not replace engine-key model/budget policies. Tokens have no expiry option and remain usable until revoked with `DELETE /api/dashboard-tokens/{id}`. Minting and revocation invalidate the local cache; a separate process can retain a cached decision for up to 30 seconds. **First login.** On localhost the initial password is `123456`; change it in Settings → Profile. On a remote host the default password is blocked (CVE-2026-56679 — a fresh install with a known default can be taken over publicly), so set `INITIAL_PASSWORD` or connect through an SSH port-forward first. ## Client IP and rate-limit bucketing Locality never trusts the request Host header. Provider-node exceptions use the direct loopback socket peer; default-password checks use the trusted client-IP resolver below. A reverse proxy without trusted end-client information still looks like its socket peer, so configure that trust explicitly before exposure. A forwarded client-IP header is only read when the TCP peer is inside the trusted set. Otherwise a client could rotate `X-Forwarded-For` and give every login attempt its own rate-limit bucket. | Variable | Effect | |---|---| | `TRUST_PROXY=true` | Trusts loopback and the RFC1918/link-local ranges | | `TRUST_CLOUDFLARE=true` | Trusts Cloudflare's forwarded headers | | `TRUSTED_PROXIES` | Comma-separated CIDRs or IPs that **replace** the defaults | Behind an untrusted proxy, every request is bucketed by the proxy's own socket address, so all its users share one login bucket: five failed attempts lock them all out. `TRUSTED_PROXIES` separates them again. ## Credential vault Provider credentials are sealed with AES-256-GCM envelope encryption (`internal/vault/vault.go`). The master key is the root of trust — losing it loses every stored credential, so the dashboard exposes status and rotation through `/api/vault/status` and `/api/vault/rotate` rather than leaving it to a file edit. Credentials are decrypted in memory only when a dispatch needs them; the database never holds a plaintext copy after migration. ## API key hashing Client API keys are stored as Argon2id verifiers with a SHA-256 lookup index (`internal/keikey/apikey.go`). The plaintext key is shown once at creation. An auth cache keeps the 64 MiB-per-verification cost off the request path, so a busy gateway does not spend its CPU re-verifying the same key. Keys issued while `#199` kept the plaintext are still revealed to a dashboard session so their clients can be migrated; rotating one replaces that plaintext with a verifier for good. Newly issued keys cannot be revealed at all — the dashboard disables the reveal control and the only recovery is rotation. ## Guardrails PII and prompt-injection detection runs before a request leaves and on the response stream (`internal/guardrails/`). Layers resolve global → provider → model → chain → API key, most-specific wins, and actions are `log_only` / `warn` / `mask` / `block`. Policy CRUD and the audit log live behind `/api/guardrails/policies` and `/api/guardrails/logs`. A `json_schema` custom pattern carries a JSON Schema document in place of a regex. It is enforced on inbound JSON bodies and buffered responses; a request that violates it is refused with the offending field named in the 400 response. A schema-only policy is active without any other detector, while streaming responses stay unblocked because bytes are already on the wire before the whole answer exists to validate. > **Guardrails and Persona pull in opposite directions.** Persona can instruct a > model to ignore its own rules; guardrails inspect what leaves your gateway for > exactly that. Turning guardrails off does not stop the provider from seeing > the same request — it only stops *you* from seeing it first. If an account > matters, read the warning on the > [Advanced Features](advanced-features.html) page before using Persona to > bypass a model's limits. ## Reversible PII vault `chat.pii_vault` accepts `off` (default) or `on`. This is an in-memory, session-scoped placeholder map, separate from encrypted credential storage. It recognizes a subset of emails, public IP addresses, NIK, card numbers, and IBAN patterns on inbound Chat/Messages paths; it does not cover the Responses path or every kind of sensitive data. Restoration is best effort and requires the exact placeholder to survive the model response. JSON transformations and placeholders split across SSE chunks are not universally restored. Excess matches or collisions can pass through raw after 256 mappings per session. Session eviction is pressure-based; the 30-minute TTL is not a guaranteed deletion timer. Do not treat this feature as an anonymization guarantee or compliance boundary. ## SSRF protection Requests the gateway makes on your behalf — provider validation, proxy tests, web fetch — are checked against SSRF rules before dispatch (`internal/handlerutil/ssrf.go`), so a custom node cannot be pointed at a link-local or metadata address and have the gateway fetch it. ## Netguard and fetch gate `internal/netguard` and `internal/fetchgate` gate outbound fetches, so a provider URL or a model-catalog sync cannot reach an address it should not. ## Security Log and Audit Log Two sidebar pages record what happened, at two levels: - **Security Log** (`/api/security-log`, `internal/securitylog/`) — per-event security records: login successes and failures, default-password rotation attempts, lockouts, and classified anomalies. Each entry carries severity, actor, IP, method, path, and status, so an incident review starts here rather than in the raw request log. - **Audit Log** (`/api/audit`, `internal/db/auditlog.go`) records dashboard actions for operational review. This is not a comprehensive tamper-evident ledger: ordinary writes are not fully wired to the internal hash-chain helpers. There is no public verification endpoint or independent anchor that proves completeness. Protect the database and retain independent logs when stronger audit evidence is required. ## TLS transport boundaries TLS fingerprinting support lives in `internal/tlsstealth`. The global switch is not consumed by every outbound transport, and provider-specific fingerprints are configured independently. A profile's advertised browser version can also differ from the underlying library version. Do not assume one toggle changes all requests. Some transports retry certificate failures with verification disabled unless `STRICT_SSL=true` or `STRICT_SSL=1`. Set strict verification for deployments that must reject such failures, and test the transport actually used. TLS fingerprinting is not a security certification or a substitute for certificate verification. ## Session and CLI tokens Dashboard sessions live in `internal/auth/session.go`; the local CLI token that lets `9routerx` talk to its own daemon lives in `internal/auth/clitoken.go`. The CLI token is what makes destructive operations work from a terminal without a browser session. ## Further reading - Security panel UI: `web/src/components/security/SecurityPanel.svelte` - Security log classification: `internal/securitylog/classify.go` - Audit log: `internal/db/auditlog.go` - Vault internals: `internal/vault/vault.go`, `internal/db/vault.go` - Guardrails: `internal/guardrails/` # Token Saver # Token Saver RTK is the feature that pays for the gateway: it compresses what your agent reads before the model sees it, cutting 20-40% of input tokens. Three further savers change how the model *writes*. All four are configurable per run and from the dashboard. ## RTK — request-side compression RTK rewrites oversized `tool_result` content into a shorter equivalent before it reaches the model. It is on by default (`RTK_ENABLED=true`). ### What it protects These are invariants, not tuning knobs — each one exists because compressing the wrong thing breaks the agent: | Guard | Rule | |---|---| | Error results | A failed command's output is **never** compressed — the agent comes back to read it again | | Protected tools | Tool names matched case-insensitively (`read` = `Read`), the same list `tokensaver.protectedTools` uses | | JSON documents | A JSON body is left intact rather than rewritten | | Filter selection | The filter is chosen by the **command** that produced the output, not by its content | | Truncation caps | `RAW_CAP = 10MB`; smart truncation only engages once output spans ≥ 250 lines | | Line-numbered dumps | A `read`/`grep` numbered dump is truncated the way upstream truncates it | ### Levels | Level | What it does | |---|---| | `off` | Nothing is compressed | | RTK only | Tool-result compression | | Stacked | RTK + one of the style savers below | The dashboard's **Compression Analytics** page (`/api/analytics/compression`) shows tokens saved, savings ratio, average duration, and the mode breakdown per provider, so you can see what RTK actually returned rather than guessing. ## Caveman — terse output style Caveman adds an output directive that makes the model answer in short, blunt sentences. Three levels (`light`, `medium`, `full`) carry progressively stricter doctrine, matching upstream `open-sse/rtk/cavemanPrompts.js`. Enable with `CAVEMAN_ENABLED=true` or `--caveman=true`. ## Ponytail — structured output style Ponytail pushes the model toward a tighter, more uniform response shape. It also has levels and is mutually exclusive with Caveman — you pick one style, not both. ## ADHD — scannable output style The ADHD saver asks for neatly structured, bulleted, easy-to-scan answers. It is the third style option, also exclusive with the other two, and it has its own levels. ## The compression suite Around RTK sits a set of guards and further compressions: | Piece | What it does | |---|---| | Anti-slop injector | Instruction text that stops the model echoing filler phrases and boilerplate back | | Context squeezer | Compresses long content in conversation context (`internal/translator/context_squeezer.go`) — a 0.75 fill ratio, engaged for content past 4000 characters, keeping the most recent turns intact | | Tool-call fallback | Stream robustness for tool calls: empty deltas are dropped and a tool call never falls back to a bare id when its name is missing | | JSON guard | JSON repair and schema validation (`internal/translator/json_guard.go`) — repairs markdown fences, Python literals, single quotes, trailing commas, and truncated payloads, and filters tool arguments against declared schemas | | Responses compact | `POST /responses/compact` compacts a Responses-API conversation, with the result verified against the original before it is served | | Output styles | Caveman and Ponytail directive modes for compressed output | Every piece is fail-open by design: when a guard cannot prove its output is equivalent, the original text passes through untouched. ## Tool-loop watch The `chat` settings section accepts `tool_loop_watch`: `off` (default), `log`, or `break`, with `tool_loop_threshold` defaulting to 3. A session identity is required. The watcher compares the first choice's ordered tool names and raw argument strings across responses. It is not semantic equivalence detection; a no-tool response does not reset the current streak. In supported buffered OpenAI-shaped responses, `break` withholds the repeated response and returns `429`. In SSE, the error is added near the end, after content may already have reached the client. The OpenAI-to-Claude streaming adapter does not call the check, so neither logging nor blocking is universal. Inactive entries are lazily expired after 10 minutes; the 2,048-entry sweep trigger is not a hard memory cap. Test your actual client/protocol before using `break` unattended. The reversible PII setting belongs to the same `chat` section; see [Security](security.md#reversible-pii-vault). Preserve sibling fields when saving a nested settings section ([Settings](settings.md#settings-api-and-history)). ## Testing a saver before enabling it Use the dashboard benches to submit a sample through the real compressor. Their management routes require a session, local CLI token, or permitted dashboard access token, not an engine API key. API clients must supply the route's sample payload rather than copying a placeholder as JSON: ```text POST /api/tokensaver/rtk/test POST /api/tokensaver/caveman/test ``` ## Runtime flags ```bash ./9routerx --rtk=false # disable RTK for this run ./9routerx --caveman=true # enable Caveman ./9routerx --ponytail=true # enable Ponytail ./9routerx --adhd=true # enable the ADHD style ./9routerx --no-injection-guard # disable the injection guard ``` Dashboard settings win unless a flag is passed explicitly, so a flag is the way to override a stored setting for one run. ## Where it lives - `internal/tokensaver/rtk.go` — the compressor - `internal/tokensaver/caveman.go` — the style savers - `internal/tokensaver/prompts_custom.go` — your own prompt presets - `internal/headroom/` — the token-compression proxy lifecycle # MCP Server # MCP Server 9RouterX ships a built-in Model Context Protocol server (`internal/mcpserver`). It speaks JSON-RPC 2.0 over two transports: **stdio** (line-delimited requests, for local IDE processes) and **HTTP POST** at `http://localhost:20128/api/mcp`. ## Enable it The server is off until `ROUTERX_MCP_TOKEN` is set to a non-empty value. An empty token means every call is refused: stdio exits with `mcp: ROUTERX_MCP_TOKEN is not set; server disabled`, and the HTTP route answers 403. | Deployment | How to set the token | | :--- | :--- | | systemd | `Environment=ROUTERX_MCP_TOKEN=` in the service unit, then `systemctl daemon-reload && systemctl restart 9routerx` | | Docker | `-e ROUTERX_MCP_TOKEN=` on `docker run`, or the `environment:` block in compose | | Tray / desktop | set the variable in the launcher environment before starting 9RouterX | Do not put the token in a committed file. Rotate it by generating a new value and restarting the gateway; existing clients must be updated to match. ## Authenticate HTTP requests carry the token as `Authorization: Bearer ` or in the `X-MCP-Token` header. Both must match `ROUTERX_MCP_TOKEN` exactly. The listener is loopback by default: do not expose `/api/mcp` to a public network. Scope the token to the operator who needs agent access and treat it like a dashboard password. ## Tools The server exposes 14 tools. Descriptions below come from `toolDefinitions()` in `internal/mcpserver/mcpserver.go`; a tool returns a result object or a tool-level error, never a JSON-RPC protocol error for business failures. | Tool | Description | | :--- | :--- | | `list_keys` | List API keys with metadata (no raw secrets) | | `get_health` | Gateway health and version | | `list_models` | Model catalog per provider | | `list_combos` | Combo configurations with strategies | | `cache_stats` | Semantic cache statistics | | `usage_summary` | Usage aggregated by provider (prompt/completion/cost) | | `security_log` | Recent security events (last N, filter by severity); optional `limit` (default 50) | | `notifications` | Notification feed with unread count | | `resilience_status` | Circuit breaker states per provider | | `team_usage` | Usage report for one team; requires `team_id` | | `backup_create` | Create an immediate database backup (write) | | `quota_check` | Per-connection quota snapshot | | `list_providers` | Provider connections with status | | `get_settings` | Current gateway settings | Several tools are pointers to richer dashboard endpoints: `list_models` points to `GET /v1/models`, `cache_stats` to `GET /api/cache`, `resilience_status` to `GET /api/resilience/status`, `backup_create` to `POST /api/settings/auto-backup`, and `quota_check` to `GET /api/usage/{connectionId}`. ## Client configuration Generic `mcpServers` block for Claude Code, Cursor or another MCP client (HTTP transport): ```json { "mcpServers": { "9routerx": { "url": "http://localhost:20128/api/mcp", "headers": { "Authorization": "Bearer " } } } } ``` For stdio transport, point the client at the `9routerx` binary with `ROUTERX_MCP_TOKEN` in its environment and let the client manage the process. ## JSON-RPC examples List tools (no server call to localhost needed to read this page): ```bash curl -s http://localhost:20128/api/mcp \ -H 'Content-Type: application/json' \ -H 'Authorization: Bearer ' \ -d '{"jsonrpc":"2.0","id":1,"method":"tools/list"}' ``` Call one tool: ```bash curl -s http://localhost:20128/api/mcp \ -H 'Content-Type: application/json' \ -H 'X-MCP-Token: ' \ -d '{"jsonrpc":"2.0","id":2,"method":"tools/call","params":{"name":"get_health","arguments":{}}}' ``` The server accepts `initialize`, `tools/list` and `tools/call`; any other method returns a JSON-RPC `method not found` error. # Settings # Settings Everything on this page lives in **Settings** in the dashboard. This page walks through each card in the order it appears, says what it is for, and tells you what to type or pick. > **One Save button.** The button at the top right, **Save Changes**, writes > everything on this page. Most cards have no Save of their own. If a value looks > like it did not stick, press Save first. --- ## Settings API and history `GET /api/settings` reads settings; updates merge **top-level keys**, not nested sections. If you submit `chat`, preserve all its sibling fields from the current value. Sending only `chat.pii_vault` inside a replacement section can drop other `chat` settings. See [Security](security.md#reversible-pii-vault) and [Token Saver](token-saver.md#tool-loop-watch) before enabling these options. `GET /api/settings/history?key=&limit=` returns best-effort history for a top-level key (default 20 results, maximum 100). Old/new values are serialized strings. `POST /api/settings/history/{id}/rollback` restores an old stored value; it does not invoke every live settings hook, so a restart or explicit reapplication can be needed. Truncated or masked values can make rollback fail with `400`. History masking is not a guarantee that nested or mixed-case secret fields are removed. Treat history payloads as sensitive and do not publish them. ## Runtime Storage Shows where your data lives and lets you move it in and out. | Field | What it is | |---|---| | Database location | Shown for reference: `~/.9router/db/data.sqlite`. Change it with `DATA_DIR` or `DB_PATH` — see [CLI](cli.html) | Two buttons: - **Download Backup** — saves your dashboard data as a `.json` file. You will be asked for your password first. - **Import Backup** — restores from that file. Accepts `.json` or `.zip`. > A backup is a copy of your dashboard **data**, not a byte-for-byte copy of the > live database file. It restores your settings, connections, and keys — it is > not a substitute for backing up the SQLite file itself. See > [Database](database.html). Automatic backup settings use a separate API and save path, not just the main Save Changes button. See [Operations](operations.md#automatic-and-remote-backups) for schedule, retention, remote destinations, and sensitive-artifact warnings. Dashboard access-token scopes are described in [Security](security.md#dashboard-access-tokens); per-key limits and scheduling hints are described in [Governance](governance.html). --- ## Security & Password Who can open the dashboard, and for how long. | Field | Options | What it does | |---|---|---| | Require login | on / off | When off, anyone who can reach the dashboard is let in. **Turn this on for anything reachable from outside your machine.** | | Require Password on Localhost | on / off | When on, even `localhost` asks for a password | | Session Timeout | `15m`, `1h`, `24h`, `7d`, `never` | How long you stay signed in before being asked again | | Change Master Password | button | Opens three fields: current, new, confirm. New password must be at least 6 characters | The default password on a fresh install is `123456`. Change it before exposing the dashboard to anything but your own machine. ### Single Sign-On (SSO) Replaces the password login with your organisation's identity provider. | Mode | What to fill in | |---|---| | **Password Only** (default) | Nothing — this is the password login above | | **OpenID Connect (OIDC)** | Issuer URL, Client ID, Scopes (default `openid profile email`) | | **SAML 2.0** | EntryPoint (SSO URL), SP Entity ID, X.509 certificate in PEM format | The login button text is set by the mode you pick, so a user sees "Sign in with OIDC" or "Sign in with SAML SSO" rather than a password field. --- ## Default Routing Strategy How the gateway chooses between your connections when you have not set up a combo. See [Architecture](architecture.html) for the details. ### Connection Fallback Strategy | Option | Behaviour | |---|---| | **Failover** | Try the next connection when one errors or is rate-limited | | **Round Robin** | Spread requests across every connection in turn | | **Sticky Round-Robin** | Keep using the same connection until a limit is reached, then rotate | If you pick Sticky Round-Robin, one more field appears: **Sticky Request Limit** — how many requests go to the same connection before rotating (1–100). ### Combo Routing Mode | Option | Behaviour | |---|---| | **First Model** | Always start from the primary model in the combo | | **Round Robin** | Rotate which model the combo starts from | ### Force Fallback When **every** account of a provider is cooling down, send the request through whichever account frees up first instead of failing outright. Upstream can still reject it — this buys a chance, not a guarantee. --- ## Observability & Storage Retention Controls what the gateway records about your traffic, and for how long. Turning recording off entirely is the **Zero-Trace / Headless** option. ### Observability | Field | Options | What it does | |---|---|---| | Enable Observability | on / off | Master switch for request recording | | Observability Mode | `full`, `errors_only`, `off` | `full` records every request; `errors_only` keeps only failures for debugging; `off` records nothing | | Diagnostics Retention | `1d` … `30d`, or `Unlimited` | How long diagnostic rows are kept. `1d` suits a low-memory box | | Max Request Records | number (min 500, step 500) | Hard cap on stored diagnostic rows | | Usage Ledger Retention | `Off`, `30d` … `365d` | How long the usage ledger is kept. **`Off` (keep forever) is the recommended default** — the ledger drives your budgets, so pruning it moves spend into per-key carryover | ### Storage numbers Four figures, read live: | Figure | Meaning | |---|---| | Database File Size | Size of the SQLite file on disk | | Request Details | How many diagnostic rows are stored, and since when | | Usage Ledger | How many usage rows are stored | | Reclaimable | Space a VACUUM would give back | If the numbers show `—`, the stats read failed — the card says so and offers a **Retry** button rather than hiding the actions. ### Three buttons | Button | What it does | |---|---| | **Prune Expired Records** | Deletes diagnostic rows past the retention setting | | **Prune Usage History** | Deletes usage rows past the ledger retention. Shows a preview of how many rows and which date first, and asks you to type `PRUNE` to confirm | | **Compact Database (VACUUM)** | Returns unused pages to disk. Shrinks the file; does not delete data | > Pruning usage history is permanent, but it is not lossy for your budgets: > the tokens are **carried over** into per-key budgets, so a key that already > spent its quota is not given a fresh one by the cleanup. The confirmation > tells you how many tokens will be carried. --- ## Global System Prompt & Anti-Poisoning Instructions added to **every** request, regardless of which model or combo serves it. This is the broadest of the three prompt-injection surfaces — the other two are [Persona](advanced-features.html) (per model) and [Token Saver](token-saver.html) (style only). | Field | Where it goes | |---|---| | **Prefix** | The very start of the system prompt | | **Suffix** | The very end, after everything else the model reads | It applies to OpenAI Chat, Claude Messages, and Responses bodies alike. > **This applies to every request, with no way to pick models.** If you only need > it on *some* models, use [Persona](advanced-features.html) instead — that one > binds a prompt to the models you choose. **Which to use for what:** put identity rules in the prefix — who the assistant is, what it must never claim. Put non-negotiable constraints in the suffix, because the suffix is the last thing the model reads before your content, and later instructions tend to outweigh earlier ones. **Load Anti-Poisoning Preset** fills the prefix with a rule that forbids the model from renaming or aliasing provider names — useful if you have seen a model write `opencode-go` as `opencode` in code or docs. --- ## White-label branding Rename the product for anyone you share the dashboard with. | Field | Notes | |---|---| | Application name | Shown in the sidebar. Leave blank for `9routerx` | | Logo URL | An HTTPS URL, or a local absolute path such as `/logo.png` | | Upload image | PNG, SVG, WebP or JPEG, max 2 MB. The file is stored in the gateway's own data directory and the URL field is filled in for you | Uploading means an operator with no public web host still gets a branded sidebar — the image is served by the gateway itself. --- ## Display How the dashboard looks. These are your preferences, and they apply immediately. | Setting | Options | Effect | |---|---|---| | Unit abbreviation | on / off | Large numbers as `1.2M` / `3.4B` instead of `1,200,000` | | Advanced settings | on / off | Unfolds the currency rate grid, the Sidebar card, and the Usage panel card below. Folding them back changes nothing about what they do | | Provider card toggle | on / off | `on` keeps the on/off switch on every provider card visible; `off` reveals it on hover | | Animation level | Full / Reduced / Minimal / Off | How much the dashboard animates. Minimal drops blur and transitions but keeps loading spinners; Off stops those too | ### Currency Every cost is measured in USD and shown in the currency you choose here. | Setting | Effect | |---|---| | Display currency | Pick from the catalog — USD, IDR, EUR and more | | Show USD next to the converted amount | Displays both, e.g. `Rp 16.500 (USD 1.00)` | | Rates | One row per currency: how much one USD buys. Edit freely | | Update currency | Refreshes every rate from a public provider | The line under the grid shows the current rate for your selected currency, so you can see what you are about to save before saving it. --- ## Sidebar Folded behind **Advanced settings**. Decides which entries appear in the sidebar and in what order. ### Presets | Preset | What it hides | |---|---| | **Default** | Plans and Persona | | **Advanced** | Nothing | | **Simple** | Media providers, CLI Tools, Skills, Console Log, Plans | | **Super-lite** | Everything except Endpoint & Key, Providers, Combos, Usage, Settings, Security | A preset fills the visibility switches and **leaves the arrangement alone** — because "what is on the sidebar" and "in which order" are two different questions. ### Arranging entries Each row has a drag handle and two arrows. Drag a row onto another to place it above or below; the arrows do the same thing from the keyboard. A row dropped into a different container is refused rather than misplaced: a media sub-entry has no place among the main entries, so the arrangement comes back unchanged. **Reset order** puts every entry back to the order this build declares. > Settings can never be hidden — the panel you are reading lives behind it. --- ## Usage dashboard Folded behind **Advanced settings**, next to the Sidebar card. Controls which panels appear on the Usage page and in what order, per section — Overview, Details, Cache Analytics, and Compression Analytics each have their own list. Same controls as the Sidebar: presets, per-panel switches, drag or arrows to reorder. One Save covers both cards. --- ## Failover Health Cache Reset Also on the Settings page, below the main grid. When a provider's credential hit a `429` and was placed in cooldown, this clears the lockout without waiting for the timer. 1. Pick the provider from the dropdown. 2. Click **Reset Cooldown**. Use this when a provider has recovered but the gateway is still holding the account out. It does not touch the provider's own state — only what this gateway remembers. --- ## Model Health The last card. Shows what the automatic model-health loop found, and lets you re-enable a model it disabled. See [Usage & Analytics](usage-analytics.html) for how the loop decides. # Usage & Analytics # Usage & Analytics Every request is written to a usage ledger, and the dashboard reads that ledger several ways. This page covers what is recorded and how to read it. ## What is recorded per request | Field | Meaning | |---|---| | Provider | Which provider served it — a registry id, or a custom node's id | | Model | The model that answered | | Prompt / completion tokens | Both directions | | Cost | From the pricing table, in your display currency | | Compression mode | `rtk`, `caveman`, `adhd`, `ponytail`, `stacked`, or none | | Tokens saved | What RTK actually returned, not an estimate | | Latency | Time to first token and total | | Outcome | Success, or the failure reason and HTTP status | | Fallback chain | Which candidates were tried before one succeeded | ## Live stream `GET /api/usage/stream` is a Server-Sent Events feed the dashboard's topology animation and recent-request list read. `GET /api/usage/stats` and `GET /api/usage/chart` serve the aggregates. ## Dashboard views The Usage page switches between several views of the same data (`web/src/components/analytics/UsageDashboard.svelte`): | View | Component | Shows | |---|---|---| | Summary KPIs | `SummaryKpiCards.svelte` | Totals for the selected period | | Chart | `UsageChart.svelte` | Volume over time | | Breakdown | `UsageBreakdownTable.svelte` | Grouped by provider, model, or key | | Provider topology | `ProviderTopologyCard.svelte` | Which providers talk to which | | Activity heatmap | `ActivityHeatmap.svelte` | When traffic happens | | Combo flow | `ComboFlowCard.svelte` | How a combo's chain resolved | | Node health | `NodeHealthTable.svelte` | Per-node errors and cooldowns | | Request details | `RequestDetailsTab.svelte` | One request's full payload | ## Custom ranges The period selector is not limited to fixed presets — `14d`, `12h`, `7d` all work, because the range parser accepts a number plus a unit (`internal/analyticsrange/range.go`). ## Where the numbers come from The window you pick decides which table the aggregates read (`internal/handlers/usage_stats.go`): - **Sub-day windows** — `today` (after local midnight), `24h`, `12h`, `3h` — scan the raw `usageHistory` ledger directly, so the numbers move the moment a request finishes. - **Day and longer windows** — `7d`, `30d`, `60d`, `all` — sum the `usageDaily` rollup rows, one JSON aggregate per calendar day. The chart's day buckets read the same rollup. The split exists so an operator narrowing to `12h` gets a to-the-minute answer without a day-granularity rollup having to invent one. One consequence worth knowing: a ledger row and its rollup are written together by the same request path, so a database that was copied, restored or backfilled **after the fact** can carry `usageHistory` rows without matching `usageDaily` rollups. The Recent Requests list (reads the raw ledger) then shows those requests while a day-window KPI reads 0, and sub-day windows only count rows whose timestamps fall inside them. Rollups are written when a request runs — backfilled rows never gain one retroactively. ## Compression analytics `GET /api/analytics/compression` reports what the token savers actually did: - Total requests and total tokens saved - Average savings ratio - Average duration - Mode breakdown, including `stacked` (RTK combined with a style saver) The mode is resolved on the live pipeline, so a request that ran RTK *and* Caveman is labelled `stacked` rather than being attributed to one of them. ## Cost display Costs are computed from the pricing table (`internal/pricing/`) and shown in your chosen currency — USD, IDR, EUR and ten more. The exchange-rate table is editable and can be refreshed from a public provider with `POST /api/settings/currency/refresh`. ## Quota tracking The Quota Tracker page reads per-provider quota and the reset schedules: - **Codex reset credits** — `GET /api/usage/{connectionId}/reset-credits`, and `POST …/reset-credits/consume` to spend one. - **GLM reset cards** (Z.ai international) — `GET|POST /api/usage/{connectionId}/glm-reset-cards`. - **Auto-ping schedule** — set a background interval that keeps quota current without traffic. ## Cache analytics `GET /api/cache` and `GET /api/cache/entries` read the semantic response cache: hit rate, entry count, and the entries themselves. `DELETE /api/cache` clears it. The dashboard reports the cache the engine actually serves from. That matters: a second cache instance would report zero entries while the engine served hits, and clearing from the dashboard would leave the engine still serving them. ### Cache-hit rates The `hitRates` block in `GET /api/cache?period=` combines metrics with different meanings. Prompt-cache rate counts usage rows containing either cached-read **or cache creation** tokens in the selected window; creation is not a cache-read hit. Semantic-cache hits/misses are counters for the current process lifetime, not that same ledger window. Compare them separately rather than treating the two percentages as one measurement. ### Savings and burn-rate estimates `GET /api/savings/summary?period=` defaults to `7d`. Prompt-cache and compression savings are estimates derived from token/pricing data. Unpriced compression tokens contribute zero USD, but prompt-cache estimates fall back to $3/million and a 90% discount when no positive price is available, even for unknown or zero-priced models. The summary includes this assumption. RTK is counted in compression, while the separate `token_saver` source currently contributes zero; do not add sources as if each were independently measured savings. `GET /api/burn-rate` projects from 24-hour gateway-wide usage. The current per-key projections reuse the total gateway rate rather than each key's actual rate. They are rough planning estimates, not a per-key forecast or a substitute for [budget enforcement](governance.md#budgets). ## Retention Usage history is pruned on a schedule. Pruning keeps a carryover per dimension, so spend already counted is not billed twice after the rows are gone — the invariant is covered by tests. ## Tracing `GET /debug/traces` gives p50/p95 latency per provider+model, which is the fastest way to find the provider that is actually slow. # CLI # CLI Every command comes from the single binary. ## Running the gateway ```bash 9routerx # foreground (port 20128, data ~/.9router) 9routerx --background # detach and return; same as `9routerx start` 9routerx -d # short alias 9routerx version # version details, plus an update check 9routerx update # check and self-update curl http://localhost:20128/health ``` ## Background daemon ```bash 9routerx start # run in the background and return 9routerx status # is it running? pid, dashboard, log 9routerx restart # replace the running daemon 9routerx logs -n 100 # tail the run log (default 40 lines) 9routerx stop # stop it ``` The detached process records itself in `DATA_DIR/run/gateway.pid` and writes its output to `DATA_DIR/run/gateway.log`. A second `start` while one is running refuses rather than fighting over the port. A daemon killed from Task Manager leaves nothing behind: the stale pid file is cleaned on the next command. `status`, `stop`, and `logs` resolve the port from the same config the server binds — including a `.env` file — so they never probe the wrong address. > Windows stops the process with `TerminateProcess` instead of `SIGTERM`, so > `stop` skips the graceful drain. Use the dashboard's Shutdown button or > `9routerx restart` when you want in-flight streams to finish first. ## Service (start on boot) ```bash 9routerx service install # pick the host's native backend 9routerx service status # which entry is in effect, and whether it is active 9routerx service start # start the supervised service now 9routerx service restart 9routerx service stop # stop now, stay enabled for boot 9routerx service uninstall # remove the entry ``` Force a backend: `--backend systemd|launchd|openrc|runit|cron`. | Backend | Scope | Needs root | |---|---|---| | systemd | user unit | no | | launchd | user agent | no | | OpenRC | system service | **yes** — use `sudo` or `--backend cron` | | runit | `~/service` | no | | cron `@reboot` | user crontab | no | | Windows | scheduled task via `schtasks` | **yes** — Administrator console | The Windows task runs as the current user at logon, so it reads that user's data dir rather than `SYSTEM`'s. ## Interactive menu Running `9routerx` with no arguments in a terminal opens a menu: ```text 1) Start the gateway 2) Start in the background 3) Show status 4) Stop 5) Show status 6) Run in the background with a tray icon (frees the terminal) 0) Exit ``` **Option 6 — tray.** The tray icon lives in a companion binary (`cmd/9routerx-tray`), not the main one: a GUI toolkit cannot be linked into the gateway without breaking the `CGO_ENABLED=0` cross-build for every target. Only the *sibling* binary is tried, so a PATH lookup cannot pick up another install's tray talking to a different gateway. Right-click the icon to open the dashboard or quit. ```bash # the tray ships as its own package 9routerx-tray --port 20128 ``` ## MITM proxy Intercepts CLI tool traffic so it can be routed through the gateway: ```bash 9routerx mitm enable # DNS redirect + TLS intercept on :443 9routerx mitm status 9routerx mitm disable # stop the proxy and remove DNS entries ``` ## Flags There are no `--port` flags; use environment variables. ### Server | Variable | Default | Effect | |---|---|---| | `PORT` | `20128` | HTTP port | | `DATA_DIR` | `~/.9router` (`%APPDATA%/9router` on Windows) | Data root | | `DB_PATH` | `$DATA_DIR/db/data.sqlite` | SQLite file | | `HOST` / `BIND_ADDR` | `127.0.0.1` | Loopback listener; set `HOST=0.0.0.0` explicitly for all IPv4 interfaces | | `INITIAL_PASSWORD` | unset (`123456` on localhost) | First dashboard password | | `API_KEY_SECRET` | built-in default | API key hashing secret | | `MACHINE_ID_SALT` | built-in default | Machine identity salt | | `9ROUTERX_BACKGROUND` | unset | Same as `--background` | | `JWT_SECRET` | generated at `$DATA_DIR/jwt-secret` | Session signing secret — set it in production so a restart does not invalidate sessions | | `AUTH_COOKIE_SECURE` | unset | Set the `Secure` flag on session cookies (behind TLS) | | `FX_LOGGING` | unset | Log Fx dependency-injection events | | `9ROUTERX_PEER_TOKEN` | unset | Peer token for internal routing | ### Token savers | Variable | Default | Flag | |---|---|---| | `RTK_ENABLED` | `true` | `--rtk=false` | | `CAVEMAN_ENABLED` | `false` | `--caveman=true` | | `PONYTAIL_ENABLED` | `false` | `--ponytail=true` | | `ADHD_ENABLED` | `false` | `--adhd=true` | | `INJECTION_GUARD_DISABLED` | `false` | `--no-injection-guard` | | `AUTO_UPDATE` | `false` | `--auto-update=true` | A flag overrides the stored dashboard setting for that run only. ### Networking and trust | Variable | Default | Effect | |---|---|---| | `HTTP_PROXY` / `HTTPS_PROXY` | Go defaults | Upstream egress proxy | | `TRUST_PROXY` | unset | Trust loopback + RFC1918/link-local forwarded IPs | | `TRUST_CLOUDFLARE` | unset | Trust Cloudflare forwarded IPs | | `TRUSTED_PROXIES` | unset | CIDR/IP list that **replaces** the defaults | | `PPROF_ENABLED` | `false` | Expose `/debug/pprof/*` | | `GEMINI_WEB_ROTATION` | `on` | Renew the Gemini Web session cookie in the background | | `FORCE_FALLBACK_ON_ALL_UNAVAILABLE` | unset | When every account of a provider is in cooldown, serve through whichever frees up first | | `STRICT_SSL` | unset | Set true/1 to forbid the insecure-TLS retry | ### OAuth overrides Built-in public client credentials exist for antigravity, gemini-cli, xai, codex, iflow and others, so most operators never set these. Override per provider: ```bash ANTIGRAVITY_OAUTH_CLIENT_ID=... ANTIGRAVITY_OAUTH_CLIENT_SECRET=... CODEX_OAUTH_CLIENT_ID=... ``` See `.env.example` for the full list. ## Verifying a release Download from [GitHub Releases](https://github.com/yanstd888/9routerx/releases/latest) and verify against `SHA256SUMS.txt`. # Architecture # Architecture ```text ┌─────────────┐ │ CLI tool │ (Claude Code, Codex, OpenClaw, Cursor, Cline...) └──────┬──────┘ │ http://localhost:20128/v1 ↓ ┌─────────────────────────────────────────────┐ │ 9RouterX (Smart Router) │ │ • RTK Token Saver (cut tool_result tokens) │ │ • Format translation (OpenAI ↔ Claude) │ │ • Quota tracking │ │ • Auto token refresh │ └──────┬──────────────────────────────────────┘ │ ├─→ [Tier 1: SUBSCRIPTION] Claude Code, Codex, GitHub Copilot │ ↓ quota exhausted ├─→ [Tier 2: CHEAP] GLM ($0.6/1M), MiniMax ($0.2/1M) │ ↓ budget limit └─→ [Tier 3: FREE] Kiro, OpenCode Free, Vertex ($300 credits) ``` ## RTK Token Saver RTK compresses `tool_result` content before it reaches the model, saving 20-40% of tokens. The guards it keeps: - A failed command's output is **never** compressed — the agent comes back to read it again. - Tool names are matched case-insensitively (`read` = `Read`), the same rule `tokensaver.protectedTools` uses. - A JSON document is left intact. - The filter is chosen by the **command** that produced the output, not by its content. - Truncation follows upstream's caps (`RAW_CAP = 10MB`, smart truncation only engages once output spans at least 250 lines). ## Combo strategies The current strategy IDs, combo budgets, family warnings, and limited arena path are documented in [Combos](combos.md#strategies). Strategy selection and enforcement vary by request path; do not infer universal support from a single strategy name. ## Design decisions that matter - **Concurrency slots are per attempt.** In a combo/fallback, one request can try several providers. A slot must be released when that attempt ends (success, failure, or failover), not once at the end of the request — otherwise slots leak permanently and the node locks itself out. - **A congestion violation writes no cooldown.** One burst over a limit must not globally park a healthy node. Only a debug trace is written. - **One source of truth for policy.** Rate limits, budgets, and the model gate all read the same resolver — no limit logic scattered around. ## Further reading Full internals: [`ARCHITECTURE.md`](https://github.com/yanstd888/9routerx/blob/main/ARCHITECTURE.md). # Database # Database 9RouterX can open an upstream 9Router SQLite database without a manual migration script. Bootstrap adds missing tables and columns. Dashboard import/export and automatic backups are separate features; they do not mean that every export is a complete database snapshot. ## Location | | Path | |---|---| | macOS / Linux | `~/.9router/db/data.sqlite` | | Windows | `%APPDATA%\9router\db\data.sqlite` | | Docker | `/data/db/data.sqlite` inside the container | ## Sharing with 9Router Stop 9Router, run 9RouterX, and log in with your existing password. Your provider connections, proxy pools, combos, API keys, model aliases, and usage history are all there — 9RouterX's dashboard renders them because it *is* the same data. Use one active gateway writer per database. Stop the legacy gateway before switching; changing only the port does not isolate SQLite or settings writes. For side-by-side evaluation, use a separate `DATA_DIR` and a stopped, copied snapshot, never the live database. 9RouterX adds more than the original connection-rotation columns, including governance, dashboard-token, settings-history, and combo-budget storage. Do not assume a reverse switch to an arbitrary upstream version preserves every 9RouterX-specific field. Keep a pre-switch snapshot and consult the current [`DATABASE.md`](https://github.com/yanstd888/9routerx/blob/main/DATABASE.md) operator contract. ## What it does not do - **No legacy JSON import.** If your 9Router data still lives in old JSON files, start upstream once to convert them, then switch. - **No destructive migrations or pre-migration backups.** Its bootstrap only ever *adds* — create missing tables, add missing columns, seed missing rows. - **No interpretation of `_meta.schemaVersion`.** That is upstream's migration bookkeeping. A database written by a much newer 9Router release should be checked before you rely on it. ## Backup Stop the daemon before making a filesystem copy of the database directory, including its WAL sidecars: ```bash cp -r ~/.9router/db ~/9router-db-backup ``` `GET /api/settings/database` exports dashboard JSON; `POST` imports it. This format is a data transfer, not a full snapshot of every table/column. In particular, the current JSON export omits combo-budget columns and auto-backup settings. Preserve a SQLite snapshot when those fields or full recovery matter. The automatic backup path creates a primary SQLite snapshot and a best-effort JSON companion. Remote Telegram/GitHub delivery prefers sensitive JSON and falls back to the full SQLite snapshot when JSON is empty or fails. Neither artifact is encrypted as a SyncBundle; the configured `.json` destination can still contain SQLite bytes, so inspect the format before restoring. Browser-profile directories are outside these built-in database backups. See [Operations](operations.md#automatic-and-remote-backups) for settings, retention, and restore limitations. ## Binary portability One binary per target, built from pure Go source with `CGO_ENABLED=0`. Every release target must still build — that is the only thing constraining a dependency here, not its size. # Parity # Parity Both projects share the same database and schema. What differs is the runtime. ## Comparison | | 9RouterX | 9Router (upstream) | |---|---|---| | Runtime | Single Go binary | Node.js + Next.js | | Dashboard | Embedded Svelte 5 | React 19 | | Database | SQLite (modernc, pure Go) | SQLite | | Schema | Same, additive | Same | | Docker | Single binary | Node | | Port | `20128` | `20128` | ## Guaranteed identical - Request/response schemas for `/v1/*` — Chat Completions, Messages, Embeddings, Audio, Models. - Dashboard endpoints `/api/*` — Connections, Combos, ProxyPools, Settings, ProviderNodes, Usage, Auth. - Combo expansion, model fallback, account rotation, and strike-breaker quota handling. - SQLite database compatibility (`~/.9router/db/data.sqlite`). Both projects share the same database and schema, so a connection you add in either dashboard shows up in the other. The supported setup is one active writer. ## What version am I running? ```bash 9routerx version ``` The dashboard's changelog modal shows both `CHANGELOG.md` and any fragment merged since the last tag, so what you read there is current even between releases. ## Different by design - Internal implementation leverages Go's performance, strong typing, small memory footprint, and idiomatic concurrency — it is not a transliteration of JavaScript. - SSE streams flow directly through `io.Reader`/`io.Writer`, never buffered whole. - SQLite access: one read per page, never N+1. ## Go-only features Some features exist only in 9RouterX and do not collide with upstream: - Per-custom-provider limits (RPM/TPM/concurrency/quota/expiry) - Per-API-key rate limiting with a FIFO queue - USD + token budgets with a request-start hard cutoff - AES-GCM credential vault - Argon2id API key hashing - PII and injection guardrails - Semantic response cache - Prometheus metrics ## Further reading - Remaining parity work: [`docs/PARITY-REMAINING.md`](https://github.com/yanstd888/9routerx/blob/main/docs/PARITY-REMAINING.md) - Upstream: [decolua/9router](https://github.com/decolua/9router) For the KeiRouter port specifically — what was taken, what was skipped, and what was never attempted — see [Advanced Features](advanced-features.html). # Advanced Features # Advanced Features Three features in 9RouterX came from other projects. Where that happened, the source is listed as a link at the end of each feature — you do not need to know where something came from to use it. Each feature below tells you **what it does** and **how to use it, step by step**. --- ## Persona — attach a system prompt to specific models **Since:** v1.9.15 · **Source:** [arewedaks/9router-go](https://github.com/arewedaks/9router-go) ### What it does You write one instruction document once, choose which models it applies to, and every request sent to those models automatically carries your instructions at the front. Your original message is untouched. ### How to use it 1. Open the dashboard and click **Persona** in the sidebar. 2. Write your instructions in the main editor. This is your default document. 3. To save several sets of instructions, use **Presets** — give each one a name. 4. To attach a preset to specific models, open the preset and pick the models. A model can only carry one preset at a time. 5. To import instructions you already have, use **Import** — paste a URL, drop a file, or upload a `.md` file. 6. Turn the feature on. **It is off by default**, and nothing is injected until you enable it. ### Covering a whole family of models at once Instead of picking models one by one, add a **keyword rule** to a preset. The keyword `deepseek` covers `providera/deepseek`, `deepseek-v4`, and every model whose name contains it — across all providers and every leg of a combo. Three matching modes: | Mode | Matches | Example | |---|---|---| | `word` (default) | A whole word | `deepseek` matches `deepseek-v4` but **not** `deepseekia` | | `partial` | Any part of the name | `seek` matches `deepseek`, `seeking` | | `regex` | A regular expression | `^deepseek-v[0-9]` | ### Blocking a model from ever receiving a prompt Two deny lists, both using the same grammar as the keyword rules: - **Per-preset excludes** — models this preset must never touch. - **Global excludes** (Settings) — outranks every preset and every exact binding. ### Which prompt wins If several rules could apply, the order is: 1. Global exclude 2. An exact binding on the model id the client sent 3. The winning preset's own excludes 4. A keyword matching the requested model, before a keyword matching a forwarded leg 5. The longest keyword (a tie goes to the preset with the lowest id) An exact binding to an **empty** prompt stays in force — it does not fall through to a keyword match. ### Notes - Injection reaches every path: single chat, Claude messages, combo fallback, and the fusion panel. For a combo, the switch is keyed to the combo name the client sends, so all legs of that combo are covered. - A Gemini binding can also send `safetySettings: BLOCK_NONE` through the official API field. If a request already carries safety settings, they are left alone. - **This is not the same as the Global System Prompt** in [Settings](settings.html). That one applies to every request with no way to pick models. Persona is the one you use when you need it on *some* models only. ### Before you use it to bypass a model's limits Persona can be used to push a model past its own restrictions — a jailbreak. Some people do this to get more out of a model than it is meant to give. Read this first. **You can get more out of a model.** A prompt that reframes the task often gets a fuller answer than the model gives by default. That is the appeal, and it is real. **You can also lose the account.** The provider on the other end sees the same traffic you do. A request that looks like an attempt to override its safety rules is grounds for it to flag, throttle, or close your account — and the decision is theirs, not yours, with no appeal and no warning you can act on. The same applies to an API key, a subscription, and any other credential you used to reach that model. What that means in practice: - **You carry the risk, not the model.** A banned account is not a bug you can report. The credential stops working and you start again somewhere else. - **One account can take others with it.** If the credential is shared — a combo, a team key, a resold plan — the ban lands on everyone using it. - **`BLOCK_NONE` is the loudest signal.** Turning off a provider's safety settings outright is the clearest possible marker that the request is not ordinary use. Use the prompt-based approach if you use anything at all. - **Nothing here is a promise.** This gateway can send a prompt. It cannot make a provider accept one, and it cannot restore an account it decides to close. If you want more from a model and the account matters, the safer path is to ask the model for more within its rules — a fuller explanation, a different angle, a longer answer — rather than instructing it to ignore them. --- ## Security — vault, guardrails, and who may spend what **Since:** v1.9.11 · **Source:** [mydisha/keirouter](https://github.com/mydisha/keirouter) ### What it does Three controls that keep your credentials, your prompts, and your budget safe. All three live on the **Security** page in the sidebar. ### Credential vault Your provider credentials are stored sealed with AES-256-GCM encryption, and only unsealed in memory when a request needs them. The database never holds a plaintext copy. **How to check it:** open **Security** and read the vault status card. It tells you whether the vault is active and how many credentials it holds. **Rotating the master key:** use **Rotate Master Key** on the same card, and type the new key when asked. There is no confirmation dialog — the rotation happens when you press it. > Losing the master key loses every stored credential. Write it down somewhere > safe before you rotate, and keep the old one until you have confirmed the new > one works. ### Guardrails Scans requests leaving and responses coming back for personal data and for attempts to override your instructions. **How to create a policy:** 1. Open **Security** and click **New Policy**. 2. Pick a **scope** — how wide the rule applies: | Scope | Applies to | |---|---| | Global | Every request | | Provider | One provider, e.g. `openai` | | Model | One model id, e.g. `gpt-4o-mini` | | Chain | One combo | | API key | One client key | 3. Pick the **detectors** — what to look for: | Detector | Finds | |---|---| | PII | Email addresses, IP addresses, national ID numbers, card and IBAN numbers | | Prompt injection | Attempts to override instructions or exfiltrate data | | Custom pattern | Your own regular expressions | 4. Pick the **action** — what happens on a match: | Action | Result | |---|---| | Allow | Detect, but never act | | Log only | Record the decision (default) | | Warn | Record and warn | | Mask | Redact the match before the request is sent | | Block | Reject the request with `400` | 5. Save. The policy is live immediately. **The kill switch.** The **Enforce guardrails** toggle at the top of the page stops both the request and response scans without deleting your policies — so a false positive that blocks real traffic can be switched off in one click, and your configuration and audit trail survive. It defaults to **on**: a policy you wrote is a decision you made, and it must not be silently ignored just because a setting was never written. **Reading the audit log.** Below the policy list, the log shows every decision with its direction (request or response), severity, and what matched. It is polled rather than streamed, so give it a moment after a request. ### Per-key limits and budgets Rate limits, spending caps, and which models each key may use. These are configured per key on the **API Keys** page, or in bulk through a plan. **Full guide:** [Governance](governance.html) --- ## Plans — one template, many keys **Since:** v1.9.11 · **Source:** [mydisha/keirouter](https://github.com/mydisha/keirouter) ### What it does A plan is a saved set of limits you can attach to any number of API keys. Set the limits once, apply the plan to ten keys, and all ten follow the same rules. Change the plan later and every key on it follows. Use it when you have keys for different purposes — one for yourself, one for a teammate, one for a public demo — and want each to have its own ceiling without configuring them one at a time. ### How to create a plan 1. Click **Plans** in the sidebar. If you do not see it, turn it on in [Settings](settings.html) → Sidebar. 2. Click **New Plan**. 3. Fill in the limits you want. **`0` means unlimited** for every number field — that is the same convention the API keys use. | Field | What it limits | |---|---| | Name | What you call this plan | | Description | Optional note to yourself | | RPM | Requests per minute | | TPM | Tokens per minute | | Concurrency | Requests in flight at once | | Budget (USD) | Spending cap for the period | | Tokens | Token cap for the period | | Period | When the budget resets — see below | | Alert % | Percentage that raises a warning before the cap is hit | | Hard cutoff | On = reject with `402` once the cap is reached (checked when a request starts, so a request already in flight can overshoot slightly). Off = warn only | | Allowed models | Which models keys on this plan may use. Leave empty for all | 4. Save. ### The four periods | Period | Resets | |---|---| | Daily | Every day at 00:00 UTC | | Weekly | Every Monday at 00:00 UTC | | Monthly | On the 1st at 00:00 UTC | | Total | Never — a lifetime budget | All reset times are UTC, regardless of your timezone. ### Attaching a plan to a key 1. Open **API Keys** in the sidebar. 2. Click the key you want, or create a new one. 3. Choose the plan from the **Plan** dropdown. 4. Save. The key list shows how many keys use each plan, so you can see the blast radius before changing one. ### How a key's limits are decided Three layers, applied in order: 1. Start from zero — no limits. 2. Apply the key's plan, if it has one. 3. Apply the key's own settings, where they are set to something other than zero. So a key with no plan and no overrides behaves exactly as it did before plans existed. A key's own settings **override** its plan — set a value on the key and that value wins. **Model access is the exception.** A key's allowed-models list and its plan's list are **combined**, not overridden — a key may add models, never remove them. That is deliberate: a plan sets the floor, and a key can only widen it. ### Deleting a plan A plan still attached to a key cannot be deleted — the gateway refuses with `409` rather than leaving those keys with no limits at all, which would silently remove their ceiling. Detach the keys first, then delete the plan. ### One correction The port plan for this feature says it is incomplete — missing periods, alert thresholds, and the spending cutoff. That is out of date. All three exist, and a key past its budget with hard cutoff on is rejected with `402 budget_exhausted`. The ceiling is checked when a request starts rather than continuously, so requests already in flight when it is crossed still complete and the key can overshoot by their cost. **Full guide:** [Governance](governance.html) # Comparison # Comparison How 9RouterX relates to **9Router** (decolua — the JavaScript project it was ported from) and **OmniRoute** (cheaper-inference). Facts only; where no public benchmark exists the wording is *on paper*. Star counts checked live on Nov 14, 2026 (9Router 32,422 · OmniRoute 87,366 · 9RouterX 68) and move constantly — judge by the feature rows. ## At a glance | Metric | 9RouterX | 9Router (decolua) | OmniRoute (cheaper-inference) | |---|---|---|---| | Runtime | Single native Go binary + embedded Svelte 5 dashboard | JavaScript / Node.js + Next.js | TypeScript / Node.js | | Install | One binary (~48 MB linux-amd64), zero runtime deps | `npm i -g 9router` (6 deps, needs Node) | npm (~105 deps) / Docker / pnpm | | Providers | 394 built-in entries (317 API category · 35 OAuth category · 31 free · 11 cookie; categories are not authentication-flow counts) | 40+ | 375–380 (150+ free) | | Free models | 245 across 37 providers (24 keyless) | 100+ | 1,400+ models, ~1.62B free tokens/mo | | Dashboard | Svelte 5 + Vite + Tailwind 4, embedded (1 dashboard dep) | Next.js React app | Desktop / PWA | | Database | Embedded SQLite, drop-in schema-compatible | Same SQLite schema | SQLite | | Usage under heavy traffic | *On paper:* compiled native process, no V8/GC overhead as queues grow — no public benchmark; measure on your workload | *On paper:* Node.js event loop; depends on Node version and warm-up | *On paper:* Node.js, same caveats | See [Providers](providers.html) for actual authentication support, [Combos](combos.html) for strategy/budget boundaries, and [Security](security.html) for masking and transport limits. Catalog size does not guarantee live upstream availability. ## What 9RouterX adds over 9Router 9RouterX is a Go port of 9Router with its own layer on top: full per-key governance (daily USD cutoffs, request limits, IP whitelists, PII masking) where upstream has basic key auth; a semantic cache + prompt cache layer where upstream passes through; the Token Saver suite (20–40% RTK compression, 50+ per-tool filters, GCF headroom, tool-call repair); a catalog of 245 free models across 37 providers (24 keyless); and MCP, A2A, TLS stealth, MITM inspector, webhooks, Telegram bot and Vault modules. Both share the same SQLite schema — a 9Router database drops straight in (see [Parity](parity)). ## Where OmniRoute is bigger OmniRoute's catalog is larger, stated plainly: ~375–380 providers (150+ free), 1,400+ models, a pooled ~1.62B free tokens/month allowance, 20 routing strategies and quota-aware fallback. That breadth is their strength. 9RouterX's difference is shape: one Go binary with zero runtime dependencies, light enough for small self-hosted machines, deeper per-key financial governance, and the Svelte 5 dashboard embedded in the same binary. Pick by what you host. ## Go + Svelte vs a Node stack *On paper — no public benchmark; measure on your workload.* A Go binary distributes as one file per platform (linux x64/arm64, macOS x64/arm64, Windows x64) instead of `npm install` with a runtime and `node_modules`; it serves the first request right after boot instead of warming up a runtime; and `9routerx update` swaps a single file instead of a package-manager update plus restart. Baseline memory of a comparable-scope Go process typically sits lower than a Node one — actual numbers depend on traffic shape and cache sizes. # Operations # Operations Everything an operator does after the first install: containers, tunnels, updates, maintenance, and the background loops that keep a deployment healthy. ## Docker ```bash docker run -d --name 9routerx --restart unless-stopped \ -p 20128:20128 -v "$HOME/.9router:/data" \ -e PORT=20128 -e DATA_DIR=/data -e HOST=0.0.0.0 \ -e INITIAL_PASSWORD=your-secure-password \ ghcr.io/yanstd888/9routerx:latest ``` `docker-compose.yml` in the repository root is the same shape if you prefer compose. Experimental releases are marked **Pre-release** and are not selected by the stable updater. GHCR publishes experimental containers as `ghcr.io/yanstd888/9routerx:exp`, separate from `latest`. The example above sets `HOST=0.0.0.0` because the default loopback listener cannot serve a published container port. Keep strong dashboard authentication enabled. ## Tunnels The dashboard can expose the gateway through a tunnel, which is how you reach it without opening a port: ```text GET /api/tunnel/status POST /api/tunnel/enable POST /api/tunnel/disable GET /api/tunnel/tailscale-check POST /api/tunnel/tailscale-enable POST /api/tunnel/tailscale-disable ``` Tailscale in a container needs the `NET_ADMIN` capability and a TUN device — see `docker-compose.yml` for the flags. ## Self-update ```bash 9routerx update # check and install 9routerx version # current version plus an update check ``` Or from the dashboard: `POST /api/version/update` and `POST /api/version/auto-update` (admin). `AUTO_UPDATE=true` turns the background checker on. `releases/latest` always points at the stable version, so an auto-update never installs an experimental build over a stable one. ### Update banner and channels When a newer release exists, the dashboard shows an update banner (`web/src/components/UpdateBanner.svelte`). What the banner offers depends on how this build was installed — `updater.DetectDistChannel()` classifies it: | Channel | Detected when | Banner offers | |---|---|---| | `binary` | a packaged release binary | "Update now" link to the release (only when hosted on the trusted release host), plus the per-OS asset name and sha256 when present. `9routerx update` remains the install path | | `npm` | installed through the npm package (`9ROUTERX_NPM_INSTALL=1`) | the `npm i -g 9routerx@latest` command with a copy button | | `dev` | built from source with no version metadata | info line and release link only | "Skip this version" (binary and npm installs) stores the version in the browser and stops the banner for it. A check that fails — 404, timeout, malformed manifest, rate limit — degrades silently: the status endpoint answers with the last cached result and `stale: true`, and the cause is classified into the structured log and the check record. The full contract, including the pinned manifest host, lives in [`docs/updater-contract.md`](https://github.com/yanstd888/9routerx/blob/main/docs/updater-contract.md). ## Database maintenance All behind a dashboard session or CLI token: ```text GET /api/settings/database Export POST /api/settings/database Import GET /api/settings/database/stats POST /api/settings/database/prune Prune old rows POST /api/settings/database/prune-usage Prune usage history POST /api/settings/database/vacuum VACUUM POST /api/settings/proxy-test Test the outbound proxy POST /api/settings/logo White-label logo upload POST /api/settings/currency/refresh Refresh exchange rates ``` Usage-history pruning keeps a **carryover** per dimension, so spend that has already been counted is not billed twice after the rows it came from are pruned. The invariant is tested: node spend is identical before and after a prune, and a quota reset is not re-banked. ## Automatic and remote backups `GET /api/settings/auto-backup` reads sanitized settings; `PATCH` changes them. Defaults are `enabled: false`, `intervalHours: 24`, `retention: 7`, and an empty `destination` (the built-in backup directory). The scheduler checks immediately at startup and then hourly; the interval is not an exact wall-clock cron. Local backups use a SQLite snapshot as the primary artifact and a best-effort JSON export. JSON is partial: it omits some storage, including combo-budget columns and the auto-backup settings scope. It is not equivalent to restoring the full SQLite snapshot ([Database](database.md#backup)). An optional `remote.kind` selects `telegram`, `github`, or an empty string to disable remote delivery. Telegram uses `telegramToken` and `telegramChat`; GitHub uses `githubToken`, `githubRepo`, `githubBranch`, and `githubPath`. GitHub defaults to branch `main` and path `backups/9routerx-backup.json`. Omitted credentials are retained; if you include a `remote` object without `kind`, the remote kind is cleared. Configuration responses replace token fields with has-token flags. Status/error fields are not equivalently sanitized: `lastRemoteError` can include a Telegram request URL containing the bot token. Treat the entire response as sensitive and redact it before sharing. **Remote backup artifacts are sensitive and not encrypted as a SyncBundle.** Delivery prefers JSON but falls back to the full SQLite snapshot when JSON export fails or is empty. The configured GitHub path, including a `.json` filename, is retained even for a SQLite fallback; inspect the format before restore. These artifacts can contain account/key material and private configuration, including fields omitted from JSON when SQLite is sent. Choose a private destination, restrict access, and review retention before enabling delivery. A remote failure does not turn a successful local backup into a failed local operation. Browser-profile directories are not included. `POST /api/settings/auto-backup` accepts `action: "backup"`, `"restore"`, or `"delete"`; the latter two take `file`. A path can be relative to the backup directory or absolute. Review the target and make an independent snapshot before restore/delete. The current delete handler ignores file-removal errors, so its success response alone is not proof that a file was deleted. ## Proxy-pool harvest `POST /api/proxy-pools/{id}/harvest` imports a user-supplied `proxies` array of 1–500 entries. It normalizes addresses (default scheme `http`) and deduplicates them. It does not discover proxies automatically. `probe` and `dropDead` both default to true. Only new entries are probed; existing pool entries stay. Eight workers share a 12-second batch context, with a 5-second HTTP probe limit, not a fresh 12-second deadline per proxy. Relays bypass the probe. An alive verdict means that the configured probe returned below `400`, not that every LLM provider is reachable. With `probe: false`, entries are stored unproven. With `dropDead: false`, dead entries can remain while `dropped` still counts dead verdicts. Duplicate/invalid-only batches can return a shorter result without `poolSize`. ## Background loops These run inside the gateway and need no external cron: | Loop | What it does | |---|---| | Gemini Web session renewal | Rotates the `__Secure-1PSIDTS` cookie so a signed-in account keeps reaching paid models | | Background catalog sync | Refreshes the model catalog from upstream | | Auto-ping scheduler | Pings providers through the real dispatch path on a schedule, keeping OAuth fresh and quota current | | Model health loop | Probes models and disables the ones that stop answering | | Usage retention loop | Prunes old usage rows and folds the carryover | The auto-ping scheduler deliberately sends its pings through the *same* handler instance the data plane uses, so a ping resolves credentials, refreshes OAuth, and picks an executor the way real traffic does. ## Headroom `/headroom/*` manages the token-compression proxy that sits in front of a CLI tool: ```text POST /headroom/start | stop | restart GET /headroom/status GET /headroom/extras POST /headroom/extras DELETE /headroom/extras GET /headroom/proxy ``` ## Metrics `GET /api/metrics` serves Prometheus. Provider-scoped rate-limit rejections carry `scope="provider"` and key-scoped ones `scope="api_key"`, so a dashboard alert can tell "this endpoint is saturated" from "this caller is abusive". ## Observability - `GET /debug/traces` — p50/p95 latency per provider+model - `GET /api/translator/console-logs/stream` — live log with a level filter - `PPROF_ENABLED=true` — exposes `/debug/pprof/*` behind admin auth. Keep it off on untrusted networks. ## Memory limit `9ROUTERX_GOMEMLIMIT` sets a soft Go heap limit when present, using Go byte-size syntax (`512MiB`, `1.5GiB`). Leave it unset to keep the runtime default; a bad value is logged and ignored at startup. This is optional: small hosts may set it to bound GC pressure, but the gateway behaves as before without it. ## Server timeouts The listener's read-header, idle, and max-header-byte limits are compiled in rather than configurable. Tune the proxy in front of the gateway instead. ## Optional runtime environment Besides the memory limit above, these environment knobs are read at startup. Unset means the documented default; a bad value is logged and ignored at startup. | Variable | Default | Effect | |---|---|---| | `SEMANTIC_CACHE_MAX_BYTES` | `64MiB` | Soft ceiling on the semantic cache store; oldest entries are trimmed past it. | | `SEMANTIC_CACHE_MAX_ENTRY_BYTES` | `512KiB` | Per-entry ceiling; larger entries are not stored. | | `STREAM_STALL_TIMEOUT_MS` | `360000` (6m) | Idle budget for an SSE stream before it is closed as stalled. Free-tier models stop after the 120s free-tier budget instead. `9ROUTERX_STREAM_STALL_TIMEOUT_MS` / `NINEROUTER_STREAM_STALL_TIMEOUT_MS` are legacy spellings; the first one set wins. | | `SEAT_ATTEMPT_BUDGET_MS` | `0` | Overall budget in milliseconds for seat-attempt retries; `0` keeps the policy default. `9ROUTERX_SEAT_ATTEMPT_BUDGET_MS` is the `9ROUTERX_`-prefixed spelling. | | `ROUTE_HEADERS` | unset | Optional extra headers attached to every upstream route call. | | `URL` | unset | Optional URL override for the CLI-tools panel. | | `SERVICE_BACKEND` | unset | Optional backend selector for the systemone lane. | ## Further reading - [`ARCHITECTURE.md`](https://github.com/yanstd888/9routerx/blob/main/ARCHITECTURE.md) - [`DATABASE.md`](https://github.com/yanstd888/9routerx/blob/main/DATABASE.md) # Governance # Governance Controls that decide *who may spend what*. Rate limits, budgets, plans, and per-key model access all read one resolver, so there is a single source of truth rather than limit logic scattered across the codebase. ## The resolver `internal/policy/policy.go` resolves an **effective policy** for a key: 1. Start from zero. 2. Overlay the key's plan, if it has one and the plan is found. 3. Overlay the key's own columns where they are non-zero. Everything downstream — rate limits, budgets, the model gate — reads that result. A key with no plan and no overrides behaves exactly as it did before plans existed. ## Rate limits Per-key limits with a FIFO queue: | Limit | Unit | |---|---| | RPM | requests per minute | | TPM | tokens per minute | | Concurrency | parallel requests | | Queue timeout | how long a request may wait for a slot | Prompt tokens are charged up front as an estimate, then reconciled when the real completion tokens arrive — so one very long response correctly reduces the running minute's budget after it finishes. **Per-provider limits are separate.** A key limit answers "how much may this caller spend"; a provider limit answers "how much can this endpoint take". Key limits run first, in middleware; provider limits run after resolution. A caller who exceeded their own limit is rejected *without* consuming provider quota — one abusive caller must not spend a healthy node's budget. ## Fair-share scheduling Fair-share is a scheduling hint between authenticated keys when the resilience concurrency cap is active. It is not a token quota, billing allocation, or reserved share. The default controller semaphore is disabled, which bypasses this scheduling path. The current ledger clears its buckets at a bucket transition, so it does not provide a reliable rolling-hour history. Do not use the hint as a fairness SLA; use the explicit rate limits and budgets above for enforceable per-key limits. ## Budgets USD and token budgets with a period and a hard cutoff, checked when a request starts: | Field | Meaning | |---|---| | `limitMicros` | USD cap, stored as integer micro-dollars — never a float | | `limitTokens` | Token cap | | `period` | `daily`, `weekly`, `monthly`, or `total` | | `alertPct` | Percentage that raises a warning header | | `hardCutoff` | `1` = reject with `402` once the limit is reached (checked at request start); `0` = warn only | Money is stored as integer micros; the float→micros conversion happens in **one** helper so it is never mixed into a guard. The ceiling is checked when a request starts, not continuously: requests already in flight when it is crossed still complete, so a key can overshoot by their cost. That is the trade for not writing a reservation on every request. ## Plans A plan is a reusable template: rate limits, budget, `allowedModels`, and the period. Assign it to many keys instead of configuring each one. ```text GET /api/plans POST /api/plans GET /api/plans/{id} PUT /api/plans/{id} DELETE /api/plans/{id} → 409 while any key still inherits it GET /api/plans/{id}/keys ``` Validation: `period` must be one of the four, `alertPct` 0–100, every limit ≥ 0, and `allowedModels` may use a trailing `*`. **A plan still attached to a key cannot be deleted.** The gateway answers `409` rather than removing the plan and leaving those keys with no limits at all — a key with no plan and no overrides is unlimited, so deleting a plan in use would silently lift the ceiling on every key that had one. Detach the keys first. ## Which limits a key actually gets Three layers, applied in order — this is the resolver above, stated as rules: 1. Start from zero — no limits. 2. Apply the key's plan, if it has one. 3. Apply the key's own settings, where they are non-zero. So a key's own value **overrides** its plan. A key with neither behaves exactly as it did before plans existed. **Model access is the exception.** A key's allowlist and its plan's are **unioned** — a key may add models, never remove them. A plan sets the floor; a key can only widen it. ## Per-key model access An allowlist per key. Empty means "all models", which is backward-compatible. - Wildcards: `claude-*`, `gpt-4*` - The gate runs before dispatch, so a denied model never reaches a provider. - How a key's list and its plan's list combine — and why a key can add but never remove — is covered under [Plans](#which-limits-a-key-actually-gets) above. ## Per-key governance Beyond rate limits and budgets, each key carries its own policy columns — all configured from the key's row on the **API Keys** page: | Field | Meaning | |---|---| | Daily cost limit | USD-per-UTC-day ceiling. The accumulator lazy-resets: a cost stamp from an earlier day makes the next write replace rather than add | | Request limit | Requests per interval (measured in minutes). `0` as the reset interval makes the cap lifetime — it never rolls | | IP whitelist | JSON array of IP/CIDR strings. Empty allows every address | | System prompt | A per-key system message injected in the client's wire format — OpenAI, Claude, and Responses bodies alike | | Endpoint permissions | A JSON object of allowed endpoint families, so a key can be scoped to, say, chat-only | | Expiry | The key stops working at its expiry timestamp | The daily cost limit is separate from the period budget above: the budget is a planned ceiling with alerts and an optional hard cutoff, both checked when a request starts; the daily cost limit is a hard per-day cap that resets itself every UTC midnight and is judged the same way. ## API key lifecycle ```text POST /api/keys/{id}/rotate Rotate: the old key stops working PUT /api/keys/{id}/toggle Enable / disable POST /api/keys/{id}/reset-quota Lift a spent quota without deleting history PUT /api/keys/{id} Metadata, expiry, limits ``` Keys are stored as Argon2id verifiers with a SHA-256 lookup index, and the plaintext is shown exactly once at creation. See [Security](security.html) for the hashing and vault details. ## Where the numbers come from The dashboard's rate-limit and quota numbers are read from the **same limiter instance the data plane enforces with**, not a private view. That is why a window shown in the dashboard matches what a request actually hits. ## Further reading - Rate limiter: `internal/middleware/ratelimit.go` - Policy resolver: `internal/policy/policy.go` - Budget enforcement: `internal/middleware/budget.go` - Model gate: `internal/handlers/chat/access.go` - Plans storage: `internal/db/plans.go` # Contributing # Contributing Issues and pull requests use templates, so pick the right one rather than opening a blank report: - **Bug report** — something behaves incorrectly. Include a reproduction, `9routerx version`, OS, and the log excerpt around the failure. - **Feature request** — the problem you cannot solve today, the surface it touches, and whether upstream already has it. - **Upstream parity** — a behaviour `decolua/9router` has that this gateway does not; link the upstream commit or PR. - **Question** — configuration and usage help. ## Checks CI runs ```bash go vet ./... go test -count=1 ./... make test-integration cd web && bun test make vet-svelte ``` ## Before writing code Read [`AGENTS.md`](https://github.com/yanstd888/9routerx/blob/main/AGENTS.md). Provider isolation and the Go/Svelte conventions there are enforced by review. ## Branches and PRs Every PR targets `main`. Branch from a clean `origin/main`: ```bash git fetch origin git worktree add ../9routerx- -b fix/ origin/main ``` ## Changelog Write a `.changes/-.md` fragment — never touch `CHANGELOG.md`. `CHANGELOG.md` is written only by `make changelog-merge` at release time. The dashboard's `GET /api/changelog` combines `CHANGELOG.md` with every fragment, so your entry appears as soon as your PR merges. # Screenshots # Screenshots This gallery preserves historical dashboard captures from the v1.0.0-era shadcn build; it is not a fresh capture of the latest release. The capture setup used fictional providers, demo models, and masked demo keys. Later UI and feature changes can differ from these images. No new screenshots were taken for this documentation update. Each page was captured in **dark and light themes**, at **desktop (1280px)** and **mobile (390px)** widths. Click any image to open the file under [`docs/screenshots/`](https://github.com/yanstd888/9routerx/tree/main/docs/screenshots). ## Providers Connect AI providers, browse the catalog, and manage custom OpenAI/Anthropic-compatible endpoints. Custom nodes show their connection state and protocol at a glance. ![Providers — dark, desktop](../docs/screenshots/providers.png) ![Providers — light, desktop](../docs/screenshots/providers-light.png) ![Providers — dark, mobile](../docs/screenshots/providers-mobile.png) ![Providers — light, mobile](../docs/screenshots/providers-mobile-light.png) ## Endpoint & API keys The endpoint your CLI tools point at, and the client keys they authenticate with. ![Endpoint & key — dark, desktop](../docs/screenshots/endpoint.png) ![Endpoint & key — light, desktop](../docs/screenshots/endpoint-light.png) ![Endpoint & key — dark, mobile](../docs/screenshots/endpoint-mobile.png) ![Endpoint & key — light, mobile](../docs/screenshots/endpoint-mobile-light.png) The key list carries per-key governance — policies, usage, and lifecycle actions — directly in the table: ![API key list — dark, desktop](../docs/screenshots/endpoint-keys.png) ## Usage & analytics Live KPIs, the tokens-over-time chart, and the provider topology map, all fed by the same usage ledger the budgets read. ![Usage overview — dark, desktop](../docs/screenshots/usage-overview.png) ![Usage overview — light, desktop](../docs/screenshots/usage-overview-light.png) ![Usage overview — dark, mobile](../docs/screenshots/usage-overview-mobile.png) ![Usage overview — light, mobile](../docs/screenshots/usage-overview-mobile-light.png) Charts and trend views: ![Usage charts — dark, desktop](../docs/screenshots/usage-charts.png) ![Usage charts — light, desktop](../docs/screenshots/usage-charts-light.png) ## Cache analytics Prompt-cache hit rate, reuse ratio, and the hourly cache trend: ![Cache analytics — dark, desktop](../docs/screenshots/usage-cache.png) ![Cache analytics — light, desktop](../docs/screenshots/usage-cache-light.png) ![Cache analytics — dark, mobile](../docs/screenshots/usage-cache-mobile.png) ![Cache analytics — light, mobile](../docs/screenshots/usage-cache-mobile-light.png) ## Request logs Every recorded request, with latency, tokens, cost, and the full payload one click away: ![Request details — dark, desktop](../docs/screenshots/request-logs.png) ![Request details — light, desktop](../docs/screenshots/request-logs-light.png) ![Request details — dark, mobile](../docs/screenshots/request-logs-mobile.png) ![Request details — light, mobile](../docs/screenshots/request-logs-mobile-light.png) ## Settings Runtime storage, session security, SSO, routing strategy, retention, branding, and display preferences: ![Settings — dark, desktop](../docs/screenshots/settings.png) ![Settings — light, desktop](../docs/screenshots/settings-light.png) ![Settings — dark, mobile](../docs/screenshots/settings-mobile.png) ![Settings — light, mobile](../docs/screenshots/settings-mobile-light.png) # Owner & Contributors # Owner & Contributors 9routerx is built in the open. This page lists everyone whose commit landed in the repository, with the profile photo and username each person uses on GitHub. The list is generated from the GitHub API, so it is the same one GitHub shows on the repository's contributors page. Contribution counts are what the API reports for the default branch. They are shown because they are the reason the order below is what it is — not as a score. Muhammad Dian @yanstd888 Maintainer of the 9RouterX fork repository owner Luqmannul Hakim @luqman-v1 Backend Engineer with Positive Mental Attitude 585 commits · original 9router-go author M Riyadh Azhar @mriazh 78 commits KunN21 @KunN-21 64 commits Helmi Amirudin @helmiau 47 commits Thomas Vincent @Enc48 21 commits Rafael Vieiras @rafaelvieiras 6 commits fajar sp @jhonoryza 5 commits raevtar @latifangren 4 commits Dicko Azrinaldi @azrinaldi 3 commits Pheo Navi @avitalbn 3 commits Romi Muharom @Leuthra 3 commits Yusron Rohmani @yxxrn 2 commits Rezha Julio @rezhajulio 2 commits Alfiansa @fiandev 2 commits Ahmad Rafi'i @rafia9005 1 commit Arcellorafi @arcelo12 1 commit F0Rextasy @F0Rextasy 1 commit Guardian @FmcStore 1 commit Muhammad Fadhli @Fadhli12 1 commit Nick Nyanjui @n1klaus 1 commit Tahsin Arafat @TahsinArafat 1 commit Ven @VenRoot 1 commit arfoux @arfoux 1 commit Razinal Rahmat @sud0su 1 commit ## Not listed `imgbot[bot]` appears in the repository's commit history with 3 commits. The GitHub API reports that account's type as `Bot`: it compresses images, and is not a person, so it is not listed among the contributors.