Skip to content

About

OpenAI-compatible API gateway for a fleet of free-opencode-api instances — failover, quotas, scheduling, and a secured admin dashboard.

Topics

Resources

Contributing

Stars

0 stars

Watchers

0 watching

Forks

Repository files navigation

OpenCode Router

An OpenAI-compatible API gateway that load-balances across a fleet of opencode-api instances.

The providers speak three wire protocols — OpenAI Chat Completions, OpenAI Responses and Anthropic Messages — each with streaming, vision (image parts) and client-defined tool calling. The router exposes all three: POST /v1/chat/completions, POST /v1/responses and POST /v1/messages, each routed to the providers configured for that protocol.

Clients talk to one endpoint. The router rotates requests across many provider instances so a per-instance quota does not become your quota, honours each provider's time windows and concurrency limit, fails over across the fleet when one instance is busy or broken, and ships a secured admin dashboard for all of it.

┌───────────┐                     ┌─────────────────┐                          ┌──────────────────┐
│  clients  │ ──────────────────▶ │ OpenCode Router │ ───────────────────────▶ │ provider 1  (v1) │
│  (SDKs)   │  ocr-… gateway key  │     :20123      │                          │ provider 2  (v1) │
│           │                     │                 │                          │ provider N  (v1) │
└───────────┘                     └─────────────────┘                          └──────────────────┘
                                           │
                                           └── /dashboard   (glass UI: 6 tabs, English, light/dark)

Contents


Why this exists

A single opencode-api instance is deliberately conservative: one completion at a time (OPENCODE_PROXY_MAX_CONCURRENCY=1), a bounded wait queue, and a free lineup that rotates and can be rate-limited or exhausted without notice. That is the right default for one machine and the wrong one for a team.

The router turns N of those instances into one endpoint that:

  • never sends more than a provider allows — per-provider max_concurrency, default 1;
  • waits instead of refusing — a bounded queue drains the moment a slot frees;
  • fails over before the first byte — a busy, broken or quota-exhausted provider is skipped, and the client never sees it;
  • respects schedules — a provider used during the night only takes requests at night, evaluated in the timezone you choose, with windows that may cross midnight;
  • keeps the wire format — OpenAI and Anthropic SSE frames, envelopes and error codes are forwarded unmodified, so a client of either protocol works unchanged;
  • forwards what the provider supports — images (image_url, input_image, Anthropic image), tool definitions and calls, and reasoning output, with no format translation on the way.

It also refuses to hide the hard parts: no model is ever substituted, token counts are never invented, and a provider that syncs a single fallback model is reported as "possibly down" rather than trusted.


Quick start

Requires Node >= 22.19 and pnpm >= 12.

pnpm install
pnpm build                                  # the dashboard bundle
pnpm start
# [router] ... the first dashboard administrator was created {"username":"admin"}
# [router] ... [warn] the dashboard password is still the built-in default, which is public knowledge
# [router] ... opencode router is listening {"url":"http://127.0.0.1:20123/", ...}

Open http://127.0.0.1:20123/dashboard and sign in with 12345678.

Sign-in asks for the password only — there is no username field, because the dashboard has one operator and one credential. The account's display name (ADMIN_USERNAME, default admin) is shown in the dashboard and never asked for.

Change that password. 12345678 is a built-in default, so it is public knowledge. The router warns at every boot while it is still in force, and raises that to error once the bind address is reachable from the network. Change it in Settings, or with node index.js --set-password.

Set ADMIN_PASSWORD to choose the password on the first boot instead. It is read only while no account exists, so setting it later has no effect — see Forgot the dashboard password. Setting it to an empty string in config.json is how you say "create no account at all": the login page then says so rather than rejecting every password.

