Skip to content

Repository files navigation

OpenCode API

A REST API gateway that exposes the AI models reachable by the OpenCode CLI 2.x runtime through OpenAI-compatible (/v1/chat/completions, /v1/responses, /v1/models) and Anthropic-compatible (/v1/messages, /v1/messages/count_tokens) endpoints. It supports streaming, vision and media input (base64 data URIs, remote URLs fetched and inlined server-side, opt-in local files), thinking-effort / reasoning control, and prompt-bridged function calling for clients that send OpenAI or Anthropic tool declarations. Point an existing OpenAI or Anthropic SDK at it by changing only the base URL.

Requirements

  • Node.js >= 20.11 — the supported range is the CI matrix: Linux with Node 20.x and 22.x, plus Windows with Node 22.x, which exercises the Windows-specific paths (O_NOFOLLOW is unavailable there, CLI discovery walks %APPDATA%/%LOCALAPPDATA%). The container image ships Node 22 (node:22-bookworm-slim).
  • pnpm (the repository ships a pnpm-lock.yaml)
  • An installed opencode CLI 2.x on PATH, or an explicit path through OPENCODE_BIN (verified against 2.3.2 and 2.4.3)
  • Network access for the OpenCode runtime to reach its model providers

Quick start

# 1. Install dependencies
pnpm install

# 2. Start the gateway (works with no configuration: the default key is sk-dummy-123)
pnpm dev            # production: pnpm build && pnpm start

Authentication is on by default with the built-in key sk-dummy-123, so the first request works immediately:

curl http://127.0.0.1:20123/v1/chat/completions \
  -H "Authorization: Bearer sk-dummy-123" \
  -H "Content-Type: application/json" \
  -d '{"model":"opencode/deepseek-v4.1-flash-free","messages":[{"role":"user","content":"Say OK"}]}'

That key ships with the project and is therefore public: anyone who can reach the port can use it. Before exposing the gateway beyond localhost, set your own:

pnpm setup                   # writes .env (keeps sk-dummy-123)
pnpm setup -- --random       # writes .env with a strong random key instead

Both print the resulting key; edit .env directly to set a specific value. Run pnpm setup -- --random --force to rotate an existing custom key.

With no .env at all the gateway still starts and logs a warning that the default key is in use. The same warning is logged when .env lists the published key explicitly, which is what .env.example and pnpm setup do — GET /admin/config reports auth.usingDefaultApiKey: true in both cases. OPENCODE_ALLOW_NO_AUTH=true disables authentication entirely on a trusted loopback host.

Health check:

curl http://127.0.0.1:20123/health
{
  "status": "ok",
  "service": "opencode-api",
  "version": "1.0.0",
  "uptimeSeconds": 3,
  "upstream": { "ready": true, "source": "spawned" }
}

First chat request:

curl http://127.0.0.1:20123/v1/chat/completions \
  -H "Authorization: Bearer $OPENCODE_API_KEY" \
  -H "Content-Type: application/json" \
  -d '{
    "model": "opencode/deepseek-v4.1-flash-free",
    "messages": [{"role": "user", "content": "Say hello in one short sentence."}]
  }'

GET /v1/models lists the exact model ids your installation exposes — use one of those. The gateway never talks to a model provider directly; it routes every turn through the OpenCode runtime, so the model must exist there.

OpenAI client

import OpenAI from "openai";

const client = new OpenAI({
  baseURL: "http://127.0.0.1:20123/v1",
  apiKey: process.env.OPENCODE_API_KEY,
});

const stream = await client.chat.completions.create({
  model: "opencode/deepseek-v4.1-flash-free",
  stream: true,
  messages: [{ role: "user", content: "Say hello in one short sentence." }],
});

for await (const chunk of stream) {
  process.stdout.write(chunk.choices[0]?.delta?.content ?? "");
}

Anthropic client

import Anthropic from "@anthropic-ai/sdk";

const client = new Anthropic({
  baseURL: "http://127.0.0.1:20123", // the SDK appends /v1/messages
  apiKey: process.env.OPENCODE_API_KEY,
});

const message = await client.messages.create({
  model: "opencode/deepseek-v4.1-flash-free",
  max_tokens: 256,
  messages: [{ role: "user", content: "Say hello in one short sentence." }],
});

console.log(message.content);

Both SDKs send the key as a header the gateway understands (Authorization: Bearer and x-api-key respectively).

How the upstream connection works

