Skip to content

Latest commit

 

History

History
208 lines (175 loc) · 23.4 KB

CONFIGURATION.md

File metadata and controls

208 lines (175 loc) · 23.4 KB

OpenCode API — configuration reference

Every setting is read from the process environment at startup. The gateway also loads .env files with dotenv: the project root first, then the current working directory. Variables already present in the real environment win, and because dotenv never overrides, a root .env wins over a .env in the directory you started from.

An empty value is treated as "not set": OPENCODE_AGENT="" behaves exactly like an unset OPENCODE_AGENT. List variables are comma separated, with surrounding whitespace trimmed and empty entries dropped.

Paths starting with ~ are expanded to the home directory and then resolved against the current working directory.

This table is derived from src/config.ts; src/config.ts reads no other variable. (Discovery and the spawned CLI read the variables listed in "Environment variables read by other libraries".)

HTTP server

Variable Type Default Description Security implication
HOST string 127.0.0.1 Interface the gateway binds. Anything other than a loopback address exposes the API (and the OpenCode agent) to the network. Set 0.0.0.0 only inside a container or behind a proxy.
PORT integer 1–65535 20123 TCP port to listen on. —
OPENCODE_MAX_BODY_BYTES integer ≥ 1024 67108864 (64 MiB) Maximum request body size. Raising it widens the memory-exhaustion surface; base64 media inflates bodies by ~33%.
OPENCODE_TRUST_PROXY true-like, false-like, a positive hop count, or a CSV list of trusted IPs/CIDRs false Trust x-forwarded-* headers for the client address. true/yes/on/enabled trusts every hop; false/no/off/disabled/0 trusts nothing; a positive integer is a hop count (1 trusts the immediate peer only, 2 the last two, …) and is compiled into Fastify's function form; 10.0.0.0/8,127.0.0.1 trusts only those peers. An unrecognised value — including a CIDR with a /0 prefix, which would trust every peer — warns (without echoing it) and falls back to false. Enable only when a proxy you control terminates the connection and overwrites the forwarded headers; otherwise clients can spoof their address in logs, metrics and the per-address rate-limit bucket, which makes the anonymous limiter ineffective. Prefer a hop count or a CIDR list over a bare true: with true the leftmost x-forwarded-for entry is trusted even when a client prepended one.
OPENCODE_BODY_TIMEOUT_MS integer ≥ 1000 300000 (5 min) Wall-clock budget for receiving one request body. A caller that opens a connection and never finishes sending is disconnected when it expires. Only body receipt is bounded; a stream: true response is never cut short by it. Bounds how long a caller can hold a connection and its body buffers (OPENCODE_MAX_BODY_BYTES each) without completing a request. Lower it if your clients never upload large media.
OPENCODE_CORS_ORIGINS CSV list (empty) Allowed browser origins; * allows all. An allowed origin receives access-control-allow-headers covering this gateway's headers plus the ones the official OpenAI and Anthropic SDKs send (openai-organization, openai-project, x-stainless-*, anthropic-dangerous-direct-browser-access), and access-control-expose-headers: x-request-id. * lets any web page call the gateway with a user's key. Prefer an explicit list.
OPENCODE_RATE_LIMIT_RPM integer ≥ 0 0 Sustained requests per minute allowed per authenticated API key; 0 disables this limiter. /admin/* uses its own separate bucket, and /metrics is charged to the per-key bucket like any other route. Failed authentication is throttled by a bucket that is always active (at least 60 failed attempts per minute per client address) plus a much higher global ceiling over all addresses, independently of this variable. Bounds how many paid upstream turns one key can trigger. A rejected request answers 429 rate_limit_error (code: rate_limit_exceeded) with a retry-after header.
OPENCODE_RATE_LIMIT_BURST integer ≥ 0 0 Token-bucket capacity per API key; 0 derives max(1, ceil(rpm / 6)). Ignored when OPENCODE_RATE_LIMIT_RPM=0. A large burst allows that many concurrent turns per key before throttling starts.

Authentication

Variable Type Default Description Security implication
OPENCODE_API_KEYS CSV list sk-dummy-123 Keys accepted from callers. When unset, the built-in development key sk-dummy-123 is used. When the published key is among the accepted keys — either because nothing was configured or because it is listed explicitly, as .env.example ships it — a warning is logged at startup and GET /admin/config reports auth.usingDefaultApiKey: true. When set but empty (OPENCODE_API_KEYS=",") the gateway refuses to start instead of silently accepting the public default. The default key is public knowledge (it ships in .env.example and the README). Set your own secret before exposing the port; rotate by listing old and new keys together.
OPENCODE_API_KEY string (unset) Single-key alias appended to OPENCODE_API_KEYS. Same as above; convenient for local use only.
OPENCODE_ALLOW_NO_AUTH boolean false Accept every caller, ignoring keys. Full unauthenticated access to every model and to the OpenCode agent. Use only on a trusted loopback host.
OPENCODE_ADMIN_API_KEYS CSV list (unset) Optional operator credential tier. When non-empty, /admin and /admin/* accept only these keys; a general OPENCODE_API_KEYS value is rejected there with 401. Unset keeps the default behaviour (any accepted API key may call the admin routes). When set but empty (OPENCODE_ADMIN_API_KEYS=",") the gateway refuses to start, exactly like OPENCODE_API_KEYS. The admin routes can restart the shared upstream (failing every in-flight turn) and drop the sticky-session cache. Give them a separate secret so a tenant key cannot.
OPENCODE_METRICS_PUBLIC boolean false Exempt GET /metrics from authentication. Metrics expose model names, route traffic and token volumes, so this is only safe when HOST is a loopback address; otherwise set OPENCODE_METRICS_TOKEN instead of exposing the endpoint anonymously. Enabling it on a non-loopback host with no token logs the exposure at error and prints a note to stderr at startup; the gateway still starts.
OPENCODE_METRICS_TOKEN string (unset) Dedicated scrape credential for GET /metrics, compared in constant time before the OPENCODE_METRICS_PUBLIC bypass. When set, /metrics requires it even if OPENCODE_METRICS_PUBLIC=true; a valid general API key is still accepted. Lets a Prometheus scraper read metrics without handing it a general-purpose key. Prefer it over making the endpoint public.

Keys are presented as Authorization: Bearer <key>, x-api-key: <key>, Authorization: Basic <base64(key:)> (key as the username, empty password). A bare value with no scheme (Authorization: <key>) is not accepted, and neither is a Basic value that carries a password or omits the colon. Query-string keys (?api_key=) are deliberately not supported because request URLs end up in access logs. Failed authentication is throttled per client address (at least 60 attempts per minute) and by a much higher global ceiling over all addresses, and logged at warn without the presented value. Because the per-address bucket is keyed on request.ip, a deployment behind a reverse proxy with the default OPENCODE_TRUST_PROXY=false resolves every caller to the proxy address: set OPENCODE_TRUST_PROXY to a hop count or a CIDR list (see "HTTP server") so the bucket is per caller rather than shared, and so the global ceiling is not what answers 429 for legitimate clients. GET /, GET /health, GET /ready and GET /healthz are always public.

pnpm setup writes .env (keeping sk-dummy-123); pnpm setup -- --random writes a freshly generated 32-byte secret instead, and --random --force replaces an existing custom key. The file is created with mode 0600 on POSIX (Windows ignores the mode).

Upstream OpenCode server

Variable Type Default Description Security implication
OPENCODE_SERVER_URL URL (unset) Explicit OpenCode server. When set, the gateway never spawns one and fails if the URL is unreachable. A URL that embeds credentials (http://user:pass@host:port) is refused at startup: Node rejects a request whose URL carries userinfo, so it could never be reached, and the credential would be echoed by /admin/config, /admin/status and the failure message. Point only at a server you control; the gateway sends prompts and attachments to it. Use OPENCODE_SERVER_PASSWORD for authentication, never the URL.
OPENCODE_SERVER_PASSWORD string (unset) Password of the explicit server (Authorization: Basic opencode:<password>). Secret; required for any non-loopback server.
OPENCODE_AUTOSTART boolean true Spawn a private opencode serve when no explicit server is configured. The child process inherits the gateway's environment, including its own provider credentials.
OPENCODE_BIN path (unset) Full path to the OpenCode CLI executable. Prefer an absolute path to a binary you installed; the gateway executes it.
OPENCODE_INTERNAL_HOST string 127.0.0.1 Hostname for the private server. Binding it to a public interface would expose an authenticated-only upstream to the network.
OPENCODE_INTERNAL_PORT integer 1–65535 20124 First port tried for the private server; the gateway retries the next nine ports if it is busy. —
OPENCODE_SERVER_ARGS CSV list (empty) Extra arguments appended to opencode serve --hostname ... --port .... Passing --standalone breaks startup (rejected by opencode 2.x).
OPENCODE_START_TIMEOUT_MS integer ≥ 1000 30000 Time allowed for the private server to report readiness. —
OPENCODE_REQUEST_TIMEOUT_MS integer ≥ 1000 600000 Wall-clock budget for one upstream turn; on expiry the session is interrupted. —
OPENCODE_FIRST_TOKEN_TIMEOUT_MS integer ≥ 1000 180000 Budget for the first text/reasoning delta of a turn. It is re-armed by every upstream liveness frame — text and reasoning deltas, a step start and native tool activity — so a turn that is actively running tools is not killed for "producing no output". —
OPENCODE_UPSTREAM_LOG_MAX_BYTES integer ≥ 0 33554432 (32 MiB) Cap on <OPENCODE_DATA_DIR>/logs/opencode-<port>.log. The file is truncated and reopened once the cap would be crossed, so the most recent output is kept instead of growing the file without bound; 0 disables the cap. The file holds the supervised server's stdout/stderr with the upstream password and any Authorization header redacted; a bound keeps a chatty server from filling the disk.

Agent and workspace

Variable Type Default Description Security implication
OPENCODE_WORKDIR path <OPENCODE_DATA_DIR>/workspace Directory handed to OpenCode as the session location. The agent runs with its tools inside this directory. Point it at a scratch directory, never at a source tree or your home directory.
OPENCODE_AGENT string build OpenCode agent used for API-driven turns. build can edit files and run commands in OPENCODE_WORKDIR. Choose a read-only agent for untrusted callers.
OPENCODE_AGENT_MAX_STEPS integer > 0 (unset) Maximum agent steps per turn. A cap limits how much work (and cost) one request can trigger.
OPENCODE_AGENT_PERMISSIONS JSON array (unset) Permission rules [{action, resource, effect}] applied to every API session. A rule without effect defaults to ask. A rule of {"action":"*","resource":"*","effect":"allow"} grants the agent unrestricted tool access. Deny rules are the safer default. Must be a JSON array of objects or the gateway refuses to start.

Gateway state, sticky sessions and models

Variable Type Default Description Security implication
OPENCODE_DATA_DIR path ./.opencode-api Gateway state directory: upstream logs, optional session file. Contains upstream log output and is treated as sensitive; the supervised server's password is redacted before it is written to <OPENCODE_DATA_DIR>/logs/opencode-<port>.log and before it can appear in an error message or in GET /admin/status. Keep the directory private anyway.
OPENCODE_SESSION_CACHE boolean true Reuse the OpenCode session that already holds the conversation prefix. Reuse is strictly prefix-checked; a mismatch replays the conversation on a fresh session. Disable for fully stateless routing: nothing is recorded, OPENCODE_SESSION_PERSIST writes no file, and the session created for a turn is deleted as soon as the turn ends.
OPENCODE_SESSION_TTL_MS integer ≥ 1000 1800000 (30 min) Idle lifetime of a cached session. Longer lifetimes keep session state in memory longer.
OPENCODE_SESSION_MAX integer ≥ 1 500 Maximum cached sessions (least recently used are evicted). —
OPENCODE_SESSION_PERSIST boolean false Persist the session cache to <OPENCODE_DATA_DIR>/sessions.json. The file records session ids, message prefixes and the OPENCODE_INSTANCE_ID of the writer. A ses_* id is only valid inside the upstream server that created it, so a file written by another instance is ignored on load; because the default instance id contains the gateway pid, a restart starts with an empty cache. Pin OPENCODE_INSTANCE_ID to keep the cache across restarts — only correct for a long-lived upstream (OPENCODE_SERVER_URL). Keep the data directory private.
OPENCODE_MODEL_CACHE_TTL_MS integer ≥ 1000 300000 (5 min) Model catalog cache lifetime. —
OPENCODE_MODEL_ALIASES JSON object (unset) Alias map applied before resolution, e.g. {"gpt-4o":"opencode/big-pickle"}. Aliases can silently redirect a familiar name to another provider model. Must be a JSON object of string values or the gateway refuses to start.

Media and vision input

Variable Type Default Description Security implication
OPENCODE_ALLOW_LOCAL_FILES boolean false Allow attachments addressed by local file path. The file is read through one O_NOFOLLOW handle after the roots check, and an unreadable file answers 400 invalid_attachment. On Windows, where O_NOFOLLOW is 0, a final component that lstat reports as a symlink or junction is refused, and the opened handle's dev/ino are compared with the pre-open lstat before any byte is read. Reading local files on behalf of a remote caller is a file-disclosure primitive. Keep it off unless callers are trusted, and make sure the allowed roots contain no untrusted writers (hard links inside a root and a swapped parent directory are not closed by realpath).
OPENCODE_ALLOWED_FILE_ROOTS CSV list of paths OPENCODE_WORKDIR Roots a local path must resolve inside (after realpath). The read itself uses one O_NOFOLLOW handle, but hard links inside a root and a swapped parent directory are not closed. Widen this only to directories that are safe to read, with no untrusted writers.
OPENCODE_ALLOW_REMOTE_MEDIA_URLS boolean true Fetch http(s):// media server-side and inline it as a data URI. The gateway performs the request, so it can reach hosts the caller cannot.
OPENCODE_ALLOW_PRIVATE_MEDIA_URLS boolean false Allow remote media on private, loopback and link-local addresses. Leave false on any deployment reachable from the network. Setting it to true is an SSRF primitive against the host network and cloud metadata endpoints; when it is enabled while HOST is not a loopback address the gateway logs a startup error naming the exposure (it still starts). The default closes SSRF against 127.0.0.1-hosted services and cloud metadata endpoints. Enable it only when every URL source is trusted and the gateway is not reachable from an untrusted network.
OPENCODE_MAX_ATTACHMENT_BYTES integer ≥ 1 20971520 (20 MiB) Maximum decoded size of one attachment and of all attachments combined in a request, enforced while media is resolved and again before it is forwarded. Bounds memory per request.
OPENCODE_MAX_ATTACHMENTS integer ≥ 1 16 Maximum attachments resolved and forwarded per request. Media beyond the cap is never fetched, and the prompt records what was dropped. —
OPENCODE_MEDIA_FETCH_TIMEOUT_MS integer ≥ 100 15000 Timeout for one remote media download. —

Media accept only data: URIs, http(s):// URLs and (opt-in) local paths; uploads are always inlined for OpenCode as a data: URI. A remote download that answers a non-identity content-encoding is rejected with 400 attachment_download_failed: the byte caps bound the bytes as received, so a compressed body is never inlined and never labelled as media. See the README section "Vision and media input".

Reasoning, tools and observability

Variable Type Default Description Security implication
OPENCODE_REASONING_DEFAULT off | on-request | always on-request Server-wide policy for thinking effort. Unrecognised values fall back to on-request and log a warning naming the variable. always selects a thinking variant even when the caller did not ask, raising cost and latency.
OPENCODE_TOOL_BRIDGE_DENY_NATIVE_TOOLS boolean true When a request declares client tools, add deny permission rules for OpenCode's built-in actions (bash, webfetch, websearch, edit, write, patch, task, skill) so the model emits a bridged tool call instead of running its own tools. Keep true. Setting it to false lets a request that declares any tool also drive the agent's shell, web and file tools. The deny rules are merged on top of OPENCODE_AGENT_PERMISSIONS for that session only.
OPENCODE_EXPOSE_NATIVE_TOOLS boolean false Stream native OpenCode tool activity as SSE events (see OPENCODE_NATIVE_TOOL_EVENT). Native tool payloads can reveal file paths and command input/output from the agent's workspace.
OPENCODE_NATIVE_TOOL_EVENT string opencode.tool_call SSE event name used for native tool activity. —
OPENCODE_REASONING_FIELD reasoning_content | both reasoning_content POST /v1/chat/completions only: when both, the adapter emits an extra reasoning alias next to reasoning_content on messages and deltas. Read into Config.reasoningField. —
OPENCODE_LOG_LEVEL string info Pino level: silent, fatal, error, warn, info, debug, trace (silent disables all output; scripts/smoke-dist.mjs uses it). Unrecognised values fall back to info and log a warning naming the variable. debug/trace add upstream request metadata, connection diagnostics and fragments of malformed upstream frames; no prompt text or credential is ever logged.
OPENCODE_LOG_PRETTY boolean true when stdout is a TTY Pretty-print logs instead of JSON lines. Needs pino-pretty, which is a dev dependency; without it the gateway falls back to JSON instead of failing.
OPENCODE_METRICS_ENABLED boolean true Enable Prometheus collection; when false, GET /metrics answers 404. —
OPENCODE_INSTANCE_ID string opencode-api-<pid> Identifier for this gateway instance. Also the fingerprint of the persisted session cache (OPENCODE_SESSION_PERSIST). Changing it invalidates the persisted session cache.

Boolean values accept 1/true/yes/on/enabled and 0/false/no/off/disabled (case-insensitive). Any other value is unrecognised: the default is kept and a warning naming the variable is logged.

Integer values must be a whole number: the entire value is parsed, so OPENCODE_REQUEST_TIMEOUT_MS=10m is not read as 10 seconds — it is treated as unrecognised, the default is kept and a warning naming the variable is logged. Out-of-range integers are clamped to the documented bounds.

OPENCODE_REASONING_DEFAULT and OPENCODE_LOG_LEVEL are unrecognised in the same way: the default (on-request, info) is kept and a warning naming the variable is logged. The warning never echoes the value, because an operator can paste a secret into the wrong variable.

OPENCODE_REASONING_FIELD follows the same rule: an unrecognised value falls back to reasoning_content and logs the same warning naming the variable.

Environment variables read by other libraries

dotenv loads .env from the project root and then the working directory. The upstream launcher inherits the gateway's full environment (so the OpenCode CLI sees its own provider credentials), and the CLI discovery code reads PATH, APPDATA, LOCALAPPDATA, PNPM_HOME, NVM_BIN, VOLTA_HOME, XDG_STATE_HOME and XDG_CONFIG_HOME when searching for the executable and a background server descriptor.

Startup validation

The gateway exits with code 1 (before it listens) when:

  1. OPENCODE_AGENT_PERMISSIONS is set but is not a JSON array of objects;
  2. OPENCODE_MODEL_ALIASES is set but is not a JSON object of string values;
  3. OPENCODE_API_KEYS / OPENCODE_API_KEY is set but yields no usable key (OPENCODE_API_KEYS=","), because silently falling back to the published default key would leave the operator believing a secret is configured;
  4. the published built-in key sk-dummy-123 is still among the accepted keys while HOST is not a loopback address. A gateway reachable from the network and accepting a key printed in this repository is the one combination that must never start silently; set a real key (or, for a throwaway trusted network, OPENCODE_ALLOW_NO_AUTH=true).
  5. OPENCODE_ADMIN_API_KEYS is set but yields no usable key (OPENCODE_ADMIN_API_KEYS=","), for the same reason as item 3: an operator who configured the tier must not silently fall back to accepting general keys on /admin/*;
  6. OPENCODE_SERVER_URL embeds credentials (http://user:pass@host:port). It cannot work — Node refuses a request whose URL carries userinfo — and the password would otherwise reach /admin/config, /admin/status and every caller-visible failure message. Set OPENCODE_SERVER_PASSWORD instead.

A missing key on a loopback host is not fatal: with neither OPENCODE_API_KEYS nor OPENCODE_API_KEY set, the gateway starts with the built-in development key sk-dummy-123 and logs a warning. The same warning is logged when the published key is configured explicitly — including the .env.example default that pnpm setup copies — because in that case the port is just as unprotected. Every variable is otherwise clamped to its documented bounds, and an unrecognised boolean, integer, reasoning default or log level falls back to the default with a warning naming the variable.

Recommended hardening for a reachable deployment

HOST=127.0.0.1
OPENCODE_ALLOW_NO_AUTH=false
OPENCODE_ALLOW_PRIVATE_MEDIA_URLS=false
OPENCODE_ALLOW_LOCAL_FILES=false
OPENCODE_AGENT_PERMISSIONS=[{"action":"*","resource":"*","effect":"ask"}]
OPENCODE_EXPOSE_NATIVE_TOOLS=false
OPENCODE_METRICS_PUBLIC=false
OPENCODE_METRICS_TOKEN=<random secret for the scraper>
OPENCODE_RATE_LIMIT_RPM=60
OPENCODE_RATE_LIMIT_BURST=10
OPENCODE_CORS_ORIGINS=https://your-app.example