Multi-provider LLM gateway. Node.js + Fastify + TypeScript + pnpm. Default port 20125.
Serves OpenAI-compatible (/v1/chat/completions, /v1/responses), Anthropic-compatible (/v1/messages)
and a premium glassmorphism dashboard with mandatory login (default password 123456).
src/types.ts, src/db/schema.ts, src/db/repos.ts, src/core/*, src/util/*, src/server.ts
and src/index.ts are the shared contract between the DB layer, the gateway and the admin API.
Changing them requires updating this file in the same PR, re-running the full verification suite
(pnpm verify) and calling the change out in the PR description. See AGENTS.md for the golden
rules (pass-through fidelity, one log row per client request, secrets never leave the server,
mandatory auth) and CONTRIBUTING.md for the workflow.
// src/core/context.ts
interface AppContext {
config: AppConfig; // host, port, dataDir, dbPath, logLevel, bodyLimit, sessionTtlMs, webDistDir,
// publicUrl, trustProxy, providerAllowPrivateHosts, defaultDashboardPassword, secret
db: { db: DatabaseSync; secret: string };
repo: Repo; // src/db/repos.ts
events: EventBus; // src/core/events.ts
logger: FastifyBaseLogger;
startedAt: number;
}
incActiveRequests(); decActiveRequests(); getActiveRequests();Repo methods (all already implemented): getSetting/setSetting/getBool/getInt/allSettings,
listProviders/getProvider/createProvider/updateProvider/deleteProvider/deleteProviderWithModels/recordProviderSuccess/recordProviderFailure,
listModels/getModel/upsertModel/updateModel/deleteModel/deleteAllModels/enabledModelIds/hasEnabledModel/setModelsEnabled/deleteModels/deleteModelsByProvider,
listApiKeys/hasActiveApiKey/countActiveApiKeys/createApiKey/getApiKey/findApiKeyByPlaintext/updateApiKey/rotateApiKey/deleteApiKey/touchApiKey,
insertLog/insertAttempt/listAttempts/getLog/listLogs/deleteLogsBefore/clearLogs/statsOverview,
createSession/getSession/touchSession/deleteSession/deleteAllSessions/deleteOtherSessions/purgeExpiredSessions/listSessions,
audit/listAudit/deleteAuditBefore/tableCounts/transaction.
upsertModel(input, known?) accepts the already-loaded row (provider sync is not N+1);
transaction(fn) runs fn inside one SQLite transaction and is re-entrant (nested calls join it).
deleteLogsBefore(ts) and clearLogs() delete request_logs and request_attempts inside one transaction
and return the request_logs row count. statsOverview computes p50/p95 from one ordered pass over the
window's non-null latencies (one windowed statement per call). Repo.recordProviderFailure never shortens an
active cooldown.
src/db/schema.ts is applied idempotently on every boot (via openDatabase) and sets
PRAGMA journal_mode = WAL, PRAGMA foreign_keys = ON and PRAGMA busy_timeout = 5000, so a second connection
(dashboard, script or a second server on one data dir) waits for the write lock instead of surfacing
SQLITE_BUSY as 500 internal_error. openDatabase additionally stamps PRAGMA user_version with
SCHEMA_VERSION (currently 1, exported from the schema module and bumped on every migration) only when it
differs, so the boot script stays lock-free for an already-initialized file while
/admin/api/diagnostics can report a data file written by a different build.
Settings keys with defaults: dashboard_password_hash, rotation_strategy (round-robin),
max_retries (3), provider_cooldown_ms (60000), request_timeout_ms (600000),
auto_sync_models (true), model_sync_interval_ms (300000), log_retention_days (30),
audit_retention_days (90), model_allow_unknown (false), upstream_user_agent (opencode-router/1.0),
stream_idle_timeout_ms (120000), upstream_response_max_bytes (0).
upstream_response_max_bytes caps a buffered (non-streaming) upstream response body: 0 means unlimited
(the default) and any other value must be 1024…1073741824. A larger body aborts the request with
502 upstream_response_too_large. Streaming responses are never buffered and are unaffected.
Environment variables (src/config.ts unless noted):
| 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 |
DASHBOARD_PASSWORD |
123456 |
Only used when the password hash is first created |
ROUTER_SECRET |
<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 |
WEB_DIST_DIR |
<repo>/web/dist |
Directory served as the dashboard build |
PUBLIC_URL |
unset | Absolute public base URL; an https:// value also forces Secure session cookies |
TRUST_PROXY |
false |
Trust X-Forwarded-* for request.ip, client_ip logging and the Secure cookie decision |
PROVIDER_ALLOW_PRIVATE_HOSTS |
false |
Allow provider test/sync to reach loopback/link-local/private hosts (SSRF guard off) |
NODE_ENV |
development |
Read by src/server.ts: production disables the pretty logger and keeps JSON logs |
Booting with the shipped default dashboard password (123456) logs a one-line warning; it never blocks
startup. Set DASHBOARD_PASSWORD before the first run, or change it in Settings → Security.
Helpers: src/util/crypto.ts (hashPassword, verifyPassword, hmacSign, generateApiKey, uuid, randomHex, sha256Hex, safeEqual),
src/util/errors.ts (ApiError, errorTypeForStatus, isRetryableStatus, upstreamErrorFrom),
src/util/upstream.ts (upstreamFetch, joinUrl, readJsonBody),
src/util/sse.ts (SseParser, formatSseFrame, formatSseJson),
src/util/models.ts (normalizeProviderModel, extractModels, resolveEffort, EFFORT_LEVELS).
src/index.ts calls registerGatewayRoutes(app, ctx), registerAdminRoutes(app, ctx) and
startScheduler(ctx) — these MUST be exported exactly as named:
src/gateway/index.ts→export async function registerGatewayRoutes(app: FastifyInstance, ctx: AppContext): Promise<void>src/admin/index.ts→export async function registerAdminRoutes(app: FastifyInstance, ctx: AppContext): Promise<void>src/admin/scheduler.ts→export function startScheduler(ctx: AppContext): () => void
Gateway API key required for every /v1/* request except GET /v1/models? No — every /v1/*
request requires a key. Accepted headers: Authorization: Bearer <token> or x-api-key: <token>.
Any other Authorization scheme (for example Basic …) counts as no credential → 401 missing_api_key.
Authentication runs in a gateway onRequest hook before the body is parsed: unauthenticated requests
are rejected without reading or buffering the body and still produce exactly one request_logs row plus a
paired request:start/request:end event pair.
request.ip is the socket address unless TRUST_PROXY is configured, so the admin login brute-force guard
and client_ip logs cannot be spoofed with X-Forwarded-For by default.
- No active API key exists at all →
401invalid_api_key-shaped error, codeno_api_key_configured, messageNo gateway API key configured. Create one in the dashboard (API Keys tab). - Key present but unknown/disabled/revoked →
401, codeinvalid_api_key. - Missing header (or a non-Bearer scheme) →
401, codemissing_api_key. On success callctx.repo.touchApiKey(key.id).
Unknown /v1/* paths (and bare /v1) are not handled by the root not-found handler: an authenticated
catch-all inside the gateway scope requires a key, writes exactly one request_logs row/event pair and
answers 404 code unknown_endpoint in the surface-appropriate error shape.
No enabled provider, or zero enabled models → 503 api_error code no_provider_configured
(resp. no_models_configured), message explaining what to configure in the dashboard.
| Route | Notes |
|---|---|
POST /v1/chat/completions |
OpenAI Chat Completions, stream + non-stream, tools, vision, reasoning_effort |
POST /v1/responses |
OpenAI Responses API, stream + non-stream |
POST /v1/messages |
Anthropic Messages, stream + non-stream |
POST /v1/messages/count_tokens |
pass-through |
GET /v1/models |
OpenAI list built from enabled DB models (see §2.4) |
GET /v1/models/:id |
single model or 404 model_not_found |
ALL /v1, ALL /v1/* |
authenticated catch-all for unknown endpoints (see § Auth) |
onRequesthook: authenticate the key (§ Auth) and emitrequest:start; a rejection here writes onerequest_logsrow and never reads the body.- Parse JSON body (invalid JSON →
400 invalid_request_error). modelrequired → else400codemodel_required.- Model must exist and be enabled in DB unless
model_allow_unknown=true→ else404model_not_foundwith message listing how to add it. - Normalize reasoning effort (§2.3) and, for chat streaming, ensure usage is reported; keep the raw client
bytes so they can be forwarded unchanged. The normalized/trimmed
modelid is written back into the forwarded body. - Select provider order (§2.2) and attempt the upstream call as a pass-through to the same surface:
POST {provider.baseUrl}/chat/completions//responses//messages//messages/count_tokenswith the provider's API key in bothAuthorization: Bearerandx-api-key. The client's raw query string is forwarded unchanged (POST /v1/messages?beta=truereaches the upstream with?beta=true), and a providerbaseUrlthat already carries a query string keeps it. The body is forwarded byte-for-byte (raw bytes captured withparseAs: 'buffer', so invalid UTF-8 survives) whenever step 5 changed nothing, else as the normalized JSON. Client headers pass through an allowlist (anthropic-beta,anthropic-version,anthropic-dangerous-direct-browser-access,openai-beta,openai-organization,openai-project,http-referer,x-title,x-stainless-*,accept,accept-language, trace headers); auth/host/content-length/connection always come from the router.anthropic-version: 2023-06-01is only defaulted for themessages/count_tokenssurfaces; a streaming request with no/wildcardacceptis forwarded astext/event-stream. - Never follow upstream redirects (
redirect: 'manual'): any3xxis a fatal upstream error (502 upstream_redirect, single attempt, provider cooled down, the provider key is never replayed). - Retry with the next provider when the attempt fails with a retryable status (
isRetryableStatus:408,409,425,429, every5xxincluding529) or a network/timeoutApiError, up tomax_retriesattempts total. A timed-out provider is logged as a real attempt, put into cooldown and failed over like any other retryable failure; the aggregated504 upstream_timeoutis only returned after every candidate is exhausted, and the log row/attempts are attributed to the provider that timed out. Any terminal failure reached after at least one real upstream call is attributed to the last attempted provider (provider_id/provider_namein the log row plus thex-opencode-router-*headers below); only pre-attempt rejections carry the request id alone. - Log the request (§2.6) exactly once per client request —
GET /v1/models*included — and log every attempt viainsertAttempt(timed-out attempts included). - A
2xxupstream whose body cannot be read (truncated/RST) is reported as502 upstream_body_failed(the upstream status is kept when it is already ≥ 400; a timeout stays504 upstream_timeout). A streaming body that exceeds the unterminated-frame cap aborts with502 upstream_frame_too_large; a buffered body that exceedsupstream_response_max_bytesaborts with502 upstream_response_too_large. - A request that exceeds
BODY_LIMITis rejected with413, codepayload_too_large(the Fastify internalFST_ERR_*code is never exposed). - A known
/v1/*path called with an unsupported method answers405with anAllowheader listing the supported methods; unknown paths keep404 unknown_endpoint. Both write exactly onerequest_logsrow.
Strip provider-internal top-level x_opencode keys from JSON responses (non-stream body, and each
SSE data: JSON payload when it parses). Everything else must be forwarded byte-for-byte, including
tool calls, images/files/audio/video content parts and Anthropic thinking blocks.
Response headers: x-opencode-router-request-id on every /v1/* response; on proxied/failed-attempt
responses also x-opencode-router-provider: <id>, x-opencode-router-name: <display name> and
x-opencode-router-attempts: <n>. Every terminal proxied failure (all_providers_failed,
all_providers_rate_limited, upstream_timeout, upstream_response_too_large,
invalid_provider_credentials) keeps all three headers, attributed to the last attempted provider;
errors raised before an attempt (auth, routing, validation) carry the request id only. Provider ids/names
are sanitized before they reach a header, and a provider id/name/baseUrl or upstream_user_agent containing
control characters is rejected at the admin API (400). A provider key that cannot be encoded as an HTTP
header value fails the attempt with 502 invalid_provider_credentials, and the key never appears in the
message.
Upstream response headers relayed to the client: retry-after, request-id, x-request-id,
openai-processing-ms, openai-version, anthropic-version, x-ratelimit-*, anthropic-ratelimit-*
and x-stainless-*; router headers, content-type and content-length win, and content-encoding is
never forwarded. 429 all_providers_rate_limited carries Retry-After (whole seconds, min 1) plus
x-opencode-router-cooldown-until (epoch ms).
rotation_strategyselects the order:round-robin(default, in-memory cursor advanced per request),priority(stablepriorityasc thencreated_atasc, cursor unused) orrandom(shuffled candidates).- Candidate set: enabled providers, ordered by
priorityasc thencreated_atasc. - Maintain an in-memory round-robin cursor; each request starts at the next provider (round-robin only).
- Skip providers whose
cooldown_until > now. - If every candidate is cooling down, fall back to the candidate with the smallest
cooldown_untilso requests still have a chance (prevents total outage). - Attempts iterate the rotated list; a provider is tried at most once per request.
- Providers skipped because of an active cooldown produce no
request_attemptsrow, andattempts/x-opencode-router-attemptscount real upstream calls only. - Fatal (non-retryable) upstream failures are attributed to the provider that answered, so the log row and the router headers are populated even though the request failed.
- On success:
recordProviderSuccess(id, latencyMs). - On retryable failure (incl.
409):recordProviderFailure(id, status, message, cooldownMs)+events.emitProvider. A cooldown is recorded for a network failure (no status),408/409/425,429,503,529, any other5xx, and any3xx; the providerstatuscolumn stayscooldownonly for429/503/529/5xx. The storedcooldown_untilis monotonic: a later failure with a shorter cooldown never lowers an active longer one, so aRetry-Afterback-off cannot be cut short by a subsequent quick failure. - An upstream
retry-after(delta seconds or HTTP-date) is capped at one hour, so a hostile or broken upstream cannot pin a provider in cooldown indefinitely. - A timed-out attempt is recorded (log row +
request_attempts), cools the provider down and fails over, exactly like any other retryable failure. - On non-retryable failure (400/401/403/404/422): stop immediately and return the upstream error
(mapped through
upstreamErrorFrom) — do not burn other providers on a client error. - All attempts exhausted → response status of the last attempt (or
502for network errors), codeall_providers_failed; if every failure was 429 use429+ codeall_providers_rate_limited(withRetry-After); if every failure was a timeout use504+ codeupstream_timeout. - Increment/decrement
incActiveRequests()/decActiveRequests()once around the whole client request, for every gateway route (GET /v1/models*and pre-attempt rejections included), so the dashboard's active-request counter matches the requests actually in flight.
- chat:
body.reasoning_effort - responses:
body.reasoning.effort - messages:
body.thinking({type:'enabled',budget_tokens}) — pass through untouched; for logging map budget → nearest effort (budget <= 1024low,<= 4096medium,<= 16384high, else max). - If the resolved model has
reasoning.supported === false: remove the reasoning hint from the upstream body (reasoning_effort,reasoning,thinking) — providers reject unknown reasoning on non-reasoning models. - If supported: replace the requested value with
resolveEffort(requested, model.reasoning.efforts); when the client sent none and the model has adefaultEffort, keep it unset (provider default) — do not invent an effort unless the client asked for one. - Expose reasoning metadata in
GET /v1/models.
{"object":"list","data":[{"id":"opencode/flint-40b-free","object":"model","created":1760659200,
"owned_by":"opencode-router","name":"Flint 40B Free","context_length":262144,"max_output_tokens":65536,
"capabilities":{"tools":true,"input":["text","image"],"output":["text"],"temperature":true},
"reasoning":{"supported":true,"efforts":["low","medium","high","xhigh","max"],"default_effort":"medium"},
"status":"active","enabled":true}]}Disabled models are omitted; empty DB → {"object":"list","data":[]}.
Forward SSE frames as they arrive (flush per frame, Content-Type: text/event-stream,
Cache-Control: no-cache, Connection: keep-alive, X-Accel-Buffering: no). Forward the original bytes:
a frame is decoded only to detect x_opencode / parse usage and re-encoded only when it is actually
rewritten, so invalid UTF-8 and a leading BOM reach the client unchanged. Every blank-line frame boundary is
recognized (\n\n, \r\n\r\n, \r\n\n, \n\r\n, \r\r), and a frame with several data: lines is decoded as
one payload so a multi-line x_opencode object is stripped too. request_timeout_ms is a real
total deadline that covers the streamed body; stream_idle_timeout_ms (default 120000, min 1000) is the
idle gap between reads/drain waits, so a stalled upstream cannot hang the request. An unterminated SSE
frame is capped at 1 MiB: on breach the upstream is aborted, the log row gets upstream_frame_too_large
with status 502.
While forwarding, feed bytes through SseParser to extract usage:
- chat: last chunk
usage(also addstream_options.include_usage = truewhen the client did not set it; the gateway never fabricates a usage frame the upstream did not send) - responses:
response.completed→response.usage - messages:
message_delta→usage(input_tokens/output_tokens,cache_read_input_tokens) Recordttfb_ms(time to first byte) on the log row. Handle client aborts without crashing (destroy the upstream body, log withok=false, codeclient_aborted, status499). An idle gap or the total deadline aborts the upstream:504+ codeupstream_timeoutwhile the response is still unsent, or a504status on the already-flushed stream. Retryable failures honour an upstreamretry-afterheader (delta seconds or HTTP-date): the cooldown becomesmax(provider_cooldown_ms, retryAfter)withretryAfterclamped to one hour (MAX_RETRY_AFTER_MS). With a non-zeroupstream_response_max_bytes, a buffered non-streaming body over the cap aborts with502 upstream_response_too_large;0is unlimited and streaming is never buffered.
One request_logs row per client request — GET /v1/models and GET /v1/models/:id included, logged with
the OpenAI (chat) surface — with:
id (uuid), ts, key_id, key_name,
provider_id/provider_name (winning provider), model, surface, stream, status, ok,
error_code, error_message, latency_ms, ttfb_ms, token fields, attempts, client_ip, user_agent.
Emit ctx.events.emitRequestStart(...) right after auth and ctx.events.emitRequestEnd({log}) at the end.
Event emission is guarded: a throwing dashboard/SSE listener is logged as a warning and can never fail the
request. Upstream error messages redact URL userinfo and query strings, are stripped of control characters,
clamped to 500 characters and additionally scrubbed of the provider credential and any Bearer …/sk-…/
x-api-key-shaped token, so provider credentials never reach request_logs.error_message,
providers.last_error or a client-visible error body. An upstream error type that is not a known
gateway error type is recorded as api_error.
- Session cookie
okr_session="<sid>.<expiresAt>.<hmac>"wherehmac = hmacSign(ctx.db.secret, "<sid>.<expiresAt>"); store the session row (ctx.repo.createSession), verify the signature, the in-cookieexpiresAt(an already-expired cookie is rejected before any DB lookup) and the DB row + expiry. Cookie flags:httpOnly,sameSite: 'lax',path: '/',maxAge=sessionTtlMs/1000,securewhen the request is https (request.protocol, anx-forwarded-proto: httpsthat is only honoured whenTRUST_PROXYis enabled, orPUBLIC_URLstarting withhttps://). - Public endpoints:
POST /admin/api/login,POST /admin/api/logout,GET /admin/api/session./loginand/settings/passwordaccept at most 4096 bytes (413above it) and reject passwords longer than 200 characters with400. - Every other
/admin/api/*route requires a valid session → else401 {error:{message,code:'unauthorized'}}. Session-authenticated mutating requests (POST/PUT/PATCH/DELETE) are additionally CSRF-guarded: a presentOriginheader whose host differs from the request host (or from thePUBLIC_URLhost when that is configured), orSec-Fetch-Site: cross-site, is rejected with403 cross_site_requestbefore any state change. Requests without those headers (CLI, the e2e suite, same-origin navigation) are unaffected, and the publicPOST /admin/api/loginis never gated by this check. POST /admin/api/login {password}: verify withverifyDashboardPassword(src/core/seed.ts); brute-force guard: max 10 failed attempts per IP and 500 failed attempts per process per 5 minutes →429withRetry-After(seconds) and{error:{code:'too_many_attempts',retryAfter}}; on success create session,repo.audit(...), return{ok:true, expiresAt}. The per-IP limit is the primary defence; the higher process-wide limit only bounds a distributed attack, so a single attacker cannot lock the operator out of the dashboard cheaply.POST /admin/api/logoutclears the cookie + deletes the session row.GET /admin/api/session→{authenticated, expiresAt?, version:'1.0.0', uptimeMs, startedAt}(never 401).HttpErrormessages are returned to the client as-is, including5xx; only unexpected errors are masked as500 internal_error(with driver/stack detail kept server-side).
Bootstrap / stats
GET /admin/api/bootstrap→{version, uptimeMs, startedAt, gatewayReady, hasProviders, hasApiKeys, hasModels, providerCount, modelCount, keyCount, syncedAt, syncProviderId, activeRequests, settings}.GET /admin/api/stats?window=1h|6h|24h|7d|30d→Repo.statsOverview(...)output (including exactrequestsLast60s/errorsLast60scounts andactiveRequests) plus{health:{status,activeRequests,providers:[{id,name,status,enabled,cooldownUntil,lastLatencyMs,successCount,failureCount,lastError,lastCheckedAt}], modelsEnabled, keysActive}, window}.activeRequestsis snapshotted once per request, so the (possibly cached) aggregate body andhealth.activeRequestsalways agree within one response.GET /admin/api/events(SSE) → emitsrequest:start,request:end,provider:update, plus astatsheartbeat every 5s with{activeRequests, requestsLast60s, errorsLast60s}. Writes apply per-client backpressure (bounded queue +drainresume; the stream is ended after repeated stalls). The session row is re-validated on every heartbeat and the stream is closed when the session disappears or expires; at most 32 concurrent streams are allowed, above that the endpoint answers503 too_many_streams.GET /admin/api/statsis served from a short (~2s) TTL cache.GET /admin/api/activity?limit=20→ merged recent log rows + provider state changes.limitis validated like the logs route (1..500; a non-integer or out-of-range value is400 invalid_request).GET /admin/api/diagnostics→ self-check report:{scheduler:{running,lastSyncAt,lastSyncError,nextSyncInMs,lastRecoveryAt}, storage:{dbPath,walSizeBytes,dbSizeBytes,busyTimeoutMs,logRows,attemptRows,sessionRows,oldestLogTs}, checks:[{id,status:'ok'|'warn'|'fail',detail}]}. Check ids:password.default(warn while the shipped default password is in use),providers.enabled,keys.active,models.enabled,version.schema(PRAGMA user_versionvsSCHEMA_VERSIONand the presence of every expected table),clock.skew(newest log/audit timestamp more than 60 s in the future) andproviders.cooldown.scheduler.nextSyncInMsisnullwhen the scheduler is stopped orauto_sync_models=false. Session-protected like every other/admin/api/*route. Every read it performs is guarded, so a database missing a table still yields a report (withversion.schema=warn) instead of a500— that is the situation the endpoint exists to diagnose.
Providers
GET /admin/api/providers→{providers:[{id,name,baseUrl,apiKeyMasked,hasApiKey,enabled,priority,status,cooldownUntil,lastError,lastCheckedAt,lastLatencyMs,successCount,failureCount,createdAt,updatedAt}]}(never return the raw key).apiKeyMaskedreveals at most 4 characters and is****for keys shorter than 12 characters.POST /admin/api/providers {id?, name, baseUrl, apiKey, enabled?, priority?}→{provider}(validate: name and baseUrl required, baseUrl must start with http:// or https://, apiKey required;id/name/baseUrlreject control characters,baseUrlrejects userinfo).apiKeymust additionally be a non-empty printable ASCII string (0x20–0x7E) of at most 4096 characters (control characters, NUL/CR/LF and other byte ranges that would make an HTTP header value invalid are rejected with400 invalid_request, without echoing the submitted value).PATCH /admin/api/providers/:id {name?, baseUrl?, apiKey?, enabled?, priority?}→{provider}. ChangingbaseUrl,apiKeyorenabledresetsstatus='unknown'andcooldownUntil=null.DELETE /admin/api/providers/:id→{ok:true, modelsRemoved}— the provider's synced models are removed and amodels_sync_provider_idpointing at it is cleared, all in the same transaction.POST /admin/api/providers/:id/test→{ok, status, latencyMs, models:number, error:null|string}(GET{baseUrl}/models). A failed test updates the provider's status/failure counters/lastErrorand emitsprovider:update, exactly like a gateway failure. The detailed upstream error text kept for the server log is scrubbed of the provider credential (A-05 policy), so a provider echoing the request cannot leak its key into a log line,providers.last_erroror a client-visible body.POST /admin/api/providers/test {baseUrl, apiKey?, id?}→ same shape, before saving. WhenapiKeyis omitted andidnames a stored provider, the stored key is reused only when the draftbaseUrlorigin equals the stored provider's origin (otherwise400 api_key_required);404for an unknownid,400when neither is given.POST /admin/api/providers/:id/sync-models→{added, updated, removed, total, providerId, syncedAt}. Test and sync (routes + scheduler) resolve the URL and refuse loopback/link-local/private hosts unlessPROVIDER_ALLOW_PRIVATE_HOSTS=true(SSRF guard).
Models
GET /admin/api/models→{models:[ModelRow...], syncedAt, syncProviderId, providers:[{id,name}]}.POST /admin/api/models {id, name?, contextLength?, maxOutputTokens?, capabilities?, reasoning?, enabled?}→{model}(sourcemanual;409when the id exists).PATCH /admin/api/models/:id {...}→{model}.DELETE /admin/api/models/:id→{ok:true}.POST /admin/api/models/bulk {action:'enable'|'disable'|'delete', ids:[...]}→{updated};idsis capped at 1000 entries (400above) and the action is applied as one set-based statement inside a transaction.POST /admin/api/models/sync {providerId?}→ per-provider result{added, updated, removed, total, providerId, syncedAt}plus an additiveproviders:[{providerId,providerName,ok,added,updated,removed,total,latencyMs,error,warning}]listing every provider that was synced. WithoutproviderIdevery enabled provider is synced (one transaction per provider, so one failure does not abort the others) and the top-level counters are the sum; withproviderIdonly that provider is synced.400when no provider exists. Sync semantics: upsert every model reported upstream withsource='sync',providerId, and delete rows withsource='sync'from that provider that no longer exist upstream. Manual rows are never deleted. Asource='sync'row already owned by a different provider is neither re-attributed nor deleted by this provider's sync (only its owner's sync garbage-collects it). A2xxresponse whose body does not contain a recognizable model array (for example{}or an HTML error page) is treated as a skipped sync: no row is deleted andmodels_synced_atis not advanced, and the result carrieswarning: 'Upstream returned no recognizable model list; the synced catalog was left unchanged'(alsoproviders[].warning); hard failures such as a network error or a non-2xx status keepproviders[].error. An explicit empty array ({"data":[]}) is a legitimate empty catalog and prunes. A successful per-provider round-trip refreshes that provider's health counters (recordProviderSuccess) and emitsprovider:update, exactly like the single-provider branch; a skipped (unrecognized) catalog does neither. Recordmodels_synced_at+models_sync_provider_idin settings for the single-provider case.
API keys
GET /admin/api/keys→{keys:[{id,name,prefix,suffix,enabled,requestCount,lastUsedAt,createdAt,revokedAt}]}.POST /admin/api/keys {name}→{key, plaintext}— plaintext returned once.PATCH /admin/api/keys/:id {name?, enabled?}→{key}.POST /admin/api/keys/:id/revoke→{key}(setsrevokedAt, disables).POST /admin/api/keys/:id/rotate→{key, plaintext}— replaces the stored hash with a new plaintext (returned exactly once) while keeping the id, name and request counters;404 key_not_foundfor unknown ids.DELETE /admin/api/keys/:id→{ok:true};404 key_not_foundfor unknown ids.
Logs
GET /admin/api/logs?limit&offset&surface&model&providerId&keyId&ok&stream&search&since&until→{logs:[...], total, limit, offset}.modelis a case-insensitive contains match (the dashboard labels it "Model contains");%and_in the value are matched literally.searchis a substring scan overmodel/key_name/provider_name/error_message; a term longer than 200 characters is rejected with400 invalid_requestat the route (the repository layer additionally truncates as defence in depth).since/untilaccept epoch milliseconds or an ISO date and must be finite and in range (400 invalid_requestotherwise).GET /admin/api/logs/:id→{log, attempts:[...]}(404when missing).DELETE /admin/api/logs→{ok:true, removed};POST /admin/api/logs/prune {days}→{removed}.GET /admin/api/logs/export?format=json|csv→ file download of the current filter. Exports are capped at 500 rows; when the cap truncates the result the response carriesX-Export-Truncated. CSV cells starting with a formula trigger (=,+,-,@, tab, CR) are prefixed with'before quoting.
Settings
GET /admin/api/settings→{settings, passwordSet, sessions:[{id,createdAt,expiresAt,lastSeenAt,clientIp,userAgent,current}], dbPath, dataDir, version, uptimeMs, counts}(sessionslists at most the 50 newest sessions;passwordSetreports whether a dashboard password hash exists).PATCH /admin/api/settings {..known keys..}→{settings, changed, ignored}. Every entry is validated first and valid ones are applied in one transaction, so one bad value changes nothing. Unknown keys — inherited object properties such asconstructorincluded — are reported asignored;log_store_bodiesno longer exists and is also reported asignored. Ranges includeaudit_retention_days1..3650,stream_idle_timeout_ms1000..3600000 andupstream_response_max_bytesexactly0or 1024..1073741824;upstream_user_agentrejects control characters.POST /admin/api/settings/password {currentPassword, newPassword}→{ok:true}(400wrong current,400when shorter than 4 chars); invalidates all other sessions.DELETE /admin/api/settings/sessions→{ok:true, revoked}(revokes every other session, not just the 50 newest; keeps the current session).DELETE /admin/api/settings/sessions/:id→{ok:true, revoked:1}for one session by id;400 cannot_revoke_currentfor the caller's own session and404 session_not_foundotherwise.POST /admin/api/settings/rotate-secret→{ok:true, secret}— refuse with409 secret_from_envwhenROUTER_SECRETis set, because the environment value would win on the next restart. Otherwise generate a new secret, persist it to<dataDir>/.secretbefore swapping the in-memoryctx.db.secret, then invalidate all dashboard sessions and return the new secret so the operator can store it (response carriescache-control: no-store). Gateway key hashes are sha256 of the plaintext, so existing keys keep working.GET /admin/api/audit?limit=100→{items:[...]}(limitrange1..500, validated like the logs route).- Audit every mutating admin action with
repo.audit(actor, action, target, detail): the actor issession:<id>on session-protected routes (ordashboardon public routes) and the client IP is recorded in the detail. Audit rows are pruned byaudit_retention_days, not bylog_retention_days.
startScheduler(ctx) returns a stop function. It:
- every
model_sync_interval_ms(min 30s) syncs models whenauto_sync_models=trueand an enabled provider exists (all enabled providers, see §3 Models); - probes providers whose cooldown is active and clears the cooldown when the probe succeeds; at most 3 probes run per tick and an in-memory cursor (reset on process restart) rotates through the cooling-down set, so providers beyond the first three are not starved. Probes go through the same SSRF guard as the admin test/sync routes;
- purges expired sessions every 10 minutes;
- never throws out of the interval callback (log warnings instead);
- does not start timers that keep the process alive (
unref()).
Vite + React 19 + TypeScript + Tailwind CSS v4 (@tailwindcss/vite), lucide-react icons,
@fontsource-variable/inter font, react-router-dom for routes. Build output MUST be web/dist
(so use build.outDir = 'dist', root = web, base = '/'). Dev server proxies /admin and /v1
to http://127.0.0.1:20125.
Files to create: web/index.html, web/vite.config.ts, web/tsconfig.json, web/src/main.tsx,
web/src/App.tsx, web/src/styles.css, web/src/lib/api.ts, web/src/lib/format.ts,
web/src/lib/theme.ts, web/src/components/**, web/src/pages/**.
The built JS/CSS/font bundles are served from GET /assets/* (path-contained inside web/dist).
Routes: / → always 302 to /dashboard, which redirects to /login when there is no valid session;
/login; /dashboard/overview, /dashboard/keys, /dashboard/providers, /dashboard/models,
/dashboard/logs, /dashboard/settings. /index.html is never served directly by the static handler:
every shell path (/, /login, /dashboard*, /index.html, any unknown path) goes through the
server-side session gate first.
- Palette: pure black/white/neutral only. Accent = white (dark mode) / black (light mode) with subtle neutral glow; status colors limited to emerald (ok), amber (warn), rose (error).
- Glassmorphism: frosted panels
backdrop-blur-xl, translucent surfaces, 1px hairline borders (border-white/10dark,border-black/5light), layered depth shadows, inner top highlight. - Ambient background: fixed radial gradient mesh + fine noise/grid overlay, slow drift animation.
- Typography: Inter Variable; tabular-nums for all numbers; tight tracking on headings; clear hierarchy.
- Motion: 150–250ms ease transitions, hover lift on cards, animated number counters, skeleton shimmer,
staggered list entrance. Respect
prefers-reduced-motion. - Light/dark toggle persisted in
localStorage(okr-theme), default dark, applied via.darkclass on<html>; Tailwind v4 dark variant wired with@custom-variant dark (&:where(.dark, .dark *)). - Custom SVG charts (area/line/donut/bars) — no chart dependency. Gradient fills, hover tooltips.
- Tables: sticky header, hover row highlight, monospace ids with copy-to-clipboard, status badges, empty states with icon + hint, pagination.
- Forms in centered glass modals; inline validation; toasts for success/error.
- Login page: centered glass card, animated background, password field with show/hide, error shake.
lib/api.ts:fetchwrapper withcredentials:'include', JSON helpers, typed responses, automatic redirect to/loginon401, error extraction{error:{message,code}}.- Overview: KPI cards (requests, success rate, tokens, avg latency), live area chart of requests/min from
/admin/api/events+/admin/api/stats, active-requests pulse, provider health list, top models, recent errors, surface split. Auto-refresh every 5s; SSE when available. - API Keys: table + create modal showing the plaintext key once with a copy button and warning, enable/disable, revoke, delete, per-key request counts.
- Providers: card/table list with status pill, cooldown countdown, latency, success/failure counters, add/edit modal (id, name, baseUrl, apiKey, priority, enabled), test connection, test-before-save, sync models, delete confirm.
- Models: search + filter, bulk enable/disable/delete, manual add modal (id, name, context, max output, capabilities toggles, reasoning efforts multi-select), sync button with provider picker, shows sync time.
- Logs: filter bar (surface/model/provider/status/stream/search/time range), live tail toggle, paginated table, row detail drawer with attempts timeline, export JSON/CSV, clear logs.
- Settings: gateway readiness checklist, rotation strategy + retry + cooldown + timeout, auto sync + interval, log retention, model_allow_unknown, change password, session list with per-session and revoke-all actions, rotate secret (with confirmation), audit log, system info (version, uptime, db path, counts).
- Global: sidebar nav with active indicator, topbar with readiness pill (
Gateway ready/Setup needed), live active-request counter, theme toggle, logout. All UI copy is English. - Everything must degrade gracefully when the gateway has no provider/key/model yet: prominent "Setup needed" banners linking to the right tab.
pnpm typecheckclean (server, dashboard,tests/**+scripts/**viatsconfig.test.json),pnpm buildproducesdist/andweb/dist/.pnpm dev(ornode dist/src/index.js) starts on 20125;GET /health→{status:'ok'}with a realuptimeMs;GET /always302-redirects to/dashboard;/dashboardwithout a session302s to/login.pnpm test(vitest unit suite) green.pnpm test:e2eboots the real server (src/index.ts) plus two deterministic mock upstreams onE2E_PORT/E2E_MOCK_A_PORT/E2E_MOCK_B_PORT(defaults 20197/20196/20195). It fails fast when a fixed port is occupied or a child exits before/health, and covers: all three surfaces (stream + non-stream), tool calling, vision, reasoning,include_usageboth directions,x_opencodestripping (including an injected SSE frame), byte-for-byte fidelity, client abort, round-robin (counters reset), 429/503/dead failover, non-retryable 400 single-attempt, timeout 504, retry-after, single-log-row assertions with a settle window, revoked/disabled keys, cookie attributes, brute-force 429, admin endpoints and the built dashboard shell.- Tooling checks:
pnpm check:docsdiffs every env var read anywhere undersrc/**, the registered routes and theDEFAULT_SETTINGSkeys against this file anddocs/API.md, compares.env.examplewith the config vars in both directions and checks the documented env defaults against the code defaults (exits 1 on drift).pnpm check:docs --self-testandnode scripts/check-commit-messages.mjs --self-testprove the gates still reject deliberately broken fixtures, and negative results are a failure: if a checker stops reporting a real problem, the self-test fails rather than passing.node scripts/check-commit-messages.mjs <base> <head> [<pr-title>]lints Conventional Commits, supports--single <sha>for a one-commit range and fails on an explicitly supplied but empty range;pnpm exec tsx scripts/screenshots.ts --strictruns the headless-Chrome UI check and fails instead of skipping when Chrome is missing (CHROME_PATHoverrides the binary). pnpm verifyrunstypecheck,test,check:docs,buildandtest:e2ein order, stopping at the first failure (--fastskipsbuildandtest:e2e); it is the single local gate that mirrors CI.