The gateway speaks the local HTTP API of an OpenCode server. It resolves one in this order, and reuses it until it dies:

  1. OPENCODE_SERVER_URL — an explicit server you manage. The endpoint must answer an authenticated GET /api/model probe; otherwise startup-time health turns unavailable. Pair it with OPENCODE_SERVER_PASSWORD.
  2. A private spawned opencode serve — the default. When no explicit server is configured and OPENCODE_AUTOSTART=true, the gateway spawns opencode serve --hostname <OPENCODE_INTERNAL_HOST> --port <OPENCODE_INTERNAL_PORT> (plus OPENCODE_SERVER_ARGS), reads server listening on <url> and server password <password> from its output, and authenticates with HTTP Basic. If the port is busy it retries the next nine ports. The process is killed when the gateway shuts down. Its stdout/stderr is appended to <OPENCODE_DATA_DIR>/logs/opencode-<port>.log.
  3. A discovered background service — the OpenCode TUI starts a background server and records it in service.json (under $XDG_STATE_HOME/opencode/ or $XDG_CONFIG_HOME/opencode/). The gateway uses it when the PID is alive and the descriptor's URL answers the probe.

OPENCODE_AUTOSTART=false skips mode 2 and goes straight to discovery.

How the CLI binary is found

For mode 2 the gateway needs the executable. OPENCODE_BIN wins when set (an absolute path is recommended). Otherwise it searches, in order:

  • every directory on PATH, for opencode / opencode2 (opencode.exe / opencode2.exe on Windows; .ps1 and .cmd shims are deliberately skipped because they cannot be spawned without a shell);
  • well-known global install locations: on Linux/macOS /usr/local/bin, /usr/bin, /opt/homebrew/bin, ~/.local/bin, ~/.bun/bin, ~/.opencode/bin, ~/.cache/opencode/bin; on Windows %APPDATA%\npm, %APPDATA%\npm\node_modules\@opencode\cli\bin, %LOCALAPPDATA%\pnpm, %LOCALAPPDATA%\Programs\opencode;
  • PNPM_HOME, NVM_BIN and VOLTA_HOME/bin when those variables are set.

When nothing is found the request fails with: OpenCode CLI executable not found. Set OPENCODE_BIN to the full path of the opencode binary. GET /admin/status reports the resolved path under upstream.binary.

Endpoints

Method Path Description
POST /v1/chat/completions OpenAI Chat Completions: streaming and non-streaming, tools, images, reasoning_effort.
POST /v1/responses OpenAI Responses API with its typed SSE event sequence.
POST /v1/completions Legacy OpenAI completions: a prompt string (an array prompt requires n: 1) mapped to one user turn, streamed or buffered.
POST /v1/messages Anthropic Messages: streaming and non-streaming, thinking, tool_use.
POST /v1/messages/count_tokens Anthropic token-count estimate for a Messages body.
POST /v1/embeddings Always 501 — OpenCode exposes no embedding model.
GET /v1/models List models, with gateway extensions: name, context_length, max_output_tokens, capabilities, reasoning, status, enabled.
GET /v1/models/{id} One model by provider/model or bare id.
GET /health Liveness plus upstream readiness snapshot (public).
GET /ready Readiness from cached state: 200 only when an upstream server is resolved and a model catalog is already cached (public, never calls upstream).
GET /healthz Minimal liveness alias (public).
GET /metrics Prometheus exposition (requires a key unless OPENCODE_METRICS_PUBLIC=true is set and no OPENCODE_METRICS_TOKEN is configured).
GET /admin/status Config, upstream, catalog and session-cache snapshot.
GET /admin/config The effective configuration, with secrets redacted.
POST /admin/models/refresh Force a model catalog reload.
GET /admin/sessions List sticky sessions.
DELETE /admin/sessions Drop every sticky session.
POST /admin/upstream/restart Restart or re-resolve the upstream server.
GET / Unauthenticated endpoint index.

Request and response shapes, SSE frames and error bodies: docs/API.md.

Streaming

Set "stream": true. Responses are text/event-stream with a : keep-alive comment every 15 s.

curl -N http://127.0.0.1:20123/v1/chat/completions \
  -H "Authorization: Bearer $OPENCODE_API_KEY" \
  -H "Content-Type: application/json" \
  -d '{
    "model": "opencode/deepseek-v4.1-flash-free",
    "stream": true,
    "messages": [{"role": "user", "content": "Count from one to five."}]
  }'
data: {"id":"chatcmpl-...","object":"chat.completion.chunk","created":1764662000,"model":"opencode/deepseek-v4.1-flash-free","choices":[{"index":0,"delta":{"role":"assistant","content":""},"finish_reason":null}]}

data: {"id":"chatcmpl-...","object":"chat.completion.chunk","created":1764662000,"model":"opencode/deepseek-v4.1-flash-free","choices":[{"index":0,"delta":{"content":"One"},"finish_reason":null}]}

