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
31 changes: 27 additions & 4 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -414,6 +414,23 @@ Limitations, stated plainly:
Bridged tools and native tools can appear in the same turn: the model may call
your tool while the OpenCode agent independently uses its own.

## JSON output mode

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

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

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

## Model naming

| Form | Example | Resolves to |
Expand Down Expand Up @@ -470,12 +487,16 @@ Every variable, with types, defaults and security notes:
`opencode_api_`: `http_requests_total`, `http_request_duration_seconds`,
`upstream_requests_total`, `upstream_request_duration_seconds`,
`tokens_total`, `completions_total`, `active_streams`, `upstream_restarts_total`,
`session_cache_entries`, plus process defaults. Requires a key unless
`session_cache_entries`, `event_stream_connected`, plus process defaults. Requires a key unless
`OPENCODE_METRICS_PUBLIC=true`.
* **`/admin/*`** — `/admin/status` (config, upstream binary and URL, catalog
counts, session count), `/admin/models/refresh`, `/admin/sessions` (list and
delete-all), `/admin/upstream/restart`. Authenticated; restrict them at the
proxy if you expose the gateway.
* **Request correlation.** Send `x-request-id` (up to 128 characters from
`A-Za-z0-9._:-`) and the gateway echoes it on the response and uses it as the
request id in its logs; anything else is replaced by a generated id. Streaming
responses carry it too.
* **Sticky sessions.** OpenAI and Anthropic clients resend the whole
conversation on every call. The gateway recognises the prefix it has already
delivered upstream and continues the same OpenCode session instead of
Expand All @@ -488,7 +509,9 @@ Every variable, with types, defaults and security notes:
`OPENCODE_SESSION_CACHE=false` for fully stateless routing.
* **Free-tier rate limits.** The bundled free models are limited per model and
per window upstream. The gateway answers `429` with a `retry-after` header in
seconds and repeats the upstream message; back off for that long. Transient
seconds and repeats the upstream message; back off for that long. A stream
that already sent its first frame cannot add a header, so the same hint is
repeated as `retry_after_ms` inside the error frame. Transient
`503 ServiceUnavailableError` ("Model is unavailable") is mapped to
`overloaded_error`. Neither is a gateway bug — switch model or wait.

Expand Down Expand Up @@ -558,7 +581,7 @@ The compose file maps `20123:20123`, reads `.env`, mounts
| --- | --- |
| `pnpm setup` | Write `.env` (keeps `sk-dummy-123`; `-- --random` generates a strong key instead). |
| `pnpm dev` | Start with `tsx watch` and reload on change. |
| `pnpm build` | Type-check-free emit with `tsc -p tsconfig.build.json` into `dist/`. |
| `pnpm build` | Type-check and emit `src/` into `dist/` with `tsc -p tsconfig.build.json`. |
| `pnpm typecheck` | `tsc -p tsconfig.json --noEmit`. |
| `pnpm test` | Unit tests (excludes `test/integration/**`). |
| `pnpm test:integration` | Integration tests against a live gateway/upstream. |
Expand All @@ -584,7 +607,7 @@ opencode-api/ # package name; the project is "OpenCode API"
│ │ ├── anthropic/ # /v1/messages, /v1/messages/count_tokens
│ │ ├── common/ # reasoning mapping, tool bridge, usage maths
│ │ └── openai/ # /v1/chat/completions, /v1/responses, /v1/models, /v1/embeddings
│ ├── http/ # SSE writer
│ ├── http/ # SSE writer, client-disconnect signal
│ ├── media/ # data URI, remote fetch, local path resolution
│ ├── metrics/ # Prometheus registry
│ ├── routes/ # health, metrics, admin
Expand Down
57 changes: 43 additions & 14 deletions docs/API.md
Original file line number Diff line number Diff line change
Expand Up @@ -23,6 +23,7 @@ operational and documented in the README.
| `x_opencode` | response field | Non-standard object attached to every completion payload: `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 `/v1/chat/completions`. |
| `x-conversation-id` | request header | Explicit sticky-session key. Requests carrying the same value reuse the same upstream OpenCode session while their message prefix still matches. |
| `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. |

