Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
41 changes: 37 additions & 4 deletions .env.example
Original file line number Diff line number Diff line change
@@ -1,8 +1,41 @@
# ---------------------------------------------------------------------------
# Server
PORT=20125
# ---------------------------------------------------------------------------
# Bind address and HTTP port.
HOST=0.0.0.0
# Data directory (sqlite db + secrets)
PORT=20125
# Pino log level: trace | debug | info | warn | error | fatal.
LOG_LEVEL=info
# Maximum request body in bytes (base64 media payloads need room).
BODY_LIMIT=134217728

# ---------------------------------------------------------------------------
# Storage
# ---------------------------------------------------------------------------
# SQLite database and the persisted signing secret live here.
DATA_DIR=./data
# Optional: override default dashboard password (hashed at first boot only)

# ---------------------------------------------------------------------------
# Security
# ---------------------------------------------------------------------------
# Only used when the dashboard password hash is first created.
# DASHBOARD_PASSWORD=123456
LOG_LEVEL=info
# HMAC secret for dashboard session cookies. When empty, a secret is generated
# once and stored in <DATA_DIR>/.secret. When set, the environment value wins on
# every boot and POST /admin/api/settings/rotate-secret returns 409 secret_from_env.
# ROUTER_SECRET=
# Dashboard session lifetime in milliseconds (default 7 days).
SESSION_TTL_MS=604800000
# Trust X-Forwarded-For/-Proto for request.ip (login brute-force guard + client_ip
# logs). Keep false unless the app runs behind a trusted reverse proxy.
TRUST_PROXY=false
# Allow provider test/sync to reach loopback/link-local/private hosts (SSRF guard).
PROVIDER_ALLOW_PRIVATE_HOSTS=false

# ---------------------------------------------------------------------------
# Dashboard assets / URLs
# ---------------------------------------------------------------------------
# Directory served as the dashboard build (default: <repo>/web/dist).
# WEB_DIST_DIR=./web/dist
# Optional absolute public base URL of this deployment.
# PUBLIC_URL=https://router.example.com
10 changes: 6 additions & 4 deletions .github/workflows/ci.yml
Original file line number Diff line number Diff line change
Expand Up @@ -22,6 +22,7 @@ jobs:
name: Commit messages
if: github.event_name == 'pull_request'
runs-on: ubuntu-latest
timeout-minutes: 10
steps:
- name: Checkout
uses: actions/checkout@v4
Expand All @@ -44,16 +45,17 @@ jobs:
"$PR_TITLE"

quality:
# Job name is a required branch-protection status check: do not rename it.
name: Lint & test
runs-on: ubuntu-latest
timeout-minutes: 20
steps:
- name: Checkout
uses: actions/checkout@v4

- name: Set up pnpm
# Version comes from package.json `packageManager` (single source of truth).
uses: pnpm/action-setup@v4
with:
version: 10

- name: Set up Node.js
uses: actions/setup-node@v4
Expand All @@ -73,14 +75,14 @@ jobs:
build-and-e2e:
name: Build & e2e
runs-on: ubuntu-latest
timeout-minutes: 30
steps:
- name: Checkout
uses: actions/checkout@v4

- name: Set up pnpm
# Version comes from package.json `packageManager` (single source of truth).
uses: pnpm/action-setup@v4
with:
version: 10

- name: Set up Node.js
uses: actions/setup-node@v4
Expand Down
7 changes: 1 addition & 6 deletions .gitignore
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,6 @@ node_modules/
# Build output (generated by `pnpm build`)
# ---------------------------------------------------------------------------
dist/
web/dist/
*.tsbuildinfo

# ---------------------------------------------------------------------------
Expand All @@ -19,6 +18,7 @@ data/
*.db
*.db-shm
*.db-wal
*.db-journal
*.sqlite
*.sqlite3
.secret
Expand Down Expand Up @@ -51,11 +51,6 @@ tmp/
.tmp/
*.local

# ---------------------------------------------------------------------------
# Generated dashboard export (scripts/screenshots.ts writes here by default)
# ---------------------------------------------------------------------------
tmp/screenshots/

# ---------------------------------------------------------------------------
# Editors and IDEs
# ---------------------------------------------------------------------------
Expand Down
4 changes: 2 additions & 2 deletions AGENTS.md
Original file line number Diff line number Diff line change
Expand Up @@ -11,7 +11,7 @@ forwards each request to one of several interchangeable providers using round-ro
rotation with failover, so a rate-limited provider never stops traffic. A React
dashboard manages providers, models, API keys, logs and settings.

Stack: Node.js ≥ 22.5 (uses `node:sqlite`), Fastify 5, TypeScript ESM, pnpm, Vite +
Stack: Node.js ≥ 22.13 (flag-free `node:sqlite`), Fastify 5, TypeScript ESM, pnpm 10, Vite +
React 19 + Tailwind CSS 4. Default port **20125**.

