Skip to content

Repository files navigation

OpenCode API

CI License: MIT Node.js OpenAI Compatible Anthropic Compatible

OpenCode API exposes OpenCode's free models as a standard REST API in three wire protocols: OpenAI Chat Completions (/v1/chat/completions), OpenAI Responses (/v1/responses) and Anthropic Messages (/v1/messages). It is a small Node.js gateway that talks to https://opencode.ai's own inference API directly — no OpenCode CLI is installed, no backend process is started — so any client that speaks one of those protocols, the official OpenAI and Anthropic SDKs, Cursor, Claude Code, or your own scripts, can use those models without a paid API key.

OpenCode rotates its free lineup, so this README only names opencode/big-pickle, the one id that stays put. It is an alias, not a model of its own: OpenCode routes it to whichever model it currently serves and never says which one, so its capabilities (context size, tool support, reasoning) can change without notice. It is the gateway's built-in default, so a chat request that omits model goes to it. Every other id comes and goes — GET /v1/models returns what the upstream serves on the free tier right now, which is a list this gateway cannot hardcode.


Table of Contents


Features

  • Three wire protocols, one pipeline — POST /v1/chat/completions (OpenAI Chat Completions), POST /v1/responses (OpenAI Responses) and POST /v1/messages (Anthropic Messages), each with streaming and non-streaming responses. A client that speaks one of them is answered in that protocol: envelope, frame names and error shapes included.
  • Vision, reasoning effort and tool calling — images travel in the upstream request body (image_url, input_image, Anthropic image blocks); a thinking level is sent in the wire's own spelling (reasoning_effort, a Responses reasoning object, or an Anthropic thinking budget); client-defined tools are declared to the upstream as native tools, so a call comes back as a real tool_calls / tool_use block (see Tool calling).
  • Zero extra infrastructure — one Node.js process. No OpenCode CLI is installed or required, no backend process is spawned, probed or shut down, and there is no session create/prompt/poll cycle: one upstream streaming call per completion is the whole of it.
  • Mandatory authentication — every request needs Authorization: Bearer <key> (the scheme is case-insensitive, and X-Api-Key: <key> works as an alias). The default key is sk-dummy-123, and authentication cannot be disabled: a blank API_KEY simply falls back to that default.
  • Only the three completion routes read a body — a request body sent to any other served route (/, /health, an OPTIONS preflight, GET/HEAD on the models routes) is refused with 400 before a byte of it is read, and the connection is closed behind the envelope: those bytes were otherwise buffered to keep the connection reusable, so an unauthenticated caller's body size could choose the process's memory (see Request bodies).
  • DISABLE_TOOLS withholds your tools — DISABLE_TOOLS=true does not forward the client's tools to the upstream and drops any call the model emits anyway, so the model answers in text. The gateway executes nothing itself in either setting: whatever the model asks for is published to the client, which decides what to run.
  • It reproduces a client the upstream accepts — and that is the gateway's own risk to run. OpenCode's free tier gates on the request's TLS fingerprint, so on opencode.ai the lane sends its HTTP through wreq-js, a Rust client built on BoringSSL; a base URL that is not that host uses plain fetch. It also reproduces the free tier's own protocol, because the upstream refuses a request without it: Authorization: Bearer public, the CLI's User-Agent, a minted ses_... session id per conversation, the <env> system marker, and OpenCode's own read/shell tool definitions. Those are load-bearing, not stylistic. The honest consequence: this works because it reproduces a client the upstream accepts today, and it stops working whenever OpenCode changes its gate. Running it is your decision. Your own API_KEY is still enforced on every request and is never sent upstream, but wreq-js is a native dependency, so the process loads a per-platform binary binding (see Security).
  • Structured logging — error / warn / info / debug levels, one-line request summaries, secrets masked.
  • Production friendly — configurable bind host, request timeouts (a body that never arrives is cut off, not held open), graceful shutdown, Docker image available.
  • Fast HTTP stack — built on Fastify 5 with precompiled response schemas and no per-request middleware chain.

How It Works

OpenAI / Anthropic client  ──HTTP──▶  OpenCode API (default :8083)  ──▶  opencode.ai inference API  ──▶  model providers

The gateway accepts requests in OpenAI Chat Completions, OpenAI Responses or Anthropic Messages form, builds the upstream request, streams the answer back as standard SSE chunks or a single JSON body in the protocol the client spoke, and owns nothing else: there is no child process, no readiness probe and no teardown. One completion is one upstream streaming call, and the client's own stream flag only decides whether the gateway relays the deltas or aggregates them into a JSON body (a free model refuses a non-streaming upstream request, so the gateway always asks for a stream).

The free upstream

The lane is a client of https://opencode.ai's own inference API, so it is worth knowing what that interaction looks like when a completion succeeds — and when one fails:

  • Three inference endpoints, one per wire: POST /inference/v1/chat/completions for the plain chat models, /inference/v1/responses for the Responses-native families (muse-spark-*, gpt, grok) and /inference/v1/messages for the Messages-native ones (union-alpha, minimax, qwen). The model id decides which one a request goes to, so a request is not converted into a wire its model is not served on. The model catalog is the one listing still served from /zen/v1/models, because only the inference paths compare the TLS fingerprint. The older /zen/v1 inference paths now answer 403 FreeTierError and are deliberately not kept as a fallback.
  • The free tier's identity, reproduced. Every inference request carries Authorization: Bearer public (a real Zen key is refused: free models are only usable from inside OpenCode), the CLI's User-Agent, and a minted ses_... session id. The session id is not decoration: the upstream accounts the free quota per session and decodes the timestamp inside it, so one long-lived id is reused per conversation — minting a fresh one per request burns the quota and surfaces as 429 FreeUsageLimitError with growing reset delays. A client that sends its own x-opencode-session, or its own conversation identity (session_id, conversation_id, prompt_cache_key, metadata.user_id), keeps one upstream session; everything else shares the gateway's canonical one.
  • Two body-side gates. A free request must declare OpenCode's own read and shell tools with their exact descriptions and parameter schemas, and must carry the CLI's <env> system marker. The marker is appended to the caller's own system prompt rather than replacing it, and the fingerprint tools are added when the client did not declare them. A caller tool that already uses one of those names has OpenCode's definition adopted in place when its arguments can carry it, and is otherwise sent under an alias and restored in the answer. A declared tool name containing terminal is answered 429 regardless of quota, so such a name travels under an alias too. All of this is in src/opencode-free/fingerprint.ts, and none of it is cosmetic.
  • The answer is one SSE stream, always. The lane asks for stream: true even when the client did not, aggregates the deltas for a non-streaming client, and reads each wire's own frame vocabulary: chat.completion.chunk for the chat wire, named response.* events for Responses, and message_start/content_block_*/message_delta/ message_stop for Messages. A successful response that is not an event stream is treated as a refusal, not as an empty answer.
  • Failures are classified, not just reported. A 429 whose body says "overloaded" is transient load shedding and is retried on a bounded backoff; a 429 that says anything else is a spent quota, and a 403 is a refused identity — both drop the cached session id so the next request mints a fresh one, and both reach the client with their own status. Everything else becomes a 502, with backend_unreachable reserved for "could not reach the upstream at all".
  • Model ids come from the upstream catalog, fetched from /zen/v1/models and narrowed to the ids the free lane can actually serve: the listing describes the whole Zen catalog, paid models included, and advertising a paid id would hand clients a 403 the list said was available. The list is cached for 10 minutes (CATALOG_TTL_MS), keeps serving the last good listing for up to an hour while a refresh fails (CATALOG_STALE_MS), and answers an empty list only when it has nothing and the refresh failed. /v1/models adds its own shorter cache on top of that.

Performance

