Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
6 changes: 6 additions & 0 deletions .env.example
Original file line number Diff line number Diff line change
Expand Up @@ -122,6 +122,12 @@ PORT=20123
# Budget for the first text/reasoning delta (default 3 min).
# OPENCODE_FIRST_TOKEN_TIMEOUT_MS=180000

# Cap on `<dataDir>/logs/opencode-<port>.log` (default 32 MiB). The supervised
# server's stdout/stderr is appended for its whole life and across restarts, so
# the file is rotated (truncated) once it would exceed this many bytes. Set 0 to
# keep it unbounded.
# OPENCODE_UPSTREAM_LOG_MAX_BYTES=33554432

# ---------------------------------------------------------------------------
# Agent and workspace
# ---------------------------------------------------------------------------
Expand Down
10 changes: 10 additions & 0 deletions .github/workflows/ci.yml
Original file line number Diff line number Diff line change
Expand Up @@ -32,6 +32,10 @@ jobs:
uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7
with:
fetch-depth: 0
# Every job runs `pnpm install --frozen-lockfile` with dependency build
# scripts allowed, so the checkout must not leave the repository token
# in `.git/config` for those scripts to read.
persist-credentials: false

- name: Set up pnpm
uses: pnpm/action-setup@73e46992e05b19abd31f2f3c20e0e7370d762115 # v6
Expand Down Expand Up @@ -100,6 +104,8 @@ jobs:
steps:
- name: Check out the repository
uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7
with:
persist-credentials: false

- name: Set up pnpm
uses: pnpm/action-setup@73e46992e05b19abd31f2f3c20e0e7370d762115 # v6
Expand Down Expand Up @@ -155,6 +161,8 @@ jobs:
steps:
- name: Check out the repository
uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7
with:
persist-credentials: false

- name: Set up pnpm
uses: pnpm/action-setup@73e46992e05b19abd31f2f3c20e0e7370d762115 # v6
Expand Down Expand Up @@ -192,6 +200,8 @@ jobs:
steps:
- name: Check out the repository
uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7
with:
persist-credentials: false

- name: Build the image
run: docker build --tag opencode-api:ci .
Expand Down
16 changes: 10 additions & 6 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -489,6 +489,7 @@ model_disabled`. Query `GET /v1/models` instead of guessing.
| `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_UPSTREAM_LOG_MAX_BYTES` | `33554432` | Cap on `<data dir>/logs/opencode-<port>.log`; the file is truncated and reopened past it, `0` keeps it unbounded. |
| `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. |
Expand Down Expand Up @@ -526,11 +527,14 @@ Every variable, with types, defaults and security notes:
`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 charged to the same rate-limit bucket as the API routes,
so an anonymous scraper cannot walk every collector without limit; only the
liveness probes and `OPTIONS` stay exempt.
`OPENCODE_METRICS_TOKEN` is configured. With a token configured the endpoint is
never anonymous: the token is accepted (and checked first), and a valid general
API key is still accepted, so a scraper can be given either. While
`OPENCODE_RATE_LIMIT_RPM` is non-zero `/metrics` is charged to the same
rate-limit bucket as the API routes, so an anonymous scraper cannot walk every
collector without limit; with the default `OPENCODE_RATE_LIMIT_RPM=0` the
limiter is off for every route. Only the liveness probes and `OPTIONS` stay
exempt.
* **`/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`
Expand Down Expand Up @@ -686,7 +690,7 @@ 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
│ │ ├── common/ # reasoning mapping, tool bridge, stop delimiters, 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
Expand Down
37 changes: 28 additions & 9 deletions docs/API.md
Original file line number Diff line number Diff line change
Expand Up @@ -87,7 +87,7 @@ with a `retry-after` header once that budget is spent.
| 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`. |
| `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. |
Expand All @@ -106,7 +106,7 @@ with a `retry-after` header once that budget is spent.
| `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. Generation upstream is not interrupted, so `usage` counts the full turn and `finish_reason` stays `stop`. |
| `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. |
Expand Down Expand Up @@ -163,8 +163,12 @@ with a `retry-after` header once that budget is spent.
* `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]`. Only
`cancelled` (client disconnect) is reported as `stop`.
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`.
Expand Down Expand Up @@ -288,7 +292,7 @@ reasoning mapping and tool bridging with the chat endpoint.
| 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`. |
| `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. |
Expand Down Expand Up @@ -407,7 +411,7 @@ 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":"","agent":"build","variant":null,"reused_session":false,"native_tool_calls":[]}}}
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":{...}}
Expand Down Expand Up @@ -515,7 +519,7 @@ the wire format. Use `/v1/chat/completions` for anything new.
| `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`. Generation upstream is not interrupted. |
| `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). |
Expand Down Expand Up @@ -601,7 +605,7 @@ Anthropic Messages API.
| `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. 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. |
| `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.) |
Expand Down Expand Up @@ -730,13 +734,28 @@ arrive in the final `message_delta.usage`, so SDK cost accounting must read usag
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:
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*`):
Expand Down
Loading
Loading