Expand Down Expand Up @@ -64,11 +65,12 @@ when `OPENCODE_METRICS_PUBLIC=true`).
| `reasoning_effort` | string | *(unset)* | `none`, `minimal`, `low`, `medium`, `high`, `xhigh`, `max` plus aliases (`off`, `min`, `maximum`, ...). |
| `reasoning.effort` | string | *(unset)* | Used when `reasoning_effort` is absent. |
| `max_tokens` / `max_completion_tokens` | number | *(unset)* | `max_completion_tokens` wins. Recorded, not enforced upstream: OpenCode's agent owns the generation budget. |
| `temperature`, `top_p` | number | *(unset)* | Accepted; sent upstream only for models whose capabilities advertise temperature support. |
| `temperature`, `top_p` | number | *(unset)* | Accepted and recorded, but not forwarded: OpenCode's agent loop owns the sampling parameters (same as `max_tokens`). |
| `stop` | string \| string[] | *(unset)* | Accepted. Empty strings are dropped. |
| `n` | number | `1` | **Only `1` is supported**; anything else returns `400 invalid_request`. |
| `user`, `metadata`, `service_tier`, `parallel_tool_calls` | — | — | Accepted; not forwarded. `metadata` is carried on the internal request for logging. |
| `seed`, `logprobs`, `logit_bias`, `presence_penalty`, `frequency_penalty`, `response_format` | — | — | Accepted and deliberately ignored. |
| `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. |
| `seed`, `logprobs`, `logit_bias`, `presence_penalty`, `frequency_penalty` | — | — | Accepted and deliberately ignored. |

### Response (`stream: false`)

Expand Down Expand Up @@ -112,7 +114,8 @@ when `OPENCODE_METRICS_PUBLIC=true`).
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 (the chat adapter reads that variable directly).
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`; the
internal `error`/`cancelled` reasons are reported as `stop`.
* `x_opencode.native_tool_calls` lists native OpenCode tool activity as
Expand All @@ -124,7 +127,8 @@ when `OPENCODE_METRICS_PUBLIC=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.
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}]}
Expand Down Expand Up @@ -192,7 +196,7 @@ data: {"error":{"message":"OpenCode did not finish the request in time.","type":
| `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` (with `retry-after` header, in seconds) |
| `429` | `rate_limit_error` | `provider.free-limit`, `rate_limit_error` (with `retry-after` header, in seconds; mid-stream the hint travels as `retry_after_ms` in the error frame instead) |
| `499` | — | client disconnected before the response started |
| `501` | `invalid_request_error` | `not_implemented_error` |
| `502` | `api_error` | `upstream_error` |
Expand Down Expand Up @@ -238,11 +242,14 @@ reasoning mapping and tool bridging with the chat endpoint.
| `max_output_tokens`, `temperature`, `top_p`, `metadata`, `parallel_tool_calls`, `truncation` | — | — | Accepted and echoed back. `parallel_tool_calls` defaults to `true`; `truncation` defaults to `"disabled"`. |
| `previous_response_id` | string | *(unset)* | Accepted and ignored — the gateway keeps no response store, so callers must resend the full `input`. Echoed as `null`. |
| `store` | boolean | `false` | Accepted and ignored; nothing is persisted. Echoed as given. |
| `text.format`, `include`, `service_tier`, `top_logprobs`, `user` | — | — | Accepted for compatibility; no effect. |
| `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". |
| `include`, `service_tier`, `top_logprobs`, `user` | — | — | Accepted for compatibility; no effect. |

`item_reference` items are skipped (they point at stored responses the gateway
does not keep). `function_call` items become assistant tool calls;
`function_call_output` items become `role: "tool"` turns.
`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.

### Response (`stream: false`)

Expand Down Expand Up @@ -355,9 +362,9 @@ data: {"type":"response.completed","sequence_number":8,"response":{"id":"resp_..
* `response.created` and `response.in_progress` are always the first two frames,
even before the upstream turn has been assigned a session.
* Reasoning deltas use `response.reasoning_summary_part.added`,
`response.reasoning_summary_text.delta` and `response.reasoning_summary_text.done`;
the closing item appears as `response.output_item.done` with
`output_index: 0`.
`response.reasoning_summary_text.delta`, `response.reasoning_summary_text.done`
and `response.reasoning_summary_part.done`; the closing item then appears as
`response.output_item.done` with `output_index: 0`.
* The message item occupies `output_index: 1` when a reasoning item precedes it.
* Tool calls are emitted at the end of the stream as
`response.output_item.added` (status `in_progress`), one
Expand Down Expand Up @@ -533,7 +540,7 @@ Anthropic shape, selected by the request path (`/v1/messages*`):
| `401` | `authentication_error` |
| `403` | `permission_error` |
| `404` | `not_found_error` |
| `429` | `rate_limit_error` (with `retry-after` header) |
| `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` |
| `504` | `timeout_error` |
Expand Down Expand Up @@ -628,7 +635,7 @@ non-OpenAI fields are gateway extensions placed next to the standard keys.
{
"id": "opencode/deepseek-v4.1-flash-free",
"object": "model",
"created": 1792195200000,
"created": 1792195200,
"owned_by": "opencode",
"name": "DeepSeek V4.1 Flash Free",
"context_length": 200000,
Expand Down Expand Up @@ -723,6 +730,24 @@ Unknown ids return `404`:
}
```