The HTTP layer is Fastify 5 with a deliberately thin lifecycle: a single onRequest hook (trace id and log summary, CORS headers, bearer auth) and no plugin-level middleware chain. Additional choices that matter under load:

  • Precompiled response schemas — /health and /v1/models are serialized through fast-json-stringify schemas compiled at startup instead of the generic JSON.stringify path, and a cached model listing is a body built once when the cache was filled: re-running the serializer for bytes that cannot have changed measured +2.7 % on the route (100.1k → 102.8k req/s).
  • Short model-list cache — /v1/models results are cached for 5 s, so client startup probes do not hit the upstream every time, and a burst that arrives with a cold cache shares a single round trip instead of one per request. An expired entry is still served (for up to 60 s) while the refresh runs in the background, so the request that crosses the 5 s boundary no longer waits for a round trip: a listing measured 5.0 ms with the blocking refresh and 0.6 ms from a warm cache. A failure is not cached either, but it is held for 1 s, so an upstream that answers 500 is not asked once per listing (measured 72.4k → 101.2k req/s on the route, +40 %). The lane's own catalog cache sits underneath (10 minutes fresh, an hour of stale service), so a refresh that does reach the network is rare.
  • No hidden allocations on the hot path — header masking for debug logs is only built when LOG_LEVEL=debug, the bearer token string is precomputed once, and request paths are parsed once per request.
  • SSE written straight to the socket — streaming replies hijack the response and write data: frames directly to the raw connection: no buffering layer, no extra copies, X-Accel-Buffering: no for proxy friendliness.
  • Logging without a framework logger — Fastify's built-in request logging is disabled; summaries are emitted from the raw response finish event, which also covers hijacked streams.
  • Pre-serialized SSE envelopes — the chat.completion.chunk wrapper (id, model, created, choices) is built once per stream, so each delta only escapes its text and appends it to a prepared prefix.
  • One budget per completion, one upstream call — the queue wait, the endpoint choice, the request and the whole answer share the request budget (OPENCODE_PROXY_REQUEST_TIMEOUT_MS), so a stalled upstream ends within the advertised timeout, and a request that waited in the queue does not get a full extra budget for its setup. There is no second trip to hide one in: the upstream call is the completion.
  • Queue drains immediately — the completion queue starts the next request on the next tick instead of after a fixed 100 ms pause, and OPENCODE_PROXY_MAX_CONCURRENCY (default 1, i.e. one completion at a time as before) can be raised to run independent completions in parallel. Raise it only if the upstream tolerates concurrent calls from one identity: they share the free tier's quota.
  • A client that gives up frees its slot — when the client closes the connection, the upstream call is aborted (AbortController) rather than left to finish for nobody, so the queue moves on instead of holding a slot for an answer that will not be read. A client that stops reading without closing is dropped after its socket makes no progress for 10 s (SSE_CLIENT_STALL_TIMEOUT_MS), with the 30 s per-write cap as the backstop, instead of parking the slot for the whole request budget; a reader that keeps draining, however slowly, is never cut.

