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
60 changes: 53 additions & 7 deletions .github/workflows/ci.yml
Original file line number Diff line number Diff line change
Expand Up @@ -20,14 +20,15 @@ env:
jobs:
commit-messages:
name: Commit messages
if: github.event_name == 'pull_request'
# Runs on PRs and on pushes to main: a required PR check that is skipped reports
# success without linting anything, so main must be linted too.
runs-on: ubuntu-latest
timeout-minutes: 10
steps:
- name: Checkout
uses: actions/checkout@v4
with:
# Full history so every commit of the PR can be inspected.
# Full history so the whole commit range is available.
fetch-depth: 0

- name: Set up Node.js
Expand All @@ -38,11 +39,19 @@ jobs:
- name: Lint commit messages and PR title
env:
PR_TITLE: ${{ github.event.pull_request.title }}
BASE_SHA: ${{ github.event_name == 'pull_request' && github.event.pull_request.base.sha || github.event.before }}
HEAD_SHA: ${{ github.event_name == 'pull_request' && github.event.pull_request.head.sha || github.sha }}
run: |
node scripts/check-commit-messages.mjs \
"${{ github.event.pull_request.base.sha }}" \
"${{ github.event.pull_request.head.sha }}" \
"$PR_TITLE"
# A brand-new branch can push with an all-zero "before" sha; fall back to the
# default range instead of failing the range check.
if [ "$BASE_SHA" = "0000000000000000000000000000000000000000" ]; then
BASE_SHA=""
fi
if [ -z "$BASE_SHA" ] || [ -z "$HEAD_SHA" ]; then
node scripts/check-commit-messages.mjs
else
node scripts/check-commit-messages.mjs "$BASE_SHA" "$HEAD_SHA" "${PR_TITLE:-}"
fi

quality:
# Job name is a required branch-protection status check: do not rename it.
Expand Down Expand Up @@ -72,6 +81,10 @@ jobs:
- name: Unit tests
run: pnpm test

- name: Documentation drift
# Fails while SPEC.md/API.md and the code disagree (env vars, routes, settings).
run: pnpm check:docs

build-and-e2e:
name: Build & e2e
runs-on: ubuntu-latest
Expand All @@ -96,14 +109,47 @@ jobs:
- name: Build server and dashboard
run: pnpm build

- name: Smoke-test the built server
# The e2e suite boots src/index.ts through tsx; this proves dist/ actually runs.
run: |
DATA_DIR="$(mktemp -d)"
PORT=20198 HOST=127.0.0.1 LOG_LEVEL=warn NODE_ENV=production \
node dist/src/index.js > "$RUNNER_TEMP/smoke.log" 2>&1 &
SERVER_PID=$!
READY=0
for _ in $(seq 1 100); do
if curl -fsS "http://127.0.0.1:20198/health" -o "$RUNNER_TEMP/health.json"; then READY=1; break; fi
if ! kill -0 "$SERVER_PID" 2>/dev/null; then
echo "server exited during boot"; cat "$RUNNER_TEMP/smoke.log"; exit 1
fi
sleep 0.2
done
if [ "$READY" != "1" ]; then echo "server never became healthy"; cat "$RUNNER_TEMP/smoke.log"; exit 1; fi
grep -q '"status":"ok"' "$RUNNER_TEMP/health.json"
DASHBOARD_STATUS="$(curl -s -o /dev/null -w '%{http_code}' http://127.0.0.1:20198/dashboard)"
if [ "$DASHBOARD_STATUS" != "302" ]; then echo "/dashboard → $DASHBOARD_STATUS (expected 302)"; exit 1; fi
DASHBOARD_LOCATION="$(curl -s -o /dev/null -w '%{redirect_url}' http://127.0.0.1:20198/dashboard)"
if [ "$DASHBOARD_LOCATION" != "http://127.0.0.1:20198/login" ]; then
echo "/dashboard redirect → $DASHBOARD_LOCATION (expected /login)"; exit 1
fi
kill -TERM "$SERVER_PID"
for _ in $(seq 1 50); do kill -0 "$SERVER_PID" 2>/dev/null || break; sleep 0.2; done
if kill -0 "$SERVER_PID" 2>/dev/null; then echo "server did not exit on SIGTERM"; exit 1; fi
wait "$SERVER_PID" || true
echo "dist smoke test passed (health 200, /dashboard 302 → /login, clean SIGTERM)"
cat "$RUNNER_TEMP/smoke.log"