Then:

  1. Providers → add one. The endpoint must end with /v1 (http://127.0.0.1:8083/v1); the API key is required because the provider enforces authentication (a provider started with a blank key uses sk-dummy-123). A loopback or private-range endpoint needs ALLOW_PRIVATE_PROVIDER_URLS, which the Providers tab can turn on in Settings.
  2. Models → Sync from upstream, then enable the models you want to expose.
  3. API Keys → create one. It is shown once; the router stores only a digest.
  4. Call it.

A demo with no real providers

pnpm mock-provider            # terminal 1: three stub providers on 4399-4401
ADMIN_PASSWORD='demo-password' pnpm start   # terminal 2
ADMIN_PASSWORD='demo-password' pnpm seed    # terminal 3: registers them, prints a key

pnpm seed prints a ready-to-paste curl. Add MOCK_FAIL=1 to the first terminal and the demo fleet has one broken instance, so the failover shows up in the Logs tab.


Docker

The image is published on Docker Hub as dinhdev666/opencode-router — multi-architecture (linux/amd64, linux/arm64), with latest and one tag per release:

docker pull dinhdev666/opencode-router:latest

docker run -d \
  --name opencode-router \
  --restart=always \
  -p 127.0.0.1:20123:20123 \
  -e ADMIN_PASSWORD='a-password-you-will-remember' \
  -v opencode-router-data:/app/data \
  dinhdev666/opencode-router:latest

To run a checkout instead of a release, build it and substitute the tag:

docker build -f docker/Dockerfile -t opencode-router:local .

or let Compose do the build for you:

ADMIN_PASSWORD='a-password-you-will-remember' docker compose up -d

The image runs as uid 1000, pins its base image by tag and digest, has a HEALTHCHECK that answers /health, and ships tini so SIGTERM reaches the drain sequence. linux/amd64 and linux/arm64.

See docker/README.md for the image tags, the environment table, volumes, the shutdown grace period and how to point the router at providers on another host.


Configuration

Resolution order is environment variable → config.json → built-in default, and a blank environment variable counts as unset, so PORT= in a .env file falls through to the file and then to the default.

  • A broken config.json stops the process with a did you mean "MAX_QUEUE"? hint, because a configuration that silently ignores a typo is a configuration that lies.
  • A bad environment variable is repaired with a warning and the router keeps booting.
  • Settings changed in the dashboard take effect immediately and are saved to the SQLite settings table, not to config.json. A saved value outranks both the file and the environment, and it survives a restart. The reset link next to a field (POST /api/settings/reset) is the way back: it deletes the saved value, and the file or the environment is in force again.

Copy config.json.example or .env.example to start.

Server and storage

Key Default Meaning
PORT 20123 port for the gateway and the dashboard
BIND_HOST 127.0.0.1 interface to bind; use 0.0.0.0 in a container
LOG_LEVEL info error, warn, info or debug
DEBUG false alias for LOG_LEVEL=debug; an explicit LOG_LEVEL wins
DATA_DIR ./data SQLite database and generated secrets

Secrets

Key Default Meaning
APP_SECRET (generated) AES-256-GCM key material for provider keys at rest. Blank ⇒ generated once into data/.app-secret (mode 0600) with a warning
SESSION_SECRET (generated) cookie-signing secret. Blank ⇒ generated once into data/.session-secret
ADMIN_PASSWORD 12345678 the dashboard password (min 8 characters). Read only while no account exists, when it creates one. The default is public knowledge — change it
ADMIN_USERNAME admin the account's display name, shown in the dashboard. Never asked for at sign-in

Changing APP_SECRET makes every stored provider key undecryptable. Set it explicitly if you run more than one replica or want the data volume to survive a rebuild.

Gateway limits

Key Default Meaning
MAX_BODY_MIB 50 largest accepted request body, mirroring the provider. Boot-only: the ceiling is handed to the HTTP parser when the app is built, so a change needs a restart
MAX_QUEUE 64 how many requests may wait for a provider slot; 0 disables queueing
MAX_QUEUE_WAIT_MS 30000 how long a queued request waits before 503 queue_full
UPSTREAM_CONNECT_TIMEOUT_MS 10000 TCP/TLS connect timeout per attempt
UPSTREAM_IDLE_TIMEOUT_MS 60000 idle timeout between upstream bytes — kept above 20 s so the provider's 15 s SSE keep-alive is not mistaken for a stall
UPSTREAM_TOTAL_TIMEOUT_MS 300000 whole-attempt ceiling, matching the provider's default

Routing and failover

Key Default Meaning
ROUTING_STRATEGY least_loaded round_robin, least_loaded, least_used, weighted, priority
MAX_ATTEMPTS 3 provider attempts per client request; a provider is never tried twice
LEAST_USED_WINDOW_MINUTES 15 look-back window for least_used
COOLDOWN_FAILURE_MS 60000 cooldown after a 502/504/connection failure
COOLDOWN_QUOTA_MS 900000 cooldown after a quota failure
COOLDOWN_BUSY_MS 1000 cooldown after 503 queue_full / gateway_shutting_down
RETRY_AFTER_CAP_MS 300000 ceiling applied to a provider-supplied Retry-After
BREAKER_THRESHOLD 5 consecutive hard failures that open a provider's circuit breaker
BREAKER_OPEN_MS 120000 how long the breaker stays open before one half-open probe
QUOTA_PATTERNS see below case-insensitive regexes matched against the upstream error

Default QUOTA_PATTERNS:

["quota", "rate.?limit", "limit exceeded", "too many requests", "exhaust", "insufficient", "\\b429\\b"]

The provider's quota error is not documented, so these are a starting point rather than a specification. Every failure logs its raw upstream summary at LOG_LEVEL=debug, and the Settings tab edits the list — tune it from the Logs tab rather than from the source.

Health probing

Key Default Meaning
HEALTH_PROBE_INTERVAL_MS 30000 interval of the unauthenticated GET {origin}/health probe; 0 disables it
HEALTH_PROBE_TIMEOUT_MS 5000 per-probe timeout
HEALTH_PROBE_CONCURRENCY 8 probes in flight at once

Probing uses the provider's own unauthenticated /health, so it never spends a completion's quota. A failed probe is shown in the dashboard but does not on its own remove a provider from routing — a one-second blip would otherwise become an outage.

Defaults the UI uses

Key Default Meaning
DEFAULT_MODEL (empty) used when a client omits model. Empty ⇒ such requests get 400 model_required
STREAM_BY_DEFAULT false answer a completion as SSE when the client sends no stream field at all, on all three routes. A client that sends an explicit stream: false still gets JSON. Runtime-editable in Settings
ROUTER_NAME OpenCode Router the name shown in the dashboard and in /health
TIMEZONE Asia/Ho_Chi_Minh IANA timezone every provider schedule is evaluated in
DEFAULT_THEME system dashboard theme before the operator toggles it

Dashboard and security

Key Default Meaning
SESSION_TTL_HOURS 168 dashboard session lifetime
CORS_ORIGINS [] allowed origins for the dashboard API; empty means same-origin only. Boot-only: the CORS plugin is registered once, so a change needs a restart
DASHBOARD_RATE_LIMIT_PER_MIN 300 per-IP limit on dashboard routes; 0 disables
GATEWAY_RATE_LIMIT_PER_MIN 0 per-IP limit on /v1/*; per-key limits live on the key. The two budgets are separate, so a dashboard page load never spends the gateway's allowance
METRICS_ENABLED false serve GET /metrics in the Prometheus text format. Off by default: the document is an inventory of the fleet
METRICS_TOKEN '' bearer token a scrape has to present. Boot-only, like every secret. While METRICS_ENABLED is on and this is blank, /metrics answers 503 metrics_token_unset rather than exposing itself
LOGIN_RATE_LIMIT_PER_MIN 10 login attempts per minute per IP
LOGIN_LOCKOUT_THRESHOLD 5 failed logins before a lockout
LOGIN_LOCKOUT_MS 900000 lockout duration
LOG_RETENTION_DAYS 30 how long logs and metric rollups are kept
LOG_BODIES false store truncated bodies for the log drawer
LOG_BODY_MAX_CHARS 2000 truncation limit for a stored body
ALLOW_PRIVATE_PROVIDER_URLS false permit loopback/private provider endpoints
TRUST_PROXY false trust X-Forwarded-*: true for one hop, or a hop count. Only behind a proxy you control — with true the client address is taken from the right of the chain, which is the entry your proxy appended
TRUSTED_PROXIES '' the proxies themselves, as a comma-separated list of IPs or CIDRs (127.0.0.1, 172.18.0.0/16). This is what makes TRUST_PROXY safe: the chain is matched by address, so any host that can reach the port but is not on this list is answered with its own socket address. Empty trusts nothing

Using it from an OpenAI SDK

The wire format is OpenAI's, so an SDK pointed at the router works without a translation layer.

JavaScript / TypeScript

import OpenAI from 'openai';

const client = new OpenAI({
    // The router's base URL, including /v1. Not the provider's.
    baseURL: 'http://127.0.0.1:20123/v1',
    // A router key (`ocr-…`), NOT a provider key. The router holds the provider keys.
    apiKey: process.env.OPENCODE_ROUTER_KEY,
});

// Non-streaming.
const completion = await client.chat.completions.create({
    // Must exactly match a model enabled in the Models tab. There is no fallback.
    model: 'opencode/big-pickle',
    messages: [{ role: 'user', content: 'Explain a load balancer in one sentence.' }],
    // These are accepted and forwarded, and the provider ignores them:
    temperature: 0.2,
    max_tokens: 256,
});
console.log(completion.choices[0]?.message?.content);
// completion.usage is always all zeros: the provider reports no usage.

// Streaming: the provider's SSE bytes are forwarded unmodified.
const stream = await client.chat.completions.create({
    model: 'opencode/big-pickle',
    messages: [{ role: 'user', content: 'Count to five.' }],
    stream: true,
});
for await (const chunk of stream) {
    process.stdout.write(chunk.choices[0]?.delta?.content ?? '');
}

// Listing models is public: no key needed.
const models = await client.models.list();
for (const model of models.data) console.log(model.id, model.owned_by);

Python

import os
from openai import OpenAI

client = OpenAI(
    base_url="http://127.0.0.1:20123/v1",
    api_key=os.environ["OPENCODE_ROUTER_KEY"],
)

response = client.chat.completions.create(
    model="opencode/big-pickle",
    messages=[{"role": "user", "content": "One sentence about gateways."}],
)
print(response.choices[0].message.content)

with client.chat.completions.create(
    model="opencode/big-pickle",
    messages=[{"role": "user", "content": "Count to five."}],
    stream=True,
) as stream:
    for chunk in stream:
        print(chunk.choices[0].delta.content or "", end="")

OpenAI Responses

The same SDK and the same base URL; only the call differs. It routes to responses-typed providers.

const answer = await client.responses.create({
    model: 'opencode/big-pickle',
    input: 'Explain a load balancer in one sentence.',
});
console.log(answer.output_text);

Anthropic Messages

Point the Anthropic SDK at the router's origin (no /v1 in the base URL — the SDK appends /v1/messages). It routes to messages-typed providers, and max_tokens is required.

from anthropic import Anthropic

client = Anthropic(base_url="http://127.0.0.1:20123", api_key=os.environ["OPENCODE_ROUTER_KEY"])
message = client.messages.create(
    model="opencode/big-pickle",
    max_tokens=1024,
    messages=[{"role": "user", "content": "One sentence about gateways."}],
)
print(message.content[-1].text)

Vision and tools

Images and client tools go through unchanged on every protocol. Chat Completions, for example:

const answer = await client.chat.completions.create({
    model: 'opencode/big-pickle',
    messages: [{
        role: 'user',
        content: [
            { type: 'text', text: 'What is in this picture?' },
            { type: 'image_url', image_url: { url: 'https://example.test/cat.png' } },
        ],
    }],
    tools: [{
        type: 'function',
        function: {
            name: 'get_weather',
            description: 'Get the weather for a city',
            parameters: { type: 'object', properties: { city: { type: 'string' } } },
        },
    }],
});
// A call the model asked for arrives as answer.choices[0].message.tool_calls;
// execute it and send the result back in a { role: 'tool', tool_call_id, content } message.

curl

curl http://127.0.0.1:20123/v1/chat/completions \
  -H "Authorization: Bearer $OPENCODE_ROUTER_KEY" \
  -H "Content-Type: application/json" \
  -d '{"model":"opencode/big-pickle","messages":[{"role":"user","content":"hello"}]}'

curl http://127.0.0.1:20123/v1/messages \
  -H "Authorization: Bearer $OPENCODE_ROUTER_KEY" \
  -H "Content-Type: application/json" \
  -H "anthropic-version: 2023-06-01" \
  -d '{"model":"opencode/big-pickle","max_tokens":256,"messages":[{"role":"user","content":"hello"}]}'

X-Api-Key: $OPENCODE_ROUTER_KEY works instead of Authorization. If both are present, Authorization decides — including when it is wrong, which is deliberate: a proxy that injects Authorization: Basic … should fail loudly, not be rescued by the other header.


API

Method Path Auth Notes
GET / public redirects to /dashboard (302)
GET /ui public redirects to /dashboard (302), for a bookmark written before the path moved
GET /status public service description and route list
GET /health public status, uptime, version, provider counts, queue length
GET /v1/models public only the models enabled in the Models tab; same shape as the provider's answer. Answers 304 with an ETag when a client sends the matching If-None-Match
GET /v1/models/{id} public the slash in opencode/<model> may be raw or %2F
POST /v1/chat/completions key OpenAI Chat Completions; stream and non-stream, vision parts, tools
POST /v1/responses key OpenAI Responses; only routable to providers whose type is responses
POST /v1/messages key Anthropic Messages; only routable to providers whose type is messages. max_tokens is required
OPTIONS any public CORS preflight
GET /metrics token Prometheus text format; off unless METRICS_ENABLED is on, and it answers 503 metrics_token_unset while METRICS_TOKEN is blank rather than exposing itself
GET /dashboard session the dashboard
POST /api/providers/{id}/probe session runs the health prober's single-provider probe now, with the same request and the same recorded last_probe_* columns as the periodic loop; answers { ok, latencyMs, lastProbeAt, lastProbeOk, reason }

Every response carries X-Request-Id, either the client's (when it matches [A-Za-z0-9._:-]{1,64}) or a generated rt-…. Use it to correlate a failure with the Logs tab. It is present on the responses no route writes too - a request the HTTP parser refuses is answered on the raw socket with its own rt-…, so a malformed client still has an identifier to quote.

POST /v1/chat/completions, POST /v1/responses and POST /v1/messages also carry x-ocr-attempts, the number of providers that request tried. It is a count and never a provider name or endpoint, so a client can tell "one provider answered" from "the router failed over twice before answering" without a dashboard login. Successful replies additionally forward the provider's x-ratelimit-* and retry-after headers when the provider sends them, so a client can throttle itself before the provider's 429.

Metrics

GET /metrics is a Prometheus scrape document and it is off by default. Turn it on with METRICS_ENABLED=true and set METRICS_TOKEN to a long random value (boot-only, so a change needs a restart); a scrape then presents Authorization: Bearer <METRICS_TOKEN>, compared as a digest in constant time. While the endpoint is enabled and the token is blank it answers 503 metrics_token_unset instead of answering anyone: a metrics surface with no credential is an inventory leak with extra steps.

curl -H "Authorization: Bearer $METRICS_TOKEN" http://127.0.0.1:20123/metrics

While METRICS_ENABLED is off the endpoint answers 404 endpoint_not_available and logs at debug, not warn: a monitoring host polling an endpoint the operator deliberately disabled would otherwise write thousands of warning lines a day and bury the ones that matter. While it is on, a METRICS_TOKEN shorter than 32 characters produces one warn at boot - the token is compared in constant time, which stops a prefix from being measurably closer but does nothing about an unlimited number of tries, and /metrics is rate-limited per address for exactly that reason.

Every series is prefixed opencode_router_: uptime and shutdown state, request and failure totals, in-flight slots, queue depth and refusals, then one sample per provider for in-flight, capacity, remaining cooldown seconds, breaker state and failures. Latency quantiles (p50, p95, p99, max) are reported in seconds over the last fifteen minutes.

Two deliberate limits. A provider appears as {provider="<id>"} and never by name or endpoint, because the document leaves the process. And a percentile over an empty window is NaN rather than an absent series, so a scraper does not keep reporting the last value it ever saw.

The model list

GET /v1/models answers the same four fields the provider does, with the same values:

{
  "object": "list",
  "data": [
    { "id": "opencode/big-pickle", "object": "model", "name": "Big Pickle", "owned_by": "opencode" }
  ]
}

name is the label the provider reports for the model, learned when you sync and stored on that model. It is not the display alias you can set in the Models tab: the alias is a dashboard label, and renaming a model in the UI does not change what clients receive. A model no sync has seen a name for falls back to the part of the id after the slash.

OpenAI's own list omits name. A client that ignores unknown fields is unaffected; one that shows a name to a person now gets the provider's rather than a derivation of the id. created is absent on purpose — the router does not know when a model was created, and a fabricated timestamp is worse than none.

The model rule

The model must exactly match an enabled model id. Otherwise:

{"error":{"message":"the model \"opencode/nope\" is not enabled on this router. Enabled models: …","type":"invalid_request_error","code":"model_not_found"}}

No fallback. If model is omitted, Settings' default model is used when it is set and enabled; otherwise 400 model_required.

Errors

All errors use the OpenAI envelope {"error":{"message","type","code"}}; code is omitted when there is none. This envelope is the router's own on all three completion routes, /v1/messages included: the gateway is an OpenAI-compatible product, and a client that had to parse an Anthropic error body for a router refusal and an Anthropic stream for a success would have two dialects for one request. A failure the provider reports after a stream has started arrives in-band in that provider's own shape, because those bytes are forwarded untouched.

Status code When
400 invalid_request, model_required, invalid_settings, invalid_provider, invalid_key, invalid_query malformed body, an unsupported content part (input_audio, file), a missing Anthropic max_tokens, an oversized tool schema, a target the URL parser cannot decode (/%zz9), no model, a refused dashboard batch
401 invalid_api_key, invalid_credentials, unauthorized, metrics_unauthorized a missing or wrong gateway key; a wrong dashboard password; a dashboard session that ended; a scrape without METRICS_TOKEN
403 key_disabled, key_expired, csrf_failed, model_not_allowed the key exists but may not be used, or may not use that model
404 model_not_found, endpoint_not_available unknown model or endpoint
404 (no code) no route matches; the body carries type: "not_found"
413 payload_too_large body over MAX_BODY_MIB
415 unsupported_media_type a content type the gateway cannot read
429 rate_limit_exceeded, login_locked per-key limit, dashboard lockout
500 internal_error a bug on this side; the message is generic on purpose
502 upstream_error every provider attempt failed; the message carries the reason
503 queue_full, no_provider_available, gateway_shutting_down, no_account_configured, metrics_token_unset queue_full and gateway_shutting_down carry Retry-After: 1; no_provider_available carries the seconds until the earliest live cooldown expires (1 at the minimum); the last two are refusals no retry fixes
504 timeout the provider exceeded UPSTREAM_TOTAL_TIMEOUT_MS

A failure before the first byte is a real HTTP error. A failure after a stream has started arrives in-band as data: {"error":…} followed by data: [DONE] — the status line is long gone.

Streaming

The provider's SSE bytes are forwarded byte for byte, including its : keep-alive comment lines. Content-Type: text/event-stream, Cache-Control: no-cache, X-Accel-Buffering: no. Nothing is buffered, and a client disconnect aborts the upstream request and frees the provider slot.

Each protocol streams in its own frame vocabulary, and the router does not translate between them:

Route Frames a client sees
/v1/chat/completions chat.completion.chunk data frames, the first with delta.role: "assistant", the last with finish_reason
/v1/responses named events response.created, response.output_text.delta (with an increasing sequence_number), response.completed
/v1/messages named events message_start, content_block_start/content_block_delta/content_block_stop, message_delta (whose usage carries input_tokens/output_tokens), message_stop

What the router adds: data: [DONE] when the upstream stream ended without it, so an SDK waiting for the terminator cannot hang, and a : keep-alive comment while the provider is silent.

When does a client get SSE? By default only when it asks: send "stream": true (or 1, "1", "true", "yes", "on", "y", "t"). If you would rather a request that says nothing about stream be answered as SSE, turn on STREAM_BY_DEFAULT in Settings (or set it in the environment or config.json). The setting changes the absent case only:

Client's body STREAM_BY_DEFAULT off (default) STREAM_BY_DEFAULT on
no stream field JSON SSE
"stream": true SSE SSE
"stream": false / 0 / "no" / "off" JSON JSON
"stream": "ture" (unreadable) 400, naming the field 400, naming the field

An explicit false winning over the setting is what keeps an SDK's non-streaming method working: OpenAI's and Anthropic's SDKs send stream only when the caller asked to stream, so the setting cannot turn a plain client.chat.completions.create() call into an SSE body it cannot parse.

Protocols, vision and tools

The provider serves three wire protocols and the router routes all three, each to the providers configured for it:

Endpoint Protocol Provider api_type
POST /v1/chat/completions OpenAI Chat Completions chat_completions
POST /v1/responses OpenAI Responses (input, instructions, reasoning.effort) responses
POST /v1/messages Anthropic Messages (max_tokens required, system, block content, thinking) messages

An endpoint with no provider of its type answers 404 endpoint_not_available — a bridge across protocols is not one of these, and a client that speaks Anthropic Messages needs a messages-typed provider behind it.

Vision. Images are accepted in each protocol's own spelling and forwarded as prompt attachments:

{"role":"user","content":[
  {"type":"text","text":"What is in this picture?"},
  {"type":"image_url","image_url":{"url":"data:image/png;base64,...","detail":"high"}}
]}

Chat Completions uses image_url; Responses uses input_image; Anthropic Messages uses {"type":"image","source":{"type":"base64","media_type":"image/png","data":"..."}} or a url source. An http(s) URL is forwarded by reference — the router never fetches it, so it is not a second SSRF surface — and a data: URI is forwarded inline. Whether a model can actually see images is the model's own capability; the provider reports its refusal, and the router does not guess on its behalf. Parts the provider cannot forward (input_audio, file) are a 400 naming the position and the type, before any provider is contacted.

Tool calling. Client-defined tools are advertised to the model by the provider and their calls are parsed back into the protocol's own shape: tool_calls with finish_reason: "tool_calls" (Chat Completions), a function_call output item (Responses), a tool_use block with stop_reason: "tool_use" (Anthropic). Send the definitions in the request (tools, plus tool_choice; Anthropic schemas are input_schema), execute the call yourself, and replay the result — a role: "tool" message with tool_call_id, a function_call_output item, or a tool_result block. The router executes nothing and rewrites nothing; a tool definition whose schema renders to more than 64 KiB is the one caller mistake it refuses itself, because the provider would refuse the same request.

Reasoning. reasoning_effort / reasoning.effort / Anthropic thinking are forwarded, and the model's reasoning text comes back where its protocol puts it (reasoning_content, a reasoning output item, a thinking block).


How routing works

Eligibility

A provider may take a request only when all of these hold:

  1. enabled;
  2. inside its active schedule (weekdays + one or more HH:mm windows, which may cross midnight, evaluated in TIMEZONE);
  3. not in cooldown;
  4. circuit breaker not open (half-open admits exactly one probe);
  5. api_type matches the endpoint (chat_completions for /v1/chat/completions, responses for /v1/responses, messages for /v1/messages);
  6. a free concurrency slot — or the router queue has room to wait for one;
  7. not known to lack the requested model (a hint from "Sync all providers"; a provider with no hints is still tried).

If nothing is eligible the answer is 503 no_provider_available with a message naming why each provider was rejected.

Strategies

Strategy Ordering
least_loaded (default) fewest in-flight, tie-broken by fewest recent requests, then by load ratio
least_used fewest requests in the last LEAST_USED_WINDOW_MINUTES, tie-broken by in-flight
round_robin a rotating cursor across the eligible set
weighted proportional to weight, without replacement
priority lowest priority number first; the rest are failover

The strategy returns an order, not a winner, so failover is one loop and the strategy never has to know about retries.

Failure classification

Outcome Action
2xx success; reset the failure counter and close the breaker
503 queue_full / gateway_shutting_down short cooldown honouring Retry-After; not counted toward the breaker
502 / 504 / connection error / timeout / other 5xx count one failure, short cooldown, try the next provider
matches a quota pattern (or an explicit 429) long cooldown (honouring Retry-After), try the next provider
401 / 403 from the provider mark the provider auth_error, try the next provider, never blame the client
400 / 413 / 415 / 422 return to the client as-is; no retry, no penalty

Retries stop at MAX_ATTEMPTS, and a provider is never tried twice in one request.

Capacity and the wait queue

Each provider has max_concurrency (default 1, matching the provider's own default). When every eligible provider is at capacity the request waits in a bounded queue (MAX_QUEUE entries, MAX_QUEUE_WAIT_MS each). A freed slot is handed straight to the oldest waiter rather than becoming free, so a burst cannot starve the queue. If the queue is full or the wait expires the answer is 503 queue_full with Retry-After: 1.

The slot is held for as long as the response is being delivered — including a whole stream — and released immediately when the client disconnects.


The dashboard

Six tabs, English throughout, light/dark following the system (or pinned), and responsive down to a phone.

Tab What it is for
Overview KPI cards (providers, requests, success/error rate, p50/p95, queue, in-flight), a per-minute traffic chart for the last 60 minutes, breakdowns by model and provider, a latency trend, errors by type, live provider health, a recent-errors feed, and a 60m/24h/7d range selector. No token KPIs — the provider always reports zero usage, and the page says so.
API Keys create/edit with name, expiry, allowed models and a per-key rate limit; one-time reveal with copy; enable switch; regenerate; revoke; usage counters; an info box listing public vs keyed endpoints with a ready curl built from the current origin.
Models "Sync from upstream" (tries the next provider on failure) — which also records what the provider calls each model, so the list can show the same label a client receives — a warning when the sync returns only the fallback model, search, per-model enable toggle, bulk enable/disable, an optional dashboard-only display alias, last-sync time, and "Sync all providers" to record which provider serves which model.
Providers endpoint, API type, API key (write-only), weight/priority, max_concurrency with a hint, weekday+window schedules that may cross midnight, a Check button that spends one minimal non-stream completion in the provider's own protocol and reports latency/status/error detail, live state with a cooldown countdown, in-flight vs max, 24h success rate and last error; edit, duplicate, delete, enable/disable and reset cooldown.
Logs filterable and paginated by time, status, model, provider, key, endpoint, streaming and request id; columns for the whole provider chain across attempts, attempts, status, latency, time-to-first-byte and queue wait; a row drawer with the retry timeline and (when body logging is on) the bodies; CSV export. No token columns.
Settings general, routing (strategy, attempts, cooldowns, quota patterns, breaker, health probe), timeouts and capacity, logging, security (change password, sessions, CORS, rate limits, private URLs), a danger zone (reset stats, clear logs, run retention), and a version/health summary. Every field shows where its value came from.

Security

  • The default password is public knowledge. 12345678 exists so a fresh install has a working dashboard rather than one nobody can sign into. The router says so at every boot while it is in force, and at error level when BIND_HOST is not loopback. The default bind address is 127.0.0.1, so a local install is not exposed; a container publishes 0.0.0.0 and needs the password changed or a port published to loopback only.
  • Dashboard login — a single password, argon2id (19 MiB, 2 passes), a signed httpOnly sameSite=strict cookie (marked secure when the request is HTTPS), a per-session CSRF token that must be echoed in X-CSRF-Token, a per-IP login rate limit and a per-IP lockout. Strict-Transport-Security and upgrade-insecure-requests are sent only over HTTPS: on a plain-HTTP deployment they would pin the browser to a scheme this router does not serve.
  • Gateway keys — ocr- + 48 random characters (280 bits over a 57-character alphabet, rejection-sampled so there is no modulo bias). Only a SHA-256 digest and a short prefix are stored; the plaintext is shown once and there is no reveal endpoint, because there is nothing to reveal. A key may be restricted to a set of models; an empty set means every enabled model.
  • Provider keys — AES-256-GCM with a key derived from APP_SECRET. A tampered or wrong-secret row fails to decrypt instead of decrypting to garbage, and the failure is reported as a configuration problem rather than a provider outage.
  • Masking — one chain in src/logger.js covers Authorization, X-Api-Key, cookies, credential-like query parameters, user:pass@ in URLs, key-shaped strings (sk-…, ocr-…, JWTs) and any value registerSensitiveValue() learned. Every log line and every 5xx message goes through it, and the config dump prints secrets as <set>.
  • Provider URLs — http/https only, must end with /v1, no credentials, no query, no fragment. Loopback, private ranges, link-local and *.internal/*.local are refused unless ALLOW_PRIVATE_PROVIDER_URLS is on, so a typo cannot reach cloud metadata or an internal panel.
  • Headers — helmet with a CSP that allows only same-origin scripts, a CORS allowlist (same-origin by default), and nosniff on every response.
  • Bodies — LOG_BODIES is off by default and truncates when on. Prompts are user data; the default configuration never stores them.

Forgot the dashboard password

ADMIN_PASSWORD is read only while no account exists, so changing it later has no effect — that is deliberate, or a stale value in a Compose file would silently overwrite a password you changed in the dashboard. Use the explicit escape hatch instead:

node index.js --set-password 'a-new-password'
# The dashboard password for "admin" was replaced.
# Every existing dashboard session was signed out.

It works whether or not an account exists, needs no server running, and exits without starting one. node index.js --help lists the flags. node index.js --version (or -v) prints the version from package.json and exits the same way — the question an operator asks of a container that may have no configuration, no data directory and no permission to write one. An argument the process does not understand is refused with the usage message and exit 2 rather than ignored: a typo used to boot a gateway that then exited 0, which reads exactly like a successful password change.

If the login page instead says "no dashboard password has been set", ADMIN_PASSWORD is set to an empty string in config.json, which is the deliberate way to refuse the built-in default. Set it to a real password and restart, or use the flag above.

Note that an empty environment variable is not this case: an unset or blank variable counts as absent (see Configuration), so -e ADMIN_PASSWORD= falls through to the built-in default 12345678 and the account is created with it. To have no account at all, put "ADMIN_PASSWORD": "" in config.json — which is what docker/docker-entrypoint.sh writes when the variable is present but blank, and why the image then logs that sign-in answers 503 no_account_configured.

Development

pnpm install
pnpm build                 # once, so /dashboard serves the app
pnpm dev                   # the router with --watch
pnpm dev:web               # rebuild the dashboard on every change (separate terminal)

The dashboard is a Vite + React + Tailwind v4 app under web/. pnpm build writes it to public/, which Fastify serves from the same port — one process, one port, and /dashboard plus any deep link under it.

The brand icons live in web/public/ (favicon.ico, favicon-96x96.png, apple-touch-icon.png) and Vite copies them into the build, so the dashboard makes no outbound request for its own logo. They are served from the same origin and are the only files at the root of the built output besides index.html.

AGENTS.md is the architecture map and the invariants; CONTRIBUTING.md has the commit convention and the PR checklist. docs/provider-contract.md is the distilled copy of the provider's documented surface — the reference the stub fixture and the smoke cases are written against.


Tests

pnpm run check        # syntax + import resolution + workflow pinning
pnpm run typecheck    # tsc --noEmit over the dashboard
pnpm run test:web     # vitest over the dashboard: the copy table, the formatters, the component kit
pnpm test             # unit files, then the integration suite
pnpm test:unit        # unit only: schedule, strategies, breaker, queue, quota, URLs, config, db
pnpm test:smoke       # integration only: stub provider + real router processes over HTTP
SMOKE_SLOW=1 pnpm test  # adds the cases that wait out a 15-second SSE silence

Nothing is mocked below the HTTP boundary: the smoke suite starts real stub providers and real router processes, and asserts what a client would see. It covers — among ~300 cases — auth enforcement on both surfaces, byte-exact streaming with keep-alive comments, a busy provider failing over, a quota failure taking the long cooldown, a 401 from a provider being the provider's problem, a client 400 never being retried, a disabled model returning 404 with no fallback, an out-of-schedule provider taking no new requests while an in-flight stream still finishes, the fallback-model sync warning, the router queue handing a freed slot to the waiting request, a clean SIGTERM drain, and the three wire protocols end to end — Anthropic event frames passed through untouched, an image part reaching the provider as an image on each route, and a tool call coming back as tool_calls, a function_call item and a tool_use block respectively.

Current state: the unit suite and the smoke suite pass, as do the dashboard's own vitest run, its typecheck and a production bundle build.


Assumptions

Written down because each one is a decision that could reasonably have gone the other way.

  1. The provider is exactly as documented. Mandatory auth, opencode/<model> ids, ignored sampling fields, zero usage, max_concurrency 1, a single static model when its backend is down, 503 with type: queue_full, 502 with code: ProviderError, three wire protocols with streaming, vision and tool calling (docs/provider-contract.md summarises that surface). If the real behaviour differs, test/stub-provider.mjs is the first thing to change.
  2. The quota error's shape is unknown. Detection is a configurable regex list plus "an explicit 429 is always quota". A false positive costs a long cooldown on a working provider, so the defaults are narrow and every failure logs its raw summary for tuning.
  3. opencode/big-pickle is an alias with a rotating target. Its capabilities, and which model it points at, can change without notice. The router badges it rather than pinning it, and never infers a model's capabilities from its id.
  4. A model list containing only opencode/big-pickle means the provider is probably down. Such a sync marks nothing as missing. A model that disappears from a real sync is kept and flagged.
  5. usage is always zero, so tokens are never charted or billed. A precise-looking number that is always wrong is worse than an absent one.
  6. One process, one port, one SQLite file. The dashboard is served by Fastify; there is no separate web server, no Redis and no external queue. DATA_DIR is the whole state, and data/.app-secret must survive a rebuild or the stored provider keys become unreadable.
  7. Per-provider concurrency 1 is the right default. It mirrors the provider, and the UI says to keep the two equal. Raising it is an explicit statement that the provider was configured to allow it.
  8. Schedules are about new requests only. A request already in flight finishes normally when its window closes.
  9. A failed health probe is information, not an outage. Routing eligibility is decided by the schedule, the cooldown and the breaker, not by one probe — a one-second blip should not remove a provider.
  10. Retries never cross a stream's first byte. Before it, failover is free; after it, the client already has part of the answer and a retry would duplicate it.
  11. No protocol is translated into another. /v1/chat/completions, /v1/responses and /v1/messages each route only to providers of the matching API type and answer 404 endpoint_not_available otherwise: a client that speaks Anthropic Messages needs a messages-typed provider, not a translator in front of a chat one. The answer a client gets is the upstream bytes, in the protocol it asked for. The seam for a translator, if one is ever wanted, is the single attempt() call in src/gateway/completions.js.
  12. English only. The dashboard UI, the code, the comments, the log messages, the documentation and the commit messages are all English. There is no second language and no language switcher, and a test fails the suite if a non-English character reaches a tracked source or document. The only non-English text anywhere is the copyright holder's name, which is a name, not a language.
  13. Node >= 22.19 and pnpm >= 12. The floor is set by the dependencies, not by preference: undici 8 requires >= 22.19 and better-sqlite3 13 requires >= 22. Node 20 was declared here once and could never have worked — the CI matrix, which runs 22, 24 and 26, is what said so. pnpm@12.18.0 is pinned through Corepack; a newer pnpm major can change install behaviour, including how dependency build scripts are approved.
  14. No Dependabot, no formatter, no linter. Dependency updates are a manual, reviewed change and the commit convention is machine-checked instead. Style is a review concern.
  15. Streaming is opt-in, unless the operator says otherwise. stream: true is the OpenAI and Anthropic default, and the router follows it: a request that does not mention stream gets JSON. STREAM_BY_DEFAULT (Settings, environment or config.json) is the deliberate way to change the absent case, and even then an explicit stream: false is honoured, because an SDK's non-streaming method must not be answered with a body it cannot parse.

License

MIT — see LICENSE. Copyright (c) 2026 Phạm Văn Định.

About

OpenAI-compatible API gateway for a fleet of free-opencode-api instances — failover, quotas, scheduling, and a secured admin dashboard.

Topics

Resources

Contributing

Stars

0 stars

Watchers

0 watching

Forks

Contributors

Languages