Skip to content

About

OpenCode Router — multi-provider LLM gateway with OpenAI- and Anthropic-compatible APIs, provider rotation and a premium dashboard.

Topics

Resources

Contributing

Stars

0 stars

Watchers

0 watching

Forks

Repository files navigation

OpenCode Router

CI License: MIT

Multi-provider LLM gateway with a premium glassmorphism dashboard. One endpoint for every client: OpenAI Chat Completions, OpenAI Responses, and Anthropic Messages — all three forwarded to a pool of interchangeable upstream providers with automatic round-robin failover so a single rate-limited provider never stops your traffic.

client (OpenAI SDK / Anthropic SDK / curl) ──▶ OpenCode Router :20125 ──▶ provider A (round-robin)
                                                                      ├─▶ provider B (failover on 429/5xx)
                                                                      └─▶ provider C (cooldown aware)

Screenshots

Login Overview (dark)
Login Overview
Overview (light) Logs
Light theme Logs
Providers Models
Providers Models

Settings

Features

  • Three native API surfaces: POST /v1/chat/completions, POST /v1/responses, POST /v1/messages (+ POST /v1/messages/count_tokens, GET /v1/models) — streaming and non-streaming.
  • Full pass-through fidelity: tool calling, vision/image/video/audio/PDF content parts, and reasoning (reasoning_effort, reasoning.effort, Anthropic thinking) are preserved end-to-end.
  • Byte-level pass-through: request bodies are forwarded unchanged unless reasoning or stream_options normalization applies, and streamed frames keep the upstream bytes (invalid UTF-8 and a leading BOM included).
  • Provider rotation: round-robin (default), priority or random ordering with automatic failover on retryable upstream errors (408/409/425/429/5xx, network errors and timeouts), per-provider cooldowns, and per-attempt logging (timed-out attempts included).
  • Gateway API keys are mandatory (okr-…, accepted as Authorization: Bearer or x-api-key; other Authorization schemes are rejected). Rotate a key without changing its id or counters.
  • Model registry: synced from any single provider (all providers expose the same catalogue) or added manually. Empty until you configure a provider.
  • Dashboard (login required, default password 123456): Overview with live traffic, API Keys (create, enable/disable, rotate, revoke), Providers (test, sync, cooldown state), Models (filters, bulk actions), Logs (filters, live tail, export), Settings (routing, retention, sessions, secret rotation, audit). Dark/light, Inter, Lucide, glassmorphism.
  • SQLite storage via Node's built-in node:sqlite — no native build step.

Requirements

  • Node.js ≥ 22.13 (flag-free node:sqlite; tested on Node 26)
  • pnpm 10+ (the repo pins pnpm@10.18.0 through packageManager)

Quick start

pnpm install
pnpm build            # compiles the server + builds the dashboard into web/dist
pnpm start            # http://127.0.0.1:20125

# development
pnpm dev              # API with watch mode (port 20125)
pnpm dev:web          # dashboard dev server (proxies /admin and /v1)

# before opening a pull request
pnpm verify           # typecheck → unit tests → docs drift → build → e2e

Open http://127.0.0.1:20125 → you are redirected to the dashboard login. Default password 123456 (change it in Settings → Security).