## 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
Expand All @@ -733,11 +758,15 @@ Unknown ids return `404`:
return a proper JSON error with an HTTP status. `/v1/responses` opens the
stream immediately and therefore reports pre-flight failures as an `error`
frame.
* 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 and releases the sticky session slot. In non-streaming mode a
cancelled request surfaces as `499`.
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.
24 changes: 20 additions & 4 deletions docs/ARCHITECTURE.md
Original file line number Diff line number Diff line change
Expand Up @@ -171,8 +171,9 @@ completion work.
### 4.1 `src/types/internal.ts` (frozen)

`Surface`, `Attachment`, `AttachmentKind`, `ToolDefinition`, `ToolCall`,
`InternalMessage`, `ReasoningRequest`, `InternalRequest`, `Usage`,
`FinishReason`, `NativeToolActivity`, `CompletionEvent`.
`InternalMessage`, `ReasoningRequest`, `ResponseFormat`,
`InternalRequest`, `Usage`, `FinishReason`, `NativeToolActivity`,
`CompletionEvent`.

### 4.2 `src/errors.ts` (frozen)

Expand Down Expand Up @@ -279,7 +280,10 @@ Shared helpers each adapter may use:
* `ctx.completion.run(request, completionDeps(ctx), { signal })` → `AsyncGenerator<CompletionEvent>`
* `ctx.completion.collect(request, completionDeps(ctx), { signal })` → `Promise<CollectedCompletion>`
* `completionDeps(ctx)` from `src/context.ts`
* `SseWriter` from `src/http/sse.ts`
* `SseWriter` from `src/http/sse.ts` (its head merges `reply.getHeaders()`,
because `reply.hijack()` bypasses Fastify's serialiser)
* `createDisconnectSignal(request, reply)` from `src/http/disconnect.ts` — the
only supported way to turn a client disconnect into an `AbortSignal`
* `ApiError` from `src/errors.ts` (throw it; the global error handler renders the
right shape — Anthropic shape for `/v1/messages*`, OpenAI shape otherwise)
* `resolveAttachment` from `src/media/resolve.ts`
Expand All @@ -298,7 +302,9 @@ tests can substitute a scripted runner (`test/helpers/context.ts`).
* Never call the model provider directly; use `runCompletion`/`collectCompletion`.
* Streaming handlers must:
* create the `SseWriter` only after validation succeeds,
* pass `{ signal }` from `request.raw` `close` events into `runCompletion`,
* pass the `createDisconnectSignal()` signal into `runCompletion` (`request.raw`
`close` fires when the body has been read on Node >= 16, so it is not a
disconnect signal),
* always `close()` the writer,
* increment `ctx.metrics.activeStreams` and decrement it in `finally`.
* Tests live in `test/**/*.test.ts` and run with `vitest`. Unit tests must not
Expand Down Expand Up @@ -336,3 +342,13 @@ tests can substitute a scripted runner (`test/helpers/context.ts`).
embedding model is exposed by OpenCode.
* Model names accept both `provider/model` and the bare `model` id, plus an
optional `#variant` suffix and `OPENCODE_MODEL_ALIASES` indirection.
* Every response carries `x-request-id`: a caller-supplied value that matches
`[A-Za-z0-9._:-]{1,128}`, otherwise a generated id. It is the Fastify request
id, so it also correlates the log lines of one request.
* JSON output is bridged through the prompt, exactly like tool calling:
`response_format` (chat) and `text.format` (responses) become a
`# Response format` prompt section (`InternalRequest.responseFormat`). Nothing
validates the reply server-side.
* Client disconnects are detected from the response connection
(`src/http/disconnect.ts`); an in-flight turn is interrupted, the sticky slot
is released and a pending media download is aborted.
Loading