## Golden rules
Expand Down Expand Up @@ -46,7 +46,7 @@ pnpm test:e2e # full acceptance: real server + deterministic mock u
pnpm test:live # smoke test against a real provider (skips on 429)
pnpm build # tsc -> dist/ and vite -> web/dist/
pnpm start # run the compiled server (node dist/src/index.js)
pnpm exec tsx scripts/screenshots.ts # headless Chrome UI check + screenshots
pnpm exec tsx scripts/screenshots.ts # headless Chrome UI check + screenshots (skips if Chrome absent)
```

Before opening a PR run at least: `pnpm typecheck && pnpm test && pnpm build && pnpm test:e2e`.
Expand Down
6 changes: 3 additions & 3 deletions CONTRIBUTING.md
Original file line number Diff line number Diff line change
Expand Up @@ -7,8 +7,8 @@ coding standards, the commit-message convention enforced by CI, and the pull-req

Requirements:

- Node.js **≥ 22.5** (the gateway uses the built-in `node:sqlite` module)
- pnpm 9+ (CI uses pnpm 10)
- Node.js **≥ 22.13** (the gateway uses the built-in `node:sqlite` module without an experimental flag)
- pnpm **10+** (the repo pins `pnpm@10.18.0` through `packageManager`; CI uses pnpm 10)
- A reachable OpenAI/Anthropic-compatible provider for manual testing (optional — the
e2e suite ships deterministic mock upstreams)

Expand Down Expand Up @@ -118,7 +118,7 @@ pull request that passes the required checks.
5. Wait for CI to go green. Required checks:
- **Commit messages** — Conventional Commits validation (commits + PR title)
- **Lint & test** — typecheck and unit tests
- **Build & e2e** — production build plus the 51-check acceptance suite
- **Build & e2e** — production build plus the end-to-end acceptance suite
6. Squash-merge the PR (the squashed commit message is the PR title). Delete the branch.

A PR that changes the gateway contract, the database schema or the admin API must also
Expand Down
48 changes: 32 additions & 16 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -36,8 +36,11 @@ client (OpenAI SDK / Anthropic SDK / curl) ──▶ OpenCode Router :20125 ─
(+ `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.
- **Provider rotation**: round-robin ordered by priority with automatic failover on `429`/`5xx`/network errors,
per-provider cooldowns, and per-attempt logging.
- **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`), per-provider cooldowns, and per-attempt logging.
- **Gateway API keys are mandatory** (`okr-…`, accepted as `Authorization: Bearer` or `x-api-key`).
- **Model registry**: synced from any single provider (all providers expose the same catalogue) or added manually.
Empty until you configure a provider.
Expand All @@ -47,8 +50,8 @@ client (OpenAI SDK / Anthropic SDK / curl) ──▶ OpenCode Router :20125 ─

## Requirements

- Node.js **≥ 22.5** (uses `node:sqlite`; tested on Node 26)
- pnpm 10+
- 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

Expand All @@ -66,20 +69,27 @@ Open <http://127.0.0.1:20125> → you are redirected to the dashboard login. Def
(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 valid
provider *and* one API key exist.
→ **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 |
| --- | --- | --- |
| `PORT` | `20125` | HTTP port |
| `HOST` | `0.0.0.0` | Bind address |
| `DATA_DIR` | `./data` | SQLite database + signing secret |
| `LOG_LEVEL` | `info` | Pino level |
| `BODY_LIMIT` | `134217728` | Max request body (base64 media) |
| `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 sessions |
| `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 |

[.env.example](.env.example) is the same list as a copy-paste template.

Runtime settings (rotation strategy, retry budget, provider cooldown, request timeout, auto model sync interval,
log retention, …) live in **Dashboard → Settings**.
Expand Down Expand Up @@ -133,8 +143,9 @@ curl http://127.0.0.1:20125/v1/messages \
curl http://127.0.0.1:20125/v1/models -H "Authorization: Bearer okr-..."
```

Every gateway response carries `x-opencode-router-provider`, `x-opencode-router-request-id` and
`x-opencode-router-attempts` headers.
Every `/v1/*` response carries `x-opencode-router-request-id`. Responses served by an upstream provider also
carry `x-opencode-router-provider` (winning provider id) and `x-opencode-router-attempts`; errors raised
before an attempt (auth, routing, validation) carry the request id only.

See [docs/API.md](docs/API.md) for the full gateway reference and [docs/SPEC.md](docs/SPEC.md) for the
dashboard/admin API contract.
Expand Down Expand Up @@ -162,10 +173,10 @@ scripts/e2e.ts full end-to-end acceptance run
```bash
pnpm typecheck # server + dashboard type checks
pnpm test # vitest unit suite (crypto, repos, stats, SSE, normalization)
pnpm test:e2e # boots a real server + mock providers; 51 acceptance checks
pnpm test:e2e # boots a real server + mock providers; full acceptance suite
pnpm test:live # smoke-tests a real provider (skips when its quota is exhausted)
pnpm build # dist/ + web/dist/
pnpm exec tsx scripts/screenshots.ts # headless Chrome UI check + PNG screenshots
pnpm exec tsx scripts/screenshots.ts # headless Chrome UI check + PNG screenshots (macOS; SKIPs without Chrome)
```