Then: Providers → Add provider (id, display name, base URL such as http://127.0.0.1:20123/v1, API key) → Test → Sync models → API Keys → Create key. The gateway refuses traffic until at least one enabled provider, one enabled model and one API key exist (the dashboard shows Gateway ready only then).

Configuration

Env Default Meaning
HOST 0.0.0.0 Bind address
PORT 20125 HTTP port
DATA_DIR ./data SQLite database + persisted signing secret
LOG_LEVEL info Pino log level
BODY_LIMIT 134217728 Max request body in bytes (base64 media)
DASHBOARD_PASSWORD 123456 Only used when the password hash is first created
ROUTER_SECRET generated in <DATA_DIR>/.secret HMAC secret for dashboard sessions; when set, rotation is refused with 409 secret_from_env
SESSION_TTL_MS 604800000 Dashboard session lifetime (7 days)
TRUST_PROXY false Trust X-Forwarded-* for request.ip (login brute-force guard + client_ip logs) — enable only behind a trusted proxy
PROVIDER_ALLOW_PRIVATE_HOSTS false Allow provider test/sync to reach loopback/link-local/private hosts (SSRF guard off)
WEB_DIST_DIR <repo>/web/dist Directory served as the dashboard build
PUBLIC_URL unset Optional absolute public base URL of this deployment
NODE_ENV unset Read by src/server.ts: production selects the production server behaviour (set by the runner, not by config.ts)

.env.example is the same list as a copy-paste template. It binds to 127.0.0.1 by default — set HOST=0.0.0.0 only behind a reverse proxy with TLS and after changing the dashboard password. pnpm check:docs fails when the template and src/config.ts disagree, or when a documented default contradicts the code.

Runtime settings (rotation strategy, retry budget, provider cooldown, request timeout, SSE idle timeout, auto model sync interval, log retention, audit retention, …) live in Dashboard → Settings.

Using the gateway

OpenAI SDK (Python)

from openai import OpenAI

client = OpenAI(base_url="http://127.0.0.1:20125/v1", api_key="okr-...")

# Chat Completions (default surface)
print(client.chat.completions.create(model="opencode/flint-40b-free",
                                     messages=[{"role": "user", "content": "hello"}]).choices[0].message.content)

# Responses surface
print(client.responses.create(model="opencode/flint-40b-free", input="hello").output_text)

Anthropic SDK (TypeScript)

import Anthropic from '@anthropic-ai/sdk';

const client = new Anthropic({ baseURL: 'http://127.0.0.1:20125', apiKey: 'okr-...' });
const message = await client.messages.create({
  model: 'opencode/flint-40b-free',
  max_tokens: 512,
  thinking: { type: 'enabled', budget_tokens: 2048 },
  messages: [{ role: 'user', content: 'hello' }],
});

curl

# chat completions (streaming)
curl -N http://127.0.0.1:20125/v1/chat/completions \
  -H "Authorization: Bearer okr-..." -H 'content-type: application/json' \
  -d '{"model":"opencode/flint-40b-free","stream":true,"reasoning_effort":"low",
       "messages":[{"role":"user","content":"hello"}]}'

# messages (Anthropic)
curl http://127.0.0.1:20125/v1/messages \
  -H "x-api-key: okr-..." -H 'anthropic-version: 2023-06-01' -H 'content-type: application/json' \
  -d '{"model":"opencode/flint-40b-free","max_tokens":256,"messages":[{"role":"user","content":"hello"}]}'

# models
curl http://127.0.0.1:20125/v1/models -H "Authorization: Bearer okr-..."

