Skip to content

Latest commit

 

History

History
547 lines (500 loc) · 42.4 KB

SPEC.md

File metadata and controls

547 lines (500 loc) · 42.4 KB

OpenCode Router — Build Spec (frozen contract)

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).

0. Frozen contracts

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.

1. Core contract you build on

// 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

2. Gateway (src/gateway/**)

Auth (mandatory)

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 → 401 invalid_api_key-shaped error, code no_api_key_configured, message No gateway API key configured. Create one in the dashboard (API Keys tab).
  • Key present but unknown/disabled/revoked → 401, code invalid_api_key.
  • Missing header (or a non-Bearer scheme) → 401, code missing_api_key. On success call ctx.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.

Provider availability

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.

Routes

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)

2.1 Request pipeline (all three surfaces)

  1. onRequest hook: authenticate the key (§ Auth) and emit request:start; a rejection here writes one request_logs row and never reads the body.
  2. Parse JSON body (invalid JSON → 400 invalid_request_error).
  3. model required → else 400 code model_required.
  4. Model must exist and be enabled in DB unless model_allow_unknown=true → else 404 model_not_found with message listing how to add it.
  5. 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 model id is written back into the forwarded body.
  6. 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_tokens with the provider's API key in both Authorization: Bearer and x-api-key. The client's raw query string is forwarded unchanged (POST /v1/messages?beta=true reaches the upstream with ?beta=true), and a provider baseUrl that already carries a query string keeps it. The body is forwarded byte-for-byte (raw bytes captured with parseAs: '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-01 is only defaulted for the messages/count_tokens surfaces; a streaming request with no/wildcard accept is forwarded as text/event-stream.
  7. Never follow upstream redirects (redirect: 'manual'): any 3xx is a fatal upstream error (502 upstream_redirect, single attempt, provider cooled down, the provider key is never replayed).
  8. Retry with the next provider when the attempt fails with a retryable status (isRetryableStatus: 408, 409, 425, 429, every 5xx including 529) or a network/timeout ApiError, up to max_retries attempts total. A timed-out provider is logged as a real attempt, put into cooldown and failed over like any other retryable failure; the aggregated 504 upstream_timeout is 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_name in the log row plus the x-opencode-router-* headers below); only pre-attempt rejections carry the request id alone.
  9. Log the request (§2.6) exactly once per client request — GET /v1/models* included — and log every attempt via insertAttempt (timed-out attempts included).
  10. A 2xx upstream whose body cannot be read (truncated/RST) is reported as 502 upstream_body_failed (the upstream status is kept when it is already ≥ 400; a timeout stays 504 upstream_timeout). A streaming body that exceeds the unterminated-frame cap aborts with 502 upstream_frame_too_large; a buffered body that exceeds upstream_response_max_bytes aborts with 502 upstream_response_too_large.
  11. A request that exceeds BODY_LIMIT is rejected with 413, code payload_too_large (the Fastify internal FST_ERR_* code is never exposed).
  12. A known /v1/* path called with an unsupported method answers 405 with an Allow header listing the supported methods; unknown paths keep 404 unknown_endpoint. Both write exactly one request_logs row.

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).

2.2 Rotation (round-robin + failover)

  • rotation_strategy selects the order: round-robin (default, in-memory cursor advanced per request), priority (stable priority asc then created_at asc, cursor unused) or random (shuffled candidates).
  • Candidate set: enabled providers, ordered by priority asc then created_at asc.
  • 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_until so 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_attempts row, and attempts / x-opencode-router-attempts count 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 other 5xx, and any 3xx; the provider status column stays cooldown only for 429/503/529/5xx. The stored cooldown_until is monotonic: a later failure with a shorter cooldown never lowers an active longer one, so a Retry-After back-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 502 for network errors), code all_providers_failed; if every failure was 429 use 429 + code all_providers_rate_limited (with Retry-After); if every failure was a timeout use 504 + code upstream_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.

2.3 Reasoning effort normalization

  • 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 <= 1024 low, <= 4096 medium, <= 16384 high, 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 a defaultEffort, keep it unset (provider default) — do not invent an effort unless the client asked for one.
  • Expose reasoning metadata in GET /v1/models.

2.4 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":[]}.

2.5 Streaming

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 add stream_options.include_usage = true when 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) Record ttfb_ms (time to first byte) on the log row. Handle client aborts without crashing (destroy the upstream body, log with ok=false, code client_aborted, status 499). An idle gap or the total deadline aborts the upstream: 504 + code upstream_timeout while the response is still unsent, or a 504 status on the already-flushed stream. Retryable failures honour an upstream retry-after header (delta seconds or HTTP-date): the cooldown becomes max(provider_cooldown_ms, retryAfter) with retryAfter clamped to one hour (MAX_RETRY_AFTER_MS). With a non-zero upstream_response_max_bytes, a buffered non-streaming body over the cap aborts with 502 upstream_response_too_large; 0 is unlimited and streaming is never buffered.

2.6 Logging

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.

3. Admin API (src/admin/**, prefix /admin/api)

Auth

  • Session cookie okr_session = "<sid>.<expiresAt>.<hmac>" where hmac = hmacSign(ctx.db.secret, "<sid>.<expiresAt>"); store the session row (ctx.repo.createSession), verify the signature, the in-cookie expiresAt (an already-expired cookie is rejected before any DB lookup) and the DB row + expiry. Cookie flags: httpOnly, sameSite: 'lax', path: '/', maxAge = sessionTtlMs/1000, secure when the request is https (request.protocol, an x-forwarded-proto: https that is only honoured when TRUST_PROXY is enabled, or PUBLIC_URL starting with https://).
  • Public endpoints: POST /admin/api/login, POST /admin/api/logout, GET /admin/api/session. /login and /settings/password accept at most 4096 bytes (413 above it) and reject passwords longer than 200 characters with 400.
  • Every other /admin/api/* route requires a valid session → else 401 {error:{message,code:'unauthorized'}}. Session-authenticated mutating requests (POST/PUT/PATCH/DELETE) are additionally CSRF-guarded: a present Origin header whose host differs from the request host (or from the PUBLIC_URL host when that is configured), or Sec-Fetch-Site: cross-site, is rejected with 403 cross_site_request before any state change. Requests without those headers (CLI, the e2e suite, same-origin navigation) are unaffected, and the public POST /admin/api/login is never gated by this check.
  • POST /admin/api/login {password}: verify with verifyDashboardPassword (src/core/seed.ts); brute-force guard: max 10 failed attempts per IP and 500 failed attempts per process per 5 minutes → 429 with Retry-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/logout clears the cookie + deletes the session row.
  • GET /admin/api/session → {authenticated, expiresAt?, version:'1.0.0', uptimeMs, startedAt} (never 401).
  • HttpError messages are returned to the client as-is, including 5xx; only unexpected errors are masked as 500 internal_error (with driver/stack detail kept server-side).

Endpoints (all JSON; errors use {error:{message,code}})

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 exact requestsLast60s/errorsLast60s counts and activeRequests) plus {health:{status,activeRequests,providers:[{id,name,status,enabled,cooldownUntil,lastLatencyMs,successCount,failureCount,lastError,lastCheckedAt}], modelsEnabled, keysActive}, window}. activeRequests is snapshotted once per request, so the (possibly cached) aggregate body and health.activeRequests always agree within one response.
  • GET /admin/api/events (SSE) → emits request:start, request:end, provider:update, plus a stats heartbeat every 5s with {activeRequests, requestsLast60s, errorsLast60s}. Writes apply per-client backpressure (bounded queue + drain resume; 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 answers 503 too_many_streams. GET /admin/api/stats is served from a short (~2s) TTL cache.
  • GET /admin/api/activity?limit=20 → merged recent log rows + provider state changes. limit is validated like the logs route (1..500; a non-integer or out-of-range value is 400 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_version vs SCHEMA_VERSION and the presence of every expected table), clock.skew (newest log/audit timestamp more than 60 s in the future) and providers.cooldown. scheduler.nextSyncInMs is null when the scheduler is stopped or auto_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 (with version.schema = warn) instead of a 500 — 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). apiKeyMasked reveals 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/baseUrl reject control characters, baseUrl rejects userinfo). apiKey must 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 with 400 invalid_request, without echoing the submitted value).
  • PATCH /admin/api/providers/:id {name?, baseUrl?, apiKey?, enabled?, priority?} → {provider}. Changing baseUrl, apiKey or enabled resets status='unknown' and cooldownUntil=null.
  • DELETE /admin/api/providers/:id → {ok:true, modelsRemoved} — the provider's synced models are removed and a models_sync_provider_id pointing 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/lastError and emits provider: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_error or a client-visible body.
  • POST /admin/api/providers/test {baseUrl, apiKey?, id?} → same shape, before saving. When apiKey is omitted and id names a stored provider, the stored key is reused only when the draft baseUrl origin equals the stored provider's origin (otherwise 400 api_key_required); 404 for an unknown id, 400 when 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 unless PROVIDER_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} (source manual; 409 when 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}; ids is capped at 1000 entries (400 above) 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 additive providers:[{providerId,providerName,ok,added,updated,removed,total,latencyMs,error,warning}] listing every provider that was synced. Without providerId every enabled provider is synced (one transaction per provider, so one failure does not abort the others) and the top-level counters are the sum; with providerId only that provider is synced. 400 when no provider exists. Sync semantics: upsert every model reported upstream with source='sync', providerId, and delete rows with source='sync' from that provider that no longer exist upstream. Manual rows are never deleted. A source='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). A 2xx response 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 and models_synced_at is not advanced, and the result carries warning: 'Upstream returned no recognizable model list; the synced catalog was left unchanged' (also providers[].warning); hard failures such as a network error or a non-2xx status keep providers[].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 emits provider:update, exactly like the single-provider branch; a skipped (unrecognized) catalog does neither. Record models_synced_at + models_sync_provider_id in 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} (sets revokedAt, 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_found for unknown ids.
  • DELETE /admin/api/keys/:id → {ok:true}; 404 key_not_found for unknown ids.

Logs

  • GET /admin/api/logs?limit&offset&surface&model&providerId&keyId&ok&stream&search&since&until → {logs:[...], total, limit, offset}. model is a case-insensitive contains match (the dashboard labels it "Model contains"); % and _ in the value are matched literally. search is a substring scan over model/key_name/provider_name/error_message; a term longer than 200 characters is rejected with 400 invalid_request at the route (the repository layer additionally truncates as defence in depth). since/until accept epoch milliseconds or an ISO date and must be finite and in range (400 invalid_request otherwise).
  • GET /admin/api/logs/:id → {log, attempts:[...]} (404 when 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 carries X-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} (sessions lists at most the 50 newest sessions; passwordSet reports 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 as constructor included — are reported as ignored; log_store_bodies no longer exists and is also reported as ignored. Ranges include audit_retention_days 1..3650, stream_idle_timeout_ms 1000..3600000 and upstream_response_max_bytes exactly 0 or 1024..1073741824; upstream_user_agent rejects control characters.
  • POST /admin/api/settings/password {currentPassword, newPassword} → {ok:true} (400 wrong current, 400 when 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_current for the caller's own session and 404 session_not_found otherwise.
  • POST /admin/api/settings/rotate-secret → {ok:true, secret} — refuse with 409 secret_from_env when ROUTER_SECRET is set, because the environment value would win on the next restart. Otherwise generate a new secret, persist it to <dataDir>/.secret before swapping the in-memory ctx.db.secret, then invalidate all dashboard sessions and return the new secret so the operator can store it (response carries cache-control: no-store). Gateway key hashes are sha256 of the plaintext, so existing keys keep working.
  • GET /admin/api/audit?limit=100 → {items:[...]} (limit range 1..500, validated like the logs route).
  • Audit every mutating admin action with repo.audit(actor, action, target, detail): the actor is session:<id> on session-protected routes (or dashboard on public routes) and the client IP is recorded in the detail. Audit rows are pruned by audit_retention_days, not by log_retention_days.

Scheduler (src/admin/scheduler.ts)

startScheduler(ctx) returns a stop function. It:

  • every model_sync_interval_ms (min 30s) syncs models when auto_sync_models=true and 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()).

4. Dashboard (web/**)

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.

Visual language (must look premium, not generic)

  • 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/10 dark, border-black/5 light), 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 .dark class 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.

Behavior

  • lib/api.ts: fetch wrapper with credentials:'include', JSON helpers, typed responses, automatic redirect to /login on 401, 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.

5. Verification requirements

  • pnpm typecheck clean (server, dashboard, tests/** + scripts/** via tsconfig.test.json), pnpm build produces dist/ and web/dist/.
  • pnpm dev (or node dist/src/index.js) starts on 20125; GET /health → {status:'ok'} with a real uptimeMs; GET / always 302-redirects to /dashboard; /dashboard without a session 302s to /login.
  • pnpm test (vitest unit suite) green.
  • pnpm test:e2e boots the real server (src/index.ts) plus two deterministic mock upstreams on E2E_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_usage both directions, x_opencode stripping (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:docs diffs every env var read anywhere under src/**, the registered routes and the DEFAULT_SETTINGS keys against this file and docs/API.md, compares .env.example with the config vars in both directions and checks the documented env defaults against the code defaults (exits 1 on drift). pnpm check:docs --self-test and node scripts/check-commit-messages.mjs --self-test prove 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 --strict runs the headless-Chrome UI check and fails instead of skipping when Chrome is missing (CHROME_PATH overrides the binary).
  • pnpm verify runs typecheck, test, check:docs, build and test:e2e in order, stopping at the first failure (--fast skips build and test:e2e); it is the single local gate that mirrors CI.