data: {"id":"chatcmpl-...","object":"chat.completion.chunk","created":1764662000,"model":"opencode/deepseek-v4.1-flash-free","choices":[{"index":0,"delta":{},"finish_reason":"stop"}]}

data: [DONE]

Anthropic streaming uses named events (message_start, content_block_delta, message_stop):

curl -N http://127.0.0.1:20123/v1/messages \
  -H "x-api-key: $OPENCODE_API_KEY" \
  -H "anthropic-version: 2023-06-01" \
  -H "Content-Type: application/json" \
  -d '{
    "model": "opencode/deepseek-v4.1-flash-free",
    "max_tokens": 256,
    "stream": true,
    "messages": [{"role": "user", "content": "Count from one to five."}]
  }'

Cancelling the client request aborts the upstream turn and interrupts the OpenCode session, so no tokens are burned on an abandoned answer.

Vision and media input

Attachments are accepted in three forms:

Form Example Default
Base64 data URI data:image/png;base64,iVBORw0KGgo... allowed
Remote URL https://example.com/chart.png allowed (OPENCODE_ALLOW_REMOTE_MEDIA_URLS=true)
Local path ./workspace/chart.png disabled (OPENCODE_ALLOW_LOCAL_FILES=false)

A local path is only accepted where the wire format has an explicit path field (the OpenAI document content part, {type:"document",document:{path:"..."}}). image_url.url, video_url.url, file.url and Anthropic source.url values must be a data: URI or an http(s):// URL — a bare filesystem path there is rejected as an invalid URL.

Remote URLs are fetched server-side and inlined, because OpenCode itself only accepts data: or file:// attachment URIs — a plain http(s):// URL is rejected upstream with Unsupported attachment URI (HTTP 400). The gateway therefore downloads the bytes (bounded by OPENCODE_MAX_ATTACHMENT_BYTES and OPENCODE_MEDIA_FETCH_TIMEOUT_MS), sniffs/completes the MIME type, and sends a data:<mime>;base64,<payload> URI. The same applies to Anthropic source.type: "base64" blocks and OpenAI image_url objects with data URIs.

Local paths must resolve, after expanding ~ and resolving symlinks, inside one of OPENCODE_ALLOWED_FILE_ROOTS (which defaults to OPENCODE_WORKDIR). Anything outside is rejected with 400.