Local benchmarks, autocannon, same machine (Node.js 26, macOS 27 on an Apple M4, loopback). The three HTTP-layer rows are unchanged by the move to the free lane; they measured this gateway against a stub that answers in ~1 ms, and they measure the gateway, never a model. The request log is off (LOG_LEVEL=error): at the default info every /v1/* request writes a line, and on a redirected stdout (a file, as in a container) those writes are synchronous, so the log — not the handler — sets the ceiling. Measured on the same machine, GET /v1/models answers ~104,900 req/s at 0.08 ms with the log off and ~71,600 req/s at 1.02 ms with the default line; /health and / log at debug and are unaffected. Keep the log on in production and read the table as what the request path costs, not as a promise with stdout in the way:

Scenario Throughput Avg latency
GET /health, -c 100 -d 10 ~109,600 req/s 0.04 ms
GET / (service index), -c 100 -d 10 ~115,400 req/s 0.03 ms
GET /v1/models (5 s cache), -c 100 -d 10 ~103,200 req/s 0.09 ms

The completion rows that used to sit below these measured the deleted opencode serve path — a session create, a prompt, the answer and a session delete — so they are gone rather than stale. A completion now costs one streaming call to the upstream plus the queue admission, and how fast that is depends entirely on the model and the upstream's own load; measure it yourself against test/lib/stub-free-upstream.ts before quoting a number.

No rate limiter, by design. The gateway bounds concurrency (OPENCODE_PROXY_MAX_CONCURRENCY), the wait queue (OPENCODE_PROXY_MAX_QUEUE: a full queue answers 503 with Retry-After: 1) and the body (OPENCODE_PROXY_MAX_BODY_MB), and nothing else. A request rate per client is deliberately absent: the only identity the gateway has is one shared API key, and it keeps no cross-process counter. If several callers share one instance, put a reverse proxy in front of it (nginx limit_req, a load-balancer rate policy) - that is where a per-address limit belongs, and it survives a restart.

For reference, the Express implementation this gateway replaced measured ~74,000 req/s on /health in the same harness at the time; the Fastify rewrite answers ~110,000 req/s on the same endpoint today, as the table above says.


Requirements

Requirement Details
Node.js 20.0 or newer (required by Fastify 5; index.ts refuses to start on an older major version and says so)
pnpm 12.0 or newer (the project's package manager)
TypeScript Installed as a dev dependency; pnpm run build compiles the project into dist/, and dist/index.js is what runs

There is nothing else to install: no OpenCode CLI, no opencode serve and no upstream account. The gateway talks to https://opencode.ai's own inference API with the free tier's own identity, so there is no local binary to find, no auth login to run and no backend to keep alive. The one runtime dependency that is not pure JavaScript is wreq-js, whose native binding is installed per platform by pnpm install; src/opencode-free/transport.ts is the only module that loads it, and only when the upstream host needs it.

Install pnpm if you do not have it yet:

corepack enable pnpm
# or
npm install -g pnpm

npm appears above only for installing pnpm itself. This project's own dependencies are managed with pnpm.


Quick Start

git clone https://github.com/dinhdev666/opencode-api.git
cd opencode-api
pnpm install
pnpm build                           # tsc -> dist/
cp config.json.example config.json   # optional: edit port, API key, upstream
pnpm start                           # builds again, then runs node dist/index.js

pnpm start runs the build first, so pnpm build is only necessary if you want to compile without starting. Nothing runs from the TypeScript sources directly: dist/index.js is the entry point.

Verify the gateway is up (OPTIONS, /health and / are the only unauthenticated routes), and list the models the free tier serves right now:

curl http://127.0.0.1:8083/health
curl -H "Authorization: Bearer sk-dummy-123" http://127.0.0.1:8083/v1/models

Send your first message — opencode/big-pickle is a stable alias for whatever model OpenCode is serving right now; any other id from that list works too:

curl -X POST http://127.0.0.1:8083/v1/chat/completions \
  -H "Content-Type: application/json" \
  -H "Authorization: Bearer sk-dummy-123" \
  -d '{"model":"opencode/big-pickle","messages":[{"role":"user","content":"hi"}],"stream":false}'

sk-dummy-123 is the built-in default key. Change API_KEY (environment variable or config.json) for any real deployment; leaving it blank still enforces the default.


Configuration

Settings are resolved in this order: environment variables → config.json → built-in defaults. An environment variable that is present but blank counts as unset, so PORT= API_KEY= npm start (a unit file's Environment=API_KEY=, an empty Helm or compose value) cannot replace the port and the key written in config.json with the defaults — a blank API_KEY used to fall through to the public sk-dummy-123 while the file named a secret.

A config.json that exists but cannot be used stops the gateway (exit 1) with the reason logged: falling back to the defaults would ignore the port and the key you wrote and serve traffic with the built-in sk-dummy-123. A missing file is normal and simply means "defaults plus environment". The file is read from the application directory — next to the compiled entry point (dist/config.json, or /app/config.json in the container) — not from the directory you start the process in; if a config.json sits in that working directory instead, startup says so: [Config] config.json is read from ...; the file at ... is ignored.

The file must be a regular file of at most 1 MiB; a UTF-8 BOM (which a Windows editor writes) is tolerated. A key the gateway knows but whose value has the wrong type stops it with the key named and the type it found ([Config] config.json API_KEY must be a string, found a boolean) instead of being coerced: a boolean API_KEY would make the literal string true the gateway's credential, which every client can guess while the startup summary still reports a custom key. The message names the type each key actually takes — a string (API_KEY, BIND_HOST, FREE_BASE_URL, LOG_LEVEL), a number (PORT and the OPENCODE_PROXY_* tuning keys, which are also accepted as a numeric string) or a boolean (DISABLE_TOOLS, FREE_IMPERSONATE, DEBUG).

A key the gateway does not read is reported and ignored, because a misspelled key used to change nothing at all while the gateway ran the default you thought you had replaced:

[Config] config.json has an unknown key 'APIKEY' (did you mean 'API_KEY'?) - it is ignored

config.json (see config.json.example):

Key Default Description
PORT 8083 Gateway listen port
BIND_HOST 127.0.0.1 Gateway bind address; use 0.0.0.0 to expose it on all interfaces
API_KEY sk-dummy-123 Bearer token clients must send. Authentication is always on — an empty or blank value falls back to sk-dummy-123
FREE_BASE_URL https://opencode.ai The upstream the lane calls. A trailing slash is stripped, a missing scheme is read as http(s)://, and the value is cut at the first control character (the text after it is dropped and reported, so the URL in force is a prefix of what was configured rather than a join of what surrounded the character) — all reported once in the startup log, before the summary, so the line an operator copies always shows the value the gateway actually uses. Any credentials in it are masked wherever it is printed, and /health reports it masked too. Point this at anything that answers the lane's three endpoints to run against a mirror or a local stub
FREE_IMPERSONATE (unset — decided from the host) Tri-state. Unset means "decide from FREE_BASE_URL's hostname": requests to opencode.ai go through the impersonating wreq-js client, anything else through plain fetch. true/false force one or the other. It exists so a lane pointed at a mirror or a test stub does not load a native binding it does not need — and so an operator can override the decision if the upstream moves
DISABLE_TOOLS false Do not forward the client's tools to the upstream, and drop any tool call a model emits anyway, so the model answers in text. The gateway never executes a tool itself in either setting. Booleans accept true/false (JSON) or 1/0, yes/no, y/n, on/off (environment or string); a value none of those match is reported in a [Config] warning together with the value actually used (DISABLE_TOOLS='maybe' is not a boolean ..., using false), for DISABLE_TOOLS, FREE_IMPERSONATE and DEBUG alike
DEBUG false This file's spelling of the switch, and the environment has two: DEBUG and OPENCODE_PROXY_DEBUG (the prefixed one wins when both are set). It promotes logging to debug when no explicit LOG_LEVEL is set — an explicit level wins and the switch is then ignored with a [Config] warning naming the spelling that was set; a value that cannot be read is reported the same way ([Config] DEBUG='maybe' is not a boolean ..., using false), and the startup summary names the source too. LOG_LEVEL=debug is the preferred way
LOG_LEVEL info error, warn, info, or debug (case-insensitive)
OPENCODE_PROXY_MAX_CONCURRENCY 1 Completions processed in parallel (1..32)
OPENCODE_PROXY_MAX_QUEUE 64 Completions that may wait for a free slot (0..4096; 0 means "never queue")
OPENCODE_PROXY_MAX_BODY_MB 50 Largest accepted request body in MiB (1..200)
OPENCODE_PROXY_REQUEST_TIMEOUT_MS 300000 Budget for one completion, in milliseconds

Environment variables:

Variable Maps to
PORT PORT
BIND_HOST BIND_HOST (OPENCODE_PROXY_BIND_HOST is read as an environment-only alias when BIND_HOST is unset)
API_KEY API_KEY
OPENCODE_FREE_BASE_URL FREE_BASE_URL
OPENCODE_FREE_IMPERSONATE FREE_IMPERSONATE (FREE_IMPERSONATE is read as an alias too)
DISABLE_TOOLS DISABLE_TOOLS (OPENCODE_DISABLE_TOOLS is still read as an alias, for setups that predate the rename)
LOG_LEVEL LOG_LEVEL
OPENCODE_PROXY_DEBUG DEBUG (wins over a bare DEBUG when both are set)

Advanced tuning (environment or config.json; the environment wins when both set the same key):

Variable Default Description
OPENCODE_PROXY_REQUEST_TIMEOUT_MS 300000 The completion budget, shared by the queue wait, the upstream request and the whole answer stream. It also bounds how long a request body may take to arrive, up to 30 s (see Request bodies). Values above MAX_TIMER_MS (2147483647) are clamped to it and reported: that is the largest delay setTimeout can hold, so a larger one fired immediately and turned every completion into an instant 504
OPENCODE_PROXY_MAX_CONCURRENCY 1 Number of completions processed in parallel (1..32). 1 keeps the historical serialized behaviour; raise it only if the upstream tolerates concurrent calls from one identity, since they share the free tier's quota
OPENCODE_PROXY_MAX_QUEUE 64 How many completions may wait for a free slot before the gateway answers 503 queue_full instead of accepting more work (the queue holds request bodies, so it is bounded). Counts waiting requests only: 0 rejects a completion when no slot is free instead of queueing it. A slot frees as soon as its response is written
OPENCODE_PROXY_MAX_BODY_MB 50 Largest accepted request body in MiB (1..200). It is the other half of the memory bound: a waiting completion pins its parsed body, so the worst case is this value times OPENCODE_PROXY_MAX_QUEUE. Prompts are small, so lowering it is the cheap way to bound a gateway whose clients are not trusted. A larger body is refused with 413 naming this limit, after the upload is drained so the client reads that error instead of a reset connection: a client that stops sending is answered after 1 s without progress, and one that is still uploading gets up to 5 s. Bytes are only half the bound: a 20 MiB body of empty message objects parsed into about 12x its size in heap, so messages over MAX_REQUEST_ENTRIES (10 000) entries and a content array over MAX_CONTENT_PARTS (10 000) parts are refused with a 400 naming the limit and what arrived (both far above any real conversation). The same ceiling covers every other client-controlled array - a chat messages[].tool_calls, a tools array on all three routes, an Anthropic system array and an Anthropic tool_result.content array
OPENCODE_PROXY_DEBUG unset The prefixed spelling of the DEBUG switch: 1/true promotes logging to debug when no explicit LOG_LEVEL is set, and it wins over a bare DEBUG when both are set. An explicit level wins and the switch is then ignored with a [Config] warning naming the spelling that was set; LOG_LEVEL=debug is the preferred way
OPENCODE_PROXY_BIND_HOST unset Fallback bind address when BIND_HOST is not set — environment only: config.json has just BIND_HOST, and this name in the file is reported as an unknown key and ignored

A tuning value that cannot be used (a typo, a negative number) is reported at startup — [Config] OPENCODE_PROXY_REQUEST_TIMEOUT_MS='abc' is not a positive number, using 300000 — instead of being replaced by the default in silence, so the log always says which value is actually in force.

LOG_LEVEL is read directly from the environment by the Node process, so it always wins over the LOG_LEVEL field in config.json.


API Reference

Base URL: http://<host>:<port>/v1 (for example http://127.0.0.1:8083/v1). Every /v1 request needs Authorization: Bearer <API_KEY> — the scheme is case-insensitive (bearer, Bearer <key> both work) and X-Api-Key: <API_KEY> is accepted as an alias for clients configured with an api-key header; when both are present the Authorization header decides. The default key is sk-dummy-123 and authentication cannot be turned off. Only OPTIONS (a preflight cannot carry credentials), /health (including its trailing-slash spelling, which the router maps to the same handler) and / are unauthenticated.

Streaming is available on all three completion routes: send "stream": true and the answer arrives as SSE in that protocol's own frame vocabulary (chat chunks, Responses events, Anthropic events). It follows each API's own default instead of being forced on — a client that sends no stream gets a JSON body, which is what the OpenAI and Anthropic SDKs expect when they call the non-streaming method — so a client opts in exactly the way its own documentation says.

Every response carries an X-Request-Id header, and the same id appears in the gateway's request log line, so a client-side failure can be matched to a log entry.

Endpoint Method Description
/ GET Service index (no key required): service name, status and the endpoint paths
/health GET Liveness probe; returns gateway status and the configured upstream URL, with any credentials in it masked (http://***@host:4097). It never calls the upstream, so it answers even when the upstream is refusing requests. The endpoint needs no key, so it must not be a way to read one
/v1/models GET OpenAI-style model list
/v1/models/{id} GET Single model; an id the provider list does not contain is still described (the gateway does not restrict models). The slash in opencode/<model> may be sent raw or as %2F. A blank id (/v1/models//) is a 404. The id-derived id/name/owned_by go through the echo rule (64 characters plus the ...[truncated N chars] marker, credentials masked - Bearer <key> answers Bearer ***); an id the provider list does contain is answered verbatim
/v1/responses POST OpenAI Responses API: input (string or items), instructions, tools, reasoning.effort, max_output_tokens, stream. Non-streaming answers the response object; stream: true answers the named SSE events (response.created … response.output_text.delta … response.completed, then [DONE]), each frame carrying an increasing sequence_number (per stream, so concurrent completions cannot number each other's frames); a failure after frames were sent ends the stream with the flat event: error payload {"type":"error","code","message","param":null,…}, which is what a typed Responses client parses - not the {"error":{...}} envelope the JSON error bodies use
/v1/messages POST Anthropic Messages API: model, max_tokens (required), system, block content, tools, thinking, stream. Non-streaming answers the message object (content blocks: thinking, text, tool_use); stream: true answers message_start, content_block_start/delta/stop, message_delta (whose usage carries input_tokens and output_tokens), message_stop
/v1/chat/completions POST Chat completions; supports stream: true for SSE. Every frame is a chat.completion.chunk with the same id/object/created/model envelope, the first one carrying delta.role: "assistant" like OpenAI's, the last one carrying finish_reason: "stop" before data: [DONE]. Comment-line keep-alives are sent whenever a stream has been silent for 15 s — before the first token and between deltas — so a proxy does not drop a connection while the model is still thinking. If the upstream fails after frames were sent, the error arrives as a data: {"error":…} frame and the stream is closed with data: [DONE] — a stream always terminates

Only the three completion POSTs read a request body: a body sent to any other served route is refused with 400 and the connection is closed (see Request bodies).

Wire details that are easy to get wrong. A Responses body carries output_text beside output, and the reasoning item is placed before the message item (the order every Responses client reads); usage is always present (zeros when the upstream published no counters). max_output_tokens is validated and accepted but reported as null: the cap is forwarded to the upstream, but the gateway cannot confirm which number was applied, so it does not echo one as if it had enforced it — the same reason Anthropic's disable_parallel_tool_use is accepted and ignored. Anthropic stop_reason is end_turn, tool_use or max_tokens, and the OpenAI-shaped finish reason is mapped onto it (length → max_tokens, tool_calls → tool_use).

A catalog call that stops answering is bounded by its own deadline (10 s at most, and never longer than the request budget), so /v1/models still answers — with the single static fallback model — instead of hanging. The same fallback covers an upstream that reports no models at all: an empty list would leave a client with nothing to choose from. A fallback answer is held for 1 s: the failing provider is not asked again for every listing that arrives in that window (it used to cost one upstream round trip per request, which is most of the route's throughput), and an upstream that recovers is still picked up within the second — not pinned by the 5 s cache a real listing gets.

Chat completions accepts the usual OpenAI fields; model IDs use the opencode/<model> form. opencode/big-pickle is a stable alias that OpenCode routes to the model it currently serves (the target is not published), and it is the gateway's built-in default, used when model is omitted; every other id is one that GET /v1/models lists for your installation right now.

Fields the gateway respects: messages (string content, or an array of parts whose text is concatenated — see Request bodies for the parts that are refused), model, stream (a boolean, or one of true/false/1/0/yes/no/y/n/on/off — hand-written clients stringify it, and a misread stream used to answer JSON to a client that was parsing SSE), stream_options.include_usage (adds the OpenAI usage chunk — choices: [] plus a zeroed usage block — as the last frame before data: [DONE]; the counts are zero for the same reason the non-streaming usage is) max_tokens and stop where the wire takes them, and tools/tool_choice (see Tool calling). A messages[].name is validated but not forwarded — the free wires carry no per-message label — so a client replaying its own history is not refused for a field this gateway cannot use. Sampling knobs (temperature, top_p, max_tokens, stop, seed, presence_penalty, frequency_penalty, response_format) and the request-level user (OpenAI's abuse-tracking field, which is not forwarded into the prompt) are accepted and ignored: the model is served by the upstream, which owns its own sampling settings, so a request that relies on them gets the model's defaults. n is ignored too — a completion always returns exactly one choice.

A stream or stream_options.include_usage value that is present but cannot be read ("stream": "ture", "stream": {}, "include_usage": "ture") is refused with a 400 naming the field and what arrived (stream must be a boolean (or one of true/false, yes/no, on/off, 1/0), found an object). Such a value used to keep the non-streaming default in silence, so a typo answered 200 application/json to a client that was parsing SSE, or dropped the usage chunk its SDK was waiting for. A missing, blank or null value still means "not streaming", and every spelling listed above keeps working; stream_options itself must be an object when it is sent. The blank spelling (stream: "", what an unset template variable produces) is "not configured" on all three routes, /v1/messages included: it answers a non-streaming 200, where that route used to be the only one that refused it.

stream_options only means something on a stream. A body that sends stream_options with stream false (or absent) is answered as JSON, and the option is ignored rather than refused: the usage chunk it asks for exists to carry numbers a streaming client cannot get any other way, a non-streaming body already carries usage, and answering 400 would refuse a request whose payload is otherwise valid. A client that sets the option on a shared body and sometimes sends stream: false should read usage from the JSON it gets back.

The request body is JSON, but a JSON body sent under application/x-www-form-urlencoded (what curl -d '{…}' labels it when you omit the header) or text/plain is parsed from the string it carries and served all the same. A leading UTF-8 BOM is tolerated there as well — PowerShell 5.1 and most Windows editors write one, and it made a valid body answer request body is not valid JSON. An unparsable body is a 400 whose message names the content type; an unrelated type (application/xml) is a 415, and so is a compressed body (Content-Encoding: gzip): the gateway does not decompress, and answering "not valid JSON" would blame the one part of the request that was correct.

A body that parses but is not a JSON object ("hi", 42, true, []) is a 400 naming what arrived (request body must be a JSON object, found an array) on every path, JSON and text alike. A JSON string body used to be read as unparsed text and answered "request body is not valid JSON" about a body that parses perfectly, while a scalar or an array carried by a text/plain request was replaced by an empty object and blamed on messages.

A body that is not there at all is not invalid JSON either: an empty body (a retry that lost its payload) answers request body is empty; send a JSON object with a messages array — under Content-Type: application/json, where the parser refuses it first and the FST_ERR_CTP_EMPTY_JSON_BODY code is kept, and under the text types, where an empty (whitespace-only included) string used to be reported as a syntax error about nothing — instead of telling the reader about the content type it had set correctly.

curl -X POST http://127.0.0.1:8083/v1/chat/completions \
  -H "Content-Type: application/json" \
  -H "Authorization: Bearer sk-dummy-123" \
  -d '{
        "model": "opencode/big-pickle",
        "messages": [{"role": "user", "content": "Explain event loops in two sentences."}],
        "stream": false
      }'

Every response carries X-Request-Id: the gateway's own gw-… id, or the value of an X-Request-Id header you send (a short token of A-Z, a-z, 0-9, ., _, :, -, up to 64 characters — anything else is replaced). The same id ends the request's log line, so a client report can be matched to a log entry, and it is exposed over CORS so browser clients can read it. Every response also carries X-Content-Type-Options: nosniff: the gateway only writes JSON and SSE, so a browser must not re-interpret a body its own guess disagrees with (on the CORS paths, on streamed responses and on the parser-level rejections alike).

Errors follow the OpenAI error envelope ({"error": {"message": ..., "type": ...}}): 400 for an invalid request (type: "invalid_request_error", with Fastify's own code such as FST_ERR_CTP_INVALID_JSON_BODY when the body could not be parsed), 401 for a missing or wrong key (type: "invalid_request_error", code: "invalid_api_key"; the message names which of the three causes it saw — no key at all, a wrong Authorization header, a wrong X-Api-Key header — and never the value that was sent), 404 for an unknown route (type: "not_found"; the message echoes the method and path and names the endpoints this gateway serves with their methods, so a client pointed at /v1/completions is told the URL it needs and a client that used PUT is told it wants POST), 408/431 for a request the HTTP parser rejected (a timeout, an oversized header block; ordinary parse errors are 400) — those also answer the envelope, with CORS headers and an X-Request-Id, 413 for a body over OPENCODE_PROXY_MAX_BODY_MB (50 MiB by default; the message names the limit it enforced, since sending less or raising the knob is the fix), 415 for a content type or content encoding the gateway cannot read, 502 for an upstream/provider failure (streaming requests included: a refusal that arrives before the first token is an HTTP error, not an empty answer, and a stream cut mid-answer is an upstream failure rather than a 500). A refusal the free tier itself made keeps its own status where a client can act on it — 403 for a refused identity and 429 for a spent quota, with Retry-After: 1 on the 429 so an SDK backs off instead of failing; everything else the upstream rejected is a 502, because a client cannot fix a 400 the free tier produced and reporting it as a gateway bug sends the reader after the wrong process. A 502 carries a code too: backend_unreachable when the upstream could not be reached at all, upstream_error otherwise. 503 in two cases — the completion queue is full (type: "queue_full") or the gateway is shutting down (code: "gateway_shutting_down"), both with a Retry-After: 1 header so SDKs retry instead of failing — and 504 on timeout, including an upstream that accepts the connection and then never answers the request (it is reported as a gateway timeout with the budget that was exceeded instead of leaving the client without a response). Everything the gateway or the upstream failed at carries type: "server_error"; an internal exception's class name is never exposed. Once a stream has started, errors are delivered in-band — never as assistant text. Chat Completions and Messages write their own error event (data: {"error": ...} then data: [DONE]; an Anthropic stream closes an open content block with content_block_stop before event: error), while Responses writes the flat event: error payload described above, so a failure is never misclassified as a client mistake and a client that reads the message off the event finds it.

Vision (images)

An image travels as the image part of the upstream request body, in the wire's own spelling, so the model provider receives it the way that endpoint expects. Three client spellings are accepted and all end up the same way:

  • Chat Completions: {"type":"image_url","image_url":{"url":"...","detail":"high"}} (a bare string is accepted too);
  • Responses: {"type":"input_image","image_url":"..."};
  • Anthropic: {"type":"image","source":{"type":"base64","media_type":"image/png","data":"..."}} or {"type":"url","url":"..."}.

A data:image/...;base64, URI is forwarded inline (bounded at 20 MiB of decoded bytes, refused above it) and an http(s) URL is forwarded by reference — the gateway never fetches it, so there is no second SSRF surface in the request path. On the Messages wire an inline URI becomes the base64 source and a remote one the url source; on the other two it is a data: URI in the same field either way. Whether the chosen model can actually see images is the upstream's own capability; the gateway forwards the image and relays the refusal, which is a sentence a client can act on, instead of guessing.

Reasoning effort (thinking)

reasoning_effort (Chat Completions, Responses: reasoning.effort) accepts minimal / low / medium / high / xhigh / max / none (plus default/auto for "no preference"). Anthropic sends a budget instead, and the gateway maps it to the closest level: < 4000 → low, < 16000 → medium, otherwise high; thinking: {"type":"disabled"} means none.

The level is then sent in the spelling of the wire the model is served on:

  • Chat Completions — a top-level reasoning_effort, for the levels that endpoint's enum accepts. default/auto and none send no field at all: asking for no raised thinking is the absence of a request, and the model's own default is what a client that does not think about thinking gets.
  • Responses — the nested object that wire takes, reasoning: {effort, summary: "auto"}; a top-level reasoning_effort is rejected there as an unknown variant.
  • Messages — thinking: {type: "enabled", budget_tokens: N}, with N from the documented band (minimal 1024, low 2048, medium 8192, high 16384, xhigh 24576, max 32000). The Messages API requires budget_tokens < max_tokens, so the output cap grows to make room when the client's own cap is lower than the budget plus 1 024; a request that sent no cap at all gets 8192, the smallest cap every free Messages-native model accepts.

A blank reasoning_effort ("", what an unset template variable produces) is "not configured" on both OpenAI-shaped routes, like a blank stream; every other unreadable value is a 400 naming the field and the levels it accepts. The vocabulary itself is closed — there is no per-model capability check, because the free lane cannot ask a model what it supports before sending the request: a level the model does not implement is the upstream's refusal to report, not a guess this gateway makes.

The reasoning text itself is returned in each protocol's own place: reasoning_content (Chat Completions), a reasoning output item (Responses), and a thinking content block (Anthropic).

Tool calling

The free lane speaks the upstream's native tool API: the client's tools are declared to the upstream in the wire's own spelling (Chat Completions {type:"function",function:{...}}, Responses {type:"function",name,...}, Messages {name,description,input_schema}), and the calls the model makes arrive as that wire's own tool-call deltas. There is no text markup anywhere in this path: src/opencode-free/stream.ts reassembles a call from its streamed fragments — the Chat wire streams an id, a name and argument fragments separately, and a half-parsed argument string is a request the client cannot send back — and the pipeline publishes each call whole.

  1. a streamed call is assembled from its fragments, and a call that never completed is never published: the client executes what it is given, so a half-parsed call is worse than no call;
  2. the caller's tool name is restored before publication when the request had to send it under an alias — a name that collides with the fingerprint tools read/shell, or one containing terminal, which the upstream refuses outright;
  3. the answer carries the protocol's own shape: finish_reason: "tool_calls" with a tool_calls array (Chat Completions), a function_call output item (Responses), or stop_reason: "tool_use" with tool_use blocks (Anthropic);
  4. the client executes the tools and sends the results back on the next request (role: "tool" with tool_call_id, function_call_output items, or Anthropic tool_result blocks), and the lane replays them in the wire's own result spelling - including the assistant turn's calls, so a client can round-trip its own history.

A tool definition is bounded on both fields: the description is capped at 4096 characters and the rendered JSON Schema at 64 KiB — a larger one is a 400 naming tools[N].parameters (Anthropic spells it input_schema), the limit and the size it rendered to, instead of being sent upstream. A role: "tool" message whose tool_call_id is present but not a string is a 400 naming the field, and an image inside a tool result is refused by name, because a tool result is forwarded as text.

tool_choice is honoured as auto, none, or one tool by name. none needs a note: the free gate refuses tool_choice: "none" with 403, so the gateway asks the upstream for auto instead and drops any call that arrives anyway — a client that asked for no tool use still gets none, but the request that went upstream does not say so. required/any is a known gap: the three request parsers accept it (it is part of the OpenAI and Anthropic vocabularies) but the lane has no upstream spelling for "must call a tool", so the value reaches the wire as a malformed named choice. Do not rely on it until the lane maps it.

DISABLE_TOOLS=true withholds the client's tools entirely: they are not forwarded, the fingerprint declarations are still sent (the upstream refuses a request without them), and any call the model emits anyway is dropped. Those fingerprint definitions are placeholders this gateway cannot execute, so the lane tells the model in the system prompt not to call them; a call to one that arrives regardless is published like any other call, which is why that instruction is not cosmetic.

Request bodies

Only the three completion routes read a body. POST /v1/chat/completions, POST /v1/responses and POST /v1/messages are the body-reading routes. Every other route the router serves - /, /health (both answered without a key), any OPTIONS preflight, and GET/HEAD on /v1/models and /v1/models/{id} - refuses a declared body (Content-Length > 0 or Transfer-Encoding) before a byte of it is read:

{"error":{"message":"this request carries a body, but only POST /v1/chat/completions, POST /v1/responses and POST /v1/messages read one; send the request without a body","type":"invalid_request_error"}}

The answer carries Connection: close and the socket is closed behind the envelope. The reason is memory rather than taste: the announced bytes on a route that never reads them were read anyway to keep the connection reusable, so an unauthenticated caller chose how much of the process's memory a request could occupy (measured: four 25 MiB bodies on GET /health grew the process by 67.7 MB, 84 MB with the connection kept alive; +0.1 MB after the refusal). The refusal is for a route that is about to answer: a path or method the router does not serve keeps its 404 sentence (POST /v1/completions, PUT /v1/chat/completions) and is answered it before the announced body is read either, and an unauthenticated caller of a protected path still gets its 401 first. The same measurement applies there: eight concurrent 4 MiB POST /v1/embeddings bodies grew the process by 78.7 MB before and +0.5 MB after, and a stalled upload that used to wait out the body deadline now reads its 404 in milliseconds.

Content parts are text and images. A content array may carry strings and parts that have a text field (text, and the Responses-API spelling input_text), plus the image parts above. Any other part — input_audio, file — is refused with a 400 that names its position and type, because the gateway cannot carry it:

{"error":{"message":"messages[0].content[1] uses an unsupported content part type \"input_audio\"; this gateway forwards text and images only","type":"invalid_request_error"}}

A part whose text field is missing is told which field is missing rather than which type is unsupported (messages[0].content[0].text is required for a text part), and an object with neither a type nor a text ({}, {"type":5}) is refused as one (… must be a string or an object with a text field, found an object without a text field) — neither quotes a type the client did not send.

Dropping those parts instead (the previous behaviour) answered a question the upstream never received, and a request whose only part was an image was reported as missing text it had never been asked for. The part's own type is what decides, before its text field: a part typed input_audio/file that also carries a string text is refused with this same answer (the chat route used to serve it as text while the other two routes refused it), while a part with no usable type that carries a string text is still text.

A part whose text field is present but not a string is named by that field (messages[0].content[1].text must be a string, found a number) instead of being called an unsupported type — text is the part type the gateway does forward. A part that is not a part at all (42, null, true) is refused the same way (messages[0].content[0] must be a string or an object with a text field, found a number), because dropping it left the request failing the "no text at all" check and blaming the client's text.

A content that is a single object instead of an array follows the same three rules, reported without a part index (messages[0].content uses an unsupported content part type "input_audio"; this gateway forwards text and images only, messages[0].content.text must be a string, found a number). Such a message used to be read as empty and dropped in silence: a request that also carried text was answered from that text alone (a confidently wrong answer), and a system/developer message written that way lost its instructions instead. A single object with a string text is a shape some clients send and is still forwarded.

A content that is a bare scalar (42, true) is refused the same way (messages[0].content must be a string or an object with a text field, found a number): it is not text the client wrote, and stringifying it sent the model the number as the question — a template that lost a field asked something nobody asked and was answered. OpenAI refuses the type as well.

A message name is accepted but not forwarded. It is validated like every other field (a present non-string is a 400 naming it), because a client replaying its own history should not be refused for a field this gateway cannot use. The free wires carry no per-message label — there is nowhere to put it — so it does not reach the model, and no USER(name): prefix is built from it any more. A name carrying a newline therefore cannot forge a second conversation line: it never leaves the gateway.

A body must arrive. A request that announces a body (Content-Length, Transfer-Encoding: chunked) has to deliver it within 30 s or the shared request budget, whichever is shorter — and that window is about silence, not about the size of the upload: it renews while the socket is making progress, so a slow client that is genuinely sending is served, up to a total of that window plus one request budget. On expiry the client receives the 408 envelope (request body was not received within …ms; send the declared body or close the connection, or, when the upload was still progressing, the window and the upload budget it exceeded) and the connection is closed; a request that was already refused (an unauthenticated one, for example) is simply disconnected, because the client is not waiting for another answer. Without that deadline a client could send Content-Length: 4096, write four bytes and hold the socket open for as long as it liked — no credential required, since the 401 is written from the headers alone while the connection stays alive to drain a body that will never arrive.


Client Examples

Python (official OpenAI SDK)

from openai import OpenAI

client = OpenAI(base_url="http://127.0.0.1:8083/v1", api_key="sk-dummy-123")
response = client.chat.completions.create(
    model="opencode/big-pickle",  # stable alias; any id from GET /v1/models works
    messages=[{"role": "user", "content": "Hello!"}],
)
print(response.choices[0].message.content)

Node.js (official OpenAI SDK)

import OpenAI from 'openai';

const client = new OpenAI({ baseURL: 'http://127.0.0.1:8083/v1', apiKey: 'sk-dummy-123' });
const res = await client.chat.completions.create({
    model: 'opencode/big-pickle', // stable alias; any id from GET /v1/models works
    messages: [{ role: 'user', content: 'Hello!' }],
});
console.log(res.choices[0].message.content);

OpenAI Responses API (same Python SDK)

stream = client.responses.create(
    model="opencode/big-pickle",
    input="Explain event loops in two sentences.",
    stream=True,
)
for event in stream:
    if event.type == "response.output_text.delta":
        print(event.delta, end="")

Anthropic Messages API (official Anthropic SDK)

from anthropic import Anthropic

client = Anthropic(base_url="http://127.0.0.1:8083", api_key="sk-dummy-123")
message = client.messages.create(
    model="opencode/big-pickle",
    max_tokens=1024,          # required by this API
    messages=[{"role": "user", "content": "Hello!"}],
    thinking={"type": "enabled", "budget_tokens": 8000},   # optional: sent as this wire's thinking budget
)
print(message.content[-1].text)

curl, all three routes

curl -s http://127.0.0.1:8083/v1/chat/completions -H 'Authorization: Bearer sk-dummy-123' \
  -H 'Content-Type: application/json' -d '{"messages":[{"role":"user","content":"hi"}]}'

curl -s http://127.0.0.1:8083/v1/responses -H 'Authorization: Bearer sk-dummy-123' \
  -H 'Content-Type: application/json' -d '{"input":"hi","stream":true}'

curl -s http://127.0.0.1:8083/v1/messages -H 'Authorization: Bearer sk-dummy-123' \
  -H 'Content-Type: application/json' -H 'anthropic-version: 2023-06-01' \
  -d '{"model":"opencode/big-pickle","max_tokens":256,"messages":[{"role":"user","content":"hi"}]}'

Any other OpenAI-compatible tool works the same way: point its base URL at http://127.0.0.1:8083/v1 and set its API key to your API_KEY value (sk-dummy-123 unless you changed it) — the key is never optional; an OpenAI Responses client uses the same base URL and /v1/responses. A client that speaks the Anthropic Messages API (Claude Code included) points at http://127.0.0.1:8083 and calls /v1/messages with the same key.


Logging

All output goes to stdout/stderr with a [gateway] prefix:

[gateway] <ISO timestamp> [LEVEL] message {"detail":"json"}
Level Content
error Upstream failures (with status code and error-body summary) and fatal startup problems. Always emitted, stderr.
warn Invalid configuration fallbacks and self-recoverable anomalies. stderr.
info Default. Startup information plus a one-line summary for every /v1/* request: method, path, model, streaming, status, latency, request id. Other paths (a health probe, the index page) are summarised at debug, so a probe loop cannot flood the log. The model id in that line is normalised (control characters replaced, length capped): it comes from the request body, and a newline in it must not be able to start a second log line. A value the operator configured (a path, a log level, a bind host, a tuning value) is normalised the same way wherever a startup line quotes it, including the [Config] note that names a value it could not use. stdout.
debug Inbound request headers and body (credential-shaped values masked), the final payload sent upstream, and full responses. stdout.

A request body that carries __proto__ as a property name, or a constructor that itself carries a prototype (the pair that turns into prototype pollution if the object is ever copied), is refused with 400 before it reaches the handler (the JSON parser's own prototype-poisoning guard, applied to a body sent as text as well); the message names that reason rather than claiming the JSON is invalid, because a body with one of those keys parses fine and the fix is to remove the key, not the comma. A plain constructor key that carries no prototype is ordinary data and is served under every content type. A 415 likewise names what it refused: unsupported content type "application/xml"; send Content-Type: application/json, and the request has a body but no Content-Type header; send Content-Type: application/json when the header is missing. The type is client input echoed into a response body, so it is bounded and masked like any other echoed value: a client that sent application/json; api_key=… is told the type it sent and not handed its secret back.

Sensitive headers such as authorization, x-api-key, cookie and any name carrying a credential segment — token, secret, session, password/passwd/pwd, key, code, sig/signature, credential, bearer — are masked before they are logged, and so are credential values sent in a query string (?api_key=…, and the spellings other clients use for the same secret: Google's ?key=…, an OAuth ?code=…, an Azure SAS ?sig=/?signature=… — in a fragment too, since a raw client can send GET /v1/models#access_token=…, which curl and browsers strip but a socket does not) and a credential carried by the configured upstream URL (http://user:secret@host:4097, a proxy in front of a mirror): the startup summary, the [Config] notes and /health show http://***@host:4097 instead. An upstream reason that quotes the same credential back — a proxy in front of the upstream reporting the Authorization: Basic … header it refused — is masked as Basic *** before it reaches a 502 body or a log line, the configured upstream credential is masked even when something quotes it base64-encoded and shorter than 16 characters, and a user:pass@ inside the URL of a request log line is masked too. The same sentence is masked in a stack trace and in a debug dump of a request body: a stack's first line is the message it repeats, so a record that masked message and printed stack verbatim published the credential the masking had just removed. A string in that dump is cut at 32 KB before it is masked, the length the finished line is cut to: a body at the 50 MiB limit cost 688 ms of event loop per debug line while only the first 32 KB of it could ever be printed. A parsed body is walked under a total node budget for the same reason — past it the masked copy says [truncated: detail budget] — so a body made of hundreds of thousands of tiny objects cannot spend seconds building output that the same 32 KB cut discards. The container's first-boot line prints the API key as its length and, above 16 characters, a 4-character prefix — docker logs is collected as often as not. Masking replaces the value of a header or key and never drops it: an odd name such as __proto__ is still shown (masked like any other), because the debug dump is what you read to see what a client actually sent. Two shapes are masked that are not headers or query strings at all: a credential that carries a space (http://user:pass phrase@host:4097, which Node's own "URL that includes credentials" sentence quotes verbatim) is masked inside a sentence, and a bare name=value pair whose name is a credential (api_key=…, application/x-api-key=…) is masked in the values echoed back into a response body, such as the Content-Type a 415 names - and the pair rule keeps scanning inside a non-credential match, so a proxy's invalid credentials: api_key=... is masked rather than swallowed whole. The quoted value no longer needs its closing quote (a truncated upload is masked) and either quote character is accepted ({'api_key': '...'}), and privatekey/privatekey_pem are credential names. A pair is masked when its name is a credential (bearer=<token> included); basic=<value> is deliberately not, because basic is an ordinary word (basic: setup). The same chain runs before a value is echoed back into a response body: a Bearer <token> above the quoted-credential rule's 16-character floor shows Bearer *** there, and a value the gateway registered as secret (its own API key) is masked by value as well, including inside a request URL whose parameter name is not a credential (GET /v1/models?model=<key> is logged and answered as ?model=***).

The startup summary prints the effective port, upstream URL, whether the transport impersonates, tool filtering, log level and capacity (Concurrency: … completion(s) processed in parallel, Wait queue: … waiting completion(s) before 503 queue_full). A OPENCODE_PROXY_MAX_CONCURRENCY / OPENCODE_PROXY_MAX_QUEUE / OPENCODE_PROXY_MAX_BODY_MB value that is not a number, or is outside its range, is reported as a warn line next to it instead of being applied silently — a throughput knob that quietly falls back to the default is indistinguishable from one that has no effect.


Docker

A container image is published for linux/amd64 and linux/arm64; there is no CLI inside it, because the gateway does not need one. See docker/README.md for image tags, environment variables, and port exposure.

docker pull dinhdev666/opencode-api:latest
docker run -d --restart=always -p 8083:8083 -e API_KEY=sk-your-key dinhdev666/opencode-api:latest

Docker Hub selects the matching architecture automatically. The image runs as the unprivileged node user (uid/gid 1000), not as root: a bind-mounted config.json or credential directory has to be readable by that user (see the container README). A new image is published by .github/workflows/docker-publish.yml whenever a v*.*.* tag is pushed — see CI and Releases.


CI and Releases

Two GitHub Actions workflows live in .github/workflows/; the CI checks need no secrets at all:

Workflow Trigger What it does
ci.yml every push to main, every pull request, manual dispatch Three jobs. Test runs pnpm run check (the TypeScript compiler over the whole project), sh -n + shellcheck on docker/docker-entrypoint.sh and pnpm test (every suite in test/, each run from its compiled file in dist/, none of which needs network access or an OpenCode CLI) on Node 20, 22 and 24, plus an advisory pnpm audit --audit-level high on the Node 22 entry only (continue-on-error: true, never a gate), plus a gate step — every action pinned to a commit SHA. No suite gates a check behind an environment variable any more: the slow checks (the 15 s SSE keep-alive line, the idle-timeout hold) run inside pnpm test on every matrix entry. Commit messages follow the convention runs pnpm run check:commits over the commits this run adds, in its own job so it cannot disappear with a matrix entry. Build the container image builds the image for the runner's architecture, builds it again for linux/amd64,linux/arm64 (the two published platforms, no registry involved), starts the container and waits for /health to answer.
docker-publish.yml pushing a v*.*.* tag, or a manual dispatch from a tag Fails if the tag does not match version in package.json, then builds linux/amd64 + linux/arm64 and pushes <version> and latest to Docker Hub. Needs the DOCKERHUB_USERNAME and DOCKERHUB_TOKEN repository secrets. The tagged commit must already be on main and every check run on it must have concluded success, skipped or neutral: a tag on a commit CI never ran is refused.

The required status checks on main are Test on Node 20, Test on Node 22, Test on Node 24, Build the container image and Commit messages follow the convention, so renaming those jobs also changes the branch protection rules.

Publishing a release is therefore just a tag:

git tag vX.Y.Z        # must match "version" in package.json
git push origin vX.Y.Z

Project Structure

.
├── index.ts                  # Entry point: merges config and starts the gateway
├── tsconfig.json             # strict TypeScript; rootDir "." -> dist/
├── src/
│   ├── proxy.ts              # Fastify app, the completion pipeline, every route, the queue call sites
│   ├── opencode-free/        # The free lane: the whole upstream conversation
│   │   ├── lane.ts           # The one object the pipeline talks to
│   │   ├── driver.ts         # One completion: identity headers, the overload retry, the stream
│   │   ├── request.ts        # Normal form -> the upstream body, on the model's own wire
│   │   ├── fingerprint.ts    # The request-side fingerprint: read/shell definitions, <env>, aliases
│   │   ├── constants.ts      # Every value the upstream gate compares, and what each is load-bearing for
│   │   ├── session.ts        # ses_... minting and the one-session-per-conversation rule
│   │   ├── transport.ts      # wreq-js on opencode.ai, plain fetch anywhere else
│   │   ├── stream.ts         # The three wires' SSE vocabularies -> one normalized event stream
│   │   ├── sse.ts            # SSE frame reader
│   │   ├── catalog.ts        # /zen/v1/models, narrowed to what the free tier serves
│   │   └── types.ts          # The lane's input contract
│   ├── chat.ts               # Chat Completions: request normalizer, body builder, SSE writer
│   ├── responses.ts          # OpenAI Responses: request normalizer, body builder, SSE writer
│   ├── anthropic.ts          # Anthropic Messages: request normalizer, body builder, SSE writer
│   ├── protocol.ts           # Shared normal form, field readers and the answer vocabulary
│   ├── wires.ts              # The protocol wires, the route table, the early-refusal envelope
│   ├── models.ts             # The model cache and the three /v1/models routes
│   ├── queue.ts              # The completion queue: limits, admission, shutdown and the 503 sentence
│   ├── reasoning-effort.ts   # Thinking effort: one vocabulary in, each wire's spelling out
│   ├── text.ts               # Request ids, log-safe truncation and masking of values
│   ├── errors.ts             # Client-facing sentences for a failed upstream call
│   ├── upstream.ts           # Classifies what was thrown (status, cause chain, error tags)
│   ├── socket.ts             # end() then destroy() fallback for a raw socket close
│   ├── api-key.ts            # The built-in API key and resolveApiKey()
│   ├── env.ts                # Upstream URL and bind-host normalisation
│   ├── options.ts            # parseBoolean()/readFlag()/readTriFlag(), the single boolean parser
│   ├── settings.ts           # Tuning-key readers and their defaults
│   ├── config.ts             # Reads config.json (a missing file is fine, an unusable one stops the gateway)
│   └── logger.ts             # Zero-dependency leveled logger with secret masking
├── config.json.example       # Sample configuration
├── package.json              # Scripts, dependencies, packageManager pin (pnpm)
├── pnpm-lock.yaml            # Locked dependency tree (pnpm)
├── docker/                   # Dockerfile, entrypoint, container documentation
├── test/
│   ├── contract.ts           # The gateway's own HTTP contract
│   ├── protocols.ts          # /v1/responses and /v1/messages end to end
│   ├── stream.ts             # The upstream-facing behaviour, asserted from the wire and the stub
│   ├── effort.ts             # Thinking-level table, its downgrade, and the level the upstream receives
│   ├── vision.ts             # Images in each wire's own shape, and the file refusal
│   ├── live-free.ts          # Opt-in: one real request to opencode.ai (not part of pnpm test)
│   ├── protocol-chat.ts      # Codec unit suite: normalizer, body builder, SSE writer
│   ├── protocol-responses.ts # The same for the Responses codec
│   ├── protocol-anthropic.ts # The same for the Anthropic codec
│   ├── lib/
│   │   ├── stub-free-upstream.ts  # The upstream stand-in, with the free tier's gates
│   │   ├── free-harness.ts        # Shared scaffolding for the .ts suites
│   │   └── codec-checks.ts        # Shared assertions the three codec suites load
│   └── checks/
│       ├── check-syntax.ts   # The dependency, package-manager, bump-bot and image invariants
│       └── check-commit-messages.ts  # Applies the CONTRIBUTING.md rules to a commit range
├── .github/workflows/
│   ├── ci.yml                # CI: typecheck, shell check, every suite on Node 20/22/24, Docker build
│   └── docker-publish.yml    # Release: multi-arch image to Docker Hub on a v*.*.* tag
├── AGENTS.md                 # Invariants, architecture map and verification rules for coding agents
├── CONTRIBUTING.md           # Setup, coding conventions, commit message standard, PR checklist
└── LICENSE

Troubleshooting

Symptom Likely cause and fix
403 with FreeTierError in the body The upstream refused this request's identity or shape. The usual causes are a request that does not declare OpenCode's own read/shell tools, one without the <env> system marker, or a FREE_BASE_URL pointing at the old /zen/v1 inference paths, which now answer 403 for every free request. src/opencode-free/fingerprint.ts documents exactly what it compares
429 with FreeUsageLimitError in the body The free quota for the session is spent. The gateway drops the session id it minted after this answer, so the next request starts on a fresh one — but a client that sends its own x-opencode-session keeps its own id, so stop sending it if the errors persist. Otherwise this is the upstream's quota, not a gateway setting
429 whose body says overloaded Transient load shedding, not a quota problem. The lane retries it on a bounded backoff (eight attempts, roughly 20 s) before surfacing it, so a client that sees one has already waited the schedule out; retrying immediately will not help
wreq-js could not be loaded The native binding for this platform is missing. pnpm install fetches the matching @wreq-js/binding-* package; a global install, an install with scripts disabled, or a container built for another architecture leaves it out. Reinstall with pnpm. If you do not need the gate at all, point FREE_BASE_URL at a mirror or stub: the binding is only loaded for opencode.ai, and only on the first completion
401 Unauthorized The request has a missing or mismatched Authorization: Bearer ... header (the message says which: no key, a wrong Authorization header, or a wrong X-Api-Key header); send the configured API_KEY (default sk-dummy-123). The upstream's Bearer public is unrelated — that is the gateway's own upstream identity, not a client credential
Requests time out The upstream is slow, or the model is thinking before its first delta. /health answers regardless, because it never calls the upstream; raise OPENCODE_PROXY_REQUEST_TIMEOUT_MS if your client can wait longer. The lane's own per-request budget is 120 s (FREE_REQUEST_TIMEOUT_MS)
403 on a request that declares tools A declared tool name containing terminal is refused by the gate regardless of quota. The lane sends such a name under an alias and restores the caller's spelling in the answer, so seeing this means the name reached the upstream some other way
429/403 from a mirror you configured Only opencode.ai compares the TLS fingerprint, so a mirror reached over FREE_BASE_URL uses plain fetch. A mirror that sits in front of the real gate will refuse it: set FREE_IMPERSONATE=true to force the impersonating client against that host
503 queue_full with Retry-After: 1 Every completion slot is busy and the wait queue is full (OPENCODE_PROXY_MAX_QUEUE, default 64). Retry after the advertised delay, or raise OPENCODE_PROXY_MAX_CONCURRENCY — but concurrent completions share the free tier's quota, so raising it can spend it faster
400 model "..." must be a "provider/model" id The model value had an empty half (opencode/ or /big-pickle). Send a full id from /v1/models, or omit model to use opencode/big-pickle
502 with code: "upstream_error" The upstream rejected the request for a reason the client cannot fix; the message carries the upstream's own sentence. Check FREE_BASE_URL, the fingerprint and the model id first
502 with code: "backend_unreachable" The upstream could not be reached at all (DNS, TLS or the network). /health keeps answering 200 throughout, because it does not call the upstream
503 with code: "gateway_shutting_down" The gateway received SIGINT/SIGTERM and is finishing the responses it already accepted. Retry after the advertised Retry-After (1 s) against a gateway that is up — a load balancer should stop sending new work on the first signal
400 ... this request carries a body, but only POST /v1/chat/completions, POST /v1/responses and POST /v1/messages read one The request sent a body to a route that reads none (/, /health, OPTIONS, GET/HEAD on /v1/models). Send it without a body; the connection is closed behind this answer
400 tools[0].parameters must not serialize to more than 65536 characters The tool's JSON Schema is over the 64 KiB cap (the description is capped at 4096 characters without an error). Shorten the schema, or move prose into the description
tool_choice: "required" behaves strangely Known gap: the parsers accept required/any, but the lane has no upstream spelling for "must call a tool". Use auto with a clear system prompt until the lane maps it
Requests fail while a body uploads The gateway answers 408 when a declared body stops arriving (no bytes for 30 s or the request budget, whichever is shorter). A slow but steady upload is served; a stalled one is closed so it cannot hold a socket without a credential
Port already in use Change PORT in config.json or the environment
The gateway exits immediately, config.json is not valid JSON ... Fix the syntax or delete config.json; the process refuses to start rather than ignore a key you configured

Security

  • Your API_KEY is always enforced. Every route except OPTIONS, /health and / requires Authorization: Bearer <API_KEY> (or X-Api-Key), there is no switch that disables it, and a blank key falls back to the built-in sk-dummy-123 — which startup warns about, because that key is public and the CORS headers allow any origin. Keep BIND_HOST on 127.0.0.1 unless you have put something in front of it.
  • The gateway holds no upstream credential. The free tier is used with the identity the CLI uses (Authorization: Bearer public, see src/opencode-free/constants.ts), so your API_KEY is never sent to opencode.ai and there is no upstream token in config.json to protect. What the gateway does protect is what it logs: request bodies and headers pass through the masking chain in src/logger.ts before they are written.
  • wreq-js is a native dependency. Reproducing the TLS fingerprint the upstream accepts needs a client that can set a cipher list, which Node's OpenSSL cannot, so the lane loads wreq-js — a Rust/BoringSSL client shipped as a per-platform binary binding. It is pinned to an exact version for that reason, it is imported lazily on the first completion (a gateway that only answers /health never loads it), and it is only used when the base URL's host is opencode.ai. Like any native dependency it is code that runs in this process; install it the way you install the rest of the tree.
  • Reproducing the upstream's gate is the gateway's own risk. The lane exists to look like a client the upstream accepts. That is not an entitlement to the service: the gate can change at any time, the free tier's quota and terms are OpenCode's to set, and a gateway that breaks when they change is the expected outcome rather than a bug in your configuration.
  • A plain-http upstream is warned about. FREE_BASE_URL over http:// to a host that is not loopback sends the whole conversation in clear text; startup says so, because the only safe place to point that at is a local mirror.

Contributing

Read CONTRIBUTING.md for the development setup, coding conventions, the Conventional Commits message standard used in this repository and the pull request checklist. AGENTS.md documents the invariants (mandatory authentication, the three wire formats) and the verification steps expected before a change is merged.


License

Released under the MIT License.
Copyright (c) 2026 Phạm Văn Định.


Related Links

Contributors

Languages