Every /v1/* response carries x-opencode-router-request-id. Responses served (or failed) by an upstream provider also carry x-opencode-router-provider, x-opencode-router-name and x-opencode-router-attempts; errors raised before an attempt (auth, routing, validation) carry the request id only. A 429 all_providers_rate_limited answer includes Retry-After and x-opencode-router-cooldown-until, and relayed upstream headers (retry-after, x-ratelimit-*, openai-*, anthropic-*, x-stainless-*) pass through.

See docs/API.md for the full gateway reference and docs/SPEC.md for the dashboard/admin API contract.

Project layout

src/
  index.ts          bootstrap (config → db → server → scheduler)
  server.ts         Fastify app, static dashboard, SPA fallback, error mapping
  config.ts         env configuration
  types.ts          shared domain types
  core/             context, event bus, first-run seeding
  db/               sqlite schema, migrations, repositories
  util/             crypto, errors, upstream fetch, SSE, model normalization
  gateway/          API-key auth, rotation, pass-through proxy, /v1/models
  admin/            dashboard API (auth, providers, models, keys, logs, settings), scheduler
web/                React 19 + Tailwind 4 dashboard (Vite)
tests/              vitest unit tests
scripts/e2e.ts      full end-to-end acceptance run

Verification

pnpm verify                 # one local gate mirroring CI (typecheck → test → check:docs → build → test:e2e)
pnpm verify --fast          # same gate without build + test:e2e (pre-commit loop)
pnpm typecheck              # server + dashboard + tests/scripts type checks
pnpm test                   # vitest unit suite (crypto, repos, stats, SSE, normalization, tooling)
pnpm check:docs             # doc drift: env vars, routes, settings, .env.example and documented defaults
pnpm check:env-example      # .env.example ↔ src/config.ts parity only
pnpm test:e2e               # boots a real server + mock providers; full acceptance suite
pnpm test:live              # smoke-tests a real provider (skips when it answers 429)
pnpm build                  # dist/ + web/dist/
pnpm self-test:docs         # negative self-tests for the docs/env checkers
pnpm self-test:commits      # negative self-tests for the commit-message linter
pnpm exec tsx scripts/screenshots.ts --strict   # headless Chrome UI check + PNG screenshots

pnpm verify stops at the first failing stage, prints a per-stage timing line and exits non-zero; CI runs the same commands as separate steps (Lint & test, Build & e2e).

The enforcement scripts ship negative self-tests: --self-test builds throw-away fixture trees/commits and requires every known bad input (undocumented env var/route/setting, missing route, bad .env.example entry, contradicting documented default, bad commit type, uppercase description, trailing period, missing BREAKING CHANGE: footer, empty range, unknown --single sha) to be rejected. CI runs them, so a silently disabled check cannot pass.

Scripts reference

Command Purpose Env knobs / flags
pnpm dev / pnpm start Run the server from source / from dist/ HOST, PORT, DATA_DIR, LOG_LEVEL, WEB_DIST_DIR
pnpm mock Standalone mock upstream MOCK_PORT (20196), MOCK_NAME (mock), MOCK_KEY (sk-dummy-123)
pnpm test:e2e Full acceptance run E2E_PORT (20197), E2E_MOCK_A_PORT (20196), E2E_MOCK_B_PORT (20195), E2E_ALT_PORT (free port)
pnpm test:live Smoke test a real provider LIVE_PORT (20194), LIVE_UPSTREAM/E2E_UPSTREAM, LIVE_KEY/E2E_UPSTREAM_KEY, LIVE_MODEL, LIVE_VISION_MODEL
pnpm exec tsx scripts/screenshots.ts Chrome/CDP UI check + screenshots CHROME_PATH; --out <dir> (./tmp/screenshots), --port <n> (20193), --mockPort <n> (20192), --cdpPort <n> (9333), --strict
pnpm check:docs / pnpm check:env-example Documentation and env-template drift --self-test
pnpm lint:commits Conventional Commits check <base-sha> <head-sha> "<pr title>", --single <sha>, --self-test

pnpm test:e2e is self-contained: it starts two deterministic mock upstreams (OpenAI + Anthropic surfaces, streaming, tools, vision, reasoning, injectable 429/5xx/delays) and verifies routing, rotation, failover, timeouts, byte fidelity, logging (exactly one row per request), auth, cookie flags, the brute-force guard, admin APIs and the built dashboard shell. It fails fast when a fixed port is occupied or a child exits before /health. Its SSE lifecycle checks wait for the endpoint's deterministic initial frame instead of sleeping.

pnpm test:live talks to a real provider; when the provider answers 429 the affected probe is reported as SKIP instead of failing (decided from the upstream status, never from error text).

scripts/screenshots.ts seeds demo data, drives headless Chrome over CDP, asserts each dashboard page renders its expected content and writes screenshots to tmp/screenshots/. It needs a Chrome/Chromium binary (CHROME_PATH, defaulting to the macOS Chrome path) that is a real executable and answers --version as a browser; without one the script prints SKIP and exits 0, so local CI-style runs use --strict, which fails instead of skipping. No CI job runs the UI check — a browser job is explicitly deferred.

Contributing

Development setup, coding standards and the enforced Conventional Commits convention are documented in CONTRIBUTING.md. main is protected: open a pull request and wait for the required checks (Commit messages, Lint & test, Build & e2e) before merging.

pnpm verify                           # the full CI-mirroring gate
pnpm lint:commits                     # validate your branch's commits locally
pnpm check:docs                       # env vars / routes / settings / .env.example vs the docs
pnpm self-test:docs                   # prove the documentation checkers still fail on bad input
node scripts/check-commit-messages.mjs origin/main HEAD "feat(gateway): example"
node scripts/check-commit-messages.mjs --single "$(git rev-parse HEAD)"

Agents and automated contributors should read AGENTS.md first.

License

MIT © 2026 Phạm Văn Định

Security notes

  • Change the dashboard password and rotate the signing secret after first login (Settings → Security).
  • Gateway keys are stored as SHA-256 hashes; the plaintext is shown exactly once at creation.
  • Provider API keys are never returned through the dashboard API (masked only).
  • Bind to 127.0.0.1 (or place behind a reverse proxy with TLS) when exposing the dashboard.
  • Leave TRUST_PROXY=false unless you run behind a reverse proxy you control: the login brute-force guard and logged client_ip key on the socket address until it is enabled.
  • Keep PROVIDER_ALLOW_PRIVATE_HOSTS=false unless providers legitimately live on loopback/private networks.

About

OpenCode Router — multi-provider LLM gateway with OpenAI- and Anthropic-compatible APIs, provider rotation and a premium dashboard.

Topics

Resources

Contributing

Stars

0 stars

Watchers

0 watching

Forks

Contributors

Languages