Supported MIME categories:

  • Images: image/png, image/jpeg, image/webp, image/gif, image/bmp, image/tiff, image/svg+xml
  • Audio: audio/mpeg, audio/mp3, audio/wav, audio/x-wav, audio/ogg, audio/opus, audio/flac, audio/aac, audio/mp4, audio/webm
  • Video: video/mp4, video/webm, video/ogg, video/quicktime
  • Documents: application/pdf
  • Text: text/*, application/json, application/xml, text/csv

Whatever the MIME category, the selected model must advertise it in capabilities.input (GET /v1/models). Asking an image-blind model for an image returns 400 unsupported_modality before anything is sent upstream.

Limits:

  • one attachment: OPENCODE_MAX_ATTACHMENT_BYTES (default 20 MiB)
  • all attachments in one request combined: the same budget
  • count: OPENCODE_MAX_ATTACHMENTS (default 16)
  • request body: OPENCODE_MAX_BODY_BYTES (default 64 MiB, matching the ~33% base64 inflation of a full 20 MiB attachment plus JSON overhead)

Rejections are explicit 400 invalid_request_error responses with a machine-readable code: invalid_attachment, attachment_too_large, attachment_download_failed, remote_media_disabled, private_media_blocked, local_files_disabled, attachment_not_found, attachment_path_forbidden, or unsupported_modality when the model cannot accept the category.

# OpenAI chat with an image, using a URL that the gateway inlines
curl http://127.0.0.1:20123/v1/chat/completions \
  -H "Authorization: Bearer $OPENCODE_API_KEY" \
  -H "Content-Type: application/json" \
  -d '{
    "model": "opencode/seaglass-alpha-free",
    "messages": [{
      "role": "user",
      "content": [
        {"type": "text", "text": "What is in this image?"},
        {"type": "image_url", "image_url": {"url": "https://example.com/chart.png"}}
      ]
    }]
  }'

Thinking effort and reasoning

Reasoning output is surfaced only when the caller asks for it (or when OPENCODE_REASONING_DEFAULT=always). A model exposes thinking effort as variants; the gateway maps the requested effort onto the closest variant the model actually offers.

  • OpenAI chat: reasoning_effort (or reasoning.effort) — none, minimal, low, medium, high, xhigh, max. Common aliases are accepted (off/disabled → none, min/lowest → minimal, default/normal/mid → medium, maximum/highest → max).
  • OpenAI Responses: reasoning.effort.
  • Anthropic: thinking: {type:"enabled", budget_tokens: N} (bucketed: <2k→minimal, <6k→low, <16k→medium, <40k→high, <80k→xhigh, else max) or thinking: {type:"disabled"}. The /v1/messages adapter also accepts the non-standard reasoning_effort string, ignored when thinking is present.
  • Explicit variant selection: append #variant to the model name, e.g. opencode/deepseek-v4.1-flash-free#max.

The nearest-variant rule: if the exact effort is unavailable, the gateway picks the closest available variant and prefers one at or above the requested effort when two are equidistant. If the model has no variant ladder at all, reasoning is silently unavailable (reasoning: false) and the request still succeeds.

Discover a model's ladder through GET /v1/models:

curl http://127.0.0.1:20123/v1/models -H "Authorization: Bearer $OPENCODE_API_KEY" |
  node -e "let s='';process.stdin.on('data',d=>s+=d).on('end',()=>{for(const m of JSON.parse(s).data)console.log(m.id, JSON.stringify(m.reasoning))})"
opencode/deepseek-v4.1-flash-free {"supported":true,"efforts":["low","high","max"],"default_effort":"high"}
opencode/big-pickle {"supported":false,"efforts":[],"default_effort":null}

reasoning.efforts is the ladder as the provider declares it (the implicit default variant is not listed) and default_effort is the effort used when a caller asks for reasoning without naming one. GET /v1/models?refresh=true forces a catalog reload.

Observed provider ladders in OpenCode 2.3.2: low,high,max; minimal,low,medium,high,xhigh,max; none,high; and models with no variants.

OPENCODE_REASONING_DEFAULT sets server-wide policy:

Value Behaviour
off Never select a variant, never surface reasoning, even if requested.
on-request Default. Surface reasoning only when the request asks for it.
always Always select a thinking-effort variant; medium when the request does not name one.

When reasoning is surfaced, OpenAI clients receive reasoning_content (and an extra reasoning alias with OPENCODE_REASONING_FIELD=both), while Anthropic clients receive a thinking content block.

Function calling

Tools are bridged through the prompt. OpenCode's agent owns its own tool set and cannot accept per-request tool schemas, so the gateway renders the caller's tools declarations into the prompt and asks the model to answer with a sentinel-delimited JSON envelope:

[[OPENCODE_TOOL_CALL]]{"name":"get_weather","arguments":{"city":"Hanoi"}}[[/OPENCODE_TOOL_CALL]]

A streaming filter removes the envelope from the text stream and converts each block into the caller's native shape: OpenAI tool_calls deltas (and finish_reason: "tool_calls"), or an Anthropic tool_use content block with input_json_delta fragments. {"tool_calls":[...]} and {"calls":[...]} envelopes, tool/tool_name/function key spellings and string-valued arguments are all tolerated. The assistant text around a call is preserved.

Limitations, stated plainly:

  • Reliability is model-dependent. A model that ignores the protocol produces prose instead of tool calls, or malformed JSON; the gateway drops an unparseable envelope rather than guessing.
  • The caller's tool is not executed upstream. The application must run it and send the result back as a tool message (OpenAI) or tool_result block (Anthropic).
  • There is one upstream turn per step: the bridged loop is driven by the client. Parallel calls inside one envelope are supported.
  • When a request declares tools, the gateway adds deny permission rules for OpenCode's built-in actions (bash, webfetch, websearch, edit, write, patch, task, skill) for that session, so the model cannot "answer" your request by running its own shell or web tools instead of emitting a bridged call. This is controlled by OPENCODE_TOOL_BRIDGE_DENY_NATIVE_TOOLS (default true); the deny rules are merged on top of OPENCODE_AGENT_PERMISSIONS. The rules apply whenever tools is non-empty — even with tool_choice: "none", which disables the bridge instructions but never the containment.
  • tool_choice: "none" disables the bridge; "required" and a named tool are rendered as instructions, not as a hard guarantee. A tool_choice that requires a tool while tools is absent or empty is rejected with 400 invalid_request (param: "tool_choice").
  • Native OpenCode tool activity (the build agent reading files, running commands) is not part of the OpenAI or Anthropic contract. It is reported as the non-standard x_opencode.native_tool_calls field of the final payload (an array of {id, name, status, input?, error?} on the OpenAI surfaces, a count on /v1/messages), and — when OPENCODE_EXPOSE_NATIVE_TOOLS=true — streamed as opencode.tool_call SSE events on /v1/chat/completions.

Bridged tools and native tools can appear in the same turn: the model may call your tool while the OpenCode agent independently uses its own.

JSON output mode

JSON output is bridged through the prompt for the same reason function calling is — OpenCode accepts no per-request output schema:

Surface Field Values
/v1/chat/completions response_format {"type":"json_object"}, {"type":"json_schema","json_schema":{name,schema}}
/v1/responses text.format {"type":"json_object"}, {"type":"json_schema",name,schema}

{"type":"text"} and an absent field leave the prompt unchanged. The gateway adds a # Response format prompt section asking for a single valid JSON value and, for a schema, for a value that validates against it. This is a model contract, not a server-enforced one: nothing validates the reply, so a model that ignores the instruction can still answer in prose. Validate the result on the client when it matters.

Model naming

Form Example Resolves to
provider/model opencode/deepseek-v4.1-flash-free canonical id
bare model id deepseek-v4.1-flash-free first model whose modelID matches
#variant suffix opencode/deepseek-v4.1-flash-free#max model plus the max thinking variant
alias gpt-4o (with OPENCODE_MODEL_ALIASES) whatever the alias maps to

Aliases are applied before resolution and accept both the full name and a provider/-prefixed default alias:

OPENCODE_MODEL_ALIASES={"gpt-4o":"opencode/big-pickle","claude-3-5-sonnet":"opencode/seaglass-alpha-free"}

Matching is case-insensitive only on the human-readable name; ids are matched exactly. Responses always report the canonical provider/model id. Unknown models return 404 model_not_found; disabled models return 400 model_disabled. Query GET /v1/models instead of guessing.

Configuration summary

Variable Default Purpose
HOST / PORT 127.0.0.1 / 20123 Listen address.
OPENCODE_API_KEYS sk-dummy-123 Accepted caller keys (comma separated). Replace the built-in default before exposing the port.
OPENCODE_ALLOW_NO_AUTH false Start without keys (dangerous).
OPENCODE_ADMIN_API_KEYS (unset) Operator keys accepted on /admin/*; when set, general API keys are rejected there.
OPENCODE_METRICS_TOKEN (unset) Dedicated scrape token for GET /metrics; configuring it keeps that endpoint authenticated even with OPENCODE_METRICS_PUBLIC=true.
OPENCODE_BODY_TIMEOUT_MS 300000 Wall-clock budget for receiving one request body; a streaming response is never cut short by it.
OPENCODE_RATE_LIMIT_RPM 0 (disabled) Per-minute request budget per API key; 0 turns rate limiting off.
OPENCODE_RATE_LIMIT_BURST 0 Burst capacity allowed on top of the per-minute budget; 0 derives max(1, ceil(rpm/6)). The limiter is off only when OPENCODE_RATE_LIMIT_RPM=0.
OPENCODE_CORS_ORIGINS (empty) Browser origins allowed to call the gateway; * allows every origin.
OPENCODE_SERVER_URL / OPENCODE_SERVER_PASSWORD (unset) Explicit upstream server.
OPENCODE_AUTOSTART true Spawn a private opencode serve.
OPENCODE_BIN (unset) Path to the OpenCode CLI executable.
OPENCODE_START_TIMEOUT_MS 30000 Time allowed for the private upstream server to report readiness.
OPENCODE_REQUEST_TIMEOUT_MS 600000 Wall-clock budget for one upstream turn.
OPENCODE_WORKDIR <data dir>/workspace Directory the agent may work in.
OPENCODE_AGENT build Default agent for API turns.
OPENCODE_AGENT_MAX_STEPS (unset) Maximum agent steps per turn.
OPENCODE_ALLOW_LOCAL_FILES false Accept local-path attachments.
OPENCODE_ALLOW_PRIVATE_MEDIA_URLS false Allow remote media on private hosts (enabling it re-opens SSRF).
OPENCODE_MAX_ATTACHMENT_BYTES 20971520 Per-request media budget.
OPENCODE_REASONING_DEFAULT on-request Global reasoning policy.
OPENCODE_SESSION_CACHE true Reuse upstream sessions.
OPENCODE_SESSION_PERSIST false Persist the session cache to <data dir>/sessions.json.
OPENCODE_MODEL_CACHE_TTL_MS 300000 Model catalog cache lifetime.
OPENCODE_TOOL_BRIDGE_DENY_NATIVE_TOOLS true Deny built-in agent tools when client tools are bridged.
OPENCODE_EXPOSE_NATIVE_TOOLS false Stream opencode.tool_call events.
OPENCODE_NATIVE_TOOL_EVENT opencode.tool_call SSE event name for native tool activity.
OPENCODE_LOG_LEVEL info Pino log level.
OPENCODE_LOG_PRETTY true on a TTY Pretty-print logs instead of JSON lines.
OPENCODE_METRICS_ENABLED true Prometheus collection; false makes GET /metrics answer 404.
OPENCODE_INSTANCE_ID opencode-api-<pid> Instance identifier, and the fingerprint of the persisted session cache.

Every variable, with types, defaults and security notes: docs/CONFIGURATION.md.

Operational notes

  • GET /health — liveness plus upstream.ready and upstream.source (env, spawned, discovered). Public, like /ready and /healthz.
  • GET /ready — 200 only when an upstream endpoint is resolved and a model catalog is already cached; 503 with upstream.error otherwise. It never calls upstream, so an anonymous probe cannot trigger work: force a refresh with the authenticated POST /admin/models/refresh. Use it for container readiness and load-balancer gating.
  • GET /metrics — Prometheus text format from prom-client, prefix opencode_api_: http_requests_total, http_request_duration_seconds, upstream_requests_total, upstream_request_duration_seconds, tokens_total, completions_total, active_streams, upstream_restarts_total, session_cache_entries, event_stream_connected, event_stream_reconnects_total, event_frames_dropped_total, rate_limit_rejections_total, plus process defaults. Requires a key unless OPENCODE_METRICS_PUBLIC=true is set and no OPENCODE_METRICS_TOKEN is configured: a configured token is always required, even when the endpoint is public, so a general API key is never handed to a scraper. /metrics is never rate limited, so a local scraper cannot be throttled by its own traffic.
  • /admin/* — /admin/status (config, upstream binary and URL, catalog counts, session count), /admin/config (effective configuration with API keys and the upstream password redacted), /admin/models/refresh, /admin/sessions (list and delete-all), /admin/upstream/restart. Authenticated; restrict them at the proxy if you expose the gateway.
  • Request correlation. Send x-request-id (up to 128 characters from A-Za-z0-9._:-) and the gateway echoes it on the response and uses it as the request id in its logs; anything else is replaced by a generated id. Streaming responses carry it too.
  • Sticky sessions. OpenAI and Anthropic clients resend the whole conversation on every call. The gateway recognises the prefix it has already delivered upstream and continues the same OpenCode session instead of replaying the transcript and re-uploading every attachment. The prefix is hashed and compared, so reuse can never change semantics: on any mismatch the gateway starts a fresh session and replays. The cache holds OPENCODE_SESSION_MAX entries for OPENCODE_SESSION_TTL_MS and is keyed by model + agent + variant + tool-set hash + permission profile + conversation root. Pass x-conversation-id to control the key explicitly, or set OPENCODE_SESSION_CACHE=false for fully stateless routing. An explicit key is still only reused while the message prefix, the model, the agent, the variant, the tool set and the permission profile match.
  • Free-tier rate limits. The bundled free models are limited per model and per window upstream. The gateway answers 429 with a retry-after header in seconds and repeats the upstream message; back off for that long. A stream that already sent its first frame cannot add a header, so the same hint is repeated as retry_after_ms inside the error frame. Transient 503 ServiceUnavailableError ("Model is unavailable") is mapped to overloaded_error. Neither is a gateway bug — switch model or wait.

Security warnings

  • The gateway can run an agent with tools. Default agent build can read and write inside OPENCODE_WORKDIR and execute commands available to the OpenCode runtime. Treat any caller who holds an API key as code-execution capable. Point OPENCODE_WORKDIR at an isolated scratch directory, choose a read-only agent, and constrain tools with OPENCODE_AGENT_PERMISSIONS.
  • The default API key is public. With no OPENCODE_API_KEYS configured the gateway accepts sk-dummy-123, which anyone reading this repository knows. The gateway therefore refuses to start when that key is still accepted on a non-loopback HOST; set your own key before exposing the port, and never enable OPENCODE_ALLOW_NO_AUTH=true on a reachable host.
  • Bridged tools do not remove the agent's own tool set. A session whose client tools are bridged still carries native tool definitions; the gateway merely denies their actions, and only when OPENCODE_TOOL_BRIDGE_DENY_NATIVE_TOOLS=true (the default). Requests without tools are not restricted by this mechanism at all — bound them with OPENCODE_AGENT_PERMISSIONS and a read-only agent instead.
  • SSRF through remote media. OPENCODE_ALLOW_PRIVATE_MEDIA_URLS is false by default. Setting it to true lets a caller make the gateway fetch http://127.0.0.1:..., RFC1918 addresses, 169.254.169.254 metadata endpoints and similar; the gateway then logs a startup error while HOST is not a loopback address. Leave it false on any deployment reachable by untrusted clients.
  • Local file disclosure. OPENCODE_ALLOW_LOCAL_FILES=false by default. If you enable it, keep OPENCODE_ALLOWED_FILE_ROOTS narrow and remember that symlinks are resolved before the check (on Windows a final symlink or junction is refused and the opened handle is re-checked against the pre-open lstat).
  • Unbounded per-key traffic. OPENCODE_RATE_LIMIT_RPM=0 disables the built-in limiter. Set it (with OPENCODE_RATE_LIMIT_BURST) on a shared deployment so one key cannot drive unlimited paid upstream turns.
  • Anonymous metrics. OPENCODE_METRICS_PUBLIC=true exposes model names and traffic without authentication; prefer OPENCODE_METRICS_TOKEN and keep the endpoint closed.
  • Put the gateway behind TLS, keep CORS origins explicit, and do not enable OPENCODE_TRUST_PROXY unless a proxy you control overwrites the forwarded headers: with a bare true the client address is caller-controlled, which also makes the per-address rate-limit bucket spoofable. Prefer a hop count (OPENCODE_TRUST_PROXY=1) or a CIDR list.
  • Admin routes restart the world. /admin/upstream/restart kills the shared upstream (every in-flight turn fails) and DELETE /admin/sessions drops the sticky cache for all callers. Set OPENCODE_ADMIN_API_KEYS to keep those routes away from tenant keys, or restrict them at the proxy.

Docker usage

The image contains the gateway only. The OpenCode CLI is not bundled: mount the binary (or a directory containing it) and point OPENCODE_BIN at it.

docker build -t opencode-api .

docker run --rm -p 20123:20123 \
  --env-file .env \
  -e HOST=0.0.0.0 -e PORT=20123 \
  -e OPENCODE_BIN=/usr/local/bin/opencode \
  -v "$PWD/.opencode-api:/data" \
  -v "$PWD/workspace:/workspace" \
  -v "$(command -v opencode):/usr/local/bin/opencode:ro" \
  opencode-api

docker compose is preconfigured; add the CLI mount shown in the comments of docker-compose.yml:

cp .env.example .env
# Replace the published default before the container can start: HOST=0.0.0.0 is
# not a loopback address, so the gateway refuses to start while
# OPENCODE_API_KEYS is still sk-dummy-123.
pnpm setup -- --random
docker compose up --build

The compose file maps 20123:20123, reads .env, mounts ${OPENCODE_DATA_DIR:-./.opencode-api}:/data and ${OPENCODE_WORKDIR:-./workspace}:/workspace, and sets OPENCODE_DATA_DIR=/data, OPENCODE_WORKDIR=/workspace and OPENCODE_BIN=/usr/local/bin/opencode.

The image itself is built from node:22-bookworm-slim, declares /data and /workspace as volumes, defaults HOST=0.0.0.0 and PORT=20123, ships a HEALTHCHECK that probes /health with the bundled Node runtime, and runs as the non-root node user (uid/gid 1000) — so the mounted directories must be writable by UID 1000. CI builds the image on every pull request (.github/workflows/ci.yml, job "Docker image") and validates this compose file.

Development

Script What it does
pnpm setup Write .env (keeps sk-dummy-123; -- --random generates a strong key instead).
pnpm dev Start with tsx watch and reload on change.
pnpm clean Remove dist/.
pnpm build Remove dist/ first, then type-check and emit src/ into it with tsc -p tsconfig.build.json, so a removed or renamed source cannot leave stale output behind.
pnpm typecheck tsc -p tsconfig.json --noEmit.
pnpm test Unit tests (excludes test/integration/**).
pnpm test:integration Integration tests against a live gateway/upstream.
pnpm test:all Unit and integration tests. Refuses to start (exit 1) unless OPENCODE_API_URL and OPENCODE_API_KEY are set, because the integration suite skips itself without them.
pnpm lint:commits Lint the latest commit message against commitlint.config.mjs.
pnpm smoke Run scripts/smoke.mjs against a running gateway.

pnpm test:all means what it says: instead of silently running the unit suite only, it prints the missing variables and exits 1. Use pnpm test for the unit suite alone and pnpm test:integration for the live suite alone.

pnpm smoke reads OPENCODE_API_URL (default http://127.0.0.1:20123) and OPENCODE_API_KEY (defaults to sk-dummy-123) and checks health, models, non-streaming chat, streaming chat and Anthropic messages:

OPENCODE_API_KEY=$(grep '^OPENCODE_API_KEYS=' .env | cut -d= -f2) pnpm smoke
node scripts/smoke.mjs --model opencode/deepseek-v4.1-flash-free --embedding-501

Project layout:

opencode-api/                 # package name; the project is "OpenCode API"
├── src/
│   ├── adapter/
│   │   ├── anthropic/       # /v1/messages, /v1/messages/count_tokens
│   │   ├── common/          # reasoning mapping, tool bridge, usage maths
│   │   └── openai/          # /v1/chat/completions, /v1/responses, /v1/completions, /v1/models, /v1/embeddings
│   ├── http/                # SSE writer, client-disconnect signal
│   ├── media/               # data URI, remote fetch, local path resolution
│   ├── metrics/             # Prometheus registry
│   ├── routes/              # health, metrics, admin
│   ├── types/               # internal + OpenCode wire types
│   ├── upstream/            # process supervision, client, event hub, models, sessions, completion
│   ├── auth.ts              # API-key authentication
│   ├── config.ts            # every environment variable
│   ├── context.ts           # shared application context
│   ├── errors.ts            # error taxonomy and wire shapes
│   ├── index.ts             # entry point
│   └── server.ts            # Fastify assembly
├── test/                    # vitest unit and integration tests
├── docs/                    # API.md, CONFIGURATION.md, ARCHITECTURE.md, VERIFICATION.md
├── scripts/                 # smoke.mjs, init-env.mjs
├── AGENTS.md                # instructions for AI coding agents
├── CONTRIBUTING.md          # workflow + commit message convention
├── LICENSE                  # MIT
├── Dockerfile
├── docker-compose.yml
└── .env.example

Troubleshooting

Symptom Cause Fix
Startup logs "using the built-in default API key" No .env, or OPENCODE_API_KEYS is unset Expected. The gateway accepts sk-dummy-123. Run pnpm setup to write .env, or set OPENCODE_API_KEYS to your own secret.
OpenCode CLI executable not found (503 upstream_unavailable) The binary is not on PATH and OPENCODE_BIN is unset Install the OpenCode CLI 2.x, or set OPENCODE_BIN to its absolute path. Check GET /admin/status → upstream.binary.
503 upstream_unavailable when OPENCODE_SERVER_URL is set That server is not reachable or rejects the probe Verify the URL and set OPENCODE_SERVER_PASSWORD; curl -u opencode:<password> <url>/api/model.
502 upstream_error mentioning "rejected the request" The gateway's upstream credential is wrong Refresh OPENCODE_SERVER_PASSWORD, or unset OPENCODE_SERVER_URL to let the gateway spawn its own server.
401 from the gateway Missing or wrong caller key Send Authorization: Bearer <key>, x-api-key: <key> or Authorization: Basic <base64(key:)>. Compare against .env.
429 with retry-after Upstream free-tier limit for that model Wait retry-after seconds, or use a different model from GET /v1/models.
No first token, then 504 timeout_error The model never produced a delta within OPENCODE_FIRST_TOKEN_TIMEOUT_MS Raise OPENCODE_FIRST_TOKEN_TIMEOUT_MS, retry, or switch model; check <OPENCODE_DATA_DIR>/logs/opencode-*.log.
Stream ends with an error frame and no output Upstream step failed mid-stream The HTTP status was already 200; inspect the frame's error.message. Model-unavailable errors are transient.
EADDRINUSE on startup Port 20123 is taken Set PORT (or stop the other process). The internal upstream port is separate and auto-retries.
404 model_not_found for a model that GET /v1/models lists A cold upstream had not registered its models yet and an old build cached the empty list The gateway retries and never caches an empty catalogue; GET /v1/models?refresh=true forces an immediate reload
400 unsupported_modality The model cannot accept that media type Pick a model whose capabilities.input includes it (GET /v1/models).
400 about attachment URI or file roots Local files disabled, or the path escapes the allowed roots Enable OPENCODE_ALLOW_LOCAL_FILES and/or add the directory to OPENCODE_ALLOWED_FILE_ROOTS.
501 from /v1/embeddings Expected: OpenCode has no embedding model Route embeddings to a dedicated provider.
Tool calls never appear The model ignored the bridged protocol Try a more instruction-following model, or tool_choice: "required"; see the function-calling limitations above.

Contributing

Bug reports and pull requests are welcome. main is protected: changes land through a pull request from a branch (feat/..., fix/..., docs/...) and only after the GitHub Actions CI workflow passes, so main cannot be pushed to directly.

Start with CONTRIBUTING.md — it covers the development workflow, the coding standards and the commit message convention (Conventional Commits, enforced by commitlint.config.mjs in CI). AGENTS.md is the condensed version for AI coding agents.

Before opening a pull request:

pnpm typecheck && pnpm build && pnpm test && pnpm lint:commits

Author

Phạm Văn Định — dinhdev666@gmail.com

License

MIT — see LICENSE.

Contributors

Languages