- name: End-to-end acceptance suite
run: pnpm test:e2e

- name: Upload build artifacts
if: github.event_name == 'push'
# Always upload so a failing e2e run still leaves the built dist/ for debugging;
# a missing artifact is an error instead of a silent no-op.
if: always()
uses: actions/upload-artifact@v4
with:
name: opencode-router-build
if-no-files-found: error
path: |
dist/
web/dist/
Expand Down
1 change: 1 addition & 0 deletions .nvmrc
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
22
32 changes: 23 additions & 9 deletions AGENTS.md
Original file line number Diff line number Diff line change
Expand Up @@ -37,19 +37,26 @@ React 19 + Tailwind CSS 4. Default port **20125**.
## Commands

```bash
pnpm install # install dependencies
pnpm install # install dependencies (Node 22+, pnpm 10+; see .nvmrc)
pnpm dev # API with watch (port 20125, serves web/dist)
pnpm dev:web # dashboard dev server (proxies /admin and /v1)
pnpm typecheck # server + web type checks
pnpm typecheck # server + web + tests/scripts type checks (tsconfig.test.json)
pnpm test # vitest unit suite
pnpm check:docs # doc-drift check: env vars, routes, settings vs docs/SPEC.md + docs/API.md
pnpm test:e2e # full acceptance: real server + deterministic mock upstreams
pnpm test:live # smoke test against a real provider (skips on 429)
pnpm test:live # smoke test against a real provider (skips on upstream 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 (skips if Chrome absent)
pnpm exec tsx scripts/screenshots.ts --strict # headless Chrome UI check; fails (not SKIP) without Chrome
```

Before opening a PR run at least: `pnpm typecheck && pnpm test && pnpm build && pnpm test:e2e`.
Script env knobs: `E2E_PORT`/`E2E_MOCK_A_PORT`/`E2E_MOCK_B_PORT` (e2e, defaults 20197/20196/20195),
`MOCK_PORT`/`MOCK_NAME`/`MOCK_KEY` (mock upstream), `LIVE_PORT`/`LIVE_UPSTREAM`/`LIVE_KEY`/`LIVE_MODEL`/
`LIVE_VISION_MODEL` (live check), `CHROME_PATH` (screenshots). `pnpm lint:commits` runs the commit-message
linter against `origin/main..HEAD`.

Before opening a PR run at least:
`pnpm typecheck && pnpm test && pnpm check:docs && pnpm build && pnpm test:e2e`.

## Layout