`pnpm test:e2e` is self-contained: it starts two deterministic mock upstreams that mimic the reference
Expand All @@ -176,7 +187,9 @@ routing, rotation, failover, logging, admin APIs, dashboard routing and the buil
provider answers `429` every probe is reported as **SKIP** instead of failing.

`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/`.
renders its expected content and writes screenshots to `tmp/screenshots/`. It needs a Chrome/Chromium binary
(`CHROME_PATH`, defaulting to the macOS Chrome path); when none is found the script prints `SKIP` and exits
without checking anything. CI does not run this script, so the UI check is a local, macOS-oriented aid.

## Contributing

Expand All @@ -201,3 +214,6 @@ Agents and automated contributors should read [AGENTS.md](AGENTS.md) first.
- 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.
50 changes: 35 additions & 15 deletions docs/API.md
Original file line number Diff line number Diff line change
Expand Up @@ -9,13 +9,15 @@ Authorization: Bearer okr-xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx
x-api-key: okr-xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx
```

Responses include:
Response headers:

| Header | Meaning |
| --- | --- |
| `x-opencode-router-provider` | id of the provider that served the request |
| `x-opencode-router-request-id` | gateway request id (same id as in the Logs tab) |
| `x-opencode-router-attempts` | number of upstream attempts (1 = first provider worked) |
| Header | Set on | Meaning |
| --- | --- | --- |
| `x-opencode-router-request-id` | every `/v1/*` response | gateway request id (same id as in the Logs tab) |
| `x-opencode-router-provider` | proxied responses | id of the provider that served the request |
| `x-opencode-router-attempts` | proxied responses | number of upstream attempts (1 = first provider worked) |

Errors raised before an upstream attempt (auth, routing, validation) carry `x-opencode-router-request-id` only.

Error envelope follows the client surface: OpenAI style `{"error":{"message","type","param","code"}}`
for chat/responses, Anthropic style `{"type":"error","error":{"type","message"}}` for messages.
Expand All @@ -32,9 +34,18 @@ for chat/responses, Anthropic style `{"type":"error","error":{"type","message"}}
| 429 | `all_providers_rate_limited` | every attempt hit a rate limit |
| 502 | `all_providers_failed` | every attempt failed (network/5xx) |

The router retries the next provider for `429`, `5xx`, `408`, `425` and network/timeout errors, up to the
configured retry budget (Dashboard → Settings → Routing). Client errors (`400/401/403/404/422`) are returned
immediately without burning other providers.
The router retries the next provider for `408`, `409`, `425`, `429`, `5xx` and network/timeout errors, up to
the configured retry budget (Dashboard → Settings → Routing). Client errors (`400/401/403/404/422`) are
returned immediately without burning other providers.

## Upstream requests

Request bodies are forwarded byte-for-byte; a JSON body is only re-serialized when reasoning normalization or
the `stream_options.include_usage` injection actually changed it. Provider credentials (`Authorization`,
`x-api-key`), `host`, `content-length` and `connection` always come from the router, while the client's
`anthropic-beta`, `openai-beta`, `x-stainless-*`, `accept` and trace headers are forwarded through an
allowlist. Upstream redirects are refused (`redirect: 'manual'`): a `3xx` response is a fatal upstream error
instead of being followed with the provider key.

---

Expand Down Expand Up @@ -132,16 +143,25 @@ Lists the enabled models from the registry in OpenAI format, enriched with capab

`GET /v1/models/:id` returns a single entry or `404 model_not_found`.

Like every other `/v1/*` request, `GET /v1/models` and `GET /v1/models/:id` write one `request_logs` row per
request (successes and rejections alike).

## `GET /health`

```json
{"status":"ok","name":"OpenCode Router","version":"1.0.0","startedAt":1765000000000,
"providers":1,"models":12,"apiKeys":true}
{"status":"ok","name":"OpenCode Router","version":"1.0.0","uptimeMs":86400000,
"startedAt":1765000000000,"providers":1,"models":12,"apiKeys":true}
```

`uptimeMs` is the real process uptime (`now - startedAt`), not a placeholder.

## Streaming

All three surfaces stream as `text/event-stream` when `stream: true` is set. Bytes are forwarded as they arrive
from the upstream provider (`Cache-Control: no-cache`, `X-Accel-Buffering: no`). The gateway parses frames
in-flight only to extract token usage for logging, and strips provider-internal `x_opencode` metadata.
Client aborts terminate the upstream request and are logged with `client_aborted`.
All three surfaces stream as `text/event-stream` when `stream: true` is set. Bytes are forwarded as they
arrive from the upstream provider (`Cache-Control: no-cache`, `X-Accel-Buffering: no`). Frames are decoded
only to extract token usage and to strip provider-internal `x_opencode` metadata, so invalid UTF-8 and a
leading BOM reach the client unchanged.

`request_timeout_ms` (Dashboard → Settings → Routing) is a total deadline that covers the streamed body, and
a stalled upstream is additionally cut off by an idle timeout between frames. Client aborts terminate the
upstream request and are logged with `client_aborted`.
Loading
Loading