Skip to content

Latest commit

 

History

History
1091 lines (930 loc) · 64.8 KB

API.md

File metadata and controls

1091 lines (930 loc) · 64.8 KB

OpenCode API — HTTP API reference

The gateway exposes eight public endpoints under a single origin. The default listen address is http://127.0.0.1:20123.

Method Path Compatibility
POST /v1/chat/completions OpenAI Chat Completions
POST /v1/responses OpenAI Responses
POST /v1/completions OpenAI legacy Completions
POST /v1/messages Anthropic Messages
POST /v1/messages/count_tokens Anthropic token counting
POST /v1/embeddings OpenAI Embeddings (always 501)
GET /v1/models OpenAI Models
GET /v1/models/{id} OpenAI Models, by bare id or alias
GET /v1/models/* OpenAI Models, by provider/model (the slash is a path separator, so this form needs the wildcard route)

Everything else (/health, /ready, /healthz, /metrics, /admin/*, /) is operational; it is summarised at the end of this document and in the README.

Extensions

Name Kind Meaning
x_opencode response field Non-standard object carried by every buffered completion payload and by the response object of the /v1/responses SSE events (response.created, response.in_progress, response.completed, response.failed): session_id, agent, variant, reused_session, and native_tool_calls (an array on the OpenAI surfaces, a count on the Anthropic surface) plus reasoning: {enabled, note} on the two OpenAI completion surfaces (/v1/chat/completions, /v1/completions). unapplied (array) names the generation knobs the request supplied that the gateway recorded but could not apply, in the fixed order temperature, top_p, presence_penalty, frequency_penalty, seed, logit_bias, max_tokens, max_completion_tokens, max_output_tokens, service_tier; the key is omitted when none were supplied. The Anthropic streamed sequence and the two OpenAI streamed sequences do not carry x_opencode; one exception: the Anthropic message_delta of a cancelled turn carries x_opencode: {"interrupted": true}, because the stop reason alone cannot express the interruption.
x-conversation-id request header Explicit sticky-session key. Requests carrying the same value reuse the same upstream OpenCode session only while the model, agent, variant, tool set, permission profile and message prefix all still match.
x-opencode-agent request header Run this request with a specific OpenCode agent instead of OPENCODE_AGENT.
x-request-id request/response header Caller-supplied correlation id, echoed on every response (JSON and SSE). Accepted when it matches [A-Za-z0-9._:-]{1,128}; anything else is replaced by a generated id. The same value is used as the request id in the gateway logs.
reasoning_effort request field Non-standard on /v1/messages: an OpenAI-style alias for thinking. Ignored when thinking is present.
opencode.tool_call SSE event name Native OpenCode tool activity (OpenAI chat surface only), emitted when OPENCODE_EXPOSE_NATIVE_TOOLS=true. Note that a request which declares tools runs with OpenCode's built-in actions denied (OPENCODE_TOOL_BRIDGE_DENY_NATIVE_TOOLS=true, the default), so native activity is normally empty for bridged turns.

Authentication is required on every endpoint in the table above. Send one of Authorization: Bearer <key>, x-api-key: <key>, Authorization: Basic <base64(key:)>. A bare value with no scheme (Authorization: <key>) is rejected. The default key is sk-dummy-123 when OPENCODE_API_KEYS is not configured; set your own before exposing the gateway (a non-loopback bind refuses to start with that published key). Query-string keys (?api_key=) are deliberately not supported because request URLs are logged. /, /health, /ready and /healthz are exempt (and /metrics when OPENCODE_METRICS_PUBLIC=true and no OPENCODE_METRICS_TOKEN is set, which re-authenticates the endpoint in constant time).

When OPENCODE_ADMIN_API_KEYS is configured, /admin and /admin/* accept only those keys; a general API key answers 401 there. Failed authentication is throttled per client address (at least 60 attempts per minute) and answers 429 with a retry-after header once that budget is spent.

Reading this reference. Request fields are validated with zod; unknown JSON fields are ignored, matching the permissive behaviour of the OpenAI and Anthropic servers. Every field listed below is one the adapters accept and validate, and the rows say exactly how each one behaves:

  • stop is honoured on /v1/chat/completions and /v1/completions (the visible text is truncated at the first delimiter, on both the buffered and the streamed path).
  • The generation knobs OpenCode's agent loop owns — temperature, top_p, presence_penalty, frequency_penalty, seed, logit_bias, max_tokens, max_completion_tokens, max_output_tokens, service_tier — are accepted and recorded for client compatibility but cannot be applied. Every response names them in x_opencode.unapplied, so a caller can detect it instead of guessing.
  • Token accounting is normalised per surface. prompt_tokens / input_tokens on the OpenAI surfaces is the whole prompt: the upstream reports cached input separately, and the gateway folds cache_read and cache_write into it, with prompt_tokens_details.cached_tokens (or input_tokens_details.cached_tokens) a subset that is never larger than the prompt. /v1/messages keeps the Anthropic convention instead, where input_tokens excludes cache_read_input_tokens and cache_creation_input_tokens. Thinking tokens are a subset of completion_tokens / output_tokens on every surface, so total_tokens is always prompt + completion.
  • A field that would change the shape of the response and cannot be emulated at all is rejected with 400 unsupported_parameter, naming the field in param (see the individual rows: logprobs/top_logprobs, non-text modalities, audio, prediction, store: true, web_search_options, the legacy functions/function_call, previous_response_id, non-empty include, best_of, suffix, and any media detail other than "auto"). A 400 with an empty param is a malformed body.

A malformed body is rejected with 400 invalid_request_error naming the offending field in param.

1. POST /v1/chat/completions

Request

Field Type Default Notes
model string — Required. provider/model, bare model id, optional #variant suffix. The model is resolved before the response starts, so an unknown or disabled model always yields a JSON 404/400, never a broken stream.
messages array — Required, at least one. Roles system, developer, user, assistant, tool. A message that carries no text, no media and no tool call (nor a tool_call_id) is dropped, and a request whose messages all drop that way is 400 invalid_request with param: "messages" rather than an empty prompt answered 200.
messages[].content string | array | null — String, or parts: text, image_url, video_url, input_audio, file, document.
messages[].content[].image_url.url string — data: URI or http(s):// URL (remote URLs are fetched and inlined). A bare filesystem path is not accepted here.
messages[].content[].video_url.url string — Same two forms.
messages[].content[].input_audio {data, format} — format is wav, mp3, m4a, mp4, webm, ogg, opus, flac, aac, pcm or a full MIME type.
messages[].content[].file {filename?, file_data?, url?, mime_type?} — file_data is base64 or a data: URI; file_id is rejected with unsupported_file_reference.
messages[].content[].document object — Accepts {url}, {data}, {path} or an Anthropic-style nested {source:{media_type,data}}.
media parts on a non-user role — — Rejected with 400 invalid_request (param: "messages"). OpenAI only allows image/audio/file parts on a user message, and the gateway forwards the attachments of user turns only, so accepting one would download and then silently drop the input.
messages[].tool_calls array — Assistant tool calls echoed back by the client.
messages[].tool_call_id string — Required on role: "tool" messages.
messages[].name string — Optional tool name on role: "tool".
stream boolean false Emit SSE frames instead of one JSON body.
stream_options.include_usage boolean false Append a usage-only chunk (with choices: []) before [DONE].
tools array (none) OpenAI declarations {type:"function",function:{name,description,parameters}}. Bridged through the prompt.
tool_choice auto | none | required | {type:"function",function:{name}} auto Rendered into the bridge instructions. 400 invalid_request (param: "tool_choice") when it requires a tool but tools is absent or empty, or when it names a function the request never declared.
reasoning_effort string (unset) none, minimal, low, medium, high, xhigh, max plus aliases (off, min, maximum, ...). A non-empty value outside that set is 400 invalid_request (param: "reasoning_effort") instead of being silently folded into medium.
reasoning.effort string (unset) Used when reasoning_effort is absent.
max_tokens / max_completion_tokens number (unset) max_completion_tokens wins. Accepted and recorded, not enforced upstream: OpenCode's agent owns the generation budget. Listed in x_opencode.unapplied when supplied.
temperature, top_p number (unset) Accepted and recorded, but not forwarded: OpenCode's agent loop owns the sampling parameters. Listed in x_opencode.unapplied when supplied.
stop string | string[] (unset) Honoured on both paths: the visible text is truncated at the first delimiter, empty strings are dropped. Bounded, because the streamed filter scans every declared delimiter on every delta: at most 16 entries, each at most 256 characters, 1024 characters in total; past that the request is 400 invalid_request with param: "stop". Generation upstream is not interrupted, so usage counts the full turn and finish_reason stays stop.
n number 1 Only 1 is supported; anything else returns 400 invalid_request.
user, metadata, service_tier — — Accepted; not forwarded and not logged. metadata is carried on the internal request so a future surface can use it, but nothing reads it today. service_tier is recorded and named in x_opencode.unapplied when supplied.
parallel_tool_calls boolean true false makes the tool bridge ask the model for at most one bridged tool call per turn; true/absent allows several.
response_format object (unset) {"type":"text"}, {"type":"json_object"} or {"type":"json_schema","json_schema":{name,schema}}. OpenCode cannot receive an output schema, so the requirement is rendered into the prompt (see "JSON output mode" below); it is a model contract, not a server-enforced one. json_schema.strict: true therefore promises a guarantee the gateway cannot give and is rejected with 400 unsupported_parameter (param: "response_format.json_schema.strict"); strict: false is accepted.
seed, logprobs, logit_bias, presence_penalty, frequency_penalty — — seed, logit_bias, presence_penalty and frequency_penalty are accepted and recorded, and named in x_opencode.unapplied when supplied. logprobs/top_logprobs are rejected with 400 unsupported_parameter unless they are disabled (logprobs: false), because the gateway cannot produce token-level scores.
best_of, suffix — — Rejected with 400 unsupported_parameter naming the field, like /v1/completions: the gateway produces exactly one candidate and does not echo a suffix. An explicit null is treated as unset.
messages[].content[].image_url.detail string auto Only "auto" is accepted; the gateway cannot downscale media, so any other value is 400 unsupported_parameter with param: "messages".
top_logprobs, modalities, audio, prediction, store, web_search_options, functions, function_call — — Rejected with 400 unsupported_parameter naming the field, because the gateway cannot produce the response shape they ask for. store: false and function_call: "none" are accepted as no-ops, and modalities: ["text"] is accepted.

Response (stream: false)

{
  "id": "chatcmpl-3f1c9d2a4b5e4c0f8a7d6e5b4a3c2d1e",
  "object": "chat.completion",
  "created": 1764662000,
  "model": "opencode/deepseek-v4.1-flash-free",
  "choices": [
    {
      "index": 0,
      "message": {
        "role": "assistant",
        "content": "Hello! How can I help?",
        "refusal": null,
        "reasoning_content": "The user greeted me, so a short greeting is enough."
      },
      "finish_reason": "stop"
    }
  ],
  "usage": {
    "prompt_tokens": 12,
    "completion_tokens": 9,
    "total_tokens": 21,
    "completion_tokens_details": { "reasoning_tokens": 6 },
    "prompt_tokens_details": { "cached_tokens": 0 }
  },
  "x_opencode": {
    "session_id": "ses_01J...",
    "agent": "build",
    "variant": "high",
    "reused_session": false,
    "reasoning": { "enabled": true, "note": null },
    "native_tool_calls": []
  }
}
  • content is null when the model produced only tool calls, matching OpenAI semantics; tool_calls is then present.
  • reasoning_content is present only when reasoning was requested and surfaced. With OPENCODE_REASONING_FIELD=both an identical reasoning field is emitted alongside it (read from Config.reasoningField, so two gateways in one process cannot share the setting).
  • finish_reason is stop, length, tool_calls or content_filter. A turn the upstream ended with error is a failure, not a completion: the buffered form answers 502 api_error / upstream_error, and the streamed form ends with the error frame below instead of a finish chunk or [DONE]. A turn the upstream interrupted (provider-side cancellation, or the shared server cancelling the session) has no dedicated OpenAI finish reason and is therefore reported as stop; completions_total still counts it as finish_reason="cancelled", and /v1/messages keeps the distinction as stop_reason: "end_turn" plus x_opencode.interrupted: true.
  • x_opencode.native_tool_calls lists native OpenCode tool activity as {id, name, status, input?, error?} with status in started, input, called, succeeded, failed.

Streaming (stream: true)

Headers: content-type: text/event-stream; charset=utf-8, cache-control: no-cache, no-transform, x-accel-buffering: no. A : keep-alive comment is written every 15 s. Frames carry the SSE data: field only — the discriminator is inside the JSON, exactly like OpenAI. Headers set by the gateway itself (CORS, x-request-id) are part of the SSE head too.

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":{"reasoning_content":"The user greeted me, "},"finish_reason":null}]}

data: {"id":"chatcmpl-...","object":"chat.completion.chunk","created":1764662000,"model":"opencode/deepseek-v4.1-flash-free","choices":[{"index":0,"delta":{"content":"Hello"},"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]

With stream_options.include_usage: true the usage chunk precedes [DONE]:

data: {"id":"chatcmpl-...","object":"chat.completion.chunk","created":1764662000,"model":"opencode/deepseek-v4.1-flash-free","choices":[],"usage":{"prompt_tokens":12,"completion_tokens":9,"total_tokens":21,"completion_tokens_details":{"reasoning_tokens":6},"prompt_tokens_details":{"cached_tokens":0}}}

data: [DONE]

A bridged tool call is withheld from the text stream and appears as a tool-call chunk with a monotonically increasing index:

data: {"id":"chatcmpl-...","object":"chat.completion.chunk","created":1764662000,"model":"opencode/deepseek-v4.1-flash-free","choices":[{"index":0,"delta":{"tool_calls":[{"index":0,"id":"call_9a1b...","type":"function","function":{"name":"get_weather","arguments":"{\"city\":\"Hanoi\"}"}}]},"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":"tool_calls"}]}

data: [DONE]

Native tool activity, when OPENCODE_EXPOSE_NATIVE_TOOLS=true, uses the named event from OPENCODE_NATIVE_TOOL_EVENT:

event: opencode.tool_call
data: {"type":"opencode.tool_call","activity":{"id":"toolu_01J...","name":"read","status":"called","input":{"filePath":"/workspace/notes.md"}}}

The stream head is written lazily. A failure raised before the first frame is reported with a real HTTP status; after that the status is already 200, so errors must be read from the final frame. A turn the upstream ends with error is such a failure — the stream closes with the error frame below (code: "upstream_error", message: "The upstream completion ended with an error.") and emits neither a finish chunk nor [DONE]:

data: {"error":{"message":"OpenCode did not finish the request in time.","type":"api_error","code":"timeout_error","param":null}}
data: {"error":{"message":"The upstream completion ended with an error.","type":"api_error","code":"upstream_error","param":null}}

Errors

{
  "error": {
    "message": "Model 'gpt-9' was not found. Call GET /v1/models for the list of available models.",
    "type": "invalid_request_error",
    "code": "model_not_found",
    "param": "model"
  }
}
Status type Typical code
400 invalid_request_error invalid_request (including a tool_choice that requires a tool but declares none), model_disabled, unsupported_modality, unsupported_file_reference, invalid_attachment, attachment_too_large, attachment_download_failed, local_files_disabled, attachment_not_found, attachment_path_forbidden, remote_media_disabled, private_media_blocked
401 invalid_request_error authentication_error
403 invalid_request_error permission_error
404 invalid_request_error model_not_found
429 rate_limit_error provider.free-limit, rate_limit_error, rate_limit_exceeded (the gateway's own limiter; with retry-after header, in seconds; mid-stream the hint travels as retry_after_ms in the error frame instead)
499 api_error timeout_error — client disconnected before the response started
501 invalid_request_error not_implemented_error
502 api_error upstream_error, upstream_invalid_json
503 api_error overloaded_error, upstream_unavailable, upstream_unreachable, upstream_unauthorized (the upstream answered 401/403: check OPENCODE_SERVER_PASSWORD), event_stream_unavailable, event_stream_lost (a mid-turn event-stream reconnect; the answer would have been incomplete)
504 api_error timeout_error, upstream_timeout
500 api_error internal_error — an unexpected gateway failure; the message never contains credentials

unsupported_parameter is also a valid 400 code: it names, in param, a request field the gateway cannot honour. See the policy in "Reading this reference".

curl

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."}]
  }'
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,"stream_options":{"include_usage":true},"messages":[{"role":"user","content":"Count to five."}]}'

2. POST /v1/responses

OpenAI Responses-style surface. It shares model resolution, media handling, reasoning mapping and tool bridging with the chat endpoint.

Request

Field Type Default Notes
model string — Required and non-empty: model: "" is 400 invalid_request with param: "model". Same naming rules as chat.
input string | array — Required, and a non-empty string or array: input: [] is 400 invalid_request with param: "input" rather than an empty prompt. Items: message ({role, content}, type optional), function_call, function_call_output, reasoning, item_reference. Roles: user, assistant, system, developer. An item that carries no text, no media and no tool call is dropped, and an input whose items all drop that way (for example a lone item_reference) is 400 invalid_request with param: "input".
input[].content parts — — input_text, output_text, summary_text (text is used), refusal (the refusal text is used), input_image, input_file, input_audio, video_url.
instructions string (unset) Prepended as a system turn and echoed on the response object.
stream boolean false Emit the typed SSE sequence.
tools array (none) Flat function tools {type:"function",name,description,parameters}.
tool_choice auto | none | required | {type:"function",name} auto Bridged into the prompt; echoed back as auto, none, required or function:<name>. Anything else (for example "bogus" or the allowed_tools form) is 400 unsupported_parameter with param: "tool_choice" instead of being silently ignored, and the echo always reflects the validated value. 400 invalid_request (param: "tool_choice") when it requires a tool but tools is absent or empty, or when it names a function the request never declared.
reasoning.effort string (unset) Same ladder as reasoning_effort. reasoning.summary is echoed only.
max_output_tokens, temperature, top_p, metadata, truncation — — Accepted and echoed back; truncation defaults to "disabled" and is not applied (the gateway never trims history), and the other four are echoed but not forwarded to the provider. metadata is not logged. max_output_tokens, temperature and top_p are named in x_opencode.unapplied when supplied.
service_tier string (unset) Accepted and recorded but not echoed; named in x_opencode.unapplied when supplied.
parallel_tool_calls boolean true Echoed; false makes the tool bridge ask for at most one bridged tool call per turn.
previous_response_id string (unset) Rejected with 400 unsupported_parameter: the gateway keeps no response store, so resend the full input. The successful response echoes it as null.
store boolean false store: false is accepted and echoed (nothing is persisted); store: true is rejected with 400 unsupported_parameter.
text.format object (unset) {"type":"text"}, {"type":"json_object"} or {"type":"json_schema",name,schema}. Rendered into the prompt like the chat response_format; see "JSON output mode". The effective format is echoed on the response object as text.format, defaulting to {"type":"text"}. strict: true promises server-enforced conformance the gateway cannot give and is rejected with 400 unsupported_parameter (param: "text.format.strict").
include, top_logprobs, modalities, audio, prediction, web_search_options, functions, function_call, seed, presence_penalty, frequency_penalty, logit_bias — — The generation knobs (seed, penalties, logit_bias) are accepted and recorded, and named in x_opencode.unapplied when supplied. Everything else in this row is rejected with 400 unsupported_parameter naming the field: include must be empty, logprobs/top_logprobs cannot be produced, an audio modality cannot be answered, and the legacy functions/function_call shape is not emulated. function_call: "none", store: false, logprobs: false and include: [] are accepted as no-ops.
input[].content[].detail string auto Only "auto" is accepted; the gateway cannot downscale media, so any other value is 400 unsupported_parameter with param: "input".
media parts on a non-user input message — — Rejected with 400 invalid_request (param: "input"). Media is accepted on a user message and inside a function_call_output (re-homed onto the enclosing user turn); any other role would have its media downloaded and then dropped, because only user turns carry attachments upstream.

item_reference items are skipped (they point at stored responses the gateway does not keep). reasoning items are accepted and ignored: a caller may resend a previous response's output verbatim, but provider-side thinking state cannot be replayed (same policy as thinking/redacted_thinking on /v1/messages). function_call items become assistant tool calls; function_call_output items become role: "tool" turns. An input_file part accepts file_data/file_url; a reference carrying only file_id is rejected with 400 unsupported_file_reference instead of being silently dropped. A function_call_output.output may itself be an array of content parts: the text parts become the tool turn, and input_image/input_file/input_audio parts are resolved like any other media and attached to the enclosing user turn, leaving a [image: <mime>] / [document: <mime>] marker in the tool text (the same rule as an Anthropic tool_result).

Response (stream: false)

{
  "id": "resp_9f2c1d4b8a7e6f5c4d3b2a1908f7e6d5",
  "object": "response",
  "created_at": 1764662000,
  "status": "completed",
  "model": "opencode/deepseek-v4.1-flash-free",
  "output": [
    {
      "id": "rs_...",
      "type": "reasoning",
      "summary": [{ "type": "summary_text", "text": "The user greeted me." }],
      "content": [{ "type": "reasoning_text", "text": "The user greeted me." }]
    },
    {
      "id": "msg_...",
      "type": "message",
      "status": "completed",
      "role": "assistant",
      "content": [{ "type": "output_text", "text": "Hello! How can I help?", "annotations": [] }]
    }
  ],
  "output_text": "Hello! How can I help?",
  "usage": {
    "input_tokens": 12,
    "output_tokens": 9,
    "total_tokens": 21,
    "input_tokens_details": { "cached_tokens": 0 },
    "output_tokens_details": { "reasoning_tokens": 6 }
  },
  "parallel_tool_calls": true,
  "tool_choice": "auto",
  "tools": [],
  "temperature": null,
  "top_p": null,
  "text": { "format": { "type": "text" } },
  "reasoning": { "effort": null, "summary": null },
  "metadata": {},
  "incomplete_details": null,
  "error": null,
  "instructions": null,
  "max_output_tokens": null,
  "previous_response_id": null,
  "store": false,
  "truncation": "disabled",
  "x_opencode": {
    "session_id": "ses_01J...",
    "agent": "build",
    "variant": null,
    "reused_session": false,
    "native_tool_calls": []
  }
}
  • status is in_progress, completed, incomplete when the upstream stopped because of the output-length limit, or failed when the turn ended with an upstream error. incomplete_details is then {"reason":"max_output_tokens"}; a failed response carries error: {code, message} and output keeps whatever was produced before the failure.

  • The reasoning output item is emitted only when reasoning was surfaced; both summary and content carry the same text.

  • text.format echoes the effective output format ({"type":"text"} when the request supplied none), so a client reading the typed response object can always see which contract was requested.

  • Bridged tool calls are appended as output items in order:

    {
      "id": "fc_...",
      "type": "function_call",
      "status": "completed",
      "call_id": "call_9a1b...",
      "name": "get_weather",
      "arguments": "{\"city\":\"Hanoi\"}"
    }

Streaming (stream: true)

The Responses surface sets the SSE event: field and repeats the type inside the JSON. sequence_number is a monotonically increasing counter.

event: response.created
data: {"type":"response.created","sequence_number":0,"response":{"id":"resp_...","object":"response","status":"in_progress","model":"opencode/deepseek-v4.1-flash-free","output":[],"x_opencode":{"session_id":"ses_...","agent":"build","variant":null,"reused_session":false,"native_tool_calls":[]}}}

event: response.in_progress
data: {"type":"response.in_progress","sequence_number":1,"response":{...}}

event: response.output_item.added
data: {"type":"response.output_item.added","sequence_number":2,"output_index":0,"item":{"id":"msg_...","type":"message","status":"in_progress","role":"assistant","content":[]}}

event: response.content_part.added
data: {"type":"response.content_part.added","sequence_number":3,"item_id":"msg_...","output_index":0,"content_index":0,"part":{"type":"output_text","text":"","annotations":[]}}

event: response.output_text.delta
data: {"type":"response.output_text.delta","sequence_number":4,"item_id":"msg_...","output_index":0,"content_index":0,"delta":"Hello"}

event: response.output_text.done
data: {"type":"response.output_text.done","sequence_number":5,"item_id":"msg_...","output_index":0,"content_index":0,"text":"Hello! How can I help?"}

event: response.content_part.done
data: {"type":"response.content_part.done","sequence_number":6,"item_id":"msg_...","output_index":0,"content_index":0,"part":{"type":"output_text","text":"Hello! How can I help?","annotations":[]}}

event: response.output_item.done
data: {"type":"response.output_item.done","sequence_number":7,"output_index":0,"item":{"id":"msg_...","type":"message","status":"completed","role":"assistant","content":[{"type":"output_text","text":"Hello! How can I help?","annotations":[]}]}}

event: response.completed
data: {"type":"response.completed","sequence_number":8,"response":{"id":"resp_...","object":"response","status":"completed","model":"opencode/deepseek-v4.1-flash-free","output":[...],"output_text":"Hello! How can I help?","usage":{"input_tokens":12,"output_tokens":9,"total_tokens":21,"input_tokens_details":{"cached_tokens":0},"output_tokens_details":{"reasoning_tokens":6}},"x_opencode":{...}}}
  • response.created and response.in_progress are the first two frames of a stream that starts at all. A failure known before the first event (for example an unavailable upstream event stream) is reported with a real HTTP status and a JSON error body, so no frame is written.

  • Reasoning deltas use response.reasoning_summary_part.added, response.reasoning_summary_text.delta, response.reasoning_summary_text.done and response.reasoning_summary_part.done. The reasoning item is announced first, with response.output_item.added at output_index: 0 and status in_progress, so every output_index a client sees is opened before its first delta; the closing item then appears as response.output_item.done with output_index: 0 and status completed.

  • The message item occupies output_index: 1 when a reasoning item precedes it. Text that arrives only in the consolidated text_end event still gets its output_item.added/content_part.added pair and is delivered through the normal delta channel: the suffix the stream has not seen yet is emitted as response.output_text.delta before response.output_text.done, so a client that accumulates deltas and a client that reads output_text always agree. The same rule applies to reasoning_end with response.reasoning_summary_text.delta.

  • Tool calls are emitted at the end of the stream as response.output_item.added (status in_progress), one response.function_call_arguments.delta carrying the whole argument string, response.function_call_arguments.done, then response.output_item.done with status completed.

  • Every response.output_item.done frame is emitted in ascending output_index order, and the sequence of their item.id values equals response.completed.response.output exactly. A turn that produces text before its reasoning therefore announces the message at output_index: 0 and the reasoning item at output_index: 1, and closes them in that order too: a client that assembles output[] from the .done frames sees the same array as one that reads the terminal object.

  • A length-limited turn ends with event: response.incomplete instead of response.completed. So does a turn the provider filtered: the response object then reports status: "incomplete" with incomplete_details: {"reason": "content_filter"} (a length limit reports {"reason": "max_output_tokens"}), and the message item is closed with status: "incomplete".

  • A failed turn ends with a terminal event: response.failed carrying the final response object with status: "failed" and its error object. Its usage is null — not zeros — when the turn failed before any usage event arrived. The flat event: error frame is also emitted for backwards compatibility:

    event: response.failed
    data: {"type":"response.failed","sequence_number":9,"response":{"id":"resp_...","object":"response","status":"failed","error":{"code":"upstream_error","message":"The upstream completion ended with an error."},"output":[...]}}
    
    event: error
    data: {"type":"error","code":"upstream_error","message":"OpenCode reported a failure.","param":null,"sequence_number":10}
    

Errors

The OpenAI error shape (same table as /v1/chat/completions). Because /v1/responses maps to the OpenAI shape, unlike /v1/messages, a bad body is 400 {"error":{"type":"invalid_request_error", ...}}.

curl

curl http://127.0.0.1:20123/v1/responses \
  -H "Authorization: Bearer $OPENCODE_API_KEY" \
  -H "Content-Type: application/json" \
  -d '{"model":"opencode/deepseek-v4.1-flash-free","instructions":"Be concise.","input":"Say hello."}'

3. POST /v1/completions

Legacy OpenAI Completions. The prompt is normalised into a single user turn and served by the same orchestrator as the chat surface; the adapter only translates the wire format. Use /v1/chat/completions for anything new.

Request

Field Type Default Notes
model string — Required. provider/model, bare id, optional #variant; resolved before the response starts (unknown models → 404).
prompt string | string[] — Required. One element is accepted and becomes the user message; more than one is 400 unsupported_parameter with param: "prompt", because the gateway produces exactly one candidate and silently joining them would return a completion that matches none of the prompts.
n number 1 Only 1 is supported; any other value is 400 invalid_request.
stream boolean false Emit text_completion SSE chunks terminated by data: [DONE].
stream_options.include_usage boolean false Adds a final usage-only chunk (choices: []).
max_tokens, temperature, top_p — (unset) Accepted and recorded; the OpenCode agent owns the generation budget and the sampling parameters, so they are not applied. All are named in x_opencode.unapplied when supplied.
stop string | string[] (unset) Honoured on both paths: the visible text is truncated at the first delimiter and finish_reason stays stop. Same caps as /v1/chat/completions (16 entries, 256 characters each, 1024 in total; 400 invalid_request with param: "stop" past that). Generation upstream is not interrupted.
presence_penalty, frequency_penalty, seed, logit_bias — (unset) Accepted and recorded, not applied; named in x_opencode.unapplied when supplied.
service_tier, user string — Accepted and ignored (user correlation is done with x-request-id); service_tier is named in x_opencode.unapplied when supplied.
echo boolean false true is rejected with 400 unsupported_parameter (the prompt is rewritten before it reaches the model).
suffix, best_of — — Rejected with 400 unsupported_parameter naming the field.
logprobs, top_logprobs — — Rejected with 400 unsupported_parameter unless disabled (logprobs: false or 0), because the gateway cannot produce token-level scores.
modalities, audio, prediction, store: true, web_search_options, functions, function_call — — Rejected with 400 unsupported_parameter naming the field; the legacy completion API cannot answer those shapes. store: false and function_call: "none" are accepted as no-ops.

x-conversation-id works exactly as on /v1/chat/completions.

Response (stream: false)

{
  "id": "cmpl-3f1c9d2a4b5e4c0f8a7d6e5b",
  "object": "text_completion",
  "created": 1764662000,
  "model": "opencode/deepseek-v4.1-flash-free",
  "choices": [
    { "text": "Hello! How can I help?", "index": 0, "logprobs": null, "finish_reason": "stop" }
  ],
  "usage": {
    "prompt_tokens": 12,
    "completion_tokens": 9,
    "total_tokens": 21,
    "completion_tokens_details": { "reasoning_tokens": 6 },
    "prompt_tokens_details": { "cached_tokens": 0 }
  },
  "x_opencode": {
    "session_id": "ses_01J...",
    "agent": "build",
    "variant": null,
    "reused_session": false,
    "reasoning": { "enabled": false, "note": null },
    "native_tool_calls": []
  }
}

Streaming (stream: true)

data: {"id":"cmpl-...","object":"text_completion","created":1764662000,"model":"opencode/deepseek-v4.1-flash-free","choices":[{"text":"Hello","index":0,"logprobs":null,"finish_reason":null}]}

data: {"id":"cmpl-...","object":"text_completion","created":1764662000,"model":"opencode/deepseek-v4.1-flash-free","choices":[{"text":"! How can I help?","index":0,"logprobs":null,"finish_reason":null}]}

data: {"id":"cmpl-...","object":"text_completion","created":1764662000,"model":"opencode/deepseek-v4.1-flash-free","choices":[{"text":"","index":0,"logprobs":null,"finish_reason":"stop"}]}

data: [DONE]

finish_reason is stop, length or content_filter; reasoning, tool calls and native tool activity have no representation in this legacy wire format and are not streamed. A turn the upstream ended with error answers 502 upstream_error (buffered) or closes the stream with the error frame and neither a finish chunk nor [DONE] (streamed). Errors use the same OpenAI error shape and status table as /v1/chat/completions.

curl

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

4. POST /v1/messages

Anthropic Messages API.

Request

Field Type Default Notes
model string — Required. Resolved before the response starts (unknown models → 404 not_found_error).
messages array — Required, at least one. Roles user and assistant only. A message whose content is an empty string or whose blocks carry no text, media or tool result is dropped, and a request whose messages all drop that way is 400 invalid_request with param: "messages" rather than an empty prompt.
messages[].content string | array — Blocks: text, image, document, audio, video, tool_use, tool_result, thinking, redacted_thinking.
image block {source} — {type:"base64",media_type,data} or {type:"url",url}.
document block {source, title?, context?} — base64, url, or {type:"text",data} for inline plain text (which is folded into the prompt text instead of being fetched).
audio block (extension) {source:{type:"base64",media_type,data}} — Non-standard; base64 sources only.
video block (extension) {source} — Non-standard; base64 or url sources.
tool_use block {id,name,input} — Assistant messages only; input is serialised to the argument string.
tool_result block {tool_use_id, content?, is_error?} — User messages only. content is a string or text/image/document blocks. Inline-text documents are folded into the tool text; image/document bytes are resolved like any other media and attached to the enclosing user turn, leaving a [image: <mime>] / [document: <mime>] marker in the tool text. is_error: true prefixes the tool text with [tool error].
thinking / redacted_thinking blocks — — Accepted for multi-turn replay compatibility and ignored: the gateway cannot store provider-side thinking state.
max_tokens integer ≥ 1 — Required by the Anthropic schema and validated (zero and negative values are 400 invalid_request with param: "max_tokens"); the upper bound is recorded but not enforced upstream (the OpenCode agent owns the generation budget), so a reply can exceed it.
stop_sequences array of string (none) Honoured on this surface, on both paths: the visible text is truncated at the first match, stop_reason becomes stop_sequence and stop_sequence names the matched entry. Empty strings are dropped. Bounded, because the streamed filter scans every declared sequence on every delta: at most 16 entries, each at most 256 characters, 1024 characters in total; past that the request is 400 invalid_request with param: "stop_sequences". Only assistant text is matched — never thinking output or tool arguments. Generation upstream is not interrupted, so usage.output_tokens still counts the whole turn and the sticky session is not disturbed.
system string | array (unset) Array form accepts {type:"text",text} blocks. Joined with blank lines.
stream boolean false Emit the Anthropic SSE sequence.
thinking object (unset) {type:"enabled",budget_tokens} or {type:"disabled"}. budget_tokens must be an integer ≥ 1, and type:"enabled" without it is 400 invalid_request with param: "thinking.budget_tokens", matching the Anthropic contract. (The non-standard effort key is accepted and mapped exactly like the top-level reasoning_effort; a request using only effort does not need a budget.)
reasoning_effort string (unset) Extension: OpenAI-style alias for thinking. Ignored when thinking is present. An unrecognised non-empty value is 400 invalid_request (param: "reasoning_effort").
output_config object (unset) {effort?, format?}. effort selects the thinking level exactly like reasoning_effort but only when thinking is absent, and format ({type:"text"} | {type:"json_object"} | {type:"json_schema",schema?}) becomes the internal response format, rendered into the prompt like response_format. null is treated as unset.
tools array (none) {name,description,input_schema}. Bridged through the prompt.
tool_choice {type:"auto"} | {type:"any"} | {type:"none"} | {type:"tool",name} auto any maps to a required call, tool to a named call. Any of auto, any and tool additionally accepts disable_parallel_tool_use: true, which caps the turn at one tool call. 400 invalid_request (param: "tool_choice") when it requires a tool but tools is absent or empty, or when a named tool was never declared.
temperature, top_p, metadata.user_id — (unset) Accepted and recorded; not forwarded to the provider (the OpenCode agent owns sampling), and metadata is not logged.
top_k, service_tier, container, mcp_servers — — Accepted and ignored.
cache_control object — Accepted on text/image/document/tool blocks and ignored.

Response (stream: false)

{
  "id": "msg_3f1c9d2a4b5e4c0f8a7d6e5b",
  "type": "message",
  "role": "assistant",
  "model": "opencode/deepseek-v4.1-flash-free",
  "content": [
    { "type": "thinking", "thinking": "The user greeted me.", "signature": "b3BlbmNvZGUtYXBpOm1zZ18zZjFjOWQyYTRiNWU0YzBmOGE3ZDZlNWI=" },
    { "type": "text", "text": "Hello! How can I help?" }
  ],
  "stop_reason": "end_turn",
  "stop_sequence": null,
  "usage": {
    "input_tokens": 12,
    "output_tokens": 9,
    "cache_creation_input_tokens": 0,
    "cache_read_input_tokens": 0
  },
  "x_opencode": {
    "session_id": "ses_01J...",
    "agent": "build",
    "variant": "high",
    "reused_session": false,
    "native_tool_calls": 0
  }
}
  • stop_reason in the final payload is end_turn, max_tokens (length limit), tool_use (tool calls were offered and produced), refusal (content filter) or stop_sequence (a stop_sequences entry matched); message_start carries null because the turn has not finished yet. stop_sequence names the matched entry, otherwise it is null. The identical filter runs on both paths, so the buffered and streamed text agree. Generation upstream is not stopped, so usage.output_tokens still reports every token the turn produced, which can exceed the visible (truncated) text.
  • A thinking block is emitted only when reasoning was requested and surfaced. Its signature is base64("opencode-api:<gateway message id>") — a deterministic placeholder derived from the response id, not a cryptographic attestation. Both paths key it on the same gateway id (message.id), so a streamed turn and the buffered form of the same turn always agree; two separate requests are different messages and therefore sign differently.
  • x_opencode.native_tool_calls is a count on this surface.
  • A turn the upstream reports as failed is not a normal response: a buffered request answers 502 api_error with the Anthropic error body, and a streamed turn ends with an error event (api_error) instead of message_delta/message_stop, so a partial answer is never presented as a completed one.
  • A turn the upstream reports as cancelled keeps stop_reason: "end_turn" but sets x_opencode.interrupted: true; the streamed form carries x_opencode: {"interrupted": true} on the final message_delta.
  • Bridged tool calls become tool_use blocks {type:"tool_use",id,name,input} where input is the parsed arguments object (an empty object when the arguments are not a JSON object).
  • An empty content array is possible if the model produced nothing.

Streaming (stream: true)

event: message_start
data: {"type":"message_start","message":{"id":"msg_...","type":"message","role":"assistant","model":"opencode/deepseek-v4.1-flash-free","content":[],"stop_reason":null,"stop_sequence":null,"usage":{"input_tokens":0,"output_tokens":0,"cache_creation_input_tokens":0,"cache_read_input_tokens":0}}}

event: content_block_start
data: {"type":"content_block_start","index":0,"content_block":{"type":"thinking","thinking":"","signature":""}}

event: content_block_delta
data: {"type":"content_block_delta","index":0,"delta":{"type":"thinking_delta","thinking":"The user greeted me."}}

event: content_block_delta
data: {"type":"content_block_delta","index":0,"delta":{"type":"signature_delta","signature":"b3BlbmNvZGUtYXBpOm1zZ18zZjFjOWQyYTRiNWU0YzBmOGE3ZDZlNWI="}}

event: content_block_stop
data: {"type":"content_block_stop","index":0}

event: content_block_start
data: {"type":"content_block_start","index":1,"content_block":{"type":"text","text":""}}

event: content_block_delta
data: {"type":"content_block_delta","index":1,"delta":{"type":"text_delta","text":"Hello"}}

event: content_block_stop
data: {"type":"content_block_stop","index":1}

event: message_delta
data: {"type":"message_delta","delta":{"stop_reason":"end_turn","stop_sequence":null},"usage":{"output_tokens":9,"input_tokens":12,"cache_read_input_tokens":0,"cache_creation_input_tokens":0}}

event: message_stop
data: {"type":"message_stop"}

Tool calls are emitted after the text blocks, each as its own block:

event: content_block_start
data: {"type":"content_block_start","index":2,"content_block":{"type":"tool_use","id":"call_9a1b...","name":"get_weather","input":{}}}

event: content_block_delta
data: {"type":"content_block_delta","index":2,"delta":{"type":"input_json_delta","partial_json":"{\"city\":\"Hanoi\"}"}}

event: content_block_stop
data: {"type":"content_block_stop","index":2}

A tool-only turn has no text block on either path: the tool_use block opens at index 0, or index 1 when a thinking block precedes it. No empty text block is emitted, and a turn that produced nothing streams no content block at all.

message_start.message.usage is always {"input_tokens": 0, "output_tokens": 0}: the gateway learns usage only when the turn ends. The authoritative totals — input_tokens, output_tokens (thinking tokens included), cache_creation_input_tokens and cache_read_input_tokens — arrive in the final message_delta.usage, so SDK cost accounting must read usage from message_delta, not from message_start.

Errors after the stream starts are delivered as an error event, and a failure raised before the first frame is reported with a real HTTP status. Whatever the turn had already delivered is still real content: a block that was open is closed with its content_block_stop (and any text the stop_sequences lookahead was still holding is flushed as a final text_delta) before the error frame, so the client can assemble the partial message. The error frame itself carries no partial message.

event: content_block_stop
data: {"type":"content_block_stop","index":0}

event: error
data: {"type":"error","error":{"type":"overloaded_error","message":"Model is unavailable"}}

Streamed block order follows arrival: each block opens at the index free when its first delta arrives, so a turn that emits text before reasoning streams [text, thinking]. The buffered content array is always ordered thinking → text → tool_use, so the two paths agree for the usual reasoning-then-text turn and a client that assembles content[] from a stream must not assume the buffered order.

Errors

Anthropic shape, selected by the request path (/v1/messages*):

{
  "type": "error",
  "error": {
    "type": "invalid_request_error",
    "message": "Model 'gpt-9' was not found. Call GET /v1/models for the list of available models."
  }
}
Status error.type
400 invalid_request_error
401 authentication_error
403 permission_error
404 not_found_error
429 rate_limit_error (with retry-after header; mid-stream the hint travels as retry_after_ms in the error frame)
502 api_error
503 overloaded_error (including event_stream_lost, a mid-turn event-stream reconnect: the message says the answer may be incomplete)
504 timeout_error

curl

curl 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,
    "messages": [{"role": "user", "content": "Say hello."}]
  }'

5. POST /v1/messages/count_tokens

Estimates the prompt size of a Messages request without running it. The body is the same as POST /v1/messages except that max_tokens is optional. The model is still resolved, so an unknown model returns 404.

Response

{
  "input_tokens": 42,
  "x_opencode": { "estimated": true, "method": "mixed" }
}

method is "mixed", or "mixed+media" when inline media was charged.

The number is an approximation: OpenCode exposes no tokenizer endpoint, so the gateway estimates one token per CJK character and characters / 4 for the rest over every message, the system prompt, and — only when the tool bridge is active, so a tool_choice that disables tool use charges neither — the tool-bridge instructions that will be prepended to the real prompt and the tool JSON schemas, plus a small per-message overhead, and never reports less than 1. Media blocks are not downloaded for this endpoint: an inline base64 block is charged ceil(decodedBytes / 750) bytes-per-token, while a url block contributes only a short placeholder because its size is unknown. x_opencode.method is "mixed+media" when inline media was present and "mixed" otherwise. The x_opencode object marks the value as an estimate so callers can decide whether it is accurate enough.

Errors

Anthropic shape, same status table as /v1/messages.

curl

curl http://127.0.0.1:20123/v1/messages/count_tokens \
  -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","messages":[{"role":"user","content":"Count these tokens."}]}'

6. POST /v1/embeddings

Always answers 501, with no model resolution and no upstream call:

{
  "error": {
    "message": "Embeddings are not supported: the OpenCode runtime does not expose an embedding model.",
    "type": "invalid_request_error",
    "code": "not_implemented_error",
    "param": null
  }
}

OpenCode's catalog contains chat/completion models only — there is no embedding model to route to, and OpenCode offers no embeddings API. Answering 501 explicitly (rather than a confusing 404) tells clients to stop retrying and keeps them from storing meaningless vectors. Point embedding workloads at a dedicated provider.

curl -i http://127.0.0.1:20123/v1/embeddings \
  -H "Authorization: Bearer $OPENCODE_API_KEY" \
  -H "Content-Type: application/json" \
  -d '{"model":"text-embedding-3-small","input":"hello"}'

7. GET /v1/models

Returns every model the OpenCode server exposes, sorted by canonical id. The non-OpenAI fields are gateway extensions placed next to the standard keys.

{
  "object": "list",
  "data": [
    {
      "id": "opencode/deepseek-v4.1-flash-free",
      "object": "model",
      "created": 1792195200,
      "owned_by": "opencode",
      "name": "DeepSeek V4.1 Flash Free",
      "context_length": 200000,
      "max_output_tokens": 8192,
      "capabilities": {
        "tools": true,
        "input": ["text", "image"],
        "output": ["text"],
        "temperature": true
      },
      "reasoning": {
        "supported": true,
        "efforts": ["low", "high", "max"],
        "default_effort": "high"
      },
      "status": "active",
      "enabled": true
    }
  ]
}
  • reasoning.efforts lists only the variants that parse as a known thinking effort, in ladder order (none, minimal, low, medium, high, xhigh, max). A model with no ladder reports supported: false, efforts: [], default_effort: null. The implicit default variant is not listed.
  • reasoning.default_effort is the effort the gateway selects when a caller asks for reasoning without naming one (the nearest effort to medium, preferring the higher of two equidistant options).
  • created is copied from the upstream time.released field — which OpenCode 2.3.2 reports in milliseconds, not the seconds OpenAI specifies — falling back to the current Unix time in seconds when the field is missing or zero.
  • The list is cached for OPENCODE_MODEL_CACHE_TTL_MS (default 5 min). Add ?refresh=true to force a catalog reload (GET /v1/models?refresh=true).
  • A cold opencode serve reports readiness before its providers are registered, so the first /api/model answer can be an empty list. The gateway retries briefly and never caches an empty catalogue, so the models appear as soon as the provider registers them instead of failing for the whole TTL.

curl

curl "http://127.0.0.1:20123/v1/models" -H "Authorization: Bearer $OPENCODE_API_KEY"
curl "http://127.0.0.1:20123/v1/models?refresh=true" -H "Authorization: Bearer $OPENCODE_API_KEY"

8. GET /v1/models/{id} and GET /v1/models/*

Returns one entry in exactly the same shape as a member of the list.

The id may be provider/model, a bare model id, an alias, or a model#variant reference. Because model ids contain /, the two spellings are registered as separate routes: {id} serves a bare id or an alias, and the wildcard * serves the canonical provider/model form, which would otherwise be split into two path segments. Both work without escaping:

curl http://127.0.0.1:20123/v1/models/opencode/deepseek-v4.1-flash-free \
  -H "Authorization: Bearer $OPENCODE_API_KEY"

curl http://127.0.0.1:20123/v1/models/deepseek-v4.1-flash-free \
  -H "Authorization: Bearer $OPENCODE_API_KEY"

Unknown ids return 404:

{
  "error": {
    "message": "Model 'nope' was not found. Call GET /v1/models for the list of available models.",
    "type": "invalid_request_error",
    "code": "model_not_found",
    "param": "model"
  }
}

Gateway root

GET / is unauthenticated and returns the endpoint index:

{
  "service": "opencode-api",
  "version": "1.0.0",
  "endpoints": [
    "POST /v1/chat/completions",
    "POST /v1/responses",
    "POST /v1/completions",
    "POST /v1/messages",
    "POST /v1/messages/count_tokens",
    "GET  /v1/models",
    "GET  /v1/models/{id}",
    "GET  /v1/models/*",
    "POST /v1/embeddings",
    "GET  /health",
    "GET  /ready",
    "GET  /healthz",
    "GET  /metrics",
    "GET  /admin/status",
    "GET  /admin/config",
    "POST /admin/models/refresh",
    "GET  /admin/sessions",
    "DELETE /admin/sessions",
    "POST /admin/upstream/restart"
  ]
}

Operational endpoints

These are not model surfaces; they report or control gateway state.

Method Path Auth Response
GET /health public {status:"ok", service, version, uptimeSeconds, upstream:{ready, source}} — liveness only, never calls upstream.
GET /ready public 200 {status:"ready", ..., upstream:{ready,source,url,models}} only when an upstream endpoint is resolved and a model catalogue is already cached; otherwise 503 {status:"unavailable", ..., upstream:{ready:false,...,error}}. Reads cached state only, so an anonymous probe cannot trigger upstream work. Force a refresh with POST /admin/models/refresh.
GET /healthz public Minimal liveness alias {status:"ok", service, version}.
GET /metrics key or OPENCODE_METRICS_TOKEN, unless OPENCODE_METRICS_PUBLIC=true and no token is configured Prometheus text exposition (opencode_api_*). 404 metrics_disabled when OPENCODE_METRICS_ENABLED=false.
GET /admin/status key (or OPENCODE_ADMIN_API_KEYS when configured) Service version, uptime, a config subset, upstream status (URL/pid/last error/stderrTail — the last 50 stderr lines of the supervised server, with any server password value redacted), catalogue counts and session-cache counts.
GET /admin/config key (or OPENCODE_ADMIN_API_KEYS when configured) The effective configuration, with auth.apiKeyCount, auth.usingDefaultApiKey and upstream.passwordConfigured instead of the secrets themselves. upstream.url, timeouts, media limits, session settings and reasoning defaults are included.
POST /admin/models/refresh key (or OPENCODE_ADMIN_API_KEYS when configured) Forces a catalogue reload and returns {refreshedAt, models, providers, agents}.
GET /admin/sessions key (or OPENCODE_ADMIN_API_KEYS when configured) Every cached sticky session: key, session id, model, agent, variant, delivered/reused counts, busy, timestamps.
DELETE /admin/sessions key (or OPENCODE_ADMIN_API_KEYS when configured) Drops every cached session; returns {cleared}.
POST /admin/upstream/restart key (or OPENCODE_ADMIN_API_KEYS when configured) Invalidates the endpoint, stops the spawned server if there is one, and resolves a new one; returns {url, source, pid}.

When OPENCODE_RATE_LIMIT_RPM is non-zero every authenticated request is charged against a per-key token bucket (with a separate bucket for /admin/*). A rejected request answers 429 with error.code: "rate_limit_exceeded" and a retry-after header in seconds. Failed authentication has its own always-on bucket (at least 60 attempts per minute per client address) plus a much higher global ceiling over every address, and also answers 429 once either is spent. /health, /ready, /healthz and / are never rate limited; /metrics is charged to the same bucket as any other route, so an anonymous scrape loop is throttled too.

OPENCODE_BODY_TIMEOUT_MS bounds how long a caller may take to send the request body; a request that never finishes is disconnected. It does not apply to a stream: true response, whose socket stays open for the whole turn.

Metrics

GET /metrics exposes the opencode_api_ series below (Prometheus text format; OPENCODE_METRICS_ENABLED=false answers 404 metrics_disabled).

Series Type Labels
http_requests_total, http_request_duration_seconds counter, histogram method, route, status
upstream_requests_total counter operation, outcome
upstream_request_duration_seconds histogram operation
tokens_total counter model, direction
completions_total counter surface, model, stream, finish_reason, error_code
active_streams gauge surface
upstream_restarts_total counter reason ∈ initial | stale | invalidated | restart
session_cache_entries gauge state ∈ entries | busy
event_stream_connected gauge —
event_stream_reconnects_total counter reason ∈ idle | ended | rejected
event_frames_dropped_total counter reason ∈ no_session | no_subscriber | malformed | stale
rate_limit_rejections_total counter scope ∈ api | admin

completions_total counts every exit, including failures: finish_reason stays within the documented finish reasons (stop, length, tool_calls, content_filter, error, cancelled) and a failure adds the gateway's own error code in error_code (empty on success) — so a lost event stream is finish_reason="error", error_code="event_stream_lost", never a finish reason of its own.

JSON output mode

OpenCode offers no per-request output-schema control: the client's tools cannot be passed to it either, and function calling is bridged through the prompt for the same reason. JSON output follows the same pattern.

  • /v1/chat/completions: response_format with {"type":"json_object"} or {"type":"json_schema","json_schema":{name,schema}}.
  • /v1/responses: text.format with {"type":"json_object"} or {"type":"json_schema",name,schema}.
  • {"type":"text"} and an absent field leave the prompt unchanged.

The gateway appends a # Response format section to the prompt asking for a single valid JSON value (plus the schema, when one was supplied) and no prose or code fence. This is a model contract, not a server-enforced one: nothing validates the reply, so a model that ignores the instruction can still return prose. Validate the reply on the client when it matters.

Streaming mechanics

  • SSE payloads are UTF-8 JSON; a payload containing newlines is split across repeated data: lines, exactly as the OpenAI and Anthropic clients expect.
  • A comment frame : keep-alive is sent every 15 s on every stream.
  • The chat, legacy-completions, Responses and Anthropic surfaces all defer writing the response head until the first frame, so pre-flight failures (unknown model, bad body, disabled media) return a proper JSON error with an HTTP status on every surface. Once the first frame is out the status is 200, and later failures arrive as an error frame (OpenAI chat/completions), event: error plus a terminal response.failed (Responses) or an error frame (Anthropic).
  • The SSE head carries every header the gateway set on the reply (CORS, x-request-id), because the response is written outside Fastify's serialiser.
  • The gateway already sends x-accel-buffering: no; use curl -N and disable any proxy buffering when testing.
  • A client disconnect aborts the upstream turn: the gateway interrupts the OpenCode session, cancels any in-flight attachment download and releases the sticky session slot. Disconnects are detected from the response connection (request.raw close fires when the body has been read, not when the caller leaves). In non-streaming mode a cancelled request surfaces as 499.
  • Sessions are reused only when the client resends a conversation whose prefix matches what the upstream session already holds. Pass x-conversation-id to make the key explicit, or set OPENCODE_SESSION_CACHE=false to disable reuse.