Expand All @@ -63,8 +70,8 @@ Before opening a PR run at least: `pnpm typecheck && pnpm test && pnpm build &&
| `src/gateway/` | `/v1/*` auth, rotation, pass-through proxy, `/v1/models` |
| `src/admin/` | `/admin/api/*` (auth, providers, models, keys, logs, settings), scheduler |
| `web/` | React 19 + Tailwind dashboard (Vite root, builds to `web/dist`) |
| `scripts/` | e2e, live check, mock upstream, commit-message linter, screenshots |
| `tests/` | vitest unit tests |
| `scripts/` | e2e, live check, mock upstream, commit-message linter, doc-drift checker, screenshots |
| `tests/` | vitest unit tests (incl. `tooling.test.ts` for the repo scripts) |
| `docs/` | `SPEC.md` (contract), `API.md` (gateway reference), screenshots |
| `.github/workflows/` | CI |

Expand All @@ -89,8 +96,13 @@ Before opening a PR run at least: `pnpm typecheck && pnpm test && pnpm build &&
```

Allowed types: `feat`, `fix`, `docs`, `style`, `refactor`, `perf`, `test`, `build`, `ci`, `chore`, `revert`.
Scopes are optional (examples: `gateway`, `admin`, `web`, `db`, `ci`, `docs`, `repo`).
The PR title is linted too because squash merges use it verbatim.
Scopes are optional (examples: `gateway`, `admin`, `web`, `db`, `ci`, `docs`, `repo`) and must match
`[a-z0-9][a-z0-9._/-]*`. The description must start with a lowercase letter (Unicode-aware: `Ä`, `修正` and
emoji-leading descriptions are rejected), must not end with a period and the whole subject is ≤ 100 chars.
Real merge commits are excluded via `git log --no-merges`; `fixup!`/`squash!`/`amend!` and the tooling's own
`Revert "…"`/`Initial commit` subjects are skipped. The PR title is linted too because squash merges use it
verbatim, and CI lints pushes to `main` as well as PRs. An explicitly supplied base/head range that contains
zero commits fails instead of passing an empty check.

## PR workflow

Expand All @@ -102,5 +114,7 @@ the required checks (`Commit messages`, `Lint & test`, `Build & e2e`), then squa
- Editing `dist/`, `web/dist/`, `data/` or `tmp/` (generated, git-ignored).
- Committing `.env`, database files, provider keys or dashboard session secrets.
- Bypassing the repository layer with ad-hoc SQL outside `src/admin`-level read helpers.
- Weakening the enforcement scripts to make them pass: `pnpm check:docs`, the commit-message linter and the
e2e single-log-row assertions must report real problems. Fix the docs/code, not the checker.
- Adding Chinese/Japanese/Vietnamese comments or UI copy to code that is otherwise English.
- Force-pushing `main` (blocked by protection) or disabling CI checks to merge.
26 changes: 17 additions & 9 deletions CONTRIBUTING.md
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,8 @@ coding standards, the commit-message convention enforced by CI, and the pull-req

Requirements:

- Node.js **≥ 22.13** (the gateway uses the built-in `node:sqlite` module without an experimental flag)
- Node.js **≥ 22.13** (the gateway uses the built-in `node:sqlite` module without an experimental flag;
`.nvmrc` pins the CI major, so `nvm use` is enough)
- 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 @@ -62,9 +63,9 @@ on a pull request **and the pull request title** must match:
| Part | Rules |
| --- | --- |
| `type` | one of `feat`, `fix`, `docs`, `style`, `refactor`, `perf`, `test`, `build`, `ci`, `chore`, `revert` |
| `scope` | optional; short noun such as `gateway`, `admin`, `web`, `db`, `ci`, `docs`, `repo` |
| `scope` | optional; matches `[a-z0-9][a-z0-9._/-]*`, short noun such as `gateway`, `admin`, `web`, `db`, `ci`, `docs`, `repo` |
| `!` | optional; marks a breaking change (add a `BREAKING CHANGE:` footer) |
| `description` | imperative, lowercase, no trailing period, whole subject ≤ 100 chars |
| `description` | starts with a lowercase letter (Unicode-aware), imperative, no trailing period, whole subject ≤ 100 chars |

Valid examples:

Expand All @@ -82,12 +83,17 @@ Invalid examples (CI will reject):
```
update stuff
Fix: Some Thing.
feat: ✨ add sparkles # must start with a lowercase letter
feat: 修正 bug # caseless/uppercase first letters are rejected
feat: Add a very long subject ...
feature(gateway): unsupported type
```

Merge commits created by GitHub are skipped by the linter; squash merges use the PR title,
which is why the title must follow the same format.
Real merge commits are excluded via `git log --no-merges`; a normal commit whose subject merely starts with
`Merge ` is still linted. `fixup!`/`squash!`/`amend!` and `Revert "…"`/`Initial commit` subjects are skipped
because tooling generates them. The linter fails when an explicitly supplied base/head range contains zero
commits (an empty check must not pass), and CI lints pushes to `main` in addition to pull requests. Squash
merges use the PR title, which is why the title must follow the same format.

Optional local helper:

Expand All @@ -107,6 +113,7 @@ pull request that passes the required checks.
```bash
pnpm typecheck
pnpm test
pnpm check:docs
pnpm build
pnpm test:e2e
```
Expand All @@ -116,13 +123,14 @@ pull request that passes the required checks.
gh pr create --fill
```
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 end-to-end acceptance suite
- **Commit messages** — Conventional Commits validation (commits + PR title; also linted on pushes to `main`)
- **Lint & test** — typecheck, unit tests and the `pnpm check:docs` drift check
- **Build & e2e** — production build, `dist/` boot smoke test and 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
update `docs/SPEC.md` and call the change out in the PR description.
update `docs/SPEC.md` and call the change out in the PR description. New env vars, routes or
`DEFAULT_SETTINGS` keys must be documented or `pnpm check:docs` fails — fix the docs, never the checker.

## Reporting bugs / requesting features

Expand Down
51 changes: 31 additions & 20 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -40,12 +40,16 @@ client (OpenAI SDK / Anthropic SDK / curl) ──▶ OpenCode Router :20125 ─
`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`).
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, Providers,
Models, Logs, Settings. Dark/light, Inter, Lucide, glassmorphism.
- **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
Expand Down Expand Up @@ -91,8 +95,8 @@ enabled provider, one enabled model *and* one API key exist (the dashboard shows

[.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**.
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

Expand Down Expand Up @@ -143,9 +147,11 @@ curl http://127.0.0.1:20125/v1/messages \
curl http://127.0.0.1:20125/v1/models -H "Authorization: Bearer okr-..."
```

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.
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](docs/API.md) for the full gateway reference and [docs/SPEC.md](docs/SPEC.md) for the
dashboard/admin API contract.
Expand All @@ -171,25 +177,29 @@ scripts/e2e.ts full end-to-end acceptance run
## Verification

```bash
pnpm typecheck # server + dashboard type checks
pnpm test # vitest unit suite (crypto, repos, stats, SSE, normalization)
pnpm typecheck # server + dashboard + tests/scripts type checks
pnpm test # vitest unit suite (crypto, repos, stats, SSE, normalization, tooling)
pnpm check:docs # doc-drift checker (env vars, routes, settings vs docs/SPEC.md + docs/API.md)
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 test:live # smoke-tests a real provider (skips when it answers 429)
pnpm build # dist/ + web/dist/
pnpm exec tsx scripts/screenshots.ts # headless Chrome UI check + PNG screenshots (macOS; SKIPs without Chrome)
pnpm exec tsx scripts/screenshots.ts --strict # headless Chrome UI check + PNG screenshots
```

`pnpm test:e2e` is self-contained: it starts two deterministic mock upstreams that mimic the reference
provider (OpenAI + Anthropic surfaces, streaming, tools, vision, reasoning, injectable 429s) and verifies
routing, rotation, failover, logging, admin APIs, dashboard routing and the built dashboard shell.
`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`; the ports are overridable with `E2E_PORT`, `E2E_MOCK_A_PORT` and `E2E_MOCK_B_PORT`.

`pnpm test:live` talks to a real provider (`LIVE_UPSTREAM`, default `http://127.0.0.1:20123/v1`); when the
provider answers `429` every probe is reported as **SKIP** instead of failing.
`pnpm test:live` talks to a real provider (`LIVE_UPSTREAM`, default `http://127.0.0.1:20123/v1`, plus
`LIVE_KEY`, `LIVE_MODEL`, `LIVE_VISION_MODEL`, `LIVE_PORT`); 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); 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.
(`CHROME_PATH`, defaulting to the macOS Chrome path); without one the script prints `SKIP` and exits 0, so
CI-invoked runs use `--strict`, which fails instead of skipping. CI does not run the UI check.

## Contributing

Expand All @@ -199,6 +209,7 @@ wait for the required checks (`Commit messages`, `Lint & test`, `Build & e2e`) b

```bash
pnpm lint:commits # validate your branch's commits locally
pnpm check:docs # env vars / routes / settings vs docs/SPEC.md + docs/API.md
node scripts/check-commit-messages.mjs origin/main HEAD "feat(gateway): example"
```

Expand Down
Loading
Loading