diff --git a/.env.example b/.env.example index 00d5378..f1c4c04 100644 --- a/.env.example +++ b/.env.example @@ -143,8 +143,9 @@ PORT=20123 # against the host network; keep it false unless you control the URL sources. # OPENCODE_ALLOW_PRIVATE_MEDIA_URLS=true -# Size and count limits. ONE attachment may not exceed MAX_ATTACHMENT_BYTES; -# the whole request may not exceed MAX_ATTACHMENT_BYTES across attachments. +# Size and count limits. The same byte budget applies to one attachment and to +# the combined total per request: an attachment that would push the request over +# the budget is dropped entirely and its name is recorded in the prompt. # OPENCODE_MAX_ATTACHMENT_BYTES=20971520 # OPENCODE_MAX_ATTACHMENTS=16 # OPENCODE_MEDIA_FETCH_TIMEOUT_MS=15000 diff --git a/README.md b/README.md index 5141690..da19f2d 100644 --- a/README.md +++ b/README.md @@ -175,16 +175,18 @@ When nothing is found the request fails with: | --- | --- | --- | | `POST` | `/v1/chat/completions` | OpenAI Chat Completions: streaming and non-streaming, tools, images, `reasoning_effort`. | | `POST` | `/v1/responses` | OpenAI Responses API with its typed SSE event sequence. | +| `POST` | `/v1/completions` | Legacy OpenAI completions: a prompt string (an array prompt requires `n: 1`) mapped to one user turn, streamed or buffered. | | `POST` | `/v1/messages` | Anthropic Messages: streaming and non-streaming, `thinking`, `tool_use`. | | `POST` | `/v1/messages/count_tokens` | Anthropic token-count estimate for a Messages body. | | `POST` | `/v1/embeddings` | Always `501` — OpenCode exposes no embedding model. | | `GET` | `/v1/models` | List models, with gateway extensions: `name`, `context_length`, `max_output_tokens`, `capabilities`, `reasoning`, `status`, `enabled`. | | `GET` | `/v1/models/{id}` | One model by `provider/model` or bare id. | | `GET` | `/health` | Liveness plus upstream readiness snapshot (public). | -| `GET` | `/ready` | Readiness: `200` only when an upstream server and a model catalog are available (public). | +| `GET` | `/ready` | Readiness from cached state: `200` only when an upstream server is resolved and a model catalog is already cached (public, never calls upstream). | | `GET` | `/healthz` | Minimal liveness alias (public). | | `GET` | `/metrics` | Prometheus exposition (requires a key unless `OPENCODE_METRICS_PUBLIC=true`). | | `GET` | `/admin/status` | Config, upstream, catalog and session-cache snapshot. | +| `GET` | `/admin/config` | The effective configuration, with secrets redacted. | | `POST` | `/admin/models/refresh` | Force a model catalog reload. | | `GET` | `/admin/sessions` | List sticky sessions. | | `DELETE` | `/admin/sessions` | Drop every sticky session. | @@ -480,9 +482,11 @@ Every variable, with types, defaults and security notes: * **`GET /health`** — liveness plus `upstream.ready` and `upstream.source` (`env`, `spawned`, `discovered`). Public, like `/ready` and `/healthz`. -* **`GET /ready`** — `200` only when an upstream server answers and the model - catalog loads; `503` with `upstream.error` otherwise. Use it for container - readiness and load-balancer gating. +* **`GET /ready`** — `200` only when an upstream endpoint is resolved and a model + catalog is already **cached**; `503` with `upstream.error` otherwise. It never + calls upstream, so an anonymous probe cannot trigger work: force a refresh with + the authenticated `POST /admin/models/refresh`. Use it for container readiness + and load-balancer gating. * **`GET /metrics`** — Prometheus text format from `prom-client`, prefix `opencode_api_`: `http_requests_total`, `http_request_duration_seconds`, `upstream_requests_total`, `upstream_request_duration_seconds`, @@ -490,9 +494,10 @@ Every variable, with types, defaults and security notes: `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. + counts, session count), `/admin/config` (effective configuration with API keys + and the upstream password redacted), `/admin/models/refresh`, `/admin/sessions` + (list and delete-all), `/admin/upstream/restart`. Authenticated; restrict them + at the proxy if you expose the gateway. * **Request correlation.** Send `x-request-id` (up to 128 characters from `A-Za-z0-9._:-`) and the gateway echoes it on the response and uses it as the request id in its logs; anything else is replaced by a generated id. Streaming @@ -606,7 +611,7 @@ opencode-api/ # package name; the project is "OpenCode API" │ ├── adapter/ │ │ ├── anthropic/ # /v1/messages, /v1/messages/count_tokens │ │ ├── common/ # reasoning mapping, tool bridge, usage maths -│ │ └── openai/ # /v1/chat/completions, /v1/responses, /v1/models, /v1/embeddings +│ │ └── openai/ # /v1/chat/completions, /v1/responses, /v1/completions, /v1/models, /v1/embeddings │ ├── http/ # SSE writer, client-disconnect signal │ ├── media/ # data URI, remote fetch, local path resolution │ ├── metrics/ # Prometheus registry diff --git a/docs/API.md b/docs/API.md index e561092..703ce9e 100644 --- a/docs/API.md +++ b/docs/API.md @@ -1,12 +1,13 @@ # OpenCode API — HTTP API reference -The gateway exposes seven public endpoints under a single origin. The default +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`) | @@ -14,13 +15,13 @@ listen address is `http://127.0.0.1:20123`. | `GET` | `/v1/models/{id}` | OpenAI Models (also accepts `provider/model` unencoded) | Everything else (`/health`, `/ready`, `/healthz`, `/metrics`, `/admin/*`, `/`) is -operational and documented in the README. +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 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_opencode` | response field | Non-standard object attached to the buffered completion payload of every surface and to the terminal response object of the OpenAI SSE streams: `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`. The Anthropic **streamed** sequence does not carry it (Anthropic's event schema has no place for extra message fields); use `stream: false` when you need it. | | `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. | @@ -68,7 +69,8 @@ when `OPENCODE_METRICS_PUBLIC=true`). | `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. | +| `user`, `metadata`, `service_tier` | — | — | Accepted; not forwarded. `metadata` is carried on the internal request for logging. | +| `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. | | `seed`, `logprobs`, `logit_bias`, `presence_penalty`, `frequency_penalty` | — | — | Accepted and deliberately ignored. | @@ -199,9 +201,10 @@ data: {"error":{"message":"OpenCode did not finish the request in time.","type": | `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` | -| `503` | `api_error` | `overloaded_error`, `upstream_unavailable`, `upstream_unreachable` | -| `504` | `api_error` | `timeout_error` | +| `502` | `api_error` | `upstream_error`, `upstream_unauthorized`, `upstream_invalid_json` | +| `503` | `api_error` | `overloaded_error`, `upstream_unavailable`, `upstream_unreachable`, `event_stream_unavailable` | +| `504` | `api_error` | `timeout_error`, `upstream_timeout` | +| `500` | `api_error` | `internal_error` — an unexpected gateway failure; the message never contains credentials | ### curl @@ -239,7 +242,8 @@ reasoning mapping and tool bridging with the chat endpoint. | `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:`. | | `reasoning.effort` | string | *(unset)* | Same ladder as `reasoning_effort`. `reasoning.summary` is echoed only. | -| `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"`. | +| `max_output_tokens`, `temperature`, `top_p`, `metadata`, `truncation` | — | — | Accepted and echoed back; `truncation` defaults to `"disabled"`. | +| `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)* | 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` | 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". | @@ -307,9 +311,12 @@ with `400 unsupported_file_reference` instead of being silently dropped. } ``` -* `status` is `in_progress`, `completed`, or `incomplete` when the upstream - stopped because of the output-length limit. `incomplete_details` is then - `{"reason":"max_output_tokens"}`. +* `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. * Bridged tool calls are appended as output items in order: @@ -373,11 +380,16 @@ data: {"type":"response.completed","sequence_number":8,"response":{"id":"resp_.. status `completed`. * A length-limited turn ends with `event: response.incomplete` instead of `response.completed`. -* Failures end with `event: error` and a flat error object: +* A failed turn ends with a terminal `event: response.failed` carrying the final + response object with `status: "failed"` and its `error` object. 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":9} + data: {"type":"error","code":"upstream_error","message":"OpenCode reported a failure.","param":null,"sequence_number":10} ``` ### Errors @@ -395,7 +407,84 @@ curl http://127.0.0.1:20123/v1/responses \ -d '{"model":"opencode/deepseek-v4.1-flash-free","instructions":"Be concise.","input":"Say hello."}' ``` -## 3. `POST /v1/messages` +## 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. An array requires an explicit `n: 1` and its elements are joined with newlines into one user message. | +| `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`, `stop` | — | *(unset)* | Accepted and recorded; the OpenCode agent owns the generation budget, so they are not enforced upstream. | +| `user` | string | — | Accepted and ignored (correlation is done with `x-request-id`). | +| `echo` | boolean | `false` | `true` is rejected with `400 unsupported_parameter` (the prompt is rewritten before it reaches the model). | +| `suffix`, `best_of`, `logprobs` | — | — | Not supported; unknown fields are ignored. | + +`x-conversation-id` works exactly as on `/v1/chat/completions`. + +### Response (`stream: false`) + +```json +{ + "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. Errors use the same OpenAI error shape and status table as +`/v1/chat/completions`. + +### curl + +```bash +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. @@ -413,14 +502,14 @@ Anthropic Messages API. | `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 (non-text blocks are noted as omitted). | | `thinking` / `redacted_thinking` blocks | — | — | Accepted for multi-turn replay compatibility and ignored: the gateway cannot store provider-side thinking state. | -| `max_tokens` | number | — | Required (the Anthropic schema requires it). | +| `max_tokens` | number ≥ 1 | — | Required by the Anthropic schema and validated; recorded but not enforced upstream (the OpenCode agent owns the generation budget), so a reply can exceed it. | | `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"}`. (The adapter validates `budget_tokens`; use the top-level `reasoning_effort` for a named effort.) | | `reasoning_effort` | string | *(unset)* | Extension: OpenAI-style alias for `thinking`. Ignored when `thinking` is present. | | `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. | -| `temperature`, `top_p`, `stop_sequences`, `metadata.user_id` | — | *(unset)* | Accepted; `metadata` is carried for logging. | +| `temperature`, `top_p`, `stop_sequences`, `metadata.user_id` | — | *(unset)* | Accepted and recorded; `temperature`/`top_p`/`stop_sequences` are not forwarded to the provider (the OpenCode agent owns sampling), and `metadata` is carried for logging. | | `top_k`, `service_tier`, `container`, `mcp_servers` | — | — | Accepted and ignored. | | `cache_control` | object | — | Accepted on text/image/document/tool blocks and ignored. | @@ -454,9 +543,11 @@ Anthropic Messages API. } ``` -* `stop_reason` is `end_turn`, `max_tokens` (length limit), `tool_use` (tool - calls were offered and produced), `refusal` (content filter) or `null`. - `stop_sequence` is always `null`. +* `stop_reason` in the final payload is `end_turn`, `max_tokens` (length limit), + `tool_use` (tool calls were offered and produced) or `refusal` (content filter); + `message_start` carries `null` because the turn has not finished yet. A matched + `stop_sequences` entry cannot be detected upstream, so `stop_sequence` is always + `null`. * A `thinking` block is emitted only when reasoning was requested and surfaced. Its `signature` is `base64("opencode-api:")` — a deterministic placeholder, not a cryptographic attestation. @@ -478,6 +569,9 @@ data: {"type":"content_block_start","index":0,"content_block":{"type":"thinking" 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} @@ -559,7 +653,7 @@ curl http://127.0.0.1:20123/v1/messages \ }' ``` -## 4. `POST /v1/messages/count_tokens` +## 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 @@ -575,11 +669,12 @@ is still resolved, so an unknown model returns `404`. ``` The number is an **approximation**: OpenCode exposes no tokenizer endpoint, so -the gateway estimates `characters / 4` over every message, the system 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; they contribute a -short placeholder instead. The `x_opencode` object marks the value as an -estimate so callers can decide whether it is accurate enough. +the gateway estimates `characters / 4` over every message, the system prompt, 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; they contribute a short +placeholder instead. The `x_opencode` object marks the value as an estimate so +callers can decide whether it is accurate enough. ### Errors @@ -595,7 +690,7 @@ curl http://127.0.0.1:20123/v1/messages/count_tokens \ -d '{"model":"opencode/deepseek-v4.1-flash-free","messages":[{"role":"user","content":"Count these tokens."}]}' ``` -## 5. `POST /v1/embeddings` +## 6. `POST /v1/embeddings` Always answers `501`, with no model resolution and no upstream call: @@ -623,7 +718,7 @@ curl -i http://127.0.0.1:20123/v1/embeddings \ -d '{"model":"text-embedding-3-small","input":"hello"}' ``` -## 6. `GET /v1/models` +## 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. @@ -682,7 +777,7 @@ curl "http://127.0.0.1:20123/v1/models" -H "Authorization: Bearer $OPENCODE_API_ curl "http://127.0.0.1:20123/v1/models?refresh=true" -H "Authorization: Bearer $OPENCODE_API_KEY" ``` -## 7. `GET /v1/models/{id}` +## 8. `GET /v1/models/{id}` Returns one entry in exactly the same shape as a member of the list. @@ -721,6 +816,7 @@ Unknown ids return `404`: "endpoints": [ "POST /v1/chat/completions", "POST /v1/responses", + "POST /v1/completions", "POST /v1/messages", "POST /v1/messages/count_tokens", "GET /v1/models", @@ -729,11 +825,29 @@ Unknown ids return `404`: "GET /health", "GET /ready", "GET /metrics", - "GET /admin/status" + "GET /admin/status", + "GET /admin/config" ] } ``` +## 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, unless `OPENCODE_METRICS_PUBLIC=true` | Prometheus text exposition (`opencode_api_*`). `404 metrics_disabled` when `OPENCODE_METRICS_ENABLED=false`. | +| `GET` | `/admin/status` | key | Service version, uptime, a config subset, upstream status (URL/pid/last error), catalogue counts and session-cache counts. | +| `GET` | `/admin/config` | key | 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 | Forces a catalogue reload and returns `{refreshedAt, models, providers, agents}`. | +| `GET` | `/admin/sessions` | key | Every cached sticky session: key, session id, model, agent, variant, delivered/reused counts, `busy`, timestamps. | +| `DELETE` | `/admin/sessions` | key | Drops every cached session; returns `{cleared}`. | +| `POST` | `/admin/upstream/restart` | key | Invalidates the endpoint, stops the spawned server if there is one, and resolves a new one; returns `{url, source, pid}`. | + ## JSON output mode OpenCode offers no per-request output-schema control: the client's tools cannot @@ -757,11 +871,13 @@ prose. Validate the reply on the client when it matters. * 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 and Anthropic surfaces defer writing the response head until the first - frame, so pre-flight failures (unknown model, bad body, disabled media) still - 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 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 diff --git a/docs/ARCHITECTURE.md b/docs/ARCHITECTURE.md index bdac69c..abd2425 100644 --- a/docs/ARCHITECTURE.md +++ b/docs/ARCHITECTURE.md @@ -7,12 +7,13 @@ changed without updating all call sites. ## 1. What the gateway does `opencode-api` exposes the AI models that the **OpenCode CLI 2.x** runtime can -reach through three industry-standard HTTP surfaces: +reach through industry-standard HTTP surfaces: | Surface | Endpoints | | --- | --- | | OpenAI chat | `POST /v1/chat/completions` | | OpenAI responses | `POST /v1/responses` | +| OpenAI completions | `POST /v1/completions` (legacy prompt completions) | | OpenAI models | `GET /v1/models`, `GET /v1/models/{id}` | | OpenAI embeddings | `POST /v1/embeddings` (explicitly unsupported → 501) | | Anthropic messages | `POST /v1/messages` | @@ -137,7 +138,12 @@ Event types the gateway consumes: The stream is documented as volatile: a slow consumer overflows and fails it, and events during a disconnect are lost. `EventHub` reconnects with backoff and -notifies subscribers so in-flight completions can reconcile. +notifies subscribers so in-flight completions can reconcile. A half-open socket +never rejects `read()`, so every read is bounded by an idle watchdog (three +documented heartbeats, overridable through `EventHubOptions.idleTimeoutMs` in +tests); expiry fails the connection so the loop reconnects. `stop()` and every +other exit cancel the response body reader, and `#controller` is cleared when a +connection attempt returns. ### 2.5 Free-tier limits @@ -182,6 +188,13 @@ completion work. `InternalRequest`, `Usage`, `FinishReason`, `NativeToolActivity`, `CompletionEvent`. +`InternalRequest.parallelToolCalls?: boolean` (absent/`true` = the model may emit +several bridged calls) was added; the unused `InternalRequest.sticky` flag was +removed; `Surface` gained the `openai.completions` member for the legacy +completions endpoint. `CompletionEvent` `text_end` and `reasoning_end` gained an +optional `messageId` (the upstream assistant message id when known) so streamed +surfaces can use the same identifiers as the buffered aggregate. + ### 4.2 `src/errors.ts` (frozen) ```ts @@ -206,13 +219,23 @@ class OpencodeClient { request(path, options): Promise; listModels(); lis class EventHub { start(); stop(); ensureConnected(timeoutMs); subscribe(sessionId, listener); onReconnect(cb) } class ModelRegistry { catalog(force?); list(); agents(); providers(); find(name); resolve(name); variantsOf(info); supportsInput(info, modality) } -class SessionStore { acquire(input): AcquireResult; commit(key, sessionId, input); release(key, keep?); - invalidate(key, reason); clear(); sweep(); list(); size(); onEvict(handler) } +class SessionStore { acquire(input): AcquireResult; commit(key, sessionId, input); + release(key, sessionId?, keep?); invalidate(key, reason, sessionId?); + clear(); sweep(now?); list(); size(); startSweeper(intervalMs?); stop(); onEvict(handler) } runCompletion(request, deps, options?): AsyncGenerator collectCompletion(request, deps, options?): Promise hashTools(tools): string ``` +`markStale(reason)` always drops the cached endpoint; when it was a spawned child +it also kills and forgets the process, so the next `resolve()` spawns a +replacement instead of retrying a dead URL. Catalogue calls (`listModels`, +`listProviders`, `listAgents`) use a short dedicated timeout +(`OpencodeClientOptions.catalogueTimeoutMs`, default 10 s) rather than the +600 s turn budget. `SessionStore.acquire({ fresh: true })` skips cached +candidates while keeping the conversation key, so a stale-session replay caches +its replacement where the next turn of that conversation will find it. + ### 4.4 `src/adapter/common/*` (frozen) ```ts @@ -222,7 +245,8 @@ supportsReasoning(variants), resolveVariant(input): VariantDecision, reasoningFromEffort(v), reasoningFromThinking(obj) // tools.ts -TOOL_CALL_OPEN, TOOL_CALL_CLOSE, createToolBridge(tools, choice): ToolBridge, +TOOL_CALL_OPEN, TOOL_CALL_CLOSE, +createToolBridge(tools, choice?, options?: { parallelToolCalls?: boolean }): ToolBridge, parseAssistantText(text): {text, calls}, parseToolCallBody(body): ToolCall[], normaliseArguments(args): string, renderTranscript(messages): string, renderToolResult(message): string, class ToolCallFilter @@ -256,7 +280,11 @@ Rules: reject `http(s)` when `config.allowRemoteMediaUrls` is false; reject private/loopback hosts when `config.allowPrivateMediaUrls` is false; reject local paths when `config.allowLocalFiles` is false and when the resolved real path is outside `config.allowedFileRoots`; enforce `config.maxAttachmentBytes` while -streaming the download (do not buffer unbounded). +streaming the download (do not buffer unbounded) and again after reading a local +file (the `stat` size can be stale). When private URLs are blocked the remote +download is dialled with `node:http`/`node:https` and a `lookup` callback pinned +to the validated address, so the guard and the connection cannot disagree (DNS +rebinding); redirects are followed manually with per-hop re-validation. ### 4.6 Surface adapters @@ -269,6 +297,9 @@ export function registerOpenAiChatRoutes(app: FastifyInstance, ctx: AppContext): // src/adapter/openai/responses.ts export function registerOpenAiResponsesRoutes(app: FastifyInstance, ctx: AppContext): void; // POST /v1/responses +// src/adapter/openai/completions.ts +export function registerOpenAiCompletionRoutes(app: FastifyInstance, ctx: AppContext): void; // POST /v1/completions + // src/adapter/openai/models.ts export function registerOpenAiModelRoutes(app: FastifyInstance, ctx: AppContext): void; // GET /v1/models, /v1/models/:id @@ -294,6 +325,9 @@ Shared helpers each adapter may use: * `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` +* `shutdown(deps, app, drainMs?)` from `src/http/shutdown.ts` — bounded drain used + by the SIGINT/SIGTERM handler (`forceCloseConnections: true` on the Fastify + instance is the first line of defence) **Never import `runCompletion` directly.** Always go through `ctx.completion`, so tests can substitute a scripted runner (`test/helpers/context.ts`). @@ -327,7 +361,10 @@ tests can substitute a scripted runner (`test/helpers/context.ts`). * Anthropic: `/v1/messages` accepts `thinking: { type, budget_tokens }` — the documented Anthropic shape — and additionally tolerates a non-standard `thinking.effort` / top-level `reasoning_effort` as a convenience. Reasoning - becomes a `thinking` content block with a deterministic `signature`. + becomes a `thinking` content block with a deterministic `signature`; the + streamed form emits the same signature as `signature_delta` before the block + stops, using the upstream assistant message id carried by `reasoning_end` / + `text_end`, so streamed and buffered signatures agree. * When a request declares client `tools`, the created session is given `deny` permission rules for OpenCode's built-in actions (`bash`, `webfetch`, `websearch`, `edit`, `write`, `patch`, `task`, `skill`), merged on top of @@ -359,3 +396,19 @@ tests can substitute a scripted runner (`test/helpers/context.ts`). * 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. +* `POST /v1/completions` maps a legacy `prompt` (a string, or a single-element + array with `n: 1`) onto one user turn and re-frames the same normalised events + as `text_completion` objects or `text_completion` SSE chunks; `echo: true` is + rejected with `400 unsupported_parameter` because the prompt is not replayed + verbatim by the agent. +* `parallel_tool_calls: false` on the OpenAI surfaces reaches the tool bridge and + caps the model at one bridged call per turn; the default wording is unchanged. +* `/v1/responses` reports `status: "failed"` with an `error` object when the turn + ends with `finishReason: "error"`, and the streamed form emits a terminal + `response.failed` event (the `event: error` frame is kept for compatibility). +* `/ready` is public and therefore reads **cached** state only; it answers `503` + until an upstream endpoint is resolved and a model catalogue has been loaded. + Forcing a refresh happens through `POST /admin/models/refresh`, which is + authenticated. +* `GET /admin/config` returns the effective configuration with the API keys and + the upstream password redacted (`apiKeyCount`, `passwordConfigured`). diff --git a/docs/CONFIGURATION.md b/docs/CONFIGURATION.md index 6d81df5..7d5089b 100644 --- a/docs/CONFIGURATION.md +++ b/docs/CONFIGURATION.md @@ -1,8 +1,10 @@ # OpenCode API — configuration reference Every setting is read from the process environment at startup. The gateway also -loads a `.env` file from the current working directory (`dotenv`); values already -present in the real environment win. +loads `.env` files with `dotenv`: the project root first, then the current working +directory. Variables already present in the real environment win, and because +`dotenv` never overrides, a root `.env` wins over a `.env` in the directory you +started from. An empty value is treated as "not set": `OPENCODE_AGENT=""` behaves exactly like an unset `OPENCODE_AGENT`. List variables are comma separated, with surrounding @@ -11,7 +13,9 @@ whitespace trimmed and empty entries dropped. Paths starting with `~` are expanded to the home directory and then resolved against the current working directory. -This table is derived from `src/config.ts`; no other variable is read. +This table is derived from `src/config.ts`; `src/config.ts` reads no other +variable. (Discovery and the spawned CLI read the variables listed in +"Environment variables read by other libraries".) ## HTTP server @@ -27,7 +31,7 @@ This table is derived from `src/config.ts`; no other variable is read. | Variable | Type | Default | Description | Security implication | | --- | --- | --- | --- | --- | -| `OPENCODE_API_KEYS` | CSV list | `sk-dummy-123` | Keys accepted from callers. When unset, the built-in development key `sk-dummy-123` is used and a warning is logged at startup. | The default key is public knowledge (it ships in `.env.example` and the README). Set your own secret before exposing the port; rotate by listing old and new keys together. | +| `OPENCODE_API_KEYS` | CSV list | `sk-dummy-123` | Keys accepted from callers. When unset, the built-in development key `sk-dummy-123` is used and a warning is logged at startup. When set but empty (`OPENCODE_API_KEYS=","`) the gateway refuses to start instead of silently accepting the public default. | The default key is public knowledge (it ships in `.env.example` and the README). Set your own secret before exposing the port; rotate by listing old and new keys together. | | `OPENCODE_API_KEY` | string | *(unset)* | Single-key alias appended to `OPENCODE_API_KEYS`. | Same as above; convenient for local use only. | | `OPENCODE_ALLOW_NO_AUTH` | boolean | `false` | Accept every caller, ignoring keys. | Full unauthenticated access to every model and to the OpenCode agent. Use only on a trusted loopback host. | | `OPENCODE_METRICS_PUBLIC` | boolean | `false` | Exempt `GET /metrics` from authentication. | Metrics expose model names, route traffic and token volumes. | @@ -62,7 +66,7 @@ existing custom key. | `OPENCODE_WORKDIR` | path | `/workspace` | Directory handed to OpenCode as the session location. | The agent runs with its tools inside this directory. Point it at a scratch directory, never at a source tree or your home directory. | | `OPENCODE_AGENT` | string | `build` | OpenCode agent used for API-driven turns. | `build` can edit files and run commands in `OPENCODE_WORKDIR`. Choose a read-only agent for untrusted callers. | | `OPENCODE_AGENT_MAX_STEPS` | integer > 0 | *(unset)* | Maximum agent steps per turn. | A cap limits how much work (and cost) one request can trigger. | -| `OPENCODE_AGENT_PERMISSIONS` | JSON array | *(unset)* | Permission rules `[{action, resource, effect}]` applied to every API session. | A rule of `{"action":"*","resource":"*","effect":"allow"}` grants the agent unrestricted tool access. Deny rules are the safer default. Must be valid JSON or the gateway refuses to start. | +| `OPENCODE_AGENT_PERMISSIONS` | JSON array | *(unset)* | Permission rules `[{action, resource, effect}]` applied to every API session. A rule without `effect` defaults to `ask`. | A rule of `{"action":"*","resource":"*","effect":"allow"}` grants the agent unrestricted tool access. Deny rules are the safer default. Must be a JSON array of objects or the gateway refuses to start. | ## Gateway state, sticky sessions and models @@ -74,7 +78,7 @@ existing custom key. | `OPENCODE_SESSION_MAX` | integer ≥ 1 | `500` | Maximum cached sessions (least recently used are evicted). | — | | `OPENCODE_SESSION_PERSIST` | boolean | `false` | Persist the session cache to `/sessions.json`. | The file records session ids and message prefixes; keep the data directory private. | | `OPENCODE_MODEL_CACHE_TTL_MS` | integer ≥ 1000 | `300000` (5 min) | Model catalog cache lifetime. | — | -| `OPENCODE_MODEL_ALIASES` | JSON object | *(unset)* | Alias map applied before resolution, e.g. `{"gpt-4o":"opencode/big-pickle"}`. | Aliases can silently redirect a familiar name to another provider model. Must be valid JSON or the gateway refuses to start. | +| `OPENCODE_MODEL_ALIASES` | JSON object | *(unset)* | Alias map applied before resolution, e.g. `{"gpt-4o":"opencode/big-pickle"}`. | Aliases can silently redirect a familiar name to another provider model. Must be a JSON object of string values or the gateway refuses to start. | ## Media and vision input @@ -109,26 +113,34 @@ uploads are always inlined for OpenCode as a `data:` URI. See the README section Boolean values accept `1/true/yes/on/enabled` and `0/false/no/off/disabled` (case-insensitive). Any other value falls back to the default. +Integer values must be a whole number: the entire value is parsed, so +`OPENCODE_REQUEST_TIMEOUT_MS=10m` is **not** read as 10 seconds — it is treated as +unrecognised, the default is kept and a warning naming the variable is logged. +Out-of-range integers are clamped to the documented bounds. + ## Environment variables read by other libraries -`dotenv` loads `.env` in the working directory. The upstream launcher inherits the -gateway's full environment (so the OpenCode CLI sees its own provider -credentials), and the CLI discovery code reads `PATH`, `APPDATA`, -`LOCALAPPDATA`, `PNPM_HOME`, `NVM_BIN`, `VOLTA_HOME`, `XDG_STATE_HOME` and -`XDG_CONFIG_HOME` when searching for the executable and a background server -descriptor. +`dotenv` loads `.env` from the project root and then the working directory. The +upstream launcher inherits the gateway's full environment (so the OpenCode CLI +sees its own provider credentials), and the CLI discovery code reads `PATH`, +`APPDATA`, `LOCALAPPDATA`, `PNPM_HOME`, `NVM_BIN`, `VOLTA_HOME`, +`XDG_STATE_HOME` and `XDG_CONFIG_HOME` when searching for the executable and a +background server descriptor. ## Startup validation The gateway exits with code 1 (before it listens) when: -1. `OPENCODE_AGENT_PERMISSIONS` is set but is not a JSON array; -2. `OPENCODE_MODEL_ALIASES` is set but is not a JSON object. +1. `OPENCODE_AGENT_PERMISSIONS` is set but is not a JSON array of objects; +2. `OPENCODE_MODEL_ALIASES` is set but is not a JSON object of string values; +3. `OPENCODE_API_KEYS` / `OPENCODE_API_KEY` is set but yields no usable key + (`OPENCODE_API_KEYS=","`), because silently falling back to the published + default key would leave the operator believing a secret is configured. A missing key is **not** fatal: with neither `OPENCODE_API_KEYS` nor `OPENCODE_API_KEY` set, the gateway starts with the built-in development key `sk-dummy-123` and logs a warning. Every variable is otherwise clamped to its -documented bounds, and an unrecognised boolean/value falls back to the default. +documented bounds, and an unrecognised boolean/integer falls back to the default. ## Recommended hardening for a reachable deployment diff --git a/docs/VERIFICATION.md b/docs/VERIFICATION.md index 71644fd..7ba474c 100644 --- a/docs/VERIFICATION.md +++ b/docs/VERIFICATION.md @@ -2,7 +2,7 @@ * **Date of audit:** 2026-12-02 (Asia/Saigon, UTC+07:00) * **Auditor:** independent adversarial verifier (did not write the code) -* **Version audited:** `opencode-api` 0.1.0 (`package.json`), working tree as of 16:05 local time +* **Version audited:** `opencode-api` 0.1.0 (`package.json` at audit time; the released package is `1.0.0`), working tree as of 16:05 local time * **Repository state:** the audit ran **before** the repository was initialised with `git init`, so it is pinned to file mtimes plus SHA-256 prefixes of the audited tree rather than to a commit. Those hashes are the pre-remediation state. @@ -84,7 +84,12 @@ FAIL POST /v1/chat/completions (non-streaming) | `POST /v1/messages` (real model) | `429` + `retry-after: 57507` | OK (expected quota) | | `POST /v1/responses` (real model) | `429` + `retry-after: 57507` | OK (expected quota) | | Same three, `stream: true` | `200 text/event-stream` + in-stream error frame, **no `retry-after`** | see F-13 | -| `GET /` (no key) | `401` | mismatch, F-10 | +| `GET /` (no key) | `401` | mismatch at audit time, F-10 — fixed afterwards (see the appendix) | + +> **The findings below are the pre-remediation record.** They describe the tree as +> it was at 16:05. The remediation log in the appendix lists what was fixed and +> which regression test now covers it; do not read an unannotated row as an open +> defect. The three surfaces are **consistent** in both modes: non-streaming 429 with `retry-after`, streaming 200 + `error` frame (status is already committed by the first frame). No defect there beyond the diff --git a/src/adapter/anthropic/countTokens.ts b/src/adapter/anthropic/countTokens.ts index ddb2d60..b25756e 100644 --- a/src/adapter/anthropic/countTokens.ts +++ b/src/adapter/anthropic/countTokens.ts @@ -17,6 +17,7 @@ import type { FastifyInstance } from "fastify"; import type { AppContext } from "../../context.js"; import type { InternalRequest } from "../../types/internal.js"; +import { createToolBridge } from "../common/tools.js"; import { estimateConversationTokens, estimateTokens } from "../common/usage.js"; import { parseAnthropicCountTokensBody, @@ -32,7 +33,8 @@ const TOOL_OVERHEAD_TOKENS = 4; * * The conversation contributes one part per message (with the per-part overhead * built into `estimateConversationTokens`), then every tool declaration - * contributes its name, description and JSON Schema. + * contributes its name, description and JSON Schema, plus the tool-bridge + * instructions that `buildPrompt` prepends for the real turn. */ export function estimateRequestTokens(request: InternalRequest): number { const parts: string[] = []; @@ -52,9 +54,10 @@ export function estimateRequestTokens(request: InternalRequest): number { TOOL_OVERHEAD_TOKENS, 0, ); + const bridgeTokens = estimateTokens(createToolBridge(request.tools, request.toolChoice).instructions); // Counts are documented as "at least one token", never zero. - return Math.max(1, conversationTokens + toolTokens); + return Math.max(1, conversationTokens + toolTokens + bridgeTokens); } export function registerAnthropicCountTokenRoutes(app: FastifyInstance, ctx: AppContext): void { diff --git a/src/adapter/anthropic/messages.ts b/src/adapter/anthropic/messages.ts index 4e88f85..6a4d63c 100644 --- a/src/adapter/anthropic/messages.ts +++ b/src/adapter/anthropic/messages.ts @@ -420,6 +420,16 @@ export async function toInternalRequest( const toolCalls: ToolCall[] = []; const toolResults: InternalMessage[] = []; + // Media resolution is the only asynchronous part of a message. The blocks are + // independent, so resolve them concurrently and re-assemble the results in + // declaration order; the attachment caps still bound the work. + const mediaBlocks = message.content.filter( + (block): block is MediaBlock => + block.type === "image" || block.type === "document" || block.type === "audio" || block.type === "video", + ); + const resolvedMedia = await Promise.all(mediaBlocks.map((block) => resolveMediaBlock(block, options))); + let mediaCursor = 0; + for (const block of message.content) { switch (block.type) { case "text": { @@ -435,7 +445,10 @@ export async function toInternalRequest( case "document": case "audio": case "video": { - const resolved = await resolveMediaBlock(block, options); + const resolved = resolvedMedia[mediaCursor]; + mediaCursor += 1; + // Unreachable: `resolvedMedia` has one entry per media block. + if (resolved === undefined) break; if (typeof resolved === "string") textParts.push(resolved); else attachments.push(resolved); break; @@ -546,10 +559,22 @@ function thinkingSignature(id: string): string { return Buffer.from(`opencode-api:${id}`).toString("base64"); } +/** + * Subject of the gateway thinking signature. + * + * The upstream assistant message id is preferred so the streamed and buffered + * paths agree for the same turn; the gateway message id is the fallback when the + * upstream did not report one. + */ +function thinkingSignatureSubject(assistantMessageId: string, messageId: string): string { + return assistantMessageId.length > 0 ? assistantMessageId : messageId; +} + function usagePayload(usage: Usage): AnthropicUsagePayload { return { input_tokens: usage.inputTokens, - output_tokens: usage.outputTokens, + // Anthropic counts thinking tokens inside `output_tokens`. + output_tokens: usage.outputTokens + usage.reasoningTokens, cache_creation_input_tokens: usage.cacheWriteTokens, cache_read_input_tokens: usage.cacheReadTokens, }; @@ -599,7 +624,11 @@ export function renderAnthropicMessage( const content: AnthropicContentBlock[] = []; if (collected.reasoning.length > 0 && reasoningRequested(request, collected.reasoningEnabled)) { - content.push({ type: "thinking", thinking: collected.reasoning, signature: thinkingSignature(id) }); + content.push({ + type: "thinking", + thinking: collected.reasoning, + signature: thinkingSignature(thinkingSignatureSubject(collected.messageId, id)), + }); } if (collected.text.length > 0) { content.push({ type: "text", text: collected.text }); @@ -656,6 +685,7 @@ async function streamAnthropicMessage( try { const id = newMessageId(); let model = request.model; + let assistantMessageId = ""; let index = 0; let openIndex = -1; let openKind: "thinking" | "text" | null = null; @@ -690,6 +720,19 @@ async function streamAnthropicMessage( const closeOpen = (): void => { if (openKind === null) return; + if (openKind === "thinking") { + send( + { + type: "content_block_delta", + index: openIndex, + delta: { + type: "signature_delta", + signature: thinkingSignature(thinkingSignatureSubject(assistantMessageId, id)), + }, + }, + "content_block_delta", + ); + } send({ type: "content_block_stop", index: openIndex }, "content_block_stop"); openKind = null; openIndex = -1; @@ -702,6 +745,7 @@ async function streamAnthropicMessage( switch (event.kind) { case "start": { model = event.model.length > 0 ? event.model : model; + assistantMessageId = event.messageId; reasoningEnabled = reasoningEnabled || event.reasoningEnabled; send( { @@ -734,7 +778,13 @@ async function streamAnthropicMessage( break; } case "reasoning_end": { - if (openKind === "thinking") closeOpen(); + // Step-scoped: a step ending does not end the turn, so the thinking + // block stays open until another kind starts or the turn ends. It + // carries the upstream assistant id when it is known, so adopt it + // before a later block change closes the thinking block. + if (event.messageId !== undefined && event.messageId.length > 0) { + assistantMessageId = event.messageId; + } break; } case "text_delta": { @@ -749,7 +799,13 @@ async function streamAnthropicMessage( break; } case "text_end": { - if (openKind === "text") closeOpen(); + // Step-scoped: a step ending does not end the turn, so the text block + // stays open until another kind starts or the turn ends. Adopt the + // upstream assistant id as soon as the event reports it, so the + // thinking signature subject matches the buffered path. + if (event.messageId !== undefined && event.messageId.length > 0) { + assistantMessageId = event.messageId; + } break; } case "tool_calls": { @@ -763,6 +819,9 @@ async function streamAnthropicMessage( case "end": { finishReason = event.finishReason; usage = event.usage; + // A turn that surfaced no upstream id in `start` may report it here; + // keep the thinking signature subject aligned with the buffered path. + if (event.messageId.length > 0) assistantMessageId = event.messageId; break; } case "error": { @@ -802,7 +861,7 @@ async function streamAnthropicMessage( { type: "content_block_delta", index: blockIndex, - delta: { type: "input_json_delta", partial_json: call.arguments }, + delta: { type: "input_json_delta", partial_json: JSON.stringify(parseToolInput(call.arguments)) }, }, "content_block_delta", ); @@ -817,7 +876,8 @@ async function streamAnthropicMessage( stop_sequence: null, }, usage: { - output_tokens: usage.outputTokens, + // Anthropic counts thinking tokens inside `output_tokens`. + output_tokens: usage.outputTokens + usage.reasoningTokens, input_tokens: usage.inputTokens, cache_read_input_tokens: usage.cacheReadTokens, cache_creation_input_tokens: usage.cacheWriteTokens, diff --git a/src/adapter/common/reasoning.ts b/src/adapter/common/reasoning.ts index b0188a4..bef6c32 100644 --- a/src/adapter/common/reasoning.ts +++ b/src/adapter/common/reasoning.ts @@ -95,12 +95,27 @@ export function budgetFromEffort(effort: Effort): number { } } +/** + * The variants that can actually satisfy a reasoning request. + * + * `default` is not an effort, and an explicit `none` variant means "thinking + * disabled" — selecting it while reporting `reasoningEnabled: true` would be a + * contradiction, so `none` is excluded from the ladder entirely. + */ +function reasoningVariants(available: string[]): Array<{ variant: string; effort: Effort }> { + const ladder: Array<{ variant: string; effort: Effort }> = []; + for (const variant of available) { + if (variant === DEFAULT_VARIANT) continue; + const effort = normaliseEffort(variant); + if (effort === undefined || effort === "none") continue; + ladder.push({ variant, effort }); + } + return ladder; +} + /** Pick the closest variant a model actually offers. */ function nearestVariant(available: string[], effort: Effort): string | undefined { - const ladder = available - .filter((variant) => variant !== DEFAULT_VARIANT) - .map((variant) => ({ variant, effort: normaliseEffort(variant) })) - .filter((entry): entry is { variant: string; effort: Effort } => entry.effort !== undefined); + const ladder = reasoningVariants(available); if (ladder.length === 0) return undefined; const targetIndex = EFFORT_ORDER.indexOf(effort); @@ -123,7 +138,7 @@ function nearestVariant(available: string[], effort: Effort): string | undefined /** True when the model exposes at least one real thinking-effort variant. */ export function supportsReasoning(available: string[]): boolean { - return available.some((variant) => variant !== DEFAULT_VARIANT && normaliseEffort(variant) !== undefined); + return reasoningVariants(available).length > 0; } /** diff --git a/src/adapter/common/tools.ts b/src/adapter/common/tools.ts index 3151047..5d2f0e6 100644 --- a/src/adapter/common/tools.ts +++ b/src/adapter/common/tools.ts @@ -21,6 +21,11 @@ export const TOOL_CALL_CLOSE = "[[/OPENCODE_TOOL_CALL]]"; export type ToolChoice = "auto" | "none" | "required" | { name: string }; +export interface ToolBridgeOptions { + /** When `false`, the prompt asks the model for at most one tool call block. */ + parallelToolCalls?: boolean; +} + export interface ToolBridge { /** Prompt fragment describing the available tools and the required protocol. */ instructions: string; @@ -68,7 +73,11 @@ function choiceInstruction(tools: ToolDefinition[], choice: ToolChoice | undefin * Build the prompt fragment that teaches the model the tool protocol. * Returns an inactive bridge when there is nothing to bridge. */ -export function createToolBridge(tools: ToolDefinition[], choice?: ToolChoice): ToolBridge { +export function createToolBridge( + tools: ToolDefinition[], + choice?: ToolChoice, + options: ToolBridgeOptions = {}, +): ToolBridge { const active = tools.length > 0 && choice !== "none"; const instructions = active @@ -92,6 +101,12 @@ export function createToolBridge(tools: ToolDefinition[], choice?: ToolChoice): "", "`arguments` must validate against the tool's JSON Schema. Never wrap the block in a code", "fence, never add commentary inside the block, and never mention the block markers in prose.", + ...(options.parallelToolCalls === false + ? [ + "", + "The caller does not support parallel tool calls: emit at most one tool call block per turn.", + ] + : []), "", "## Available tools", "", @@ -203,29 +218,18 @@ export function parseToolCallBody(body: string): ToolCall[] { .trim(); if (cleaned === "") return []; - let parsed: unknown; - try { - parsed = JSON.parse(cleaned); - } catch { - // The model may have emitted a trailing comma or an unquoted key; try a - // light repair before giving up. - const repaired = cleaned.replace(/,\s*([}\]])/g, "$1"); - try { - parsed = JSON.parse(repaired); - } catch { - return []; - } - } - const results: ToolCall[] = []; const pushCall = (name: unknown, args: unknown): void => { if (typeof name !== "string" || name.trim() === "") return; results.push({ id: `call_${randomUUID().replace(/-/g, "").slice(0, 24)}`, name: name.trim(), arguments: normaliseArguments(args) }); }; - if (Array.isArray(parsed)) { - for (const entry of parsed) collectFromObject(entry, pushCall); - } else if (typeof parsed === "object" && parsed !== null) { + const collectParsed = (parsed: unknown): void => { + if (Array.isArray(parsed)) { + for (const entry of parsed) collectFromObject(entry, pushCall); + return; + } + if (typeof parsed !== "object" || parsed === null) return; const record = parsed as Record; const nested = record["tool_calls"] ?? record["calls"] ?? record["toolCalls"]; if (Array.isArray(nested)) { @@ -243,11 +247,85 @@ export function parseToolCallBody(body: string): ToolCall[] { pushCall(name, args); } } + }; + + const whole = parseJsonValue(cleaned); + if (whole) { + collectParsed(whole.value); + return results; } + // The model may have emitted several adjacent top-level JSON values inside one + // envelope (one per call). Parse each complete value instead of leaking the + // markers into the assistant text. + for (const value of scanTopLevelJsonValues(cleaned)) collectParsed(value); return results; } +/** Parse one JSON value, retrying after the light trailing-comma repair. */ +function parseJsonValue(text: string): { value: unknown } | undefined { + try { + return { value: JSON.parse(text) }; + } catch { + // The model may have emitted a trailing comma or an unquoted key; try a + // light repair before giving up. + const repaired = text.replace(/,\s*([}\]])/g, "$1"); + try { + return { value: JSON.parse(repaired) }; + } catch { + return undefined; + } + } +} + +/** + * Extract every complete top-level JSON object/array from `text`. + * + * String literals are skipped so a brace inside a string cannot desynchronise + * the depth counter. Values that do not parse are ignored. + */ +function scanTopLevelJsonValues(text: string): unknown[] { + const values: unknown[] = []; + let depth = 0; + let start = -1; + let inString = false; + let escaped = false; + + for (let index = 0; index < text.length; index += 1) { + const char = text[index]; + if (inString) { + if (escaped) escaped = false; + else if (char === "\\") escaped = true; + else if (char === '"') inString = false; + continue; + } + if (char === '"') { + inString = true; + continue; + } + if (char === "{" || char === "[") { + if (depth === 0) { + start = index; + depth = 1; + } else { + depth += 1; + } + continue; + } + if (char === "}" || char === "]") { + if (depth === 0) continue; + depth -= 1; + if (depth === 0 && start !== -1) { + const parsed = parseJsonValue(text.slice(start, index + 1)); + if (parsed) values.push(parsed.value); + start = -1; + } + } + } + + return values; +} + /** Keys that describe arguments rather than name a tool in the map shorthand. */ const RESERVED_ARGUMENT_KEYS = new Set([ "arguments", diff --git a/src/adapter/openai/chat.ts b/src/adapter/openai/chat.ts index 6171aec..2982b5a 100644 --- a/src/adapter/openai/chat.ts +++ b/src/adapter/openai/chat.ts @@ -157,15 +157,93 @@ const chatRequestSchema = z.object({ type ChatRequest = z.infer; type ChatMessage = z.infer; +type ChatContentPart = z.infer; type ChatFile = z.infer["file"]; +/** + * Optional top-level request fields that OpenAI SDKs commonly serialise as an + * explicit `null` when the caller did not set them. + * + * OpenAI treats such a value as "unset", so they are dropped before validation + * instead of being rejected with a 400 (see `normaliseNullFields`). + * `messages[].content` is deliberately absent: it is already `.nullish()` and a + * `null` content keeps its meaning (an assistant turn with only tool calls). + */ +const NULLABLE_TOP_LEVEL_FIELDS: ReadonlySet = new Set([ + "stream", + "stream_options", + "temperature", + "top_p", + "max_tokens", + "max_completion_tokens", + "stop", + "n", + "reasoning_effort", + "reasoning", + "user", + "metadata", + "service_tier", + "parallel_tool_calls", + "seed", + "logprobs", + "logit_bias", + "presence_penalty", + "frequency_penalty", + "response_format", + "tools", + "tool_choice", +]); + +/** + * Drop explicit `null` values for the optional top-level request fields. + * + * Known-but-null fields become absent; every other key (including unknown ones) + * is passed through untouched, so nothing else about validation changes. The + * original object is returned when there is nothing to strip. + */ +export function normaliseNullFields(body: unknown): unknown { + if (!isRecord(body)) return body; + let changed = false; + const normalised: Record = {}; + for (const [key, value] of Object.entries(body)) { + if (value === null && NULLABLE_TOP_LEVEL_FIELDS.has(key)) { + changed = true; + continue; + } + normalised[key] = value; + } + return changed ? normalised : body; +} + +/** Validate a chat-completions body, treating `null` optionals as absent. */ +function parseChatRequest(body: unknown): ChatRequest { + const parsed = chatRequestSchema.safeParse(normaliseNullFields(body)); + if (!parsed.success) throw invalidRequestFromZod(parsed.error); + return parsed.data; +} + +/** `docs/API.md` requires a non-empty `tool_call_id` on every `role: "tool"` message. */ +function assertToolCallIds(messages: ChatMessage[]): void { + const invalid = messages.some((message) => message.role === "tool" && !hasText(message.tool_call_id)); + if (invalid) { + throw ApiError.badRequest('Every `role: "tool"` message must carry a non-empty `tool_call_id`.', { + code: "invalid_request", + param: "messages", + }); + } +} + +/** True when an optional string field carries a non-empty value. */ +function hasText(value: string | undefined): boolean { + return value !== undefined && value.length > 0; +} + // ----------------------------------------------------------------- routes --- export function registerOpenAiChatRoutes(app: FastifyInstance, ctx: AppContext): void { app.post("/v1/chat/completions", async (request, reply) => { - const parsed = chatRequestSchema.safeParse(request.body); - if (!parsed.success) throw invalidRequestFromZod(parsed.error); - const body = parsed.data; + const body = parseChatRequest(request.body); + assertToolCallIds(body.messages); if (body.n !== undefined && body.n !== 1) { throw ApiError.badRequest("Only `n: 1` is supported by this gateway.", { @@ -242,6 +320,8 @@ async function buildRequest( const stop = normaliseStop(body.stop); if (stop !== undefined && stop.length > 0) internal.stop = stop; + if (body.parallel_tool_calls !== undefined) internal.parallelToolCalls = body.parallel_tool_calls; + const conversationKey = headerValue(request, "x-conversation-id"); if (conversationKey !== undefined) internal.conversationKey = conversationKey; @@ -255,43 +335,25 @@ async function buildRequest( async function toInternalMessage(message: ChatMessage, config: Config, signal: AbortSignal): Promise { const texts: string[] = []; - const attachments: Attachment[] = []; + const pending: Array> = []; if (typeof message.content === "string") { texts.push(message.content); } else if (Array.isArray(message.content)) { for (const part of message.content) { - switch (part.type) { - case "text": - texts.push(part.text); - break; - case "image_url": - attachments.push(await resolveAttachment(mediaUrlSource(part.image_url.url), config, { signal })); - break; - case "video_url": - attachments.push(await resolveAttachment(mediaUrlSource(part.video_url.url), config, { signal })); - break; - case "input_audio": - attachments.push( - await resolveAttachment( - { base64: part.input_audio.data, mime: audioMime(part.input_audio.format) }, - config, - { signal }, - ), - ); - break; - case "file": - attachments.push(await resolveAttachment(fileSource(part.file), config, { signal })); - break; - case "document": - attachments.push(await resolveAttachment(documentSource(part.document), config, { signal })); - break; - default: - break; + if (part.type === "text") { + texts.push(part.text); + continue; } + const source = mediaSourceOf(part); + if (source !== undefined) pending.push(resolveAttachment(source, config, { signal })); } } + // Media parts are independent: resolve them concurrently and keep the + // declaration order, so N remote attachments cost max(latency), not the sum. + const attachments = pending.length > 0 ? await Promise.all(pending) : []; + const internal: InternalMessage = { role: message.role, text: texts.filter((text) => text.length > 0).join("\n"), @@ -312,6 +374,24 @@ async function toInternalMessage(message: ChatMessage, config: Config, signal: A return internal; } +/** The media source a non-text content part carries, if any. */ +function mediaSourceOf(part: Exclude>): MediaSource | undefined { + switch (part.type) { + case "image_url": + return mediaUrlSource(part.image_url.url); + case "video_url": + return mediaUrlSource(part.video_url.url); + case "input_audio": + return { base64: part.input_audio.data, mime: audioMime(part.input_audio.format) }; + case "file": + return fileSource(part.file); + case "document": + return documentSource(part.document); + default: + return undefined; + } +} + function toToolCalls(calls: ChatMessage["tool_calls"]): ToolCall[] { if (!calls) return []; return calls.map((call) => ({ @@ -469,8 +549,11 @@ function messagePayload(collected: CollectedCompletion, field: ReasoningField): return message; } -/** Native OpenCode activity, exposed as a non-standard extension object. */ -function openCodeExtension(collected: CollectedCompletion): Record { +/** + * Native OpenCode activity, exposed as a non-standard extension object. + * Shared with the legacy completions surface (`completions.ts`). + */ +export function openCodeExtension(collected: CollectedCompletion): Record { return { session_id: collected.sessionId, agent: collected.agent, @@ -481,13 +564,23 @@ function openCodeExtension(collected: CollectedCompletion): Record { - const total = - usage.totalTokens > 0 ? usage.totalTokens : usage.inputTokens + usage.outputTokens + usage.reasoningTokens; +/** + * Map the internal usage onto OpenAI's shape. + * + * OpenAI counts thinking tokens inside `completion_tokens` (they are the + * `reasoning_tokens` subset), so `completion = output + reasoning` and + * `total = prompt + completion` always holds; `usage.totalTokens` is ignored + * because it is the same sum and cannot disagree. + * + * Shared with the legacy completions surface (`completions.ts`). + */ +export function openAiUsage(usage: Usage): Record { + const prompt = usage.inputTokens; + const completion = usage.outputTokens + usage.reasoningTokens; return { - prompt_tokens: usage.inputTokens, - completion_tokens: usage.outputTokens, - total_tokens: total, + prompt_tokens: prompt, + completion_tokens: completion, + total_tokens: prompt + completion, completion_tokens_details: { reasoning_tokens: usage.reasoningTokens }, prompt_tokens_details: { cached_tokens: usage.cacheReadTokens }, }; @@ -623,7 +716,8 @@ function streamToolCall(call: ToolCall, index: number): Record // ------------------------------------------------------------------ helpers --- -function mapFinishReason(reason: FinishReason): string { +/** Map the internal finish reason onto the OpenAI wire value; shared with `completions.ts`. */ +export function mapFinishReason(reason: FinishReason): string { switch (reason) { case "length": return "length"; @@ -678,7 +772,8 @@ function normaliseStop(stop: string | string[] | undefined): string[] | undefine return stop.filter((entry) => entry.length > 0); } -function headerValue(request: FastifyRequest, name: string): string | undefined { +/** Read a non-empty, trimmed request header. Shared with the legacy surface. */ +export function headerValue(request: FastifyRequest, name: string): string | undefined { const raw = request.headers[name]; if (typeof raw === "string") { const trimmed = raw.trim(); diff --git a/src/adapter/openai/completions.ts b/src/adapter/openai/completions.ts new file mode 100644 index 0000000..85aad75 --- /dev/null +++ b/src/adapter/openai/completions.ts @@ -0,0 +1,292 @@ +/** + * OpenAI-compatible legacy completions surface (`POST /v1/completions`). + * + * The endpoint predates chat completions: the caller sends a raw `prompt` + * (string or an array of strings) and receives `text_completion` objects or an + * SSE stream of `text_completion` chunks. Everything is normalised into a + * single user turn and served by `ctx.completion`, exactly like the chat + * surface; this module only translates wire formats. + * + * Only one completion per request is supported (`n` must be `1`), and `echo` + * is rejected because the upstream prompt is rewritten before it reaches the + * model. + */ +import { randomUUID } from "node:crypto"; +import type { FastifyInstance, FastifyReply } from "fastify"; +import { z } from "zod"; +import { completionDeps, type AppContext } from "../../context.js"; +import { ApiError, toApiError, toOpenAiError } from "../../errors.js"; +import { createDisconnectSignal } from "../../http/disconnect.js"; +import { SseWriter } from "../../http/sse.js"; +import { + EMPTY_USAGE, + type FinishReason, + type InternalMessage, + type InternalRequest, + type Usage, +} from "../../types/internal.js"; +import type { CollectedCompletion } from "../../upstream/completion.js"; +import type { ResolvedModel } from "../../upstream/models.js"; +import { + headerValue, + mapFinishReason, + normaliseNullFields, + openAiUsage, + openCodeExtension, +} from "./chat.js"; + +/** Metric label for this surface. */ +const SURFACE = "openai.completions"; + +// --------------------------------------------------------------- validation --- + +const completionRequestSchema = z.object({ + model: z.string().min(1), + prompt: z.union([z.string(), z.array(z.string())]), + // Only `1` is supported; an array `prompt` therefore maps to one user turn. + n: z.number().optional(), + stream: z.boolean().optional(), + stream_options: z.object({ include_usage: z.boolean().optional() }).optional(), + max_tokens: z.number().optional(), + temperature: z.number().optional(), + stop: z.union([z.string(), z.array(z.string())]).optional(), + user: z.string().optional(), + // Accepted for API compatibility and deliberately unsupported. + echo: z.boolean().optional(), +}); + +type CompletionRequest = z.infer; + +/** Validate a legacy-completions body, treating `null` optionals as absent. */ +function parseCompletionRequest(body: unknown): CompletionRequest { + const parsed = completionRequestSchema.safeParse(normaliseNullFields(body)); + if (!parsed.success) throw invalidRequestFromZod(parsed.error); + return parsed.data; +} + +// ----------------------------------------------------------------- routes --- + +export function registerOpenAiCompletionRoutes(app: FastifyInstance, ctx: AppContext): void { + app.post("/v1/completions", async (request, reply) => { + const body = parseCompletionRequest(request.body); + + if (body.echo === true) { + throw ApiError.badRequest("`echo` is not supported by this gateway.", { + code: "unsupported_parameter", + param: "echo", + }); + } + + if (body.n !== undefined && body.n !== 1) { + throw ApiError.badRequest("Only `n: 1` is supported by this gateway.", { + code: "invalid_request", + param: "n", + }); + } + + // An array `prompt` is only supported for a single completion. + if (Array.isArray(body.prompt) && body.n !== 1) { + throw ApiError.badRequest("An array `prompt` requires `n: 1`.", { + code: "invalid_request", + param: "prompt", + }); + } + + // Resolve before running so an unknown/disabled model fails with an HTTP + // status even when the completion runner would only report it mid-stream. + const resolved = await ctx.models.resolve(body.model); + + const abort = createDisconnectSignal(request, reply); + try { + const internal = buildRequest(body, resolved); + const conversationKey = headerValue(request, "x-conversation-id"); + if (conversationKey !== undefined) internal.conversationKey = conversationKey; + const agent = headerValue(request, "x-opencode-agent"); + if (agent !== undefined) internal.agent = agent; + + if (body.stream !== true) { + const collected = await ctx.completion.collect(internal, completionDeps(ctx), { + signal: abort.signal, + }); + return reply.send(completionBody(collected)); + } + + await streamCompletion(ctx, internal, reply, { + includeUsage: body.stream_options?.include_usage === true, + signal: abort.signal, + }); + return reply; + } finally { + abort.dispose(); + } + }); +} + +// ------------------------------------------------------- request translation --- + +function buildRequest(body: CompletionRequest, resolved: ResolvedModel): InternalRequest { + const text = Array.isArray(body.prompt) ? body.prompt.join("\n") : body.prompt; + const messages: InternalMessage[] = [{ role: "user", text }]; + + const internal: InternalRequest = { + surface: "openai.completions", + model: resolved.canonical, + messages, + stream: body.stream === true, + tools: [], + }; + + if (resolved.variant !== undefined) internal.variant = resolved.variant; + if (typeof body.temperature === "number") internal.temperature = body.temperature; + if (typeof body.max_tokens === "number") internal.maxTokens = body.max_tokens; + + const stop = normaliseStop(body.stop); + if (stop !== undefined && stop.length > 0) internal.stop = stop; + + return internal; +} + +function normaliseStop(stop: string | string[] | undefined): string[] | undefined { + if (stop === undefined) return undefined; + if (typeof stop === "string") return stop.length > 0 ? [stop] : []; + return stop.filter((entry) => entry.length > 0); +} + +// --------------------------------------------------------- non-streaming out --- + +function completionBody(collected: CollectedCompletion): Record { + return { + id: `cmpl-${randomUUID().replace(/-/g, "")}`, + object: "text_completion", + created: unixSeconds(), + model: collected.model, + choices: [ + { + text: collected.text, + index: 0, + logprobs: null, + finish_reason: mapFinishReason(collected.finishReason), + }, + ], + usage: openAiUsage(collected.usage), + x_opencode: openCodeExtension(collected), + }; +} + +// ------------------------------------------------------------- streaming out --- + +interface StreamOptions { + includeUsage: boolean; + signal: AbortSignal; +} + +async function streamCompletion( + ctx: AppContext, + request: InternalRequest, + reply: FastifyReply, + options: StreamOptions, +): Promise { + const id = `cmpl-${randomUUID().replace(/-/g, "")}`; + const created = unixSeconds(); + const base = { id, object: "text_completion", created, model: request.model }; + + let writer: SseWriter | undefined; + let startEmitted = false; + let finishReason: FinishReason = "stop"; + let usage: Usage = { ...EMPTY_USAGE }; + + // Headers are sent lazily so that a failure before the first event is still + // reported with a proper HTTP status instead of a 200 SSE body. + const ensure = (): SseWriter => { + if (writer === undefined) writer = new SseWriter(reply); + if (!startEmitted) { + startEmitted = true; + writer.open(); + } + return writer; + }; + + const chunk = (text: string, reason: string | null): Record => ({ + ...base, + choices: [{ text, index: 0, logprobs: null, finish_reason: reason }], + }); + + ctx.metrics.activeStreams.inc({ surface: SURFACE }); + try { + for await (const event of ctx.completion.run(request, completionDeps(ctx), { signal: options.signal })) { + switch (event.kind) { + case "start": + ensure(); + break; + + case "text_delta": + ensure().send(chunk(event.text, null)); + break; + + case "usage": + usage = event.usage; + break; + + case "end": + finishReason = event.finishReason; + usage = event.usage; + break; + + case "error": + if (writer === undefined) throw event.error; + writer.send(openAiErrorFrame(event.error)); + return; + + default: + // Reasoning deltas, tool calls and native tool activity have no + // representation in the legacy completions wire format. + break; + } + } + + const active = ensure(); + active.send(chunk("", mapFinishReason(finishReason))); + if (options.includeUsage) { + active.send({ ...base, choices: [], usage: openAiUsage(usage) }); + } + active.send("[DONE]"); + } catch (error) { + const apiError = toApiError(error, "The completion stream failed."); + if (writer === undefined) throw apiError; + writer.send(openAiErrorFrame(apiError)); + } finally { + writer?.close(); + ctx.metrics.activeStreams.dec({ surface: SURFACE }); + } +} + +// ------------------------------------------------------------------ helpers --- + +/** + * Build an in-stream OpenAI error frame. + * + * Headers are already committed by the time a mid-stream failure happens, so the + * rate-limit hint that would normally be a `retry-after` header is carried in the + * frame itself as the non-standard `retry_after_ms` field. + */ +function openAiErrorFrame(error: ApiError): Record { + const body = toOpenAiError(error) as unknown as Record; + if (error.retryAfterMs !== undefined && error.retryAfterMs > 0) { + body["retry_after_ms"] = error.retryAfterMs; + } + return body; +} + +function invalidRequestFromZod(error: z.ZodError): ApiError { + const issue = error.issues[0]; + if (issue === undefined) return ApiError.badRequest("Invalid request body.", { code: "invalid_request" }); + const path = issue.path.map((segment) => String(segment)).join("."); + return ApiError.badRequest(path === "" ? issue.message : `${issue.message} (at ${path})`, { + code: "invalid_request", + param: path === "" ? undefined : path, + }); +} + +function unixSeconds(): number { + return Math.floor(Date.now() / 1000); +} \ No newline at end of file diff --git a/src/adapter/openai/responses.ts b/src/adapter/openai/responses.ts index a2e1488..eb774e9 100644 --- a/src/adapter/openai/responses.ts +++ b/src/adapter/openai/responses.ts @@ -16,8 +16,10 @@ * server-side response store, so callers must resend the full `input`. * - `store` is accepted and ignored; responses are never persisted, and the * echoed response always reports `store: false`. - * - `include`, `service_tier`, `top_logprobs`, `user` and `text.format` are - * accepted for API compatibility and have no effect on the completion. + * - `include`, `service_tier`, `top_logprobs` and `user` are accepted for API + * compatibility and have no effect on the completion. `text.format` is not + * in this list: it is rendered into the prompt like the chat + * `response_format` (see "JSON output mode"). */ import { randomUUID } from "node:crypto"; import type { FastifyInstance, FastifyReply, FastifyRequest } from "fastify"; @@ -30,8 +32,8 @@ import { ApiError, toApiError } from "../../errors.js"; import { createDisconnectSignal } from "../../http/disconnect.js"; import { SseWriter } from "../../http/sse.js"; import { resolveAttachment, type MediaSource } from "../../media/resolve.js"; +import type { ResolvedModel } from "../../upstream/models.js"; import type { - Attachment, CompletionEvent, FinishReason, InternalMessage, @@ -184,6 +186,47 @@ type ResponsesRequest = z.infer; type InputItem = z.infer; type ContentPart = z.infer; +/** + * Optional top-level fields for which an explicit `null` means "unset". + * + * OpenAI SDKs serialise an untouched option as `null`, and OpenAI accepts that; + * dropping the key before validation keeps zod (which rejects `null` for a + * plain `.optional()`) from answering 400 for an omitted option. Required + * fields (`model`, `input`) and the already-nullable `previous_response_id` are + * deliberately absent from the set, as is per-item `messages[].content`. + */ +const NULL_MEANS_UNSET_FIELDS: ReadonlySet = new Set([ + "instructions", + "stream", + "max_output_tokens", + "temperature", + "top_p", + "reasoning", + "tools", + "tool_choice", + "text", + "metadata", + "user", + "store", + "truncation", + "parallel_tool_calls", + "include", + "service_tier", + "top_logprobs", +]); + +/** Drop top-level `null` values for the optional request fields above. */ +function normaliseNullOptionals(body: unknown): unknown { + if (typeof body !== "object" || body === null || Array.isArray(body)) return body; + const record = body as Record; + const cleaned: Record = {}; + for (const [key, value] of Object.entries(record)) { + if (value === null && NULL_MEANS_UNSET_FIELDS.has(key)) continue; + cleaned[key] = value; + } + return cleaned; +} + // ------------------------------------------------------------- wire payloads --- interface SummaryTextPart { @@ -240,7 +283,7 @@ interface ResponseBody { id: string; object: "response"; created_at: number; - status: "in_progress" | "completed" | "incomplete"; + status: "in_progress" | "completed" | "incomplete" | "failed"; model: string; output: ResponseOutputItem[]; output_text: string; @@ -253,7 +296,7 @@ interface ResponseBody { reasoning: { effort: string | null; summary: string | null }; metadata: Record; incomplete_details: { reason: string } | null; - error: null; + error: { code: string; message: string } | null; instructions: null; max_output_tokens: number | null; previous_response_id: null; @@ -291,11 +334,22 @@ interface Prepared { reasoningRequested: boolean; } +/** + * Failure reported when the upstream turn ended with `finishReason: "error"`. + * + * The orchestrator does not surface the upstream error object on the collected + * result, so the terminal response carries this stable surrogate. + */ +const FAILED_TURN: { code: string; message: string } = { + code: "upstream_error", + message: "The upstream completion ended with an error.", +}; + // ------------------------------------------------------------------ routing --- export function registerOpenAiResponsesRoutes(app: FastifyInstance, ctx: AppContext): void { app.post("/v1/responses", async (request: FastifyRequest, reply: FastifyReply) => { - const parsed = responsesRequest.safeParse(request.body ?? {}); + const parsed = responsesRequest.safeParse(normaliseNullOptionals(request.body ?? {})); if (!parsed.success) { const issue = parsed.error.issues[0]; const param = issue !== undefined && issue.path.length > 0 ? issue.path.join(".") : undefined; @@ -312,9 +366,11 @@ export function registerOpenAiResponsesRoutes(app: FastifyInstance, ctx: AppCont try { // Resolve the model before opening a stream so an unknown model is - // reported as an HTTP 404 rather than as an in-stream error event. - await ctx.models.resolve(body.model); - const prepared = await prepare(body, request, ctx, abort.signal); + // reported as an HTTP 404 rather than as an in-stream error event. The + // orchestrator needs the canonical id plus any `#variant` suffix; the raw + // caller string is never forwarded or echoed. + const resolved = await ctx.models.resolve(body.model); + const prepared = await prepare(body, resolved, request, ctx, abort.signal); if (body.stream === true) { await streamResponse(prepared, reply, ctx, abort.signal); @@ -328,7 +384,7 @@ export function registerOpenAiResponsesRoutes(app: FastifyInstance, ctx: AppCont return reply.status(200).send( baseResponse(prepared, { id: newId("resp"), - status: collected.finishReason === "length" ? "incomplete" : "completed", + status: responseStatus(collected.finishReason), output, outputText: collected.text, usage: toResponseUsage(collected.usage), @@ -338,6 +394,7 @@ export function registerOpenAiResponsesRoutes(app: FastifyInstance, ctx: AppCont variant: collected.variant ?? null, reusedSession: collected.reusedSession, nativeTools: collected.nativeTools, + error: collected.finishReason === "error" ? FAILED_TURN : null, }), ); } finally { @@ -356,6 +413,7 @@ export function registerOpenAiResponsesRoutes(app: FastifyInstance, ctx: AppCont */ async function prepare( body: ResponsesRequest, + resolved: ResolvedModel, request: FastifyRequest, ctx: AppContext, signal: AbortSignal, @@ -385,23 +443,25 @@ async function prepare( const internal: InternalRequest = { surface: "openai.responses", - model: body.model, + model: resolved.canonical, messages, stream: body.stream === true, tools, + ...(resolved.variant !== undefined ? { variant: resolved.variant } : {}), ...(choice !== undefined ? { toolChoice: choice } : {}), ...(reasoning !== undefined ? { reasoning } : {}), ...(responseFormat !== undefined ? { responseFormat } : {}), ...(body.temperature !== undefined ? { temperature: body.temperature } : {}), ...(body.top_p !== undefined ? { topP: body.top_p } : {}), ...(body.max_output_tokens !== undefined ? { maxTokens: body.max_output_tokens } : {}), + ...(body.parallel_tool_calls !== undefined ? { parallelToolCalls: body.parallel_tool_calls } : {}), ...(conversationKey !== undefined ? { conversationKey } : {}), ...(agent !== undefined ? { agent } : {}), ...(body.metadata !== undefined ? { metadata: body.metadata } : {}), }; const echo: ResponseEcho = { - model: body.model, + model: resolved.canonical, tools: tools.map((tool) => ({ type: "function", name: tool.name, @@ -512,11 +572,12 @@ async function mapMessageItem( const message: InternalMessage = { role, text: text.join("\n") }; if (media.length > 0) { - const attachments: Attachment[] = []; - for (const source of media) { - attachments.push(await resolveAttachment(source, ctx.config, { signal })); - } - message.attachments = attachments; + // The parts of one message are independent, so they resolve concurrently; + // `Promise.all` preserves the declaration order of `media` in the result. + // The per-attachment and attachment-count caps still bound the work. + message.attachments = await Promise.all( + media.map((source) => resolveAttachment(source, ctx.config, { signal })), + ); } return message; } @@ -605,10 +666,15 @@ function newId(prefix: string): string { } function toResponseUsage(usage: Usage): ResponseUsage { + // Reasoning tokens are a subset of the output tokens on the OpenAI wire + // format, so `output_tokens` folds them in while + // `output_tokens_details.reasoning_tokens` keeps exposing the subset. That + // makes `input_tokens + output_tokens === total_tokens` for every turn. + const outputTokens = usage.outputTokens + usage.reasoningTokens; return { input_tokens: usage.inputTokens, - output_tokens: usage.outputTokens, - total_tokens: usage.totalTokens, + output_tokens: outputTokens, + total_tokens: usage.inputTokens + outputTokens, input_tokens_details: { cached_tokens: usage.cacheReadTokens }, output_tokens_details: { reasoning_tokens: usage.reasoningTokens }, }; @@ -662,17 +728,34 @@ interface ResponseState { variant: string | null; reusedSession: boolean; nativeTools: NativeToolActivity[]; + /** Populated only for a `failed` response. */ + error?: { code: string; message: string } | null; +} + +/** Wire status for a finished turn; only `length`/`error` override `completed`. */ +function responseStatus(finishReason: FinishReason): ResponseBody["status"] { + if (finishReason === "error") return "failed"; + if (finishReason === "length") return "incomplete"; + return "completed"; } function baseResponse(prepared: Prepared, state: ResponseState): ResponseBody { const inProgress = state.status === "in_progress"; - const incomplete = !inProgress && state.finishReason === "length"; + const failed = state.status === "failed"; + const incomplete = !inProgress && !failed && state.finishReason === "length"; + const status: ResponseBody["status"] = inProgress + ? "in_progress" + : failed + ? "failed" + : incomplete + ? "incomplete" + : "completed"; return { id: state.id, object: "response", created_at: Math.floor(Date.now() / 1000), - status: inProgress ? "in_progress" : incomplete ? "incomplete" : "completed", + status, model: prepared.echo.model, output: state.output, output_text: state.outputText, @@ -685,7 +768,7 @@ function baseResponse(prepared: Prepared, state: ResponseState): ResponseBody { reasoning: { effort: prepared.echo.reasoningEffort, summary: prepared.echo.reasoningSummary }, metadata: prepared.echo.metadata, incomplete_details: incomplete ? { reason: "max_output_tokens" } : null, - error: null, + error: state.error ?? null, instructions: null, max_output_tokens: prepared.echo.maxOutputTokens, previous_response_id: null, @@ -722,6 +805,19 @@ interface StreamState { calls: ToolCall[]; usage: Usage | null; finishReason: FinishReason; + /** + * Next `sequence_number` to emit. It lives on the state (rather than in a + * local of `pipeEvents`) so a failure raised after the loop — in + * `finaliseStream`, or by the outer catch — still emits the next contiguous + * value instead of restarting or jumping. + */ + sequence: number; + /** + * Send the SSE head on first use. Opening lazily keeps the status line + * unsent until the first event (or the first failure) is known, so a + * pre-stream error is still reported as a real HTTP status. + */ + ensureOpen: () => void; } async function streamResponse( @@ -733,47 +829,52 @@ async function streamResponse( const writer = new SseWriter(reply); ctx.metrics.activeStreams.inc({ surface: SURFACE }); let opened = false; - - try { + const ensureOpen = (): void => { + if (opened) return; writer.open(); opened = true; + }; + const state: StreamState = { + id: newId("resp"), + sessionId: "", + agent: prepared.request.agent ?? "", + variant: null, + reusedSession: false, + nativeTools: [], + reasoningEnabled: false, + reasoningRequested: prepared.reasoningRequested, + reasoningId: newId("rs"), + reasoningStarted: false, + reasoningVisible: false, + reasoningText: "", + messageId: newId("msg"), + messageStarted: false, + text: "", + calls: [], + usage: null, + finishReason: "stop", + sequence: 0, + ensureOpen, + }; - const state: StreamState = { - id: newId("resp"), - sessionId: "", - agent: prepared.request.agent ?? "", - variant: null, - reusedSession: false, - nativeTools: [], - reasoningEnabled: false, - reasoningRequested: prepared.reasoningRequested, - reasoningId: newId("rs"), - reasoningStarted: false, - reasoningVisible: false, - reasoningText: "", - messageId: newId("msg"), - messageStarted: false, - text: "", - calls: [], - usage: null, - finishReason: "stop", - }; - + try { const events = ctx.completion.run(prepared.request, completionDeps(ctx), { signal }); await pipeEvents(events, writer, prepared, state); } catch (error) { // A head that could not be written still has a status line to send, so the // failure is rethrown for Fastify; only a started stream reports in-band. if (!opened) throw error; - const apiError = toApiError(error, "OpenCode completion failed."); - writer.send(errorFrame(apiError, Number.MAX_SAFE_INTEGER), "error"); + sendFailure(writer, prepared, state, toApiError(error, "OpenCode completion failed.")); } finally { ctx.metrics.activeStreams.dec({ surface: SURFACE }); if (opened) writer.close(); } } -function errorFrame(error: ApiError, sequence: number): Record { +function errorFrame( + error: { code: string; message: string; param?: string; retryAfterMs?: number }, + sequence: number, +): Record { return { type: "error", code: error.code, @@ -786,13 +887,74 @@ function errorFrame(error: ApiError, sequence: number): Record }; } +/** + * Write one frame, advancing the shared counter only once it has been emitted. + * + * A payload that cannot be serialised never reaches the wire, so it must not + * consume a `sequence_number`; doing so would leave a hole in the stream. + */ +function emitFrame( + writer: SseWriter, + state: StreamState, + event: string, + build: (sequence: number) => Record, +): void { + const sequence = state.sequence; + state.ensureOpen(); + writer.send(build(sequence), event); + state.sequence = sequence + 1; +} + +/** Terminal response object for a stream that failed after its first frames. */ +function failedStreamResponse( + prepared: Prepared, + state: StreamState, + error: { code: string; message: string }, +): ResponseBody { + const output: ResponseOutputItem[] = []; + if (state.reasoningVisible && state.reasoningText.length > 0) { + output.push(reasoningItem(state.reasoningId, state.reasoningText)); + } + if (state.messageStarted || state.text.length > 0) { + output.push(messageItem(state.messageId, state.text, "completed")); + } + for (const call of state.calls) output.push(functionCallItem(call, "completed")); + + return baseResponse(prepared, { + id: state.id, + status: "failed", + output, + outputText: state.text, + usage: toResponseUsage(state.usage ?? EMPTY_USAGE), + finishReason: state.finishReason, + sessionId: state.sessionId, + agent: state.agent, + variant: state.variant, + reusedSession: state.reusedSession, + nativeTools: state.nativeTools, + error, + }); +} + +/** + * Emit the legacy flat `event: error` frame followed by the spec-shaped + * terminal `response.failed` event, both consuming the live counter. + */ +function sendFailure(writer: SseWriter, prepared: Prepared, state: StreamState, error: ApiError): void { + emitFrame(writer, state, "error", (sequence) => errorFrame(error, sequence)); + emitFrame(writer, state, "response.failed", (sequence) => ({ + type: "response.failed", + sequence_number: sequence, + response: failedStreamResponse(prepared, state, { code: error.code, message: error.message }), + })); +} + async function pipeEvents( events: AsyncGenerator, writer: SseWriter, prepared: Prepared, state: StreamState, ): Promise { - let sequence = 0; const inProgress = (): ResponseBody => baseResponse(prepared, { id: state.id, @@ -805,16 +967,29 @@ async function pipeEvents( variant: state.variant, reusedSession: state.reusedSession, nativeTools: state.nativeTools, + error: null, }); - writer.send({ type: "response.created", sequence_number: sequence++, response: inProgress() }, "response.created"); - writer.send( - { type: "response.in_progress", sequence_number: sequence++, response: inProgress() }, - "response.in_progress", - ); + // Pull the first event before committing the head. A failure raised while the + // orchestrator prepares the turn (event stream unavailable, upstream refusal) + // must reach the caller as a real HTTP status, not as a 200 SSE body. + const iterator = events[Symbol.asyncIterator](); + const first = await iterator.next(); + + emitFrame(writer, state, "response.created", (sequence) => ({ + type: "response.created", + sequence_number: sequence, + response: inProgress(), + })); + emitFrame(writer, state, "response.in_progress", (sequence) => ({ + type: "response.in_progress", + sequence_number: sequence, + response: inProgress(), + })); try { - for await (const event of events) { + for (let result = first; !result.done; result = await iterator.next()) { + const event = result.value; switch (event.kind) { case "start": state.sessionId = event.sessionId; @@ -829,30 +1004,24 @@ async function pipeEvents( state.reasoningVisible = true; if (!state.reasoningStarted) { state.reasoningStarted = true; - writer.send( - { - type: "response.reasoning_summary_part.added", - sequence_number: sequence++, - item_id: state.reasoningId, - output_index: reasoningOutputIndex(), - summary_index: 0, - part: { type: "summary_text", text: "" }, - }, - "response.reasoning_summary_part.added", - ); - } - state.reasoningText += event.text; - writer.send( - { - type: "response.reasoning_summary_text.delta", - sequence_number: sequence++, + emitFrame(writer, state, "response.reasoning_summary_part.added", (sequence) => ({ + type: "response.reasoning_summary_part.added", + sequence_number: sequence, item_id: state.reasoningId, output_index: reasoningOutputIndex(), summary_index: 0, - delta: event.text, - }, - "response.reasoning_summary_text.delta", - ); + part: { type: "summary_text", text: "" }, + })); + } + state.reasoningText += event.text; + emitFrame(writer, state, "response.reasoning_summary_text.delta", (sequence) => ({ + type: "response.reasoning_summary_text.delta", + sequence_number: sequence, + item_id: state.reasoningId, + output_index: reasoningOutputIndex(), + summary_index: 0, + delta: event.text, + })); break; } @@ -864,80 +1033,62 @@ async function pipeEvents( if (state.reasoningText.length === 0) break; state.reasoningStarted = true; state.reasoningVisible = true; - writer.send( - { - type: "response.reasoning_summary_part.added", - sequence_number: sequence++, - item_id: state.reasoningId, - output_index: reasoningOutputIndex(), - summary_index: 0, - part: { type: "summary_text", text: "" }, - }, - "response.reasoning_summary_part.added", - ); - } - if (!state.reasoningVisible) break; - writer.send( - { - type: "response.reasoning_summary_text.done", - sequence_number: sequence++, + emitFrame(writer, state, "response.reasoning_summary_part.added", (sequence) => ({ + type: "response.reasoning_summary_part.added", + sequence_number: sequence, item_id: state.reasoningId, output_index: reasoningOutputIndex(), summary_index: 0, - text: state.reasoningText, - }, - "response.reasoning_summary_text.done", - ); - writer.send( - { - type: "response.reasoning_summary_part.done", - sequence_number: sequence++, - item_id: state.reasoningId, - output_index: reasoningOutputIndex(), - summary_index: 0, - part: { type: "summary_text", text: state.reasoningText }, - }, - "response.reasoning_summary_part.done", - ); + part: { type: "summary_text", text: "" }, + })); + } + if (!state.reasoningVisible) break; + emitFrame(writer, state, "response.reasoning_summary_text.done", (sequence) => ({ + type: "response.reasoning_summary_text.done", + sequence_number: sequence, + item_id: state.reasoningId, + output_index: reasoningOutputIndex(), + summary_index: 0, + text: state.reasoningText, + })); + emitFrame(writer, state, "response.reasoning_summary_part.done", (sequence) => ({ + type: "response.reasoning_summary_part.done", + sequence_number: sequence, + item_id: state.reasoningId, + output_index: reasoningOutputIndex(), + summary_index: 0, + part: { type: "summary_text", text: state.reasoningText }, + })); break; } case "text_delta": { if (!state.messageStarted) { state.messageStarted = true; - writer.send( - { - type: "response.output_item.added", - sequence_number: sequence++, - output_index: messageOutputIndex(state), - item: messageItem(state.messageId, "", "in_progress"), - }, - "response.output_item.added", - ); - writer.send( - { - type: "response.content_part.added", - sequence_number: sequence++, - item_id: state.messageId, - output_index: messageOutputIndex(state), - content_index: 0, - part: { type: "output_text", text: "", annotations: [] }, - }, - "response.content_part.added", - ); - } - state.text += event.text; - writer.send( - { - type: "response.output_text.delta", - sequence_number: sequence++, + emitFrame(writer, state, "response.output_item.added", (sequence) => ({ + type: "response.output_item.added", + sequence_number: sequence, + output_index: messageOutputIndex(state), + item: messageItem(state.messageId, "", "in_progress"), + })); + emitFrame(writer, state, "response.content_part.added", (sequence) => ({ + type: "response.content_part.added", + sequence_number: sequence, item_id: state.messageId, output_index: messageOutputIndex(state), content_index: 0, - delta: event.text, - }, - "response.output_text.delta", - ); + part: { type: "output_text", text: "", annotations: [] }, + })); + } + state.text += event.text; + emitFrame(writer, state, "response.output_text.delta", (sequence) => ({ + type: "response.output_text.delta", + sequence_number: sequence, + item_id: state.messageId, + output_index: messageOutputIndex(state), + content_index: 0, + delta: event.text, + })); break; } @@ -963,7 +1114,7 @@ async function pipeEvents( break; case "error": - writer.send(errorFrame(event.error, sequence++), "error"); + sendFailure(writer, prepared, state, event.error); return; default: @@ -971,16 +1122,15 @@ async function pipeEvents( } } } catch (error) { - writer.send(errorFrame(toApiError(error, "OpenCode completion failed."), sequence++), "error"); + sendFailure(writer, prepared, state, toApiError(error, "OpenCode completion failed.")); return; } - finaliseStream(writer, prepared, state, sequence); + finaliseStream(writer, prepared, state); } -/** Emit the closing frames plus `response.completed` / `response.incomplete`. */ -function finaliseStream(writer: SseWriter, prepared: Prepared, state: StreamState, startSequence: number): void { - let sequence = startSequence; +/** Emit the closing frames plus `response.completed` / `response.incomplete` / `response.failed`. */ +function finaliseStream(writer: SseWriter, prepared: Prepared, state: StreamState): void { let outputIndex = 0; // Items already announced through `response.output_item.done`; the closing // `response.completed` payload must reuse these exact ids and shapes, not @@ -989,102 +1139,84 @@ function finaliseStream(writer: SseWriter, prepared: Prepared, state: StreamStat if (state.reasoningVisible) { const item = reasoningItem(state.reasoningId, state.reasoningText); - writer.send( - { - type: "response.output_item.done", - sequence_number: sequence++, - output_index: outputIndex, - item, - }, - "response.output_item.done", - ); + emitFrame(writer, state, "response.output_item.done", (sequence) => ({ + type: "response.output_item.done", + sequence_number: sequence, + output_index: outputIndex, + item, + })); doneItems.push(item); outputIndex += 1; } if (state.messageStarted) { - writer.send( - { - type: "response.output_text.done", - sequence_number: sequence++, - item_id: state.messageId, - output_index: outputIndex, - content_index: 0, - text: state.text, - }, - "response.output_text.done", - ); - writer.send( - { - type: "response.content_part.done", - sequence_number: sequence++, - item_id: state.messageId, - output_index: outputIndex, - content_index: 0, - part: { type: "output_text", text: state.text, annotations: [] }, - }, - "response.content_part.done", - ); + emitFrame(writer, state, "response.output_text.done", (sequence) => ({ + type: "response.output_text.done", + sequence_number: sequence, + item_id: state.messageId, + output_index: outputIndex, + content_index: 0, + text: state.text, + })); + emitFrame(writer, state, "response.content_part.done", (sequence) => ({ + type: "response.content_part.done", + sequence_number: sequence, + item_id: state.messageId, + output_index: outputIndex, + content_index: 0, + part: { type: "output_text", text: state.text, annotations: [] }, + })); const item = messageItem(state.messageId, state.text, "completed"); - writer.send( - { - type: "response.output_item.done", - sequence_number: sequence++, - output_index: outputIndex, - item, - }, - "response.output_item.done", - ); + emitFrame(writer, state, "response.output_item.done", (sequence) => ({ + type: "response.output_item.done", + sequence_number: sequence, + output_index: outputIndex, + item, + })); doneItems.push(item); outputIndex += 1; } for (const call of state.calls) { const item = functionCallItem(call, "in_progress"); - writer.send( - { type: "response.output_item.added", sequence_number: sequence++, output_index: outputIndex, item }, - "response.output_item.added", - ); - writer.send( - { - type: "response.function_call_arguments.delta", - sequence_number: sequence++, - item_id: item.id, - output_index: outputIndex, - delta: call.arguments, - }, - "response.function_call_arguments.delta", - ); - writer.send( - { - type: "response.function_call_arguments.done", - sequence_number: sequence++, - item_id: item.id, - output_index: outputIndex, - arguments: call.arguments, - }, - "response.function_call_arguments.done", - ); + emitFrame(writer, state, "response.output_item.added", (sequence) => ({ + type: "response.output_item.added", + sequence_number: sequence, + output_index: outputIndex, + item, + })); + emitFrame(writer, state, "response.function_call_arguments.delta", (sequence) => ({ + type: "response.function_call_arguments.delta", + sequence_number: sequence, + item_id: item.id, + output_index: outputIndex, + delta: call.arguments, + })); + emitFrame(writer, state, "response.function_call_arguments.done", (sequence) => ({ + type: "response.function_call_arguments.done", + sequence_number: sequence, + item_id: item.id, + output_index: outputIndex, + arguments: call.arguments, + })); const completedItem = { ...item, status: "completed" } as ResponseOutputItem; - writer.send( - { - type: "response.output_item.done", - sequence_number: sequence++, - output_index: outputIndex, - item: completedItem, - }, - "response.output_item.done", - ); + emitFrame(writer, state, "response.output_item.done", (sequence) => ({ + type: "response.output_item.done", + sequence_number: sequence, + output_index: outputIndex, + item: completedItem, + })); doneItems.push(completedItem); outputIndex += 1; } const incomplete = state.finishReason === "length"; + const failed = state.finishReason === "error"; const output: ResponseOutputItem[] = doneItems; const final = baseResponse(prepared, { id: state.id, - status: incomplete ? "incomplete" : "completed", + status: failed ? "failed" : incomplete ? "incomplete" : "completed", output, outputText: state.text, usage: toResponseUsage(state.usage ?? EMPTY_USAGE), @@ -1094,10 +1226,17 @@ function finaliseStream(writer: SseWriter, prepared: Prepared, state: StreamStat variant: state.variant, reusedSession: state.reusedSession, nativeTools: state.nativeTools, + error: failed ? FAILED_TURN : null, }); - const type = incomplete ? "response.incomplete" : "response.completed"; - writer.send({ type, sequence_number: sequence++, response: final }, type); + if (failed) { + // The flat error frame is kept for clients written against the previous + // behaviour; `response.failed` below is the spec-shaped terminal event. + emitFrame(writer, state, "error", (sequence) => errorFrame(FAILED_TURN, sequence)); + } + + const type = failed ? "response.failed" : incomplete ? "response.incomplete" : "response.completed"; + emitFrame(writer, state, type, (sequence) => ({ type, sequence_number: sequence, response: final })); } /** Reasoning always occupies output index 0 when it is visible. */ diff --git a/src/config.ts b/src/config.ts index 206e497..f4cd69d 100644 --- a/src/config.ts +++ b/src/config.ts @@ -106,11 +106,40 @@ function envOptStr(name: string): string | undefined { return env(name); } +/** + * Warn about an environment value that cannot be parsed. + * + * Configuration is resolved before the process logger exists, so this writes to + * the console directly. The variable name is logged; the value is not, because + * an operator can put secrets in the wrong variable. + */ +function warnInvalidEnv(name: string, fallback?: number): void { + const suffix = fallback === undefined ? "" : `; using the default (${fallback})`; + console.warn(`opencode-api: ignoring invalid value for ${name}${suffix}`); +} + +/** + * Parse a whole integer string. + * + * `Number.parseInt` accept any numeric prefix, so `"10m"` became 10 and + * `"0x1000"` became 0: a typo silently misconfigured a timeout or a size cap. + * Only a string made up entirely of an optional sign and decimal digits is + * accepted here. + */ +function parseStrictInt(raw: string): number | undefined { + if (!/^-?\d+$/.test(raw)) return undefined; + const parsed = Number(raw); + return Number.isSafeInteger(parsed) ? parsed : undefined; +} + function envInt(name: string, fallback: number, min = Number.NEGATIVE_INFINITY, max = Number.POSITIVE_INFINITY): number { const raw = env(name); if (raw === undefined) return fallback; - const parsed = Number.parseInt(raw, 10); - if (!Number.isFinite(parsed)) return fallback; + const parsed = parseStrictInt(raw); + if (parsed === undefined) { + warnInvalidEnv(name, fallback); + return fallback; + } return Math.min(max, Math.max(min, parsed)); } @@ -137,38 +166,82 @@ export function resolvePath(value: string): string { return path.resolve(expanded); } +function isPlainObject(value: unknown): value is Record { + return typeof value === "object" && value !== null && !Array.isArray(value); +} + +/** + * Parse the agent permission ruleset. + * + * Only "unset" yields `undefined`: a set variable whose JSON is not an array of + * rule objects used to be ignored, which silently dropped an intended `deny` + * rule. It is now a startup error. A rule without an explicit `effect` defaults + * to `ask`, never `allow`. + */ function parsePermissions(): Config["agentPermissions"] { const raw = env("OPENCODE_AGENT_PERMISSIONS"); if (raw === undefined) return undefined; + + let parsed: unknown; try { - const parsed: unknown = JSON.parse(raw); - if (!Array.isArray(parsed)) return undefined; - const rules = parsed - .filter((entry): entry is Record => typeof entry === "object" && entry !== null) - .map((entry) => ({ - action: String(entry["action"] ?? "*"), - resource: String(entry["resource"] ?? "*"), - effect: String(entry["effect"] ?? "allow"), - })); - return rules.length > 0 ? rules : undefined; + parsed = JSON.parse(raw); } catch { + throw new Error("OPENCODE_AGENT_PERMISSIONS must be valid JSON: an array of {action, resource, effect} rules."); + } + if (!Array.isArray(parsed)) { throw new Error("OPENCODE_AGENT_PERMISSIONS must be a JSON array of {action, resource, effect} rules."); } + + const rules = parsed.map((entry, index) => { + if (!isPlainObject(entry)) { + throw new Error(`OPENCODE_AGENT_PERMISSIONS[${index}] must be an object with action, resource and effect.`); + } + for (const key of ["action", "resource", "effect"] as const) { + const value = entry[key]; + if (value !== undefined && typeof value !== "string") { + throw new Error(`OPENCODE_AGENT_PERMISSIONS[${index}].${key} must be a string.`); + } + } + return { + action: typeof entry["action"] === "string" ? entry["action"] : "*", + resource: typeof entry["resource"] === "string" ? entry["resource"] : "*", + effect: typeof entry["effect"] === "string" ? entry["effect"] : "ask", + }; + }); + + return rules; } +/** + * Parse the model alias map. + * + * As with the permission rules, valid JSON of the wrong shape is a startup + * error instead of a silent no-op. + */ function parseAliases(): Record | undefined { const raw = env("OPENCODE_MODEL_ALIASES"); if (raw === undefined) return undefined; + + let parsed: unknown; try { - const parsed: unknown = JSON.parse(raw); - if (typeof parsed !== "object" || parsed === null || Array.isArray(parsed)) return undefined; - const entries = Object.entries(parsed as Record) - .filter(([, value]) => typeof value === "string") - .map(([key, value]) => [key, value as string] as const); - return entries.length > 0 ? Object.fromEntries(entries) : undefined; + parsed = JSON.parse(raw); } catch { - throw new Error("OPENCODE_MODEL_ALIASES must be a JSON object of { alias: \"provider/model\" }."); + throw new Error('OPENCODE_MODEL_ALIASES must be valid JSON: an object of { alias: "provider/model" }.'); } + if (!isPlainObject(parsed)) { + throw new Error('OPENCODE_MODEL_ALIASES must be a JSON object of { alias: "provider/model" }.'); + } + + const entries: Array = []; + for (const [key, value] of Object.entries(parsed)) { + if (typeof value !== "string" || value.trim() === "") { + throw new Error(`OPENCODE_MODEL_ALIASES["${key}"] must be a non-empty "provider/model" string.`); + } + entries.push([key, value]); + } + // `Object.fromEntries` defines own properties, so a `__proto__` alias cannot + // mutate the prototype of the returned map. + return Object.fromEntries(entries); } let cached: Config | undefined; @@ -184,6 +257,18 @@ export function loadConfig(overrides: Partial = {}): Config { const singleKey = envOptStr("OPENCODE_API_KEY"); if (singleKey !== undefined) apiKeys.push(singleKey); + // An explicitly configured key set that yields nothing usable (for example + // `OPENCODE_API_KEYS=","`) must not fall back to the published default key: + // the operator believes the gateway is protected while `sk-dummy-123` is + // accepted. Only a genuinely unset/empty variable uses the default. + const keysConfigured = env("OPENCODE_API_KEYS") !== undefined || singleKey !== undefined; + if (apiKeys.length === 0 && keysConfigured) { + throw new Error( + "OPENCODE_API_KEYS/OPENCODE_API_KEY is set but contains no usable key. " + + "Provide at least one non-empty key, or unset the variable to use the built-in development key.", + ); + } + // The gateway always accepts at least one key, so it starts out of the box. // `sk-dummy-123` is a well-known development placeholder: anyone who can reach // the port can use it, so it must be replaced before exposing the gateway. @@ -219,8 +304,12 @@ export function loadConfig(overrides: Partial = {}): Config { agentMaxSteps: (() => { const raw = env("OPENCODE_AGENT_MAX_STEPS"); if (raw === undefined) return undefined; - const parsed = Number.parseInt(raw, 10); - return Number.isFinite(parsed) && parsed > 0 ? parsed : undefined; + const parsed = parseStrictInt(raw); + if (parsed === undefined || parsed <= 0) { + warnInvalidEnv("OPENCODE_AGENT_MAX_STEPS"); + return undefined; + } + return parsed; })(), dataDir, diff --git a/src/http/shutdown.ts b/src/http/shutdown.ts new file mode 100644 index 0000000..91e351f --- /dev/null +++ b/src/http/shutdown.ts @@ -0,0 +1,97 @@ +/** + * Bounded process shutdown. + * + * Fastify's `close()` waits for in-flight requests, and an SSE completion can + * hold it open for the whole upstream timeout budget (600 s by default). The + * drain is therefore bounded: when the deadline expires the remaining + * connections are force-closed and the stop hooks run anyway, so the spawned + * `opencode serve` child never outlives the gateway. + */ +import type { FastifyInstance } from "fastify"; +import type { Logger } from "../logger.js"; + +/** Default drain deadline: enough for a normal request, far below any grace period. */ +export const DEFAULT_DRAIN_MS = 10_000; + +/** The context surface `shutdown` needs; structurally satisfied by `AppContext`. */ +export interface ShutdownDeps { + readonly log: Pick; + readonly events: { stop(): Promise }; + readonly sessions: { stop(): void }; + readonly upstream: { stop(): Promise }; +} + +/** The app surface `shutdown` needs; structurally satisfied by `FastifyInstance`. */ +export type ShutdownApp = Pick & { + readonly server?: { closeAllConnections?: () => void }; +}; + +/** + * Deps objects whose shutdown already ran. The process-level guard in + * `src/index.ts` stays, and this one keeps the helper itself safe to call from + * more than one signal path. + */ +const completed = new WeakSet(); + +/** + * Stop the gateway within `drainMs`. + * + * Order: close the HTTP server (bounded), then the event stream, the session + * store and the upstream process. A failing hook is logged and does not prevent + * the hooks after it from running. + */ +export async function shutdown(deps: ShutdownDeps, app: ShutdownApp, drainMs = DEFAULT_DRAIN_MS): Promise { + if (completed.has(deps)) return; + completed.add(deps); + + const startedAt = Date.now(); + deps.log.info({ drainMs }, "shutting down"); + + await drain(app, drainMs, deps.log); + await stop("events", () => deps.events.stop(), deps.log); + await stop("sessions", async () => { + deps.sessions.stop(); + }, deps.log); + await stop("upstream", () => deps.upstream.stop(), deps.log); + + deps.log.info({ elapsedMs: Date.now() - startedAt }, "shutdown complete"); +} + +/** Race `app.close()` against the drain deadline. */ +async function drain(app: ShutdownApp, drainMs: number, log: ShutdownDeps["log"]): Promise { + // Attach a handler immediately: a rejection after the deadline would otherwise + // surface as an unhandled rejection. + const closing = Promise.resolve() + .then(() => app.close()) + .catch((error: unknown) => { + log.warn({ err: error instanceof Error ? error.message : String(error) }, "closing the HTTP server failed"); + }); + + let timer: NodeJS.Timeout | undefined; + const deadline = new Promise((resolve) => { + timer = setTimeout(() => { + log.warn({ drainMs }, "drain deadline reached; force-closing remaining connections"); + try { + app.server?.closeAllConnections?.(); + } catch { + /* the server is already closing */ + } + resolve(); + }, drainMs); + timer.unref(); + }); + + try { + await Promise.race([closing, deadline]); + } finally { + if (timer !== undefined) clearTimeout(timer); + } +} + +async function stop(name: string, action: () => Promise, log: ShutdownDeps["log"]): Promise { + try { + await action(); + } catch (error) { + log.warn({ hook: name, err: error instanceof Error ? error.message : String(error) }, "shutdown hook failed"); + } +} diff --git a/src/index.ts b/src/index.ts index 3d237ac..15f4c2c 100644 --- a/src/index.ts +++ b/src/index.ts @@ -14,6 +14,7 @@ import { createLogger } from "./logger.js"; import { createMetrics } from "./metrics/registry.js"; import type { AppContext } from "./context.js"; import { defaultCompletionRunner } from "./context.js"; +import { DEFAULT_DRAIN_MS, shutdown as performShutdown } from "./http/shutdown.js"; import { OpencodeClient } from "./upstream/client.js"; import { EventHub } from "./upstream/events.js"; import { ModelRegistry } from "./upstream/models.js"; @@ -51,7 +52,9 @@ async function main(): Promise { `That key is public knowledge (it ships with the project), so replace it in ${path.join(projectRoot, ".env")} ` + "before exposing this port to anything but localhost.\n" + `Set OPENCODE_ALLOW_NO_AUTH=true to disable authentication entirely on a trusted host.`; - log.warn({ apiKey: DEFAULT_API_KEY }, "using the built-in default API key"); + // The structured log never carries the key itself (AGENTS.md forbids logging + // credentials); the stderr note below is the operator-facing explanation. + log.warn({ usingDefaultApiKey: true }, "using the built-in default API key"); process.stderr.write(`\n${note}\n\n`); } @@ -122,15 +125,8 @@ async function main(): Promise { const shutdown = async (signal: string): Promise => { if (shuttingDown) return; shuttingDown = true; - log.info({ signal }, "shutting down"); - try { - await app.close(); - } catch { - /* ignore */ - } - await events.stop(); - sessions.stop(); - await upstream.stop(); + log.info({ signal }, "received shutdown signal"); + await performShutdown(ctx, app, DEFAULT_DRAIN_MS); process.exit(0); }; @@ -144,7 +140,10 @@ async function main(): Promise { log.error({ err: reason instanceof Error ? reason.message : String(reason) }, "unhandled promise rejection"); }); process.on("uncaughtException", (error) => { + // Keep the log line, then leave: a process in an unknown state must not keep + // accepting requests. log.error({ err: error.message, stack: error.stack }, "uncaught exception"); + process.exit(1); }); } diff --git a/src/media/resolve.ts b/src/media/resolve.ts index 2be2f99..26734f5 100644 --- a/src/media/resolve.ts +++ b/src/media/resolve.ts @@ -13,8 +13,11 @@ * streamed with a hard cap so a hostile or accidental large response cannot * exhaust memory. */ +import type { LookupAddress } from "node:dns"; import dns from "node:dns/promises"; import fsp from "node:fs/promises"; +import http from "node:http"; +import https from "node:https"; import net from "node:net"; import path from "node:path"; import type { Config } from "../config.js"; @@ -131,30 +134,53 @@ async function resolveUrl( ); } - let parsed = parseHttpUrl(source.url, field); - await assertRemoteHostAllowed(parsed, config, field); + let current = parseHttpUrl(source.url, field); const controller = new AbortController(); const timer = setTimeout(() => controller.abort(new Error("media fetch timeout")), config.mediaFetchTimeoutMs); const onAbort = (): void => controller.abort(signal?.reason); - signal?.addEventListener("abort", onAbort, { once: true }); + // `AbortSignal.abort()` is already aborted, and an already-aborted signal never + // fires its listeners: without this branch an aborted caller still downloaded + // every remaining attachment. + if (signal?.aborted) controller.abort(signal.reason); + else signal?.addEventListener("abort", onAbort, { once: true }); try { - // Redirects are followed manually so every hop is re-validated: letting - // `fetch` follow them would let an allowed public URL bounce the request to - // loopback or a cloud metadata endpoint. - let response: Response | undefined; + // Redirects are followed manually so every hop is re-validated: letting the + // HTTP client follow them would let an allowed public URL bounce the request + // to loopback or a cloud metadata endpoint. for (let hop = 0; hop <= MAX_REDIRECTS; hop += 1) { - response = await fetch(parsed, { - redirect: "manual", - signal: controller.signal, - headers: { accept: "*/*", "user-agent": "opencode-api/0.1" }, - }); - - const location = response.headers.get("location"); - if (!isRedirect(response.status) || !location) break; + const pinned = await resolvePinnedAddress(current, config, field); + const response = await requestMedia(current, controller.signal, pinned); + + const location = headerValue(response.headers["location"]); + if (!isRedirect(response.status) || !location) { + if (response.status < 200 || response.status >= 300) { + response.body.destroy(); + throw ApiError.badRequest(`Attachment download failed with HTTP ${response.status}: ${current.toString()}`, { + code: "attachment_download_failed", + param: field, + }); + } + + const declaredLength = Number(headerValue(response.headers["content-length"]) ?? "0"); + if (Number.isFinite(declaredLength) && declaredLength > config.maxAttachmentBytes) { + response.body.destroy(); + throw ApiError.badRequest( + `Attachment is larger than the ${config.maxAttachmentBytes}-byte limit (content-length: ${declaredLength}).`, + { code: "attachment_too_large", param: field }, + ); + } + + const buffer = await readBounded(response.body, config.maxAttachmentBytes, field); + const headerMime = normalise(headerValue(response.headers["content-type"]) ?? "") || undefined; + const name = source.name ?? deriveName(current, headerMime); + const mime = sniffOrDeclare(buffer, headerMime ?? source.mime, name); + return toAttachment(buffer, mime, name, field, current.toString()); + } if (hop === MAX_REDIRECTS) { + response.body.destroy(); throw ApiError.badRequest(`Attachment URL exceeded ${MAX_REDIRECTS} redirects: ${source.url}`, { code: "attachment_download_failed", param: field, @@ -163,51 +189,28 @@ async function resolveUrl( let next: URL; try { - next = new URL(location, parsed); + next = new URL(location, current); } catch { + response.body.destroy(); throw ApiError.badRequest(`Attachment redirect returned an invalid location: ${location}`, { code: "attachment_download_failed", param: field, }); } - await assertRemoteHostAllowed(parseHttpUrl(next.toString(), field), config, field); - parsed = next; - // Release the redirect body before issuing the next request. - await response.body?.cancel().catch(() => undefined); - response = undefined; - } - - if (!response) { - throw ApiError.badRequest(`Attachment download produced no response: ${source.url}`, { - code: "attachment_download_failed", - param: field, - }); - } - - if (!response.ok) { - throw ApiError.badRequest(`Attachment download failed with HTTP ${response.status}: ${parsed.toString()}`, { - code: "attachment_download_failed", - param: field, - }); + // Scheme allow-list before the next hop; the address guard runs per hop. + parseHttpUrl(next.toString(), field); + response.body.destroy(); + current = next; } - const declaredLength = Number(response.headers.get("content-length") ?? "0"); - if (Number.isFinite(declaredLength) && declaredLength > config.maxAttachmentBytes) { - throw ApiError.badRequest( - `Attachment is larger than the ${config.maxAttachmentBytes}-byte limit (content-length: ${declaredLength}).`, - { code: "attachment_too_large", param: field }, - ); - } - - const buffer = await readBounded(response, config.maxAttachmentBytes, field); - const headerMime = normalise(response.headers.get("content-type") ?? "") || undefined; - const name = source.name ?? deriveName(parsed, headerMime); - const mime = sniffOrDeclare(buffer, headerMime ?? source.mime, name); - return toAttachment(buffer, mime, name, field, parsed.toString()); + throw ApiError.badRequest(`Attachment URL exceeded ${MAX_REDIRECTS} redirects: ${source.url}`, { + code: "attachment_download_failed", + param: field, + }); } catch (error) { if (error instanceof ApiError) throw error; const reason = error instanceof Error ? error.message : String(error); - throw ApiError.badRequest(`Could not download attachment from ${parsed.toString()}: ${reason}`, { + throw ApiError.badRequest(`Could not download attachment from ${current.toString()}: ${reason}`, { code: "attachment_download_failed", param: field, }); @@ -217,39 +220,30 @@ async function resolveUrl( } } -/** Maximum number of redirect hops followed for a remote attachment. */ -const MAX_REDIRECTS = 5; - -function isRedirect(status: number): boolean { - return status === 301 || status === 302 || status === 303 || status === 307 || status === 308; +/** An address that passed the private-network guard and will be dialled directly. */ +interface PinnedAddress { + readonly address: string; + /** 4 or 6. */ + readonly family: number; } -function parseHttpUrl(value: string | undefined, field: string): URL { - let parsed: URL; - try { - parsed = new URL(value ?? ""); - } catch { - throw ApiError.badRequest(`Invalid attachment URL: ${value}`, { code: "invalid_attachment", param: field }); - } - if (parsed.protocol !== "http:" && parsed.protocol !== "https:") { - throw ApiError.badRequest(`Unsupported attachment URL protocol: ${parsed.protocol}`, { - code: "invalid_attachment", - param: field, - }); - } - return parsed; +/** First value of an HTTP header that Node may expose as an array. */ +function headerValue(value: string | string[] | undefined): string | undefined { + if (Array.isArray(value)) return value[0]; + return value; } /** - * Reject private / loopback / link-local destinations when - * `OPENCODE_ALLOW_PRIVATE_MEDIA_URLS` is disabled. + * Resolve the host of a URL and return the address the connection must use. * - * Both the literal host and every address it resolves to are checked, so a - * public hostname pointing at `127.0.0.1` cannot be used to reach the gateway's - * own upstream server or a cloud metadata endpoint. + * With `OPENCODE_ALLOW_PRIVATE_MEDIA_URLS=true` the guard is off and `undefined` + * is returned: the public path keeps the default connect-time resolution. With + * the guard on, the address is pinned and handed to the request through a + * `lookup` callback, so the socket connects to exactly the address that was + * validated instead of resolving the hostname a second time (DNS rebinding). */ -async function assertRemoteHostAllowed(url: URL, config: Config, field: string): Promise { - if (config.allowPrivateMediaUrls) return; +async function resolvePinnedAddress(url: URL, config: Config, field: string): Promise { + if (config.allowPrivateMediaUrls) return undefined; const hostname = url.hostname.replace(/^\[|\]$/g, ""); if (isPrivateHost(hostname)) { @@ -259,15 +253,33 @@ async function assertRemoteHostAllowed(url: URL, config: Config, field: string): ); } - if (net.isIP(hostname) !== 0) return; - - let addresses: Array<{ address: string }>; - try { - addresses = await dns.lookup(hostname, { all: true, verbatim: true }); - } catch { - // Resolution failure is reported by `fetch` with a clearer message. - return; + const literal = net.isIP(hostname); + if (literal !== 0) return { address: hostname, family: literal }; + + const validated = await lookupAddresses(hostname); + assertAddressesPublic(validated, hostname, field); + + // Resolve once more immediately before dialling: the first answer validated + // above, the second is what the socket will use. Both must be public, so a + // hostname that flips to a private address between the check and the connect + // is rejected instead of reached. + const pinned = await lookupAddresses(hostname); + assertAddressesPublic(pinned, hostname, field); + const first = pinned[0]; + if (first === undefined) { + throw ApiError.badRequest(`Attachment host ${hostname} resolved to no addresses.`, { + code: "attachment_download_failed", + param: field, + }); } + return { address: first.address, family: first.family }; +} + +async function lookupAddresses(hostname: string): Promise { + return dns.lookup(hostname, { all: true, verbatim: true }); +} + +function assertAddressesPublic(addresses: readonly LookupAddress[], hostname: string, field: string): void { for (const entry of addresses) { if (isPrivateHost(entry.address)) { throw ApiError.badRequest( @@ -278,6 +290,87 @@ async function assertRemoteHostAllowed(url: URL, config: Config, field: string): } } +/** A `net` lookup callback that always returns the pinned address. */ +function pinnedLookup(pinned: PinnedAddress): net.LookupFunction { + return (hostname, options, callback) => { + if (options.all === true) { + callback(null, [{ address: pinned.address, family: pinned.family }]); + return; + } + callback(null, pinned.address, pinned.family); + }; +} + +interface MediaResponse { + readonly status: number; + readonly headers: http.IncomingHttpHeaders; + readonly body: http.IncomingMessage; +} + +/** + * Issue one GET for a remote attachment. + * + * `node:http`/`node:https` are used directly instead of `fetch` because they + * accept a `lookup` callback: that is what pins the connection to the validated + * address. Host and (for HTTPS) SNI keep the original hostname. + */ +function requestMedia(url: URL, signal: AbortSignal, pinned: PinnedAddress | undefined): Promise { + return new Promise((resolve, reject) => { + const isHttps = url.protocol === "https:"; + const hostname = url.hostname.replace(/^\[|\]$/g, ""); + const options: https.RequestOptions = { + protocol: url.protocol, + hostname, + port: url.port !== "" ? Number(url.port) : isHttps ? 443 : 80, + path: `${url.pathname}${url.search}`, + method: "GET", + headers: { + accept: "*/*", + // `node:http` does not decompress bodies the way `fetch` did, so ask for + // the bytes as they are stored. + "accept-encoding": "identity", + "user-agent": "opencode-api/0.1", + // Preserve the caller-visible authority even when the socket is pinned. + host: url.host, + }, + signal, + ...(pinned ? { lookup: pinnedLookup(pinned) } : {}), + }; + // TLS SNI must stay the hostname, not the pinned address. + if (isHttps && net.isIP(hostname) === 0) options.servername = hostname; + + const request = (isHttps ? https : http).request(options); + request.once("error", reject); + request.once("response", (response) => { + resolve({ status: response.statusCode ?? 0, headers: response.headers, body: response }); + }); + request.end(); + }); +} + +/** Maximum number of redirect hops followed for a remote attachment. */ +const MAX_REDIRECTS = 5; + +function isRedirect(status: number): boolean { + return status === 301 || status === 302 || status === 303 || status === 307 || status === 308; +} + +function parseHttpUrl(value: string | undefined, field: string): URL { + let parsed: URL; + try { + parsed = new URL(value ?? ""); + } catch { + throw ApiError.badRequest(`Invalid attachment URL: ${value}`, { code: "invalid_attachment", param: field }); + } + if (parsed.protocol !== "http:" && parsed.protocol !== "https:") { + throw ApiError.badRequest(`Unsupported attachment URL protocol: ${parsed.protocol}`, { + code: "invalid_attachment", + param: field, + }); + } + return parsed; +} + async function resolveLocalFile(source: MediaSource, config: Config, field: string): Promise { if (!config.allowLocalFiles) { throw ApiError.badRequest( @@ -322,6 +415,10 @@ async function resolveLocalFile(source: MediaSource, config: Config, field: stri const buffer = await fsp.readFile(realPath); const name = source.name ?? path.basename(realPath); + // The pre-read `stat` can be stale (a file that grows between the two calls) + // or meaningless (procfs reports size 0 for a regular file), so the bytes that + // were actually read are checked against the same budget as well. + assertWithinBudget(buffer.byteLength, config, field, name); const mime = sniffOrDeclare(buffer, source.mime, name); return toAttachment(buffer, mime, name, field, realPath); } @@ -386,29 +483,15 @@ function assertWithinBudget(bytes: number, config: Config, field: string, name: } } -async function readBounded(response: Response, maxBytes: number, field: string): Promise { - if (!response.body) { - const buffer = Buffer.from(await response.arrayBuffer()); - if (buffer.byteLength > maxBytes) { - throw ApiError.badRequest(`Attachment download exceeded the ${maxBytes}-byte limit.`, { - code: "attachment_too_large", - param: field, - }); - } - return buffer; - } - - const reader = response.body.getReader(); +async function readBounded(body: http.IncomingMessage, maxBytes: number, field: string): Promise { const chunks: Buffer[] = []; let total = 0; - for (;;) { - const chunk = await reader.read(); - if (chunk.done) break; - const buffer = Buffer.from(chunk.value); + for await (const chunk of body as AsyncIterable) { + const buffer = Buffer.isBuffer(chunk) ? chunk : Buffer.from(chunk); total += buffer.byteLength; if (total > maxBytes) { - await reader.cancel().catch(() => undefined); + body.destroy(); throw ApiError.badRequest(`Attachment download exceeded the ${maxBytes}-byte limit.`, { code: "attachment_too_large", param: field, diff --git a/src/metrics/registry.ts b/src/metrics/registry.ts index 0fee1e4..6a1daf6 100644 --- a/src/metrics/registry.ts +++ b/src/metrics/registry.ts @@ -38,7 +38,7 @@ export function createMetrics(options: { enabled: boolean; prefix?: string } = { name: `${prefix}http_request_duration_seconds`, help: "HTTP request latency in seconds.", labelNames: ["method", "route", "status"] as const, - buckets: [0.01, 0.05, 0.1, 0.25, 0.5, 1, 2.5, 5, 10, 30, 60, 120], + buckets: [0.01, 0.05, 0.1, 0.25, 0.5, 1, 2.5, 5, 10, 30, 60, 120, 300, 600], registers: [registry], }); diff --git a/src/routes/admin.ts b/src/routes/admin.ts index c9ed90f..acfa6a1 100644 --- a/src/routes/admin.ts +++ b/src/routes/admin.ts @@ -37,6 +37,73 @@ export function registerAdminRoutes(app: FastifyInstance, ctx: AppContext): void }; }); + app.get("/admin/config", async () => { + const config = ctx.config; + // Redacted on purpose: the response is reachable by any authenticated + // caller, so secrets (API keys, the upstream password) are never echoed. + return { + host: config.host, + port: config.port, + bodyLimitBytes: config.bodyLimitBytes, + trustProxy: config.trustProxy, + auth: { + apiKeyCount: config.apiKeys.length, + usingDefaultApiKey: config.usingDefaultApiKey, + allowNoAuth: config.allowNoAuth, + metricsPublic: config.metricsPublic, + }, + corsOrigins: config.corsOrigins, + upstream: { + url: config.upstreamUrl ?? null, + passwordConfigured: config.upstreamPassword !== undefined, + autostart: config.upstreamAutostart, + binary: config.upstreamBin ?? null, + host: config.upstreamHost, + port: config.upstreamPort, + extraArgs: config.upstreamExtraArgs, + startTimeoutMs: config.upstreamStartTimeoutMs, + requestTimeoutMs: config.upstreamRequestTimeoutMs, + firstTokenTimeoutMs: config.upstreamFirstTokenTimeoutMs, + }, + agent: { + name: config.agent, + workdir: config.workdir, + maxSteps: config.agentMaxSteps ?? null, + permissionRuleCount: config.agentPermissions?.length ?? 0, + }, + sessions: { + dataDir: config.dataDir, + cacheEnabled: config.sessionCacheEnabled, + ttlMs: config.sessionTtlMs, + maxEntries: config.sessionMaxEntries, + persist: config.sessionPersist, + }, + models: { + cacheTtlMs: config.modelCacheTtlMs, + aliases: Object.keys(config.modelAliases ?? {}), + }, + media: { + allowLocalFiles: config.allowLocalFiles, + allowedFileRoots: config.allowedFileRoots, + allowRemoteMediaUrls: config.allowRemoteMediaUrls, + allowPrivateMediaUrls: config.allowPrivateMediaUrls, + maxAttachmentBytes: config.maxAttachmentBytes, + maxAttachments: config.maxAttachments, + fetchTimeoutMs: config.mediaFetchTimeoutMs, + }, + reasoning: { + default: config.reasoningDefault, + field: config.reasoningField, + toolBridgeDenyNativeTools: config.toolBridgeDenyNativeTools, + exposeNativeTools: config.exposeNativeTools, + nativeToolEventName: config.nativeToolEventName, + }, + logLevel: config.logLevel, + metricsEnabled: config.metricsEnabled, + instanceId: config.instanceId, + }; + }); + app.post("/admin/models/refresh", async () => { const catalog = await ctx.models.catalog(true); return { diff --git a/src/routes/health.ts b/src/routes/health.ts index 7cc4152..e5ff618 100644 --- a/src/routes/health.ts +++ b/src/routes/health.ts @@ -17,25 +17,23 @@ export function registerHealthRoutes(app: FastifyInstance, ctx: AppContext): voi }, })); + /** + * Readiness probe. + * + * This route is public and unauthenticated, so it must never trigger upstream + * work: refreshing the catalogue is the job of `POST /admin/models/refresh`. + * It only reports the state the gateway already holds. + */ app.get("/ready", async (request, reply) => { const status = ctx.upstream.status(); - try { - await ctx.models.catalog(); - const models = await ctx.models.list(); - return { - status: "ready", - service: SERVICE_NAME, - version: VERSION, - upstream: { - ready: true, - source: status.source ?? null, - url: status.url ?? null, - models: models.length, - }, - }; - } catch (error) { - const message = error instanceof Error ? error.message : String(error); - request.log.warn({ err: message }, "readiness probe failed"); + const catalog = ctx.models.cached; + const ready = status.ready && catalog !== undefined; + + if (!ready) { + request.log.debug( + { upstreamReady: status.ready, hasCatalog: catalog !== undefined }, + "readiness probe: cached state is not ready", + ); return reply.status(503).send({ status: "unavailable", service: SERVICE_NAME, @@ -44,12 +42,25 @@ export function registerHealthRoutes(app: FastifyInstance, ctx: AppContext): voi ready: false, source: status.source ?? null, url: status.url ?? null, - error: message, + models: catalog?.models.length ?? 0, + error: catalog === undefined ? "model catalogue is not cached" : "upstream endpoint is not ready", }, }); } + + return { + status: "ready", + service: SERVICE_NAME, + version: VERSION, + upstream: { + ready: true, + source: status.source ?? null, + url: status.url ?? null, + models: catalog.models.length, + }, + }; }); // Common alias used by container orchestrators. app.get("/healthz", async () => ({ status: "ok", service: SERVICE_NAME, version: VERSION })); -} +} \ No newline at end of file diff --git a/src/server.ts b/src/server.ts index 7c9dc57..b5c074b 100644 --- a/src/server.ts +++ b/src/server.ts @@ -5,6 +5,7 @@ import { randomUUID } from "node:crypto"; import type { IncomingHttpHeaders } from "node:http"; import Fastify, { type FastifyInstance, type FastifyRequest } from "fastify"; import { registerOpenAiChatRoutes } from "./adapter/openai/chat.js"; +import { registerOpenAiCompletionRoutes } from "./adapter/openai/completions.js"; import { registerOpenAiEmbeddingRoutes } from "./adapter/openai/embeddings.js"; import { registerOpenAiModelRoutes } from "./adapter/openai/models.js"; import { registerOpenAiResponsesRoutes } from "./adapter/openai/responses.js"; @@ -51,6 +52,10 @@ export async function buildServer(ctx: AppContext): Promise { // Upstream calls are long; never let Fastify cut a streaming response short. requestTimeout: 0, connectionTimeout: 0, + // Shutdown must not wait for an in-flight SSE stream to finish: `close()` + // also tears down hijacked sockets, so SIGTERM cannot hang for the whole + // upstream timeout budget. + forceCloseConnections: true, }) as unknown as FastifyInstance; // Every response — JSON, error and SSE alike — carries the request id. @@ -81,7 +86,10 @@ export async function buildServer(ctx: AppContext): Promise { // ------------------------------------------------------------- metrics --- app.addHook("onResponse", async (request, reply) => { - const route = request.routeOptions?.url ?? request.url.split("?")[0] ?? "unknown"; + // Never use the raw request URL as a label: prom-client keeps one series per + // label set forever, so an anonymous caller hitting random paths could grow + // the process heap without bound. Unmatched requests share one sentinel. + const route = request.routeOptions?.url ?? "unmatched"; const labels = { method: request.method, route, status: String(reply.statusCode) }; ctx.metrics.httpRequests.inc(labels); const elapsed = reply.elapsedTime; @@ -137,6 +145,7 @@ export async function buildServer(ctx: AppContext): Promise { registerOpenAiModelRoutes(app, ctx); registerOpenAiChatRoutes(app, ctx); registerOpenAiResponsesRoutes(app, ctx); + registerOpenAiCompletionRoutes(app, ctx); registerOpenAiEmbeddingRoutes(app, ctx); registerAnthropicMessageRoutes(app, ctx); @@ -148,6 +157,7 @@ export async function buildServer(ctx: AppContext): Promise { endpoints: [ "POST /v1/chat/completions", "POST /v1/responses", + "POST /v1/completions", "POST /v1/messages", "POST /v1/messages/count_tokens", "GET /v1/models", @@ -157,6 +167,7 @@ export async function buildServer(ctx: AppContext): Promise { "GET /ready", "GET /metrics", "GET /admin/status", + "GET /admin/config", ], })); diff --git a/src/types/internal.ts b/src/types/internal.ts index 1098a8b..032652c 100644 --- a/src/types/internal.ts +++ b/src/types/internal.ts @@ -1,14 +1,14 @@ /** * Internal, wire-format-agnostic representation of a chat/completion request. * - * Every public API surface (OpenAI chat completions, OpenAI responses, - * Anthropic messages) is normalised into these types before it reaches the - * OpenCode upstream layer. Adapters only translate between their own wire - * format and this model. + * Every public API surface (OpenAI chat completions, OpenAI legacy completions, + * OpenAI responses, Anthropic messages) is normalised into these types before it + * reaches the OpenCode upstream layer. Adapters only translate between their own + * wire format and this model. */ /** Which public API surface produced a request. Used to shape the response. */ -export type Surface = "openai.chat" | "openai.responses" | "anthropic.messages"; +export type Surface = "openai.chat" | "openai.completions" | "openai.responses" | "anthropic.messages"; export type MessageRole = "system" | "developer" | "user" | "assistant" | "tool"; @@ -102,6 +102,11 @@ export interface InternalRequest { /** Client tools to bridge into the prompt. Empty when the caller sent none. */ tools: ToolDefinition[]; toolChoice?: "auto" | "none" | "required" | { name: string }; + /** + * When `false`, the bridged tool instructions ask the model for at most one + * tool call per turn. Unset and `true` both mean "as many as it needs". + */ + parallelToolCalls?: boolean; reasoning?: ReasoningRequest; /** Requested JSON output shape; rendered into the prompt. */ responseFormat?: ResponseFormat; @@ -113,8 +118,6 @@ export interface InternalRequest { conversationKey?: string; /** OpenCode agent to run the turn with; defaults to the server configuration. */ agent?: string; - /** Whether to persist a sticky session for this request. */ - sticky?: boolean; /** * Extra client-side correlation data echoed back in logs. Never forwarded to * the upstream model provider. @@ -171,9 +174,21 @@ export type CompletionEvent = note?: string; } | { kind: "reasoning_delta"; text: string; ordinal: number } - | { kind: "reasoning_end"; text: string; ordinal: number } + | { + kind: "reasoning_end"; + text: string; + ordinal: number; + /** Upstream assistant message id, when known. */ + messageId?: string; + } | { kind: "text_delta"; text: string; ordinal: number } - | { kind: "text_end"; text: string; ordinal: number } + | { + kind: "text_end"; + text: string; + ordinal: number; + /** Upstream assistant message id, when known. */ + messageId?: string; + } | { kind: "tool_calls"; calls: ToolCall[] } | { kind: "native_tool"; activity: NativeToolActivity } | { kind: "usage"; usage: Usage } diff --git a/src/upstream/client.ts b/src/upstream/client.ts index 774281f..8e2eb0a 100644 --- a/src/upstream/client.ts +++ b/src/upstream/client.ts @@ -31,6 +31,18 @@ export interface RequestOptions { operation: string; } +/** + * Catalogue and probe calls must not inherit the turn budget (600 s by default): + * a hung upstream would block `/v1/models`, `/ready`, the startup warm-up and + * every `ModelRegistry.resolve()` for minutes. + */ +const CATALOGUE_TIMEOUT_MS = 10_000; + +export interface OpencodeClientOptions { + /** Override the catalogue budget; tests use a small value instead of waiting 10 s. */ + catalogueTimeoutMs?: number; +} + interface UpstreamErrorEnvelope { _tag?: string; message?: string; @@ -55,12 +67,20 @@ export class OpencodeClient { readonly #log: Logger; readonly #metrics: Metrics; readonly #config: Config; + readonly #catalogueTimeoutMs: number; - constructor(upstream: UpstreamProcess, config: Config, log: Logger, metrics: Metrics) { + constructor( + upstream: UpstreamProcess, + config: Config, + log: Logger, + metrics: Metrics, + options: OpencodeClientOptions = {}, + ) { this.#process = upstream; this.#config = config; this.#log = log; this.#metrics = metrics; + this.#catalogueTimeoutMs = options.catalogueTimeoutMs ?? CATALOGUE_TIMEOUT_MS; } get config(): Config { @@ -102,8 +122,6 @@ export class OpencodeClient { signal: controller.signal, }); - duration(this.#metrics, options.operation, startedAt); - if (response.status === 401) { outcome = "unauthorized"; this.#process.markStale("OpenCode rejected the gateway credentials."); @@ -167,6 +185,9 @@ export class OpencodeClient { } finally { clearTimeout(timer); options.signal?.removeEventListener("abort", onAbort); + // Observed exactly once for every outcome: success, HTTP error, timeout, + // network error and abort. + duration(this.#metrics, options.operation, startedAt); if (outcome === "success") { this.#metrics.upstreamRequests.inc({ operation: options.operation, outcome }); } @@ -176,7 +197,7 @@ export class OpencodeClient { async listModels(): Promise { const response = await this.request & { location?: unknown }>( "/api/model", - { operation: "model.list" }, + { operation: "model.list", timeoutMs: this.#catalogueTimeoutMs }, ); return response.data ?? []; } @@ -184,6 +205,7 @@ export class OpencodeClient { async listProviders(): Promise { const response = await this.request>("/api/provider", { operation: "provider.list", + timeoutMs: this.#catalogueTimeoutMs, }); return response.data ?? []; } @@ -191,6 +213,7 @@ export class OpencodeClient { async listAgents(): Promise { const response = await this.request>("/api/agent", { operation: "agent.list", + timeoutMs: this.#catalogueTimeoutMs, }); return response.data ?? []; } diff --git a/src/upstream/completion.ts b/src/upstream/completion.ts index dfbe814..8981a2b 100644 --- a/src/upstream/completion.ts +++ b/src/upstream/completion.ts @@ -108,8 +108,18 @@ export async function* runCompletion( if (prepared.reused && isStaleSession(apiError)) { deps.log.info({ sessionId: prepared.sessionId }, "sticky session vanished upstream; replaying on a new session"); deps.sessions.invalidate(prepared.key, "stale-session", prepared.sessionId); - const fresh = await prepare(request, deps, agent, { forceFresh: true }); - yield* execute(fresh, deps, options); + // The replay is itself fallible. `execute()` releases its own record in + // `finally`, so never let a replay failure escape the generator: surface + // it as an `error` event and make sure the fresh slot is not left busy. + let fresh: Prepared | undefined; + try { + fresh = await prepare(request, deps, agent, { forceFresh: true }); + yield* execute(fresh, deps, options); + } catch (replayError) { + const replayApiError = toApiError(replayError, "OpenCode completion replay failed."); + if (fresh) deps.sessions.release(fresh.key, fresh.sessionId, false); + yield { kind: "error", error: replayApiError }; + } return; } deps.sessions.release(prepared.key, prepared.sessionId, false); @@ -200,10 +210,13 @@ async function prepare( validateAttachments(request, modelInfo, models); - const bridge = createToolBridge(request.tools, request.toolChoice); + const bridge = createToolBridge(request.tools, request.toolChoice, { + parallelToolCalls: request.parallelToolCalls, + }); const toolsHash = hashTools(request.tools); const acquire = sessions.acquire({ - key: options.forceFresh ? undefined : request.conversationKey, + key: request.conversationKey, + fresh: options.forceFresh, model: resolved.canonical, agent, variant: decision.variant, @@ -211,45 +224,51 @@ async function prepare( toolsHash, }); - const key = options.forceFresh && request.conversationKey - ? `${request.conversationKey}:fresh:${Date.now().toString(36)}` - : acquire.key; + const key = acquire.key; let sessionId = acquire.sessionId; let reused = acquire.reused && !options.forceFresh; - if (!reused || !sessionId) { - const created = await client.createSession({ - model: { - providerID: resolved.providerID, - id: resolved.modelID, - ...(decision.variant ? { variant: decision.variant } : {}), - }, - agent, - title: deriveTitle(request.messages), - location: { directory: config.workdir }, - metadata: { gateway: "opencode-api", surface: request.surface }, - ...(permissionsFor(config, bridge.active) ? { permissions: permissionsFor(config, bridge.active) as never } : {}), - }); - sessionId = created.id; - reused = false; - } + try { + if (!reused || !sessionId) { + const created = await client.createSession({ + model: { + providerID: resolved.providerID, + id: resolved.modelID, + ...(decision.variant ? { variant: decision.variant } : {}), + }, + agent, + title: deriveTitle(request.messages), + location: { directory: config.workdir }, + metadata: { gateway: "opencode-api", surface: request.surface }, + ...(permissionsFor(config, bridge.active) ? { permissions: permissionsFor(config, bridge.active) as never } : {}), + }); + sessionId = created.id; + reused = false; + } - const { text, files } = buildPrompt(acquire.pending, bridge, request.responseFormat, config); + const { text, files } = buildPrompt(acquire.pending, bridge, request.responseFormat, config); - return { - request, - resolved: { canonical: resolved.canonical, providerID: resolved.providerID, modelID: resolved.modelID }, - modelInfo, - decision, - bridge, - agent, - acquire: { ...acquire, pending: acquire.pending }, - sessionId, - reused, - promptText: text, - promptFiles: files, - key, - }; + return { + request, + resolved: { canonical: resolved.canonical, providerID: resolved.providerID, modelID: resolved.modelID }, + modelInfo, + decision, + bridge, + agent, + acquire: { ...acquire, pending: acquire.pending }, + sessionId, + reused, + promptText: text, + promptFiles: files, + key, + }; + } catch (error) { + // `acquire()` already reserved the record when it reused a session. Anything + // that fails before `execute()` runs would otherwise leave it `busy: true` + // until the sweeper reclaims it. + if (reused && sessionId) sessions.release(acquire.key, sessionId, false); + throw error; + } } async function* execute( @@ -265,7 +284,14 @@ async function* execute( let sessionSettled = false; try { - await events.ensureConnected(5_000); + if (!(await events.ensureConnected(5_000))) { + // Without the event stream there is nowhere for the turn's events to + // arrive, so fail before spending an upstream (billed) turn. The `finally` + // below releases the session slot. + throw ApiError.unavailable("OpenCode event stream is not connected.", { + code: "event_stream_unavailable", + }); + } yield { kind: "start", @@ -363,7 +389,12 @@ async function* execute( case "session.text.ended": { const text = typeof data["text"] === "string" ? data["text"] : ""; - yield { kind: "text_end", text, ordinal: numberValue(data["ordinal"]) }; + yield { + kind: "text_end", + text, + ordinal: numberValue(data["ordinal"]), + ...(messageId !== "" ? { messageId } : {}), + }; break; } @@ -385,6 +416,7 @@ async function* execute( kind: "reasoning_end", text: typeof data["text"] === "string" ? data["text"] : "", ordinal: numberValue(data["ordinal"]), + ...(messageId !== "" ? { messageId } : {}), }; } break; @@ -439,7 +471,12 @@ async function* execute( rawFinish = typeof data["rawFinish"] === "string" ? data["rawFinish"] : undefined; yield { kind: "usage", usage }; const nativeToolFinished = finishReason === "tool_calls"; - if (singleStep && !nativeToolFinished) { + // A bridged turn may only end on the first step when a bridged tool + // call was actually parsed. Otherwise (no call yet, or a native step) + // keep consuming until `session.execution.*` / `session.idle`: later + // steps can still carry the answer. The step budget, request deadline + // and first-token deadline still bound the loop. + if (singleStep && !nativeToolFinished && bridgedToolCalls > 0) { yield* finalise(); return; } diff --git a/src/upstream/events.ts b/src/upstream/events.ts index a514aa1..6c302a6 100644 --- a/src/upstream/events.ts +++ b/src/upstream/events.ts @@ -16,11 +16,21 @@ import { authHeaders, type UpstreamProcess } from "./process.js"; export type EventListener = (event: OpencodeEvent) => void; export type ReconnectListener = () => void; +/** Documented upstream heartbeat period; three missed beats mean a half-open socket. */ +const HEARTBEAT_INTERVAL_MS = 15_000; +const IDLE_READ_TIMEOUT_MS = HEARTBEAT_INTERVAL_MS * 3; + +export interface EventHubOptions { + /** Override the idle-read watchdog; tests use a small value instead of waiting 45 s. */ + idleTimeoutMs?: number; +} + export class EventHub { readonly #upstream: UpstreamProcess; readonly #config: Config; readonly #log: Logger; readonly #metrics: Metrics; + readonly #idleTimeoutMs: number; #controller?: AbortController; #running = false; @@ -33,11 +43,18 @@ export class EventHub { readonly #listeners = new Map>(); readonly #reconnectListeners = new Set(); - constructor(upstream: UpstreamProcess, config: Config, log: Logger, metrics: Metrics) { + constructor( + upstream: UpstreamProcess, + config: Config, + log: Logger, + metrics: Metrics, + options: EventHubOptions = {}, + ) { this.#upstream = upstream; this.#config = config; this.#log = log; this.#metrics = metrics; + this.#idleTimeoutMs = options.idleTimeoutMs ?? IDLE_READ_TIMEOUT_MS; } get connected(): boolean { @@ -135,34 +152,47 @@ export class EventHub { const controller = new AbortController(); this.#controller = controller; - const response = await fetch(`${endpoint.url}/api/event`, { - headers: { ...authHeaders(endpoint.password), accept: "text/event-stream", "cache-control": "no-cache" }, - signal: controller.signal, - }); + try { + const response = await fetch(`${endpoint.url}/api/event`, { + headers: { ...authHeaders(endpoint.password), accept: "text/event-stream", "cache-control": "no-cache" }, + signal: controller.signal, + }); - if (!response.ok || !response.body) { - throw new Error(`event stream rejected with status ${response.status}`); - } + if (!response.ok || !response.body) { + throw new Error(`event stream rejected with status ${response.status}`); + } - this.#log.debug({ url: endpoint.url }, "event stream connected"); - this.#reconnectDelayMs = 250; + this.#log.debug({ url: endpoint.url }, "event stream connected"); + this.#reconnectDelayMs = 250; - const reader = response.body.getReader(); - const decoder = new TextDecoder(); - let buffer = ""; + const reader = response.body.getReader(); + const decoder = new TextDecoder(); + let buffer = ""; - while (this.#running) { - const chunk = await reader.read(); - if (chunk.done) break; - buffer += decoder.decode(chunk.value, { stream: true }); - - let boundary = findBoundary(buffer); - while (boundary !== -1) { - const frame = buffer.slice(0, boundary.index); - buffer = buffer.slice(boundary.index + boundary.length); - this.#handleFrame(frame); - boundary = findBoundary(buffer); + try { + while (this.#running) { + // A socket that is half-open after the upstream died never rejects + // `read()`, so each read is bounded by the idle watchdog: on expiry the + // stream fails and `#loop` reconnects instead of hanging forever. + const chunk = await withIdleDeadline(reader.read(), this.#idleTimeoutMs); + if (chunk.done) break; + buffer += decoder.decode(chunk.value, { stream: true }); + + let boundary = findBoundary(buffer); + while (boundary !== -1) { + const frame = buffer.slice(0, boundary.index); + buffer = buffer.slice(boundary.index + boundary.length); + this.#handleFrame(frame); + boundary = findBoundary(buffer); + } + } + } finally { + // Release the response body on every exit path; without this a stop() or a + // reconnect leaks one upstream SSE consumer. + await reader.cancel().catch(() => undefined); } + } finally { + if (this.#controller === controller) this.#controller = undefined; } } @@ -238,5 +268,24 @@ function findBoundary(buffer: string): { index: number; length: number } | -1 { } function delay(ms: number): Promise { - return new Promise((resolve) => setTimeout(resolve, ms)); + return new Promise((resolve) => { + // The backoff timer must not keep the process alive after `stop()`. + setTimeout(resolve, ms).unref?.(); + }); +} + +/** Reject when `read` has not settled within `idleTimeoutMs`. */ +async function withIdleDeadline(read: Promise, idleTimeoutMs: number): Promise { + let timer: NodeJS.Timeout | undefined; + const deadline = new Promise((_resolve, reject) => { + timer = setTimeout(() => reject(new Error(`event stream idle for ${idleTimeoutMs} ms`)), idleTimeoutMs); + }); + // The watchdog can win the race while the read is still pending; `cancel()` + // settles it later, so make sure that cannot become an unhandled rejection. + void read.catch(() => undefined); + try { + return await Promise.race([read, deadline]); + } finally { + if (timer !== undefined) clearTimeout(timer); + } } diff --git a/src/upstream/process.ts b/src/upstream/process.ts index 9c45513..acb7846 100644 --- a/src/upstream/process.ts +++ b/src/upstream/process.ts @@ -432,12 +432,33 @@ export class UpstreamProcess { this.#child = undefined; } - /** Mark the current endpoint dead, e.g. after an authentication failure. */ + /** + * Mark the current endpoint dead, e.g. after a timeout, a network error or an + * authentication failure. + * + * The endpoint is always dropped, including a spawned one: keeping it would + * make every later request reuse a URL that just failed. A spawned server is + * also killed here, so the next `resolve()` starts a replacement instead of + * leaving a hung child listening on the internal port. + */ markStale(reason: string): void { - if (this.#endpoint?.source !== "spawned") { - this.#endpoint = undefined; - } + const stale = this.#endpoint; + this.#endpoint = undefined; this.#lastError = reason; + + if (stale?.source !== "spawned") return; + const child = this.#child; + if (!child || child.exitCode !== null) return; + + // Clear the handle before killing: the exit of a server we no longer track + // must not overwrite `lastError` (see `#onChildExit`). + this.#child = undefined; + this.#log.warn({ pid: child.pid, reason }, "terminating the stale OpenCode server"); + try { + child.kill("SIGKILL"); + } catch { + /* already gone */ + } } } diff --git a/src/upstream/sessions.ts b/src/upstream/sessions.ts index de77e87..a8888f6 100644 --- a/src/upstream/sessions.ts +++ b/src/upstream/sessions.ts @@ -48,6 +48,12 @@ export interface AcquireInput { messages: InternalMessage[]; /** Fingerprint of the tool definitions, so sessions are not shared across tool sets. */ toolsHash: string; + /** + * Skip every cached candidate and start a new upstream session while keeping + * the conversation key, so the replacement is cached under the same key (used + * to recover after the upstream session vanished). + */ + fresh?: boolean; } export interface AcquireResult { @@ -125,6 +131,11 @@ export class SessionStore { if (messages.length === 0) { return { reused: false, pending: messages, messages, key, reason: "empty-conversation" }; } + if (input.fresh === true) { + // Force a brand-new upstream session but keep `key`, so `commit()` caches + // the replacement where the next turn will look for it. + return { reused: false, pending: messages, messages, key, reason: "forced-fresh" }; + } const candidates = this.#records.get(key); if (!candidates || candidates.length === 0) { @@ -356,12 +367,10 @@ export class SessionStore { const now = Date.now(); let restored = 0; for (const value of Object.values(parsed as Record)) { - if (typeof value !== "object" || value === null) continue; - const record = value as SessionRecord; - if (typeof record.sessionId !== "string" || typeof record.prefixHash !== "string") continue; - if (now - (record.lastUsedAt ?? 0) > this.#config.sessionTtlMs) continue; + const record = restoreRecord(value, now, this.#config.sessionTtlMs); + if (!record) continue; const candidates = this.#records.get(record.key) ?? []; - candidates.push({ ...record, busy: false }); + candidates.push(record); this.#records.set(record.key, candidates); restored += 1; } @@ -393,6 +402,64 @@ export class SessionStore { } } +function isNonEmptyString(value: unknown): value is string { + return typeof value === "string" && value.length > 0; +} + +function isFiniteNumber(value: unknown): value is number { + return typeof value === "number" && Number.isFinite(value); +} + +/** + * Validate one persisted record. + * + * A corrupt or older entry used to be restored anyway: with a missing + * `lastUsedAt` every comparison in `sweep()` is false (`NaN`), so the record was + * immortal. `lastUsedAt` is recovered from `createdAt` instead of dropping an + * otherwise usable session. + */ +function restoreRecord(value: unknown, now: number, ttlMs: number): SessionRecord | undefined { + if (typeof value !== "object" || value === null) return undefined; + const candidate = value as Record; + + const key = candidate["key"]; + const sessionId = candidate["sessionId"]; + const model = candidate["model"]; + const agent = candidate["agent"]; + const prefixHash = candidate["prefixHash"]; + if (!isNonEmptyString(key)) return undefined; + if (!isNonEmptyString(sessionId)) return undefined; + if (!isNonEmptyString(model)) return undefined; + if (!isNonEmptyString(agent)) return undefined; + if (!isNonEmptyString(prefixHash)) return undefined; + + const deliveredCount = candidate["deliveredCount"]; + if (!isFiniteNumber(deliveredCount) || deliveredCount <= 0) return undefined; + + const createdAt = candidate["createdAt"]; + if (!isFiniteNumber(createdAt)) return undefined; + + const persistedLastUsedAt = candidate["lastUsedAt"]; + const lastUsedAt = isFiniteNumber(persistedLastUsedAt) ? persistedLastUsedAt : createdAt; + if (now - lastUsedAt > ttlMs) return undefined; + + const variant = candidate["variant"]; + const reusedCount = candidate["reusedCount"]; + return { + key, + sessionId, + model, + agent, + variant: isNonEmptyString(variant) ? variant : undefined, + deliveredCount, + prefixHash, + createdAt, + lastUsedAt, + busy: false, + reusedCount: isFiniteNumber(reusedCount) && reusedCount >= 0 ? reusedCount : 0, + }; +} + /** * Stable conversation key derived from the request when no explicit key is sent. * diff --git a/test/admin.test.ts b/test/admin.test.ts new file mode 100644 index 0000000..43de1db --- /dev/null +++ b/test/admin.test.ts @@ -0,0 +1,58 @@ +/** + * Operational `/admin/*` endpoints. + * + * The config view is the only new one; the point of these tests is that it is + * authenticated and never echoes a secret back to the caller. + */ +import { describe, expect, it } from "vitest"; +import { buildServer } from "../src/server.js"; +import { createTestContext } from "./helpers/context.js"; + +const AUTH = { authorization: "Bearer test-key" }; + +describe("GET /admin/config", () => { + it("requires an API key", async () => { + const ctx = createTestContext(); + const app = await buildServer(ctx); + const response = await app.inject({ method: "GET", url: "/admin/config" }); + expect(response.statusCode).toBe(401); + expect((response.json() as { error?: unknown }).error).toBeDefined(); + await app.close(); + }); + + it("returns the effective configuration with every secret redacted", async () => { + const ctx = createTestContext({ + config: { + upstreamUrl: "http://127.0.0.1:20124", + upstreamPassword: "super-secret-upstream-password", + agentPermissions: [{ action: "bash", resource: "*", effect: "deny" }], + modelAliases: { "gpt-4o": "opencode/big-pickle" }, + }, + }); + const app = await buildServer(ctx); + const response = await app.inject({ method: "GET", url: "/admin/config", headers: AUTH }); + expect(response.statusCode).toBe(200); + + const body = response.json() as Record; + const auth = body["auth"] as Record; + // The key count and the default-key flag are reported; the keys themselves + // are not. + expect(auth["apiKeyCount"]).toBe(1); + expect(auth["usingDefaultApiKey"]).toBe(false); + + const upstream = body["upstream"] as Record; + expect(upstream["url"]).toBe("http://127.0.0.1:20124"); + expect(upstream["passwordConfigured"]).toBe(true); + + const agent = body["agent"] as Record; + expect(agent["permissionRuleCount"]).toBe(1); + const models = body["models"] as Record; + expect(models["aliases"]).toEqual(["gpt-4o"]); + + const serialised = response.body; + expect(serialised).not.toContain("test-key"); + expect(serialised).not.toContain("super-secret-upstream-password"); + expect(serialised).not.toContain("Bearer"); + await app.close(); + }); +}); \ No newline at end of file diff --git a/test/anthropic-count-tokens.test.ts b/test/anthropic-count-tokens.test.ts new file mode 100644 index 0000000..131dd45 --- /dev/null +++ b/test/anthropic-count-tokens.test.ts @@ -0,0 +1,85 @@ +/** + * `POST /v1/messages/count_tokens` estimate tests. + * + * The endpoint only estimates (`characters / 4`); these tests pin what the + * estimate must charge. In particular the tool-bridge instructions that + * `buildPrompt` prepends to the real turn, which the conversation and tool + * schema parts alone do not cover. + */ +import type { FastifyInstance } from "fastify"; +import { afterEach, describe, expect, it } from "vitest"; + +import { createToolBridge } from "../src/adapter/common/tools.js"; +import { buildServer } from "../src/server.js"; +import type { ToolDefinition } from "../src/types/internal.js"; +import { createTestContext } from "./helpers/context.js"; + +const AUTH = { authorization: "Bearer test-key" }; +const MODEL = "deepseek-v4.1-flash-free"; + +const apps: FastifyInstance[] = []; + +afterEach(async () => { + await Promise.all(apps.splice(0).map((app) => app.close())); +}); + +async function server(): Promise { + const app = await buildServer(createTestContext()); + apps.push(app); + return app; +} + +async function estimateInputTokens(app: FastifyInstance, payload: object): Promise { + const response = await app.inject({ + method: "POST", + url: "/v1/messages/count_tokens", + headers: { ...AUTH, "content-type": "application/json" }, + payload, + }); + expect(response.statusCode).toBe(200); + return (JSON.parse(response.body) as { input_tokens: number }).input_tokens; +} + +describe("POST /v1/messages/count_tokens estimate", () => { + it("charges the tool-bridge instructions when tools are declared", async () => { + const app = await server(); + const messages = [{ role: "user", content: "hi" }]; + + const withoutTools = await estimateInputTokens(app, { model: MODEL, messages }); + const withTools = await estimateInputTokens(app, { + model: MODEL, + messages, + tools: [{ name: "noop", description: "Do nothing", input_schema: { type: "object", properties: {} } }], + }); + + const definition: ToolDefinition = { + name: "noop", + description: "Do nothing", + parameters: { type: "object", properties: {} }, + }; + const instructions = createToolBridge([definition]).instructions; + expect(instructions.length).toBeGreaterThan(0); + expect(withTools - withoutTools).toBeGreaterThanOrEqual(instructions.length / 4); + + // Without tools the estimate is the conversation estimate alone: the single + // "hi" message is 1 token plus the 4-token per-message overhead. + expect(withoutTools).toBe(5); + }); + + it("does not charge the bridge when tool_choice disables tool use", async () => { + const app = await server(); + const messages = [{ role: "user", content: "hi" }]; + const tools = [{ name: "noop", description: "Do nothing", input_schema: { type: "object", properties: {} } }]; + + const auto = await estimateInputTokens(app, { model: MODEL, messages, tools }); + const disabled = await estimateInputTokens(app, { + model: MODEL, + messages, + tools, + tool_choice: { type: "none" }, + }); + + expect(disabled).toBeLessThan(auto); + expect(createToolBridge([{ name: "noop", description: "Do nothing", parameters: { type: "object" } }], "none").instructions).toBe(""); + }); +}); diff --git a/test/anthropic.test.ts b/test/anthropic.test.ts index 35144a3..e8cc83e 100644 --- a/test/anthropic.test.ts +++ b/test/anthropic.test.ts @@ -4,6 +4,7 @@ * Everything runs against the scripted completion runner in * `test/helpers/context.ts`; no live OpenCode server is involved. */ +import { createServer } from "node:http"; import type { FastifyInstance } from "fastify"; import { afterEach, describe, expect, it } from "vitest"; @@ -40,13 +41,19 @@ interface StreamFrame { type: string; index?: number; content_block?: { type?: string; id?: string; name?: string }; - delta?: { type?: string; stop_reason?: string | null; partial_json?: string }; + delta?: { type?: string; stop_reason?: string | null; partial_json?: string; signature?: string }; usage?: Record; message?: { id?: string; model?: string; role?: string }; } -function usage(inputTokens: number, outputTokens: number): Usage { - return { ...EMPTY_USAGE, inputTokens, outputTokens, totalTokens: inputTokens + outputTokens }; +function usage(inputTokens: number, outputTokens: number, reasoningTokens = 0): Usage { + return { + ...EMPTY_USAGE, + inputTokens, + outputTokens, + reasoningTokens, + totalTokens: inputTokens + outputTokens + reasoningTokens, + }; } const apps: FastifyInstance[] = []; @@ -175,6 +182,52 @@ describe("POST /v1/messages", () => { expect(capture.request?.maxTokens).toBe(64); }); + it("resolves the media blocks of one message concurrently, keeping declaration order", async () => { + const fixture = createServer((_request, response) => { + setTimeout(() => { + response.writeHead(200, { "content-type": "image/png" }); + response.end(Buffer.from(PNG_1X1, "base64")); + }, 60); + }); + await new Promise((resolve) => fixture.listen(0, "127.0.0.1", resolve)); + const address = fixture.address(); + if (address === null || typeof address === "string") throw new Error("fixture server did not bind a TCP port"); + const base = `http://127.0.0.1:${address.port}`; + + const capture: { request?: InternalRequest } = {}; + const { app } = await serverWith({ + onRun: (request) => { + capture.request = request; + }, + }); + try { + const started = performance.now(); + const response = await post(app, "/v1/messages", { + model: MODEL, + max_tokens: 64, + messages: [ + { + role: "user", + content: [ + { type: "image", source: { type: "url", url: `${base}/first.png` } }, + { type: "image", source: { type: "url", url: `${base}/second.png` } }, + ], + }, + ], + }); + const elapsed = performance.now() - started; + + expect(response.statusCode).toBe(200); + const origins = capture.request?.messages[0]?.attachments?.map((attachment) => attachment.origin); + expect(origins).toEqual([`${base}/first.png`, `${base}/second.png`]); + // Serial resolution would need at least 120 ms for two 60 ms responses. + expect(elapsed).toBeLessThan(110); + } finally { + fixture.closeAllConnections(); + await new Promise((resolve) => fixture.close(() => resolve())); + } + }); + it("turns scripted tool calls into tool_use blocks with parsed input", async () => { const events: CompletionEvent[] = [ { @@ -240,10 +293,181 @@ describe("POST /v1/messages", () => { expect(body.content[0]?.["thinking"]).toBe("Weighing the options."); const signature = body.content[0]?.["signature"]; expect(typeof signature).toBe("string"); - expect(Buffer.from(String(signature), "base64").toString("utf8")).toBe(`opencode-api:${body.id}`); + // The signature subject is the upstream assistant message id of the turn. + expect(Buffer.from(String(signature), "base64").toString("utf8")).toBe("opencode-api:msg_think"); expect(body.content[1]).toEqual({ type: "text", text: "Answer." }); }); + it("streams a signature_delta before the thinking block stop, matching the buffered signature", async () => { + const events: CompletionEvent[] = [ + { + kind: "start", + sessionId: "ses_sig", + messageId: "msg_sig", + model: CANONICAL_MODEL, + agent: "build", + reusedSession: false, + reasoningEnabled: true, + }, + { kind: "reasoning_delta", text: "Considering.", ordinal: 0 }, + { kind: "reasoning_end", text: "Considering.", ordinal: 0 }, + { kind: "text_delta", text: "Done.", ordinal: 0 }, + { kind: "end", finishReason: "stop", usage: usage(5, 2), messageId: "msg_sig" }, + ]; + const { app } = await serverWith({ script: () => events }); + const payload = (stream: boolean) => ({ + model: MODEL, + max_tokens: 64, + stream, + thinking: { type: "enabled", budget_tokens: 2_048 }, + messages: [{ role: "user", content: "Think about it" }], + }); + + const streamed = await post(app, "/v1/messages", payload(true)); + const buffered = await post(app, "/v1/messages", payload(false)); + expect(streamed.statusCode).toBe(200); + expect(buffered.statusCode).toBe(200); + + const payloads = parseSse(streamed.body).map((frame) => JSON.parse(frame.data) as StreamFrame); + const signatureAt = payloads.findIndex( + (frame) => frame.type === "content_block_delta" && frame.delta?.type === "signature_delta", + ); + const thinkingStopAt = payloads.findIndex( + (frame) => frame.type === "content_block_stop" && frame.index === 0, + ); + expect(signatureAt).toBeGreaterThan(-1); + expect(thinkingStopAt).toBeGreaterThan(signatureAt); + + const bufferedBody = JSON.parse(buffered.body) as AnthropicResponseBody; + const bufferedSignature = bufferedBody.content[0]?.["signature"]; + expect(typeof bufferedSignature).toBe("string"); + expect(payloads[signatureAt]?.delta?.signature).toBe(bufferedSignature); + expect(Buffer.from(String(bufferedSignature), "base64").toString("utf8")).toBe("opencode-api:msg_sig"); + }); + + it("keeps one thinking and one text block across agent steps", async () => { + const events: CompletionEvent[] = [ + { + kind: "start", + sessionId: "ses_multi", + messageId: "msg_multi", + model: CANONICAL_MODEL, + agent: "build", + reusedSession: false, + reasoningEnabled: true, + }, + { kind: "reasoning_delta", text: "Weighing.", ordinal: 0 }, + { kind: "reasoning_end", text: "Weighing.", ordinal: 0 }, + { kind: "text_delta", text: "First", ordinal: 0 }, + { kind: "text_end", text: "First", ordinal: 0 }, + { kind: "text_delta", text: " second", ordinal: 0 }, + { kind: "text_end", text: " second", ordinal: 0 }, + { kind: "end", finishReason: "stop", usage: usage(8, 4), messageId: "msg_multi" }, + ]; + const { app } = await serverWith({ script: () => events }); + const payload = (stream: boolean) => ({ + model: MODEL, + max_tokens: 64, + stream, + thinking: { type: "enabled", budget_tokens: 2_048 }, + messages: [{ role: "user", content: "Two steps" }], + }); + + const streamed = await post(app, "/v1/messages", payload(true)); + const buffered = await post(app, "/v1/messages", payload(false)); + expect(streamed.statusCode).toBe(200); + expect(buffered.statusCode).toBe(200); + + const payloads = parseSse(streamed.body).map((frame) => JSON.parse(frame.data) as StreamFrame); + const startedTypes = payloads + .filter((frame) => frame.type === "content_block_start") + .map((frame) => frame.content_block?.type); + const bufferedBody = JSON.parse(buffered.body) as AnthropicResponseBody; + expect(startedTypes).toEqual(bufferedBody.content.map((block) => block["type"])); + expect(startedTypes).toEqual(["thinking", "text"]); + + // The second step continues the open text block instead of opening a new one. + const textDeltas = payloads.filter((frame) => frame.delta?.type === "text_delta"); + expect(textDeltas.map((frame) => frame.index)).toEqual([1, 1]); + }); + + it("uses the assistant id reported by the end event for the thinking signature", async () => { + const events: CompletionEvent[] = [ + { + kind: "start", + sessionId: "ses_late", + messageId: "", + model: CANONICAL_MODEL, + agent: "build", + reusedSession: false, + reasoningEnabled: true, + }, + { kind: "reasoning_delta", text: "Only thinking.", ordinal: 0 }, + { kind: "reasoning_end", text: "Only thinking.", ordinal: 0 }, + { kind: "end", finishReason: "stop", usage: usage(4, 1), messageId: "msg_late" }, + ]; + const { app } = await serverWith({ script: () => events }); + + const streamed = await post(app, "/v1/messages", { + model: MODEL, + max_tokens: 64, + stream: true, + thinking: { type: "enabled", budget_tokens: 2_048 }, + messages: [{ role: "user", content: "Think only" }], + }); + const payloads = parseSse(streamed.body).map((frame) => JSON.parse(frame.data) as StreamFrame); + const signature = payloads.find((frame) => frame.delta?.type === "signature_delta")?.delta?.signature; + + expect(Buffer.from(String(signature), "base64").toString("utf8")).toBe("opencode-api:msg_late"); + }); + + it("matches the buffered signature when the assistant id only arrives on step events", async () => { + // The real orchestrator yields `start` before the upstream id is known and + // reports it on the step-scoped end events; both adapters must key the + // thinking signature on the same subject in that case. + const events: CompletionEvent[] = [ + { + kind: "start", + sessionId: "ses_step_sig", + messageId: "", + model: CANONICAL_MODEL, + agent: "build", + reusedSession: false, + reasoningEnabled: true, + }, + { kind: "reasoning_delta", text: "Considering.", ordinal: 0 }, + { kind: "reasoning_end", text: "Considering.", ordinal: 0, messageId: "msg_step_sig" }, + { kind: "text_delta", text: "Done.", ordinal: 0 }, + { kind: "text_end", text: "Done.", ordinal: 0, messageId: "msg_step_sig" }, + { kind: "end", finishReason: "stop", usage: usage(5, 2), messageId: "msg_step_sig" }, + ]; + const { app } = await serverWith({ script: () => events }); + const payload = (stream: boolean) => ({ + model: MODEL, + max_tokens: 64, + stream, + thinking: { type: "enabled", budget_tokens: 2_048 }, + messages: [{ role: "user", content: "Think about it" }], + }); + + const streamed = await post(app, "/v1/messages", payload(true)); + const buffered = await post(app, "/v1/messages", payload(false)); + expect(streamed.statusCode).toBe(200); + expect(buffered.statusCode).toBe(200); + + const payloads = parseSse(streamed.body).map((frame) => JSON.parse(frame.data) as StreamFrame); + const signatureAt = payloads.findIndex( + (frame) => frame.type === "content_block_delta" && frame.delta?.type === "signature_delta", + ); + expect(signatureAt).toBeGreaterThan(-1); + + const bufferedBody = JSON.parse(buffered.body) as AnthropicResponseBody; + const bufferedSignature = bufferedBody.content[0]?.["signature"]; + expect(typeof bufferedSignature).toBe("string"); + expect(Buffer.from(String(bufferedSignature), "base64").toString("utf8")).toBe("opencode-api:msg_step_sig"); + expect(payloads[signatureAt]?.delta?.signature).toBe(bufferedSignature); + }); + it("maps a length finish reason to max_tokens", async () => { const events: CompletionEvent[] = [ { @@ -323,6 +547,7 @@ describe("POST /v1/messages", () => { "message_start", "content_block_start", "content_block_delta", + "content_block_delta", "content_block_stop", "content_block_start", "content_block_delta", @@ -351,10 +576,11 @@ describe("POST /v1/messages", () => { const deltas = payloads.filter((payload) => payload.type === "content_block_delta"); expect(deltas.map((payload) => [payload.index, payload.delta?.type])).toEqual([ [0, "thinking_delta"], + [0, "signature_delta"], [1, "text_delta"], [2, "input_json_delta"], ]); - expect(deltas[2]?.delta?.partial_json).toBe('{"q":"x"}'); + expect(deltas[3]?.delta?.partial_json).toBe('{"q":"x"}'); const stops = payloads.filter((payload) => payload.type === "content_block_stop"); expect(stops.map((payload) => payload.index)).toEqual([0, 1, 2]); @@ -373,6 +599,90 @@ describe("POST /v1/messages", () => { expect(response.body).not.toContain("[DONE]"); }); + it("counts reasoning tokens inside output_tokens in both modes", async () => { + const events: CompletionEvent[] = [ + { + kind: "start", + sessionId: "ses_usage", + messageId: "msg_usage", + model: CANONICAL_MODEL, + agent: "build", + reusedSession: false, + reasoningEnabled: true, + }, + { kind: "text_delta", text: "Answer.", ordinal: 0 }, + { kind: "usage", usage: usage(10, 3, 5) }, + { kind: "end", finishReason: "stop", usage: usage(10, 3, 5), messageId: "msg_usage" }, + ]; + const { app } = await serverWith({ script: () => events }); + const payload = (stream: boolean) => ({ + model: MODEL, + max_tokens: 64, + stream, + thinking: { type: "enabled", budget_tokens: 2_048 }, + messages: [{ role: "user", content: "Count the tokens" }], + }); + + const streamed = await post(app, "/v1/messages", payload(true)); + const buffered = await post(app, "/v1/messages", payload(false)); + expect(streamed.statusCode).toBe(200); + expect(buffered.statusCode).toBe(200); + + const bufferedBody = JSON.parse(buffered.body) as AnthropicResponseBody; + expect(bufferedBody.usage).toEqual({ + input_tokens: 10, + output_tokens: 8, + cache_creation_input_tokens: 0, + cache_read_input_tokens: 0, + }); + + const payloads = parseSse(streamed.body).map((frame) => JSON.parse(frame.data) as StreamFrame); + const messageDelta = payloads.find((frame) => frame.type === "message_delta"); + expect(messageDelta?.usage).toEqual({ + output_tokens: 8, + input_tokens: 10, + cache_read_input_tokens: 0, + cache_creation_input_tokens: 0, + }); + }); + + it("normalises streamed tool-call arguments exactly like the buffered payload", async () => { + const events: CompletionEvent[] = [ + { + kind: "start", + sessionId: "ses_args", + messageId: "msg_args", + model: CANONICAL_MODEL, + agent: "build", + reusedSession: false, + reasoningEnabled: false, + }, + { kind: "tool_calls", calls: [{ id: "toolu_arr", name: "lookup", arguments: "[1,2]" }] }, + { kind: "usage", usage: usage(9, 6) }, + { kind: "end", finishReason: "tool_calls", usage: usage(9, 6), messageId: "msg_args" }, + ]; + const { app } = await serverWith({ script: () => events }); + const payload = (stream: boolean) => ({ + model: MODEL, + max_tokens: 64, + stream, + messages: [{ role: "user", content: "Look it up" }], + tools: [{ name: "lookup", input_schema: { type: "object" } }], + }); + + const buffered = await post(app, "/v1/messages", payload(false)); + const streamed = await post(app, "/v1/messages", payload(true)); + expect(buffered.statusCode).toBe(200); + expect(streamed.statusCode).toBe(200); + + const bufferedBody = JSON.parse(buffered.body) as AnthropicResponseBody; + expect(bufferedBody.content).toEqual([{ type: "tool_use", id: "toolu_arr", name: "lookup", input: {} }]); + + const payloads = parseSse(streamed.body).map((frame) => JSON.parse(frame.data) as StreamFrame); + const inputDelta = payloads.find((frame) => frame.delta?.type === "input_json_delta"); + expect(inputDelta?.delta?.partial_json).toBe("{}"); + }); + it("emits an SSE error frame for a mid-stream failure", async () => { const events: CompletionEvent[] = [ { diff --git a/test/client.test.ts b/test/client.test.ts index c7f28b4..e91e9fa 100644 --- a/test/client.test.ts +++ b/test/client.test.ts @@ -8,7 +8,7 @@ import http from "node:http"; import type { AddressInfo } from "node:net"; import { afterEach, describe, expect, it } from "vitest"; import { createLogger } from "../src/logger.js"; -import { createMetrics } from "../src/metrics/registry.js"; +import { createMetrics, type Metrics } from "../src/metrics/registry.js"; import { OpencodeClient } from "../src/upstream/client.js"; import type { UpstreamProcess } from "../src/upstream/process.js"; import { testConfig } from "./helpers/context.js"; @@ -16,13 +16,17 @@ import { testConfig } from "./helpers/context.js"; interface FakeUpstream { url: string; client: OpencodeClient; + metrics: Metrics; close: () => Promise; } const open: FakeUpstream[] = []; /** Start a server that accepts the request and never answers. */ -async function hangingUpstream(upstreamRequestTimeoutMs: number): Promise { +async function hangingUpstream( + upstreamRequestTimeoutMs: number, + clientOptions: { catalogueTimeoutMs?: number } = {}, +): Promise { const server = http.createServer(() => { /* deliberately never respond */ }); @@ -37,10 +41,11 @@ async function hangingUpstream(upstreamRequestTimeoutMs: number): Promise undefined, } as unknown as UpstreamProcess; - const client = new OpencodeClient(upstream, config, log, metrics); + const client = new OpencodeClient(upstream, config, log, metrics, clientOptions); const item: FakeUpstream = { url: `http://127.0.0.1:${port}`, client, + metrics, close: async () => { server.closeAllConnections(); await new Promise((resolve) => server.close(() => resolve())); @@ -50,6 +55,24 @@ async function hangingUpstream(upstreamRequestTimeoutMs: number): Promise; + value: number; +} + +interface MetricEntry { + name: string; + type: string; + values?: MetricValueEntry[]; +} + +/** Read one metric out of `registry.getMetricsAsJSON()` without assuming its type. */ +async function metricValues(upstream: FakeUpstream, name: string): Promise { + const json = (await upstream.metrics.registry.getMetricsAsJSON()) as unknown as MetricEntry[]; + return json.find((entry) => entry.name === name)?.values ?? []; +} + afterEach(async () => { while (open.length > 0) { const item = open.pop(); @@ -59,7 +82,7 @@ afterEach(async () => { describe("OpencodeClient", () => { it("reports its own request timeout as a 504", async () => { - const upstream = await hangingUpstream(150); + const upstream = await hangingUpstream(150, { catalogueTimeoutMs: 150 }); await expect(upstream.client.listModels()).rejects.toMatchObject({ status: 504, @@ -68,6 +91,41 @@ describe("OpencodeClient", () => { }); }); + it("records upstream latency for a request that timed out", async () => { + const upstream = await hangingUpstream(150, { catalogueTimeoutMs: 150 }); + + await expect(upstream.client.listModels()).rejects.toMatchObject({ code: "upstream_timeout" }); + + // The histogram used to be observed only after `fetch()` resolved, so exactly + // the slow cases (timeouts, 5xx, network errors) were missing from it. + const duration = await metricValues(upstream, "opencode_api_upstream_request_duration_seconds"); + const count = duration.find((value) => value.metricName === "opencode_api_upstream_request_duration_seconds_count"); + const sum = duration.find((value) => value.metricName === "opencode_api_upstream_request_duration_seconds_sum"); + expect(count?.value).toBe(1); + expect(sum?.value).toBeGreaterThan(0); + + const requests = await metricValues(upstream, "opencode_api_upstream_requests_total"); + expect(requests).toHaveLength(1); + expect(requests[0]?.value).toBe(1); + expect(requests[0]?.labels?.["outcome"]).toBe("timeout"); + }); + + it("gives catalogue requests a short timeout instead of the turn budget", async () => { + const upstream = await hangingUpstream(60_000, { catalogueTimeoutMs: 300 }); + + // The 60 s configured request timeout must not apply to any catalogue call. + const calls: Array<() => Promise> = [ + () => upstream.client.listModels(), + () => upstream.client.listProviders(), + () => upstream.client.listAgents(), + ]; + for (const call of calls) { + const started = Date.now(); + await expect(call()).rejects.toMatchObject({ code: "upstream_timeout" }); + expect(Date.now() - started).toBeLessThan(5_000); + } + }); + it("still reports a caller abort as 499", async () => { const upstream = await hangingUpstream(10_000); const controller = new AbortController(); @@ -78,5 +136,12 @@ describe("OpencodeClient", () => { setTimeout(() => controller.abort(), 50); await expect(pending).rejects.toMatchObject({ status: 499 }); + + // An aborted request is a slow path too, so its latency must be observed. + const duration = await metricValues(upstream, "opencode_api_upstream_request_duration_seconds"); + const count = duration.find( + (value) => value.metricName === "opencode_api_upstream_request_duration_seconds_count", + ); + expect(count?.value).toBe(1); }); }); \ No newline at end of file diff --git a/test/completion.test.ts b/test/completion.test.ts index 1b2e68b..7771360 100644 --- a/test/completion.test.ts +++ b/test/completion.test.ts @@ -1,6 +1,7 @@ import { describe, expect, it } from "vitest"; import { createLogger } from "../src/logger.js"; import { createMetrics } from "../src/metrics/registry.js"; +import { ApiError } from "../src/errors.js"; import { collectCompletion, runCompletion, type CompletionDeps } from "../src/upstream/completion.js"; import { EventHub, type EventListener } from "../src/upstream/events.js"; import { ModelRegistry } from "../src/upstream/models.js"; @@ -25,6 +26,7 @@ interface Harness { function harness( script: (sessionId: string, call: number) => OpencodeEvent[], configOverrides: Parameters[0] = {}, + options: { ensureConnected?: () => Promise } = {}, ): Harness { const config = testConfig({ modelCacheTtlMs: 60_000, ...configOverrides }); const log = createLogger(config); @@ -44,7 +46,7 @@ function harness( set.delete(listener); }; }, - ensureConnected: async () => true, + ensureConnected: options.ensureConnected ?? (async () => true), start: () => undefined, stop: async () => undefined, onReconnect: () => () => undefined, @@ -200,6 +202,18 @@ describe("collectCompletion", () => { expect(promptCalls[0]?.text).toContain("Hello"); }); + it("asks for a single bridged call when parallel tool calls are disabled", async () => { + const { deps, promptCalls } = harness(() => simpleTurn("ok")); + await collectCompletion( + request({ + tools: [{ name: "get_weather", description: "weather", parameters: { type: "object" } }], + parallelToolCalls: false, + }), + deps, + ); + expect(promptCalls[0]?.text).toContain("at most one tool call block"); + }); + it("renders the requested JSON output format into the prompt", async () => { const { deps, promptCalls } = harness(() => simpleTurn('{"ok":true}')); await collectCompletion( @@ -324,6 +338,122 @@ describe("collectCompletion", () => { expect(result.nativeTools[1]?.input).toEqual({ command: "ls" }); expect(result.calls).toEqual([]); }); + + it("fails fast when the event stream is not connected", async () => { + const { deps, promptCalls, sessions } = harness(() => simpleTurn("ok"), {}, { ensureConnected: async () => false }); + + await expect(collectCompletion(request(), deps)).rejects.toMatchObject({ + status: 503, + code: "event_stream_unavailable", + }); + + // No upstream turn may be started without a stream to receive its events. + expect(promptCalls).toHaveLength(0); + expect(sessions.list().every((record) => !record.busy)).toBe(true); + }); + + it("yields an error event instead of throwing when the stale-session replay fails", async () => { + const { deps, sessions } = harness((_sessionId, call) => { + if (call === 0) return simpleTurn("Hi there"); + if (call === 1) throw new ApiError(404, "not_found_error", "session vanished upstream"); + throw new ApiError(500, "internal_error", "replay failed"); + }); + + await collectCompletion( + request({ conversationKey: "stale-replay", messages: [{ role: "user", text: "Hello" }] }), + deps, + ); + + const events: CompletionEvent[] = []; + let thrown: unknown; + try { + for await (const item of runCompletion( + request({ + conversationKey: "stale-replay", + messages: [ + { role: "user", text: "Hello" }, + { role: "assistant", text: "Hi there" }, + { role: "user", text: "again" }, + ], + }), + deps, + )) { + events.push(item); + } + } catch (error) { + thrown = error; + } + + expect(thrown).toBeUndefined(); + expect(events.at(-1)?.kind).toBe("error"); + expect(sessions.list().every((record) => !record.busy)).toBe(true); + }); + + it("caches the replayed session under the conversation key so the next turn reuses it", async () => { + const { deps, sessions, createSessionCalls } = harness((_sessionId, call) => { + if (call === 0) return simpleTurn("Hi there"); + if (call === 1) throw new ApiError(404, "not_found_error", "session vanished upstream"); + return simpleTurn("recovered"); + }); + + const first = [{ role: "user" as const, text: "Hello" }]; + const second = [...first, { role: "assistant" as const, text: "Hi there" }, { role: "user" as const, text: "again" }]; + + await collectCompletion(request({ conversationKey: "stale-replay", messages: first }), deps); + await collectCompletion(request({ conversationKey: "stale-replay", messages: second }), deps); + + // One session for the first turn, one for the replay. + expect(createSessionCalls).toHaveLength(2); + + // The replacement must be cached under the conversation key, not under the + // one-shot `:fresh:` key the replay used to derive. + const records = sessions.list(); + expect(records).toHaveLength(1); + expect(records[0]?.key).toBe("stale-replay"); + expect(records[0]?.busy).toBe(false); + + // A third turn with the same conversation key reuses it instead of creating + // yet another upstream session. + await collectCompletion( + request({ + conversationKey: "stale-replay", + messages: [...second, { role: "assistant", text: "recovered" }, { role: "user", text: "one more" }], + }), + deps, + ); + expect(createSessionCalls).toHaveLength(2); + }); + + it("keeps consuming after a non-tool step end when no bridged call was parsed", async () => { + const { deps } = harness(() => [ + event("session.step.started", { assistantMessageID: "msg_a1" }), + event("session.step.ended", { + assistantMessageID: "msg_a1", + finish: "stop", + tokens: { input: 10, output: 2, reasoning: 0, cache: { read: 0, write: 0 } }, + }), + event("session.text.delta", { assistantMessageID: "msg_a1", ordinal: 0, delta: "late" }), + event("session.execution.succeeded", { assistantMessageID: "msg_a1" }), + ]); + + const events: CompletionEvent[] = []; + for await (const item of runCompletion( + request({ stream: true, tools: [{ name: "get_weather", description: "weather", parameters: { type: "object" } }] }), + deps, + )) { + events.push(item); + } + + const text = events + .filter((item): item is Extract => item.kind === "text_delta") + .map((item) => item.text) + .join(""); + expect(text).toBe("late"); + + const ends = events.filter((item): item is Extract => item.kind === "end"); + expect(ends).toHaveLength(1); + expect(ends[0]?.finishReason).toBe("stop"); + }); }); describe("runCompletion streaming", () => { @@ -343,6 +473,43 @@ describe("runCompletion streaming", () => { expect(text).toBe("one two three"); }); + it("carries the upstream assistant id on the step-scoped text_end and reasoning_end", async () => { + const { deps } = harness(() => [ + event("session.step.started", { assistantMessageID: "msg_step", agent: "build" }), + event("session.reasoning.delta", { assistantMessageID: "msg_step", ordinal: 0, delta: "weighing" }), + event("session.reasoning.ended", { assistantMessageID: "msg_step", ordinal: 0, text: "weighing" }), + event("session.text.delta", { assistantMessageID: "msg_step", ordinal: 0, delta: "answer" }), + event("session.text.ended", { assistantMessageID: "msg_step", ordinal: 0, text: "answer" }), + event("session.step.ended", { + assistantMessageID: "msg_step", + finish: "stop", + tokens: { input: 3, output: 2, reasoning: 1, cache: { read: 0, write: 0 } }, + }), + event("session.execution.succeeded", { assistantMessageID: "msg_step" }), + ]); + + const events: CompletionEvent[] = []; + for await (const item of runCompletion( + request({ stream: true, reasoning: { enabled: true, effort: "medium" } }), + deps, + )) { + events.push(item); + } + + // The step-scoped events come first; `finalise()` emits its own aggregated + // pair later in the turn. + const reasoningEnd = events.find( + (item): item is Extract => item.kind === "reasoning_end", + ); + const textEnd = events.find( + (item): item is Extract => item.kind === "text_end", + ); + expect(reasoningEnd?.text).toBe("weighing"); + expect(reasoningEnd?.messageId).toBe("msg_step"); + expect(textEnd?.text).toBe("answer"); + expect(textEnd?.messageId).toBe("msg_step"); + }); + it("reuses a sticky session for the next turn and only sends the new message", async () => { const { deps, promptCalls, createSessionCalls } = harness(() => simpleTurn("Hi there")); diff --git a/test/config.test.ts b/test/config.test.ts index f2967df..e34e57d 100644 --- a/test/config.test.ts +++ b/test/config.test.ts @@ -1,5 +1,5 @@ import os from "node:os"; -import { afterEach, describe, expect, it } from "vitest"; +import { afterEach, describe, expect, it, vi } from "vitest"; import { isAuthorized } from "../src/auth.js"; import { DEFAULT_API_KEY, loadConfig, resetConfigCache, type Config } from "../src/config.js"; import { buildServer } from "../src/server.js"; @@ -7,6 +7,16 @@ import { createTestContext } from "./helpers/context.js"; const KEY_VARS = ["OPENCODE_API_KEYS", "OPENCODE_API_KEY"] as const; +/** Variables a test changed, with their original value, restored after each test. */ +const savedEnv = new Map(); + +function setEnv(name: string, value: string | undefined): void { + if (!savedEnv.has(name)) savedEnv.set(name, process.env[name]); + if (value === undefined) delete process.env[name]; + else process.env[name] = value; + resetConfigCache(); +} + function clearKeyEnv(): void { for (const name of KEY_VARS) delete process.env[name]; resetConfigCache(); @@ -24,6 +34,12 @@ function config(overrides: Partial = {}): Config { } afterEach(() => { + for (const [name, value] of savedEnv) { + if (value === undefined) delete process.env[name]; + else process.env[name] = value; + } + savedEnv.clear(); + vi.restoreAllMocks(); clearKeyEnv(); }); @@ -90,4 +106,97 @@ describe("default API key", () => { await app.close(); }); +}); + +describe("integer parsing", () => { + it("falls back to the default for a value that is not a whole integer", () => { + const warn = vi.spyOn(console, "warn").mockImplementation(() => undefined); + setEnv("OPENCODE_REQUEST_TIMEOUT_MS", "10m"); + expect(config().upstreamRequestTimeoutMs).toBe(600_000); + expect(warn).toHaveBeenCalledTimes(1); + expect(String(warn.mock.calls[0]?.[0])).toContain("OPENCODE_REQUEST_TIMEOUT_MS"); + }); + + it("does not read a numeric prefix out of a hexadecimal-looking value", () => { + const warn = vi.spyOn(console, "warn").mockImplementation(() => undefined); + setEnv("OPENCODE_START_TIMEOUT_MS", "0x1000"); + expect(config().upstreamStartTimeoutMs).toBe(30_000); + expect(warn).toHaveBeenCalledTimes(1); + }); + + it("accepts a whole integer", () => { + setEnv("OPENCODE_SESSION_MAX", "25"); + expect(config().sessionMaxEntries).toBe(25); + }); + + it("still treats an empty value as unset", () => { + const warn = vi.spyOn(console, "warn").mockImplementation(() => undefined); + setEnv("OPENCODE_REQUEST_TIMEOUT_MS", ""); + expect(config().upstreamRequestTimeoutMs).toBe(600_000); + expect(warn).not.toHaveBeenCalled(); + }); +}); + +describe("OPENCODE_AGENT_PERMISSIONS", () => { + it("refuses to start when the JSON is not an array", () => { + setEnv("OPENCODE_AGENT_PERMISSIONS", '{"action":"*"}'); + expect(() => config()).toThrow(/OPENCODE_AGENT_PERMISSIONS/); + }); + + it("refuses to start when a rule is not an object", () => { + setEnv("OPENCODE_AGENT_PERMISSIONS", '["bash"]'); + expect(() => config()).toThrow(/OPENCODE_AGENT_PERMISSIONS\[0\]/); + }); + + it("defaults a missing effect to ask, never allow", () => { + setEnv("OPENCODE_AGENT_PERMISSIONS", '[{"action":"bash","resource":"*"}]'); + expect(config().agentPermissions).toEqual([{ action: "bash", resource: "*", effect: "ask" }]); + }); + + it("keeps explicit rules", () => { + setEnv("OPENCODE_AGENT_PERMISSIONS", '[{"action":"webfetch","resource":"*","effect":"deny"}]'); + expect(config().agentPermissions).toEqual([{ action: "webfetch", resource: "*", effect: "deny" }]); + }); + + it("keeps an explicitly empty ruleset empty instead of treating it as unset", () => { + setEnv("OPENCODE_AGENT_PERMISSIONS", "[]"); + expect(config().agentPermissions).toEqual([]); + }); +}); + +describe("OPENCODE_MODEL_ALIASES", () => { + it("refuses to start when the JSON is not an object", () => { + setEnv("OPENCODE_MODEL_ALIASES", "[]"); + expect(() => config()).toThrow(/OPENCODE_MODEL_ALIASES/); + }); + + it("refuses to start when an alias is not a string", () => { + setEnv("OPENCODE_MODEL_ALIASES", '{"gpt-4o":42}'); + expect(() => config()).toThrow(/OPENCODE_MODEL_ALIASES/); + }); + + it("parses a valid alias map", () => { + setEnv("OPENCODE_MODEL_ALIASES", '{"gpt-4o":"opencode/big-pickle"}'); + expect(config().modelAliases).toEqual({ "gpt-4o": "opencode/big-pickle" }); + }); + + it("keeps an explicitly empty alias map empty instead of treating it as unset", () => { + setEnv("OPENCODE_MODEL_ALIASES", "{}"); + expect(config().modelAliases).toEqual({}); + }); +}); + +describe("explicitly empty key configuration", () => { + it("refuses to start instead of installing the published default key", () => { + setEnv("OPENCODE_API_KEYS", " , "); + expect(() => config()).toThrow(/no usable key/); + }); + + it("still uses the default key when the variable is unset", () => { + setEnv("OPENCODE_API_KEYS", ""); + setEnv("OPENCODE_API_KEY", undefined); + const resolved = config(); + expect(resolved.apiKeys).toEqual([DEFAULT_API_KEY]); + expect(resolved.usingDefaultApiKey).toBe(true); + }); }); \ No newline at end of file diff --git a/test/events.test.ts b/test/events.test.ts index 3d48829..60ae49b 100644 --- a/test/events.test.ts +++ b/test/events.test.ts @@ -13,11 +13,17 @@ interface Fixture { url: string; close: () => Promise; connectionCount: () => number; + /** Connections whose response the fixture server observed closing. */ + closedCount: () => number; } /** Start a fake `/api/event` server and point an EventHub at it. */ -async function fixture(writeFrames: (response: http.ServerResponse, connection: number) => () => void): Promise { +async function fixture( + writeFrames: (response: http.ServerResponse, connection: number) => () => void, + options: { idleTimeoutMs?: number } = {}, +): Promise { let connections = 0; + let closed = 0; const cleanups: Array<() => void> = []; const server = http.createServer((request, response) => { @@ -27,6 +33,9 @@ async function fixture(writeFrames: (response: http.ServerResponse, connection: return; } connections += 1; + response.on("close", () => { + closed += 1; + }); response.writeHead(200, { "content-type": "text/event-stream" }); cleanups.push(writeFrames(response, connections)); }); @@ -42,15 +51,18 @@ async function fixture(writeFrames: (response: http.ServerResponse, connection: resolve: async () => ({ url, password: undefined, source: "env" as const }), } as unknown as UpstreamProcess; - const hub = new EventHub(upstream, config, log, metrics); + const hub = new EventHub(upstream, config, log, metrics, options); return { hub, url, connectionCount: () => connections, + closedCount: () => closed, close: async () => { for (const cleanup of cleanups) cleanup(); await hub.stop(); + // Never let a leaked response body hang the suite teardown. + server.closeAllConnections(); await new Promise((resolve) => server.close(() => resolve())); }, }; @@ -201,6 +213,48 @@ describe("EventHub", () => { expect(deltas).toContain("conn1"); expect(deltas).toContain("conn2"); }); + + it("cancels the upstream response when the hub stops", async () => { + const item = await fixture((response) => { + response.write(frame({ id: "e0", type: "server.connected", data: {} })); + return () => undefined; + }); + active.push(item); + + expect(await item.hub.ensureConnected(2_000)).toBe(true); + expect(item.connectionCount()).toBe(1); + expect(item.closedCount()).toBe(0); + + await item.hub.stop(); + + // Without `reader.cancel()` the response body stays open, so the fixture + // never observes the connection closing. + await waitFor(() => item.closedCount() === 1); + }); + + it("reconnects when the upstream stops sending heartbeats", async () => { + const item = await fixture((response) => { + response.write(frame({ id: "e0", type: "server.connected", data: {} })); + // Then nothing: a half-open socket that never ends the response. + return () => undefined; + }, { idleTimeoutMs: 150 }); + active.push(item); + + let reconnectObservedDisconnect = false; + item.hub.onReconnect(() => { + if (!item.hub.connected) reconnectObservedDisconnect = true; + }); + + item.hub.start(); + expect(await item.hub.ensureConnected(2_000)).toBe(true); + + // The idle watchdog must fail the silent stream so the loop reconnects; the + // fixture answers `server.connected` again on the second connection. + await waitFor(() => item.connectionCount() >= 2 && item.hub.connected); + expect(reconnectObservedDisconnect).toBe(true); + // The abandoned connection is cancelled, not left open. + await waitFor(() => item.closedCount() >= 1); + }); }); async function waitFor(predicate: () => boolean, timeoutMs = 3_000): Promise { diff --git a/test/health.test.ts b/test/health.test.ts new file mode 100644 index 0000000..10415ad --- /dev/null +++ b/test/health.test.ts @@ -0,0 +1,103 @@ +/** + * Health and readiness probes, plus the HTTP latency buckets operators read + * alongside them. + * + * `/ready` is public, so it must answer from cached state only: an anonymous + * probe may not trigger an upstream catalogue call (or a spawn attempt). + */ +import { describe, expect, it, vi } from "vitest"; +import { createMetrics } from "../src/metrics/registry.js"; +import type { UpstreamStatus } from "../src/upstream/process.js"; +import { buildServer } from "../src/server.js"; +import { createTestContext, defaultModels } from "./helpers/context.js"; + +describe("health routes", () => { + it("answers /ready from cached state without calling the upstream", async () => { + const ctx = createTestContext(); + const listModels = vi.spyOn(ctx.client, "listModels"); + const app = await buildServer(ctx); + + try { + const first = await app.inject({ method: "GET", url: "/ready" }); + const second = await app.inject({ method: "GET", url: "/ready" }); + + expect(listModels).not.toHaveBeenCalled(); + expect(first.statusCode).toBe(503); + expect(second.statusCode).toBe(503); + expect(first.json()).toMatchObject({ status: "unavailable", upstream: { ready: false } }); + } finally { + await app.close(); + } + }); + + it("reports ready once the catalogue is cached", async () => { + const ctx = createTestContext(); + await ctx.models.catalog(); + const app = await buildServer(ctx); + + try { + const response = await app.inject({ method: "GET", url: "/ready" }); + expect(response.statusCode).toBe(200); + expect(response.json()).toMatchObject({ + status: "ready", + upstream: { ready: true, models: defaultModels().length }, + }); + } finally { + await app.close(); + } + }); + + it("returns 503 when the upstream endpoint is not ready", async () => { + const ctx = createTestContext(); + await ctx.models.catalog(); + (ctx.upstream as unknown as { status: () => UpstreamStatus }).status = () => ({ ready: false }); + const app = await buildServer(ctx); + + try { + const response = await app.inject({ method: "GET", url: "/ready" }); + expect(response.statusCode).toBe(503); + expect(response.json()).toMatchObject({ status: "unavailable", upstream: { ready: false } }); + } finally { + await app.close(); + } + }); + + it("keeps /health and /healthz cheap and public", async () => { + const ctx = createTestContext(); + const listModels = vi.spyOn(ctx.client, "listModels"); + const app = await buildServer(ctx); + + try { + const health = await app.inject({ method: "GET", url: "/health" }); + const healthz = await app.inject({ method: "GET", url: "/healthz" }); + + expect(health.statusCode).toBe(200); + expect(health.json()).toMatchObject({ status: "ok", upstream: { ready: true } }); + expect(healthz.statusCode).toBe(200); + expect(listModels).not.toHaveBeenCalled(); + } finally { + await app.close(); + } + }); +}); + +describe("HTTP latency histogram", () => { + it("can describe completions longer than two minutes", async () => { + const metrics = createMetrics({ enabled: false }); + const labels = { method: "POST", route: "/v1/chat/completions", status: "200" }; + metrics.httpDuration.observe(labels, 200); + metrics.httpDuration.observe(labels, 500); + + const exported = await metrics.registry.getMetricsAsJSON(); + const histogram = exported.find((entry) => entry.name === "opencode_api_http_request_duration_seconds"); + expect(histogram).toBeDefined(); + const values = histogram?.values ?? []; + const bucket = (le: string): number | undefined => + values.find((value) => String(value.labels["le"]) === le)?.value; + + // A 200 s completion lands under le="300" (previously +Inf); 500 s gets le="600". + expect(bucket("300")).toBe(1); + expect(bucket("600")).toBe(2); + expect(bucket("+Inf")).toBe(2); + }); +}); \ No newline at end of file diff --git a/test/helpers/context.ts b/test/helpers/context.ts index 660e208..028c040 100644 --- a/test/helpers/context.ts +++ b/test/helpers/context.ts @@ -31,6 +31,7 @@ export function testConfig(overrides: Partial = {}): Config { resetConfigCache(); return loadConfig({ apiKeys: ["test-key"], + usingDefaultApiKey: false, allowNoAuth: false, upstreamAutostart: false, logLevel: "silent", @@ -174,6 +175,9 @@ export function aggregate(request: InternalRequest, events: CompletionEvent[]) { case "end": result.finishReason = event.finishReason as never; result.usage = event.usage; + // Mirror `collectCompletion`: the terminal event carries the upstream + // assistant message id, which the surfaces use for thinking signatures. + result.messageId = event.messageId || result.messageId; break; case "error": throw event.error; diff --git a/test/media.test.ts b/test/media.test.ts index 9f1a42a..60374c0 100644 --- a/test/media.test.ts +++ b/test/media.test.ts @@ -1,9 +1,11 @@ import http from "node:http"; -import type { AddressInfo } from "node:net"; +import type { LookupAddress, LookupOptions } from "node:dns"; +import dns from "node:dns/promises"; import fsp from "node:fs/promises"; +import type { AddressInfo } from "node:net"; import os from "node:os"; import path from "node:path"; -import { afterAll, beforeAll, describe, expect, it } from "vitest"; +import { afterAll, afterEach, beforeAll, describe, expect, it, vi } from "vitest"; import { loadConfig, resetConfigCache, type Config } from "../src/config.js"; import { ApiError } from "../src/errors.js"; import { buildDataUri, isPrivateHost, isWithinRoots, resolveAttachment } from "../src/media/resolve.js"; @@ -25,6 +27,10 @@ function config(overrides: Partial = {}): Config { } as Partial); } +afterEach(() => { + vi.restoreAllMocks(); +}); + describe("mime helpers", () => { it("classifies MIME families", () => { expect(isImage("image/png")).toBe(true); @@ -109,9 +115,13 @@ describe("resolveAttachment", () => { describe("remote URLs", () => { let server: http.Server; let baseUrl: string; + let port = 0; + /** Requests that actually reached the fixture server. */ + let hits = 0; beforeAll(async () => { server = http.createServer((request, response) => { + hits += 1; if (request.url === "/image.png") { response.writeHead(200, { "content-type": "image/png" }); response.end(PNG_BUFFER); @@ -127,15 +137,22 @@ describe("resolveAttachment", () => { response.end(Buffer.alloc(4096, 1)); return; } + if (request.url === "/slow") { + // Never ends: only an abort (or the fetch timeout) can settle this. + response.writeHead(200, { "content-type": "image/png" }); + return; + } response.writeHead(404); response.end(); }); await new Promise((resolve) => server.listen(0, "127.0.0.1", resolve)); const address = server.address() as AddressInfo; + port = address.port; baseUrl = `http://127.0.0.1:${address.port}`; }); afterAll(async () => { + server.closeAllConnections(); await new Promise((resolve) => server.close(() => resolve())); }); @@ -183,6 +200,81 @@ describe("resolveAttachment", () => { resolveAttachment({ url: `${baseUrl}/missing.png` }, config({ allowPrivateMediaUrls: true })), ).rejects.toMatchObject({ code: "attachment_download_failed" }); }); + + it("honours a signal that is already aborted", async () => { + const startedAt = Date.now(); + await expect( + resolveAttachment({ url: `${baseUrl}/slow` }, config({ allowPrivateMediaUrls: true }), { + signal: AbortSignal.abort(), + }), + ).rejects.toMatchObject({ code: "attachment_download_failed" }); + // The body never ends; without the pre-check this waits for the 15 s fetch timeout. + expect(Date.now() - startedAt).toBeLessThan(2_000); + }); + + it("blocks hostnames whose DNS answer turns private before the connection", async () => { + const hitsBefore = hits; + const lookup = vi + .spyOn(dns, "lookup") + .mockResolvedValueOnce([{ address: "93.184.216.34", family: 4 }] as unknown as LookupAddress) + .mockResolvedValueOnce([{ address: "127.0.0.1", family: 4 }] as unknown as LookupAddress); + + await expect( + resolveAttachment( + { url: `${baseUrl.replace("127.0.0.1", "media.example.test")}/image.png` }, + config({ allowPrivateMediaUrls: false }), + ), + ).rejects.toMatchObject({ code: "private_media_blocked" }); + + expect(lookup).toHaveBeenCalledTimes(2); + expect(hits).toBe(hitsBefore); + }); + + it("downloads a public address through the pinned lookup", async () => { + const realRequest = http.request.bind(http); + const captured: http.RequestOptions[] = []; + const requestSpy = vi.spyOn(http, "request").mockImplementation((( + options: http.RequestOptions, + callback?: (response: http.IncomingMessage) => void, + ) => { + captured.push(options); + // The fixture only exists on loopback: rewrite the socket target while + // keeping everything the gateway set, including the pinned lookup. + return realRequest({ ...options, hostname: "127.0.0.1", port }, callback); + }) as typeof http.request); + const lookup = vi + .spyOn(dns, "lookup") + .mockResolvedValue([{ address: "93.184.216.34", family: 4 }] as unknown as LookupAddress); + + const attachment = await resolveAttachment( + { url: `http://media.example.test:${port}/image.png` }, + config({ allowPrivateMediaUrls: false }), + ); + + expect(attachment.mime).toBe("image/png"); + expect(attachment.size).toBe(PNG_BUFFER.byteLength); + expect(attachment.origin).toBe(`http://media.example.test:${port}/image.png`); + expect(lookup).toHaveBeenCalledTimes(2); + + const options = captured[0]; + expect(options?.headers).toMatchObject({ host: `media.example.test:${port}` }); + const pinnedLookup = options?.lookup; + expect(typeof pinnedLookup).toBe("function"); + if (typeof pinnedLookup !== "function") throw new Error("expected a pinned lookup"); + + const addresses = await new Promise((resolve, reject) => { + pinnedLookup("media.example.test", { all: true } satisfies LookupOptions, (error, address) => { + if (error) reject(error); + else if (Array.isArray(address)) resolve(address); + else reject(new Error("expected all addresses")); + }); + }); + // The socket target is the validated address, not a fresh resolution. + expect(addresses).toEqual([{ address: "93.184.216.34", family: 4 }]); + + requestSpy.mockRestore(); + lookup.mockRestore(); + }); }); describe("local files", () => { @@ -217,6 +309,19 @@ describe("resolveAttachment", () => { expect(attachment.name).toBe("image.png"); }); + it("re-checks the size after reading, not only from stat", async () => { + const cap = PNG_BUFFER.byteLength + 16; + const readSpy = vi.spyOn(fsp, "readFile").mockResolvedValue(Buffer.alloc(cap * 2, 7) as never); + await expect( + resolveAttachment( + { path: path.join(workspace, "image.png") }, + config({ allowLocalFiles: true, allowedFileRoots: [workspace], maxAttachmentBytes: cap }), + ), + ).rejects.toMatchObject({ code: "attachment_too_large" }); + expect(readSpy).toHaveBeenCalledTimes(1); + readSpy.mockRestore(); + }); + it("refuses files outside the allowed roots", async () => { await expect( resolveAttachment( diff --git a/test/openai-chat.test.ts b/test/openai-chat.test.ts index 91f2f70..2666b6a 100644 --- a/test/openai-chat.test.ts +++ b/test/openai-chat.test.ts @@ -2,6 +2,8 @@ * Unit tests for the OpenAI-compatible chat completions surface. */ import { afterEach, describe, expect, it } from "vitest"; +import http from "node:http"; +import type { AddressInfo } from "node:net"; import { ApiError } from "../src/errors.js"; import { buildServer } from "../src/server.js"; import { EMPTY_USAGE, type CompletionEvent, type InternalRequest, type Usage } from "../src/types/internal.js"; @@ -10,6 +12,26 @@ import { createTestContext, defaultScript, parseSse, parseSseJson, testConfig } const AUTH = { authorization: "Bearer test-key" }; const MODEL = "opencode/deepseek-v4.1-flash-free"; +const PNG_BASE64 = + "iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAYAAAAfFcSJAAAADUlEQVR42mP8z8BQDwAEhQGAhKmMIQAAAABJRU5ErkJggg=="; + +/** Serve one tiny PNG per request after `delayMs`, so serial fetches are measurable. */ +async function startPngFixture(delayMs: number): Promise<{ origin: string; close: () => Promise }> { + const body = Buffer.from(PNG_BASE64, "base64"); + const server = http.createServer((_request, response) => { + setTimeout(() => { + response.writeHead(200, { "content-type": "image/png", "content-length": String(body.byteLength) }); + response.end(body); + }, delayMs); + }); + await new Promise((resolve) => server.listen(0, "127.0.0.1", resolve)); + const address = server.address() as AddressInfo; + return { + origin: `http://127.0.0.1:${address.port}`, + close: () => new Promise((resolve) => server.close(() => resolve())), + }; +} + const USAGE: Usage = { ...EMPTY_USAGE, inputTokens: 12, outputTokens: 4, totalTokens: 16 }; interface Chunk { @@ -192,8 +214,160 @@ describe("POST /v1/chat/completions (non-streaming)", () => { await app.close(); }); - it("includes cot-style reasoning_content when reasoning_effort is set", async () => { - const script = (request: InternalRequest): CompletionEvent[] => [ + it("treats explicit null optionals as absent", async () => { + const captured: InternalRequest[] = []; + const ctx = createTestContext({ onRun: (request) => captured.push(request) }); + const app = await buildServer(ctx); + + const response = await app.inject({ + method: "POST", + url: "/v1/chat/completions", + headers: AUTH, + payload: { + model: MODEL, + messages: [{ role: "user", content: "Hi" }], + stream: null, + stream_options: null, + temperature: null, + top_p: null, + max_tokens: null, + max_completion_tokens: null, + stop: null, + n: null, + reasoning_effort: null, + reasoning: null, + user: null, + metadata: null, + service_tier: null, + parallel_tool_calls: null, + seed: null, + logprobs: null, + logit_bias: null, + presence_penalty: null, + frequency_penalty: null, + response_format: null, + tools: null, + tool_choice: null, + }, + }); + + expect(response.statusCode).toBe(200); + const request = captured[0]; + expect(request?.stream).toBe(false); + expect(request?.temperature).toBeUndefined(); + expect(request?.topP).toBeUndefined(); + expect(request?.maxTokens).toBeUndefined(); + expect(request?.stop).toBeUndefined(); + expect(request?.reasoning).toBeUndefined(); + expect(request?.responseFormat).toBeUndefined(); + expect(request?.toolChoice).toBeUndefined(); + expect(request?.parallelToolCalls).toBeUndefined(); + expect(request?.metadata).toBeUndefined(); + expect(request?.tools).toEqual([]); + expect(request?.messages).toEqual([{ role: "user", text: "Hi" }]); + + await app.close(); + }); + + it("still accepts a null messages[].content", async () => { + const captured: InternalRequest[] = []; + const ctx = createTestContext({ onRun: (request) => captured.push(request) }); + const app = await buildServer(ctx); + + const response = await app.inject({ + method: "POST", + url: "/v1/chat/completions", + headers: AUTH, + payload: { + model: MODEL, + messages: [ + { + role: "assistant", + content: null, + tool_calls: [{ id: "call_1", type: "function", function: { name: "lookup", arguments: "{}" } }], + }, + ], + }, + }); + + expect(response.statusCode).toBe(200); + expect(captured[0]?.messages[0]?.text).toBe(""); + expect(captured[0]?.messages[0]?.toolCalls).toHaveLength(1); + await app.close(); + }); + + it("rejects role tool without a tool_call_id", async () => { + const app = await buildServer(createTestContext()); + const response = await app.inject({ + method: "POST", + url: "/v1/chat/completions", + headers: AUTH, + payload: { model: MODEL, messages: [{ role: "tool", content: "42" }] }, + }); + + expect(response.statusCode).toBe(400); + const body = response.json() as { error: { code: string; param: string } }; + expect(body.error.code).toBe("invalid_request"); + expect(body.error.param).toBe("messages"); + await app.close(); + }); + + it("accepts role tool with a non-empty tool_call_id", async () => { + const captured: InternalRequest[] = []; + const ctx = createTestContext({ onRun: (request) => captured.push(request) }); + const app = await buildServer(ctx); + + const response = await app.inject({ + method: "POST", + url: "/v1/chat/completions", + headers: AUTH, + payload: { model: MODEL, messages: [{ role: "tool", tool_call_id: "call_1", content: "42" }] }, + }); + + expect(response.statusCode).toBe(200); + expect(captured[0]?.messages[0]).toMatchObject({ role: "tool", text: "42", toolCallId: "call_1" }); + await app.close(); + }); + + it("records parallel_tool_calls: false on the internal request", async () => { + const captured: InternalRequest[] = []; + const ctx = createTestContext({ onRun: (request) => captured.push(request) }); + const app = await buildServer(ctx); + + const response = await app.inject({ + method: "POST", + url: "/v1/chat/completions", + headers: AUTH, + payload: { + model: MODEL, + messages: [{ role: "user", content: "Hi" }], + tools: [{ type: "function", function: { name: "ping" } }], + parallel_tool_calls: false, + }, + }); + + expect(response.statusCode).toBe(200); + expect(captured[0]?.parallelToolCalls).toBe(false); + await app.close(); + }); + + it("leaves parallelToolCalls unset when the caller did not send the flag", async () => { + const captured: InternalRequest[] = []; + const ctx = createTestContext({ onRun: (request) => captured.push(request) }); + const app = await buildServer(ctx); + + await app.inject({ + method: "POST", + url: "/v1/chat/completions", + headers: AUTH, + payload: { model: MODEL, messages: [{ role: "user", content: "Hi" }] }, + }); + + expect(captured[0]?.parallelToolCalls).toBeUndefined(); + await app.close(); + }); + + it("includes cot-style reasoning_content when reasoning_effort is set", async () => { const script = (request: InternalRequest): CompletionEvent[] => [ { kind: "start", sessionId: "ses_reason", @@ -367,7 +541,8 @@ describe("POST /v1/chat/completions (non-streaming)", () => { expect(response.statusCode).toBe(200); const message = captured[0]?.messages[0]; - expect(message?.text).toBe("what is this?"); const attachments = message?.attachments ?? []; + expect(message?.text).toBe("what is this?"); + const attachments = message?.attachments ?? []; expect(attachments).toHaveLength(4); expect(attachments[0]).toMatchObject({ kind: "image", mime: "image/png" }); expect(attachments[1]?.kind).toBe("audio"); @@ -378,6 +553,51 @@ describe("POST /v1/chat/completions (non-streaming)", () => { await app.close(); }); + it("resolves a message's remote media parts concurrently, in declaration order", async () => { + const DELAY_MS = 80; + const fixture = await startPngFixture(DELAY_MS); + try { + const captured: InternalRequest[] = []; + const ctx = createTestContext({ onRun: (request) => captured.push(request) }); + const app = await buildServer(ctx); + + const startedAt = Date.now(); + const response = await app.inject({ + method: "POST", + url: "/v1/chat/completions", + headers: AUTH, + payload: { + model: MODEL, + messages: [ + { + role: "user", + content: [ + { type: "image_url", image_url: { url: `${fixture.origin}/first.png` } }, + { type: "image_url", image_url: { url: `${fixture.origin}/second.png` } }, + ], + }, + ], + }, + }); + const elapsed = Date.now() - startedAt; + + expect(response.statusCode).toBe(200); + const attachments = captured[0]?.messages[0]?.attachments ?? []; + expect(attachments).toHaveLength(2); + // Declaration order is preserved even though both downloads run at once. + expect(attachments[0]?.origin).toBe(`${fixture.origin}/first.png`); + expect(attachments[1]?.origin).toBe(`${fixture.origin}/second.png`); + + // Serial resolution would cost at least 2 x 80 ms; concurrent resolution + // costs max(latency), so anything well under the serial sum proves the overlap. + expect(elapsed).toBeLessThan(DELAY_MS * 2 - 40); + + await app.close(); + } finally { + await fixture.close(); + } + }); + it("rejects a file part that only carries a file_id", async () => { const app = await buildServer(createTestContext()); const response = await app.inject({ @@ -457,6 +677,84 @@ describe("POST /v1/chat/completions (non-streaming)", () => { }); }); +describe("usage accounting", () => { + // Reasoning tokens are a subset of completion tokens: 5 + 3 = 8. + const REASONING_USAGE: Usage = { + ...EMPTY_USAGE, + inputTokens: 10, + outputTokens: 5, + reasoningTokens: 3, + totalTokens: 18, + }; + + const usageScript = (request: InternalRequest): CompletionEvent[] => [ + { + kind: "start", + sessionId: "ses_usage", + messageId: "msg_usage", + model: request.model, + agent: "build", + reusedSession: false, + reasoningEnabled: true, + }, + { kind: "text_delta", text: "Answer", ordinal: 0 }, + { kind: "end", finishReason: "stop", usage: REASONING_USAGE, messageId: "msg_usage" }, + ]; + + it("counts reasoning tokens inside completion_tokens in the buffered body", async () => { + const app = await buildServer(createTestContext({ script: usageScript })); + const response = await app.inject({ + method: "POST", + url: "/v1/chat/completions", + headers: AUTH, + payload: { model: MODEL, messages: [{ role: "user", content: "Hi" }], reasoning_effort: "high" }, + }); + + expect(response.statusCode).toBe(200); + const usage = (response.json() as ChatBody).usage; + expect(usage).toEqual({ + prompt_tokens: 10, + completion_tokens: 8, + total_tokens: 18, + completion_tokens_details: { reasoning_tokens: 3 }, + prompt_tokens_details: { cached_tokens: 0 }, + }); + expect((usage["prompt_tokens"] as number) + (usage["completion_tokens"] as number)).toBe(usage["total_tokens"]); + + await app.close(); + }); + + it("counts reasoning tokens inside completion_tokens in the streamed usage chunk", async () => { + const app = await buildServer(createTestContext({ script: usageScript })); + const response = await app.inject({ + method: "POST", + url: "/v1/chat/completions", + headers: AUTH, + payload: { + model: MODEL, + messages: [{ role: "user", content: "Hi" }], + reasoning_effort: "high", + stream: true, + stream_options: { include_usage: true }, + }, + }); + + const chunks = parseSseJson(response.body).map((frame) => frame.json); + const usage = chunks.at(-1)?.usage ?? {}; + expect(usage).toEqual({ + prompt_tokens: 10, + completion_tokens: 8, + total_tokens: 18, + completion_tokens_details: { reasoning_tokens: 3 }, + prompt_tokens_details: { cached_tokens: 0 }, + }); + expect((usage["prompt_tokens"] as number) + (usage["completion_tokens"] as number)).toBe(usage["total_tokens"]); + expect(parseSse(response.body).at(-1)?.data).toBe("[DONE]"); + + await app.close(); + }); +}); + describe("POST /v1/chat/completions (streaming)", () => { it("emits the chunk sequence and terminates with [DONE]", async () => { const app = await buildServer(createTestContext()); diff --git a/test/openai-completions.test.ts b/test/openai-completions.test.ts new file mode 100644 index 0000000..103bc20 --- /dev/null +++ b/test/openai-completions.test.ts @@ -0,0 +1,339 @@ +/** + * Unit tests for the OpenAI-compatible legacy completions surface. + */ +import { describe, expect, it } from "vitest"; +import type { FastifyInstance } from "fastify"; +import { ApiError } from "../src/errors.js"; +import { buildServer } from "../src/server.js"; +import { EMPTY_USAGE, type CompletionEvent, type InternalRequest } from "../src/types/internal.js"; +import { createTestContext, parseSse, parseSseJson } from "./helpers/context.js"; + +const AUTH = { authorization: "Bearer test-key" }; +const MODEL = "opencode/deepseek-v4.1-flash-free"; + +/** Build the real gateway; `buildServer` registers the completions surface. */ +async function buildCompletionServer(ctx: ReturnType): Promise { + return buildServer(ctx); +} + +interface CompletionChoice { + text: string; + index: number; + logprobs: null; + finish_reason: string | null; +} + +interface CompletionBody { + id: string; + object: string; + created: number; + model: string; + choices: CompletionChoice[]; + usage: Record; + x_opencode: Record; +} + +function textScript(request: InternalRequest): CompletionEvent[] { + return [ + { + kind: "start", + sessionId: "ses_cmpl", + messageId: "msg_cmpl", + model: request.model, + agent: "build", + reusedSession: false, + reasoningEnabled: false, + }, + { kind: "text_delta", text: "Hello", ordinal: 0 }, + { kind: "text_delta", text: " world", ordinal: 0 }, + { kind: "end", finishReason: "stop", usage: { ...EMPTY_USAGE, inputTokens: 12, outputTokens: 4, totalTokens: 16 }, messageId: "msg_cmpl" }, + ]; +} + +describe("POST /v1/completions (non-streaming)", () => { + it("returns an OpenAI text_completion object and maps the prompt to one user message", async () => { + const captured: InternalRequest[] = []; + const ctx = createTestContext({ script: textScript, onRun: (request) => captured.push(request) }); + const app = await buildCompletionServer(ctx); + + const response = await app.inject({ + method: "POST", + url: "/v1/completions", + headers: AUTH, + payload: { model: MODEL, prompt: "Say hello", max_tokens: 32, temperature: 0.2, stop: "END", user: "u-1" }, + }); + + expect(response.statusCode).toBe(200); + const body = response.json() as CompletionBody; + expect(body.id).toMatch(/^cmpl-/); + expect(body.object).toBe("text_completion"); + expect(body.model).toBe(MODEL); + expect(body.created).toBeGreaterThan(0); + expect(body.choices).toEqual([ + { text: "Hello world", index: 0, logprobs: null, finish_reason: "stop" }, + ]); + expect(body.usage).toEqual({ + prompt_tokens: 12, + completion_tokens: 4, + total_tokens: 16, + completion_tokens_details: { reasoning_tokens: 0 }, + prompt_tokens_details: { cached_tokens: 0 }, + }); + expect(body.x_opencode).toMatchObject({ + session_id: "ses_cmpl", + agent: "build", + variant: null, + reused_session: false, + reasoning: { enabled: false, note: null }, + native_tool_calls: [], + }); + + expect(captured[0]?.surface).toBe("openai.completions"); + expect(captured[0]?.messages).toEqual([{ role: "user", text: "Say hello" }]); + expect(captured[0]?.maxTokens).toBe(32); + expect(captured[0]?.temperature).toBe(0.2); + expect(captured[0]?.stop).toEqual(["END"]); + expect(captured[0]?.stream).toBe(false); + + await app.close(); + }); + + it("forwards x-conversation-id and x-opencode-agent", async () => { + const captured: InternalRequest[] = []; + const ctx = createTestContext({ onRun: (request) => captured.push(request) }); + + const app = await buildCompletionServer(ctx); + const response = await app.inject({ + method: "POST", + url: "/v1/completions", + headers: { ...AUTH, "x-conversation-id": "conv-42", "x-opencode-agent": "plan" }, + payload: { model: MODEL, prompt: "Continue this thought" }, + }); + expect(response.statusCode).toBe(200); + // The correlation header and the agent override work exactly as on the chat + // surface. + expect(captured[0]?.conversationKey).toBe("conv-42"); + expect(captured[0]?.agent).toBe("plan"); + await app.close(); + }); + + it("joins an array prompt into one user turn with n: 1", async () => { + const captured: InternalRequest[] = []; + const ctx = createTestContext({ onRun: (request) => captured.push(request) }); + + const app = await buildCompletionServer(ctx); + + const response = await app.inject({ + method: "POST", + url: "/v1/completions", + headers: AUTH, + payload: { model: MODEL, prompt: ["first", "second"], n: 1 }, + }); + + expect(response.statusCode).toBe(200); + expect(captured[0]?.messages).toEqual([{ role: "user", text: "first\nsecond" }]); + await app.close(); + }); + + it("rejects n != 1 with 400", async () => { + const ctx = createTestContext(); + const app = await buildCompletionServer(ctx); + + const response = await app.inject({ + method: "POST", + url: "/v1/completions", + headers: AUTH, + payload: { model: MODEL, prompt: "hi", n: 2 }, + }); + + expect(response.statusCode).toBe(400); + expect((response.json() as { error: { param: string } }).error.param).toBe("n"); + await app.close(); + }); + + it("rejects an array prompt without n: 1", async () => { + const ctx = createTestContext(); + const app = await buildCompletionServer(ctx); + + const missingN = await app.inject({ + method: "POST", + url: "/v1/completions", + headers: AUTH, + payload: { model: MODEL, prompt: ["a", "b"] }, + }); + expect(missingN.statusCode).toBe(400); + expect((missingN.json() as { error: { param: string } }).error.param).toBe("prompt"); + + const nIsTwo = await app.inject({ + method: "POST", + url: "/v1/completions", + headers: AUTH, + payload: { model: MODEL, prompt: ["a", "b"], n: 2 }, + }); + expect(nIsTwo.statusCode).toBe(400); + expect((nIsTwo.json() as { error: { param: string } }).error.param).toBe("n"); + await app.close(); + }); + + it("rejects echo: true with 400 unsupported_parameter", async () => { + const ctx = createTestContext(); + const app = await buildCompletionServer(ctx); + + const response = await app.inject({ + method: "POST", + url: "/v1/completions", + headers: AUTH, + payload: { model: MODEL, prompt: "hi", echo: true }, + }); + + expect(response.statusCode).toBe(400); + const body = response.json() as { error: { code: string; param: string } }; + expect(body.error.code).toBe("unsupported_parameter"); + expect(body.error.param).toBe("echo"); + await app.close(); + }); + + it("rejects an unknown model with 404 before streaming", async () => { + const ctx = createTestContext(); + const app = await buildCompletionServer(ctx); + + const response = await app.inject({ + method: "POST", + url: "/v1/completions", + headers: AUTH, + payload: { model: "opencode/nope", prompt: "hi", stream: true }, + }); + + expect(response.statusCode).toBe(404); + expect(response.headers["content-type"]).toContain("application/json"); + expect((response.json() as { error: { code: string } }).error.code).toBe("model_not_found"); + await app.close(); + }); + + it("rejects a missing prompt and a missing model with 400", async () => { + const ctx = createTestContext(); + const app = await buildCompletionServer(ctx); + + const missingPrompt = await app.inject({ + method: "POST", + url: "/v1/completions", + headers: AUTH, + payload: { model: MODEL }, + }); + expect(missingPrompt.statusCode).toBe(400); + + const missingModel = await app.inject({ + method: "POST", + url: "/v1/completions", + headers: AUTH, + payload: { prompt: "hi" }, + }); + expect(missingModel.statusCode).toBe(400); + await app.close(); + }); +}); + +describe("POST /v1/completions (streaming)", () => { + it("emits text_completion chunks in order and terminates with [DONE]", async () => { + const ctx = createTestContext({ script: textScript }); + const app = await buildCompletionServer(ctx); + + const response = await app.inject({ + method: "POST", + url: "/v1/completions", + headers: AUTH, + payload: { model: MODEL, prompt: "Say hello", stream: true }, + }); + + expect(response.statusCode).toBe(200); + expect(response.headers["content-type"]).toContain("text/event-stream"); + + const frames = parseSse(response.body); + expect(frames.at(-1)?.data).toBe("[DONE]"); + + const chunks = parseSseJson<{ id: string; object: string; created: number; model: string; choices: CompletionChoice[] }>( + response.body, + ).map((frame) => frame.json); + expect(chunks.length).toBeGreaterThanOrEqual(3); + expect(new Set(chunks.map((chunk) => chunk.id)).size).toBe(1); + expect(chunks.every((chunk) => chunk.object === "text_completion")).toBe(true); + expect(chunks.every((chunk) => chunk.model === MODEL)).toBe(true); + expect(chunks.map((chunk) => chunk.choices[0]?.text)).toEqual(["Hello", " world", ""]); + expect(chunks[0]?.choices[0]?.logprobs).toBeNull(); + expect(chunks[0]?.choices[0]?.index).toBe(0); + expect(chunks[0]?.choices[0]?.finish_reason).toBeNull(); + expect(chunks.at(-1)?.choices[0]?.finish_reason).toBe("stop"); + + await app.close(); + }); + + it("appends a usage chunk before [DONE] when include_usage is set", async () => { + const ctx = createTestContext({ script: textScript }); + const app = await buildCompletionServer(ctx); + + const response = await app.inject({ + method: "POST", + url: "/v1/completions", + headers: AUTH, + payload: { model: MODEL, prompt: "Say hello", stream: true, stream_options: { include_usage: true } }, + }); + + const chunks = parseSseJson<{ choices: CompletionChoice[]; usage?: Record }>(response.body).map( + (frame) => frame.json, + ); + const usageChunk = chunks.at(-1); + expect(usageChunk?.choices).toEqual([]); + expect(usageChunk?.usage).toEqual({ + prompt_tokens: 12, + completion_tokens: 4, + total_tokens: 16, + completion_tokens_details: { reasoning_tokens: 0 }, + prompt_tokens_details: { cached_tokens: 0 }, + }); + expect(parseSse(response.body).at(-1)?.data).toBe("[DONE]"); + + await app.close(); + }); + + it("reports a pre-stream failure with a real HTTP status", async () => { + const ctx = createTestContext({ + script: () => { + throw new Error("upstream exploded"); + }, + }); + const app = await buildCompletionServer(ctx); + + const response = await app.inject({ + method: "POST", + url: "/v1/completions", + headers: AUTH, + payload: { model: MODEL, prompt: "hi", stream: true }, + }); + + expect(response.statusCode).toBe(500); + expect((response.json() as { error: { type: string } }).error.type).toBe("api_error"); + await app.close(); + }); + + it("reports an error frame when the stream fails after the first chunk", async () => { + const ctx = createTestContext({ + script: (request: InternalRequest): CompletionEvent[] => [ + ...textScript(request).slice(0, -1), + { kind: "error", error: ApiError.unavailable("late failure") }, + ], + }); + const app = await buildCompletionServer(ctx); + + const response = await app.inject({ + method: "POST", + url: "/v1/completions", + headers: AUTH, + payload: { model: MODEL, prompt: "hi", stream: true }, + }); + + expect(response.statusCode).toBe(200); + const frames = parseSseJson<{ error?: { message: string } }>(response.body); + expect(frames.at(-1)?.json.error?.message).toBe("late failure"); + await app.close(); + }); +}); diff --git a/test/openai-responses.test.ts b/test/openai-responses.test.ts index 439d314..af3ac68 100644 --- a/test/openai-responses.test.ts +++ b/test/openai-responses.test.ts @@ -4,18 +4,25 @@ * The upstream is fully scripted through `createTestContext`, so no live * OpenCode server is required. */ -import { afterEach, describe, expect, it } from "vitest"; +import http from "node:http"; +import type { AddressInfo } from "node:net"; +import { afterAll, afterEach, beforeAll, describe, expect, it } from "vitest"; import Fastify, { type FastifyInstance, type FastifyReply, type FastifyRequest } from "fastify"; import { registerOpenAiResponsesRoutes } from "../src/adapter/openai/responses.js"; import { requireApiKey } from "../src/auth.js"; +import type { AppContext, CompletionRunner } from "../src/context.js"; import { ApiError, toApiError, toOpenAiError } from "../src/errors.js"; -import { EMPTY_USAGE, type CompletionEvent, type InternalRequest } from "../src/types/internal.js"; +import { EMPTY_USAGE, type CompletionEvent, type InternalRequest, type Usage } from "../src/types/internal.js"; import { createTestContext, defaultScript, parseSse, type TestContextOptions } from "./helpers/context.js"; /** 1x1 transparent PNG. */ const PNG_BASE64 = "iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAYAAAAfFcSJAAAADUlEQVR42mP8z8BQDwAEhQGAhKmMIQAAAABJRU5ErkJggg=="; const PNG_DATA_URI = `data:image/png;base64,${PNG_BASE64}`; +const PNG_BUFFER = Buffer.from(PNG_BASE64, "base64"); + +/** Delay the media fixture applies to every response, in milliseconds. */ +const MEDIA_DELAY_MS = 120; const apps: FastifyInstance[] = []; @@ -33,9 +40,16 @@ afterEach(async () => { * parallel workstreams. This test only exercises the Responses surface, so it * mounts that route plus the same auth hook and OpenAI-shaped error rendering * the real server uses, keeping the unit test independent of the other files. + * + * `run` optionally replaces the scripted runner, which lets a test throw from + * inside the completion stream itself. */ -async function makeApp(options: TestContextOptions = {}): Promise { - const ctx = createTestContext(options); +async function makeApp( + options: TestContextOptions = {}, + run?: CompletionRunner["run"], +): Promise { + const base = createTestContext(options); + const ctx: AppContext = run === undefined ? base : { ...base, completion: { ...base.completion, run } }; const app = Fastify({ requestTimeout: 0, connectionTimeout: 0 }); app.addHook("preHandler", requireApiKey(ctx.config)); @@ -87,7 +101,7 @@ interface ResponsePayload { max_output_tokens: number | null; reasoning: { effort: string | null; summary: string | null }; incomplete_details: { reason: string } | null; - error: null; + error: { code: string; message: string } | null; instructions: null; previous_response_id: null; store: boolean; @@ -298,6 +312,7 @@ describe("POST /v1/responses (non-streaming)", () => { expect(captured?.temperature).toBe(0.3); expect(captured?.topP).toBe(0.9); expect(captured?.toolChoice).toBe("required"); + expect(captured?.parallelToolCalls).toBe(false); expect(captured?.reasoning).toEqual({ enabled: true, effort: "high" }); expect(captured?.tools).toEqual([ { name: "lookup", description: "Look something up", parameters: { type: "object", properties: {} } }, @@ -443,9 +458,161 @@ describe("POST /v1/responses (non-streaming)", () => { const body = response.json() as { error: { param: string | null } }; expect(body.error.param).toBe("model"); }); + + it("forwards the canonical model and the #variant suffix, and echoes the canonical id", async () => { + let captured: InternalRequest | undefined; + const app = await makeApp({ onRun: (request) => (captured = request) }); + + const response = await app.inject({ + method: "POST", + url: "/v1/responses", + headers: AUTH, + payload: { model: "opencode/deepseek-v4.1-flash-free#high", input: "Say hello." }, + }); + + expect(response.statusCode).toBe(200); + const body = response.json() as ResponsePayload; + expect(captured?.model).toBe("opencode/deepseek-v4.1-flash-free"); + expect(captured?.variant).toBe("high"); + expect(body.model).toBe("opencode/deepseek-v4.1-flash-free"); + }); + + it("treats an explicit top-level null on optional fields as absent", async () => { + const captured: InternalRequest[] = []; + const app = await makeApp({ onRun: (request) => captured.push(request) }); + + const nullish = await app.inject({ + method: "POST", + url: "/v1/responses", + headers: AUTH, + payload: { + model: "opencode/deepseek-v4.1-flash-free", + input: "hi", + instructions: null, + stream: null, + temperature: null, + top_p: null, + max_output_tokens: null, + metadata: null, + parallel_tool_calls: null, + truncation: null, + tools: null, + tool_choice: null, + text: null, + reasoning: null, + include: null, + user: null, + }, + }); + const plain = await app.inject({ + method: "POST", + url: "/v1/responses", + headers: AUTH, + payload: { model: "opencode/deepseek-v4.1-flash-free", input: "hi" }, + }); + + expect(nullish.statusCode).toBe(200); + expect(plain.statusCode).toBe(200); + expect(captured).toHaveLength(2); + expect(captured[0]).toEqual(captured[1]); + }); + + it("folds reasoning tokens into output_tokens and keeps total = input + output", async () => { + const usage: Usage = { ...EMPTY_USAGE, inputTokens: 10, outputTokens: 5, reasoningTokens: 3, totalTokens: 18 }; + const app = await makeApp({ + script: (request): CompletionEvent[] => [ + { kind: "start", sessionId: "ses_usage", messageId: "msg_usage", model: request.model, agent: "build", reusedSession: false, reasoningEnabled: true }, + { kind: "reasoning_delta", text: "think", ordinal: 0 }, + { kind: "reasoning_end", text: "think", ordinal: 0 }, + { kind: "text_delta", text: "answer", ordinal: 0 }, + { kind: "end", finishReason: "stop", usage, messageId: "msg_usage" }, + ], + }); + const payload = { + model: "opencode/deepseek-v4.1-flash-free", + input: "Think.", + reasoning: { effort: "high" }, + }; + + const buffered = await app.inject({ method: "POST", url: "/v1/responses", headers: AUTH, payload }); + expect(buffered.statusCode).toBe(200); + const bufferedBody = buffered.json() as ResponsePayload; + expect(bufferedBody.usage).toMatchObject({ + input_tokens: 10, + output_tokens: 8, + total_tokens: 18, + output_tokens_details: { reasoning_tokens: 3 }, + }); + expect(bufferedBody.usage.input_tokens + bufferedBody.usage.output_tokens).toBe(bufferedBody.usage.total_tokens); + + const streamed = await app.inject({ + method: "POST", + url: "/v1/responses", + headers: AUTH, + payload: { ...payload, stream: true }, + }); + expect(streamed.statusCode).toBe(200); + const streamedBody = frames(streamed.payload).at(-1)?.json["response"] as ResponsePayload; + expect(streamedBody.usage).toMatchObject({ input_tokens: 10, output_tokens: 8, total_tokens: 18 }); + expect(streamedBody.usage.output_tokens_details.reasoning_tokens).toBe(3); + expect(streamedBody.usage.input_tokens + streamedBody.usage.output_tokens).toBe(streamedBody.usage.total_tokens); + }); + + it("reports a failed turn as status failed with an error object", async () => { + const app = await makeApp({ + script: (request): CompletionEvent[] => { + const usage = { ...EMPTY_USAGE, inputTokens: 3, outputTokens: 2, totalTokens: 5 }; + return [ + { kind: "start", sessionId: "ses_fail", messageId: "msg_fail", model: request.model, agent: "build", reusedSession: false, reasoningEnabled: false }, + { kind: "text_delta", text: "partial", ordinal: 0 }, + { kind: "end", finishReason: "error", usage, messageId: "msg_fail" }, + ]; + }, + }); + + const response = await app.inject({ + method: "POST", + url: "/v1/responses", + headers: AUTH, + payload: { model: "opencode/deepseek-v4.1-flash-free", input: "Go." }, + }); + + expect(response.statusCode).toBe(200); + const body = response.json() as ResponsePayload; + expect(body.status).toBe("failed"); + expect(body.error).toEqual({ + code: "upstream_error", + message: "The upstream completion ended with an error.", + }); + expect(body.incomplete_details).toBeNull(); + expect(body.output_text).toBe("partial"); + }); }); describe("POST /v1/responses (streaming)", () => { + it("reports a failure raised before the first event with a real HTTP status", async () => { + const app = await makeApp({ + script: () => { + // Same class of pre-flight failure as an unavailable upstream event + // stream: it surfaces while the orchestrator prepares the turn. + throw new ApiError(503, "overloaded_error", "event stream unavailable", { + code: "event_stream_unavailable", + }); + }, + }); + + const response = await app.inject({ + method: "POST", + url: "/v1/responses", + headers: AUTH, + payload: { model: "opencode/deepseek-v4.1-flash-free", input: "hi", stream: true }, + }); + + // The SSE head must not be committed before the first event is known. + expect(response.statusCode).toBe(503); + expect(response.headers["content-type"]).toContain("application/json"); + }); + it("emits the typed event sequence with monotonic sequence numbers", async () => { const app = await makeApp({ script: (): CompletionEvent[] => { @@ -583,6 +750,106 @@ describe("POST /v1/responses (streaming)", () => { expect(parsed.some((frame) => frame.json["type"] === "response.completed")).toBe(false); }); + it("ends a failed turn with a terminal response.failed event", async () => { + const app = await makeApp({ + script: (request): CompletionEvent[] => { + const usage = { ...EMPTY_USAGE, inputTokens: 3, outputTokens: 2, totalTokens: 5 }; + return [ + { kind: "start", sessionId: "ses_fail_stream", messageId: "msg_fail_stream", model: request.model, agent: "build", reusedSession: false, reasoningEnabled: false }, + { kind: "text_delta", text: "partial", ordinal: 0 }, + { kind: "end", finishReason: "error", usage, messageId: "msg_fail_stream" }, + ]; + }, + }); + + const response = await app.inject({ + method: "POST", + url: "/v1/responses", + headers: AUTH, + payload: { model: "opencode/deepseek-v4.1-flash-free", input: "Go.", stream: true }, + }); + + expect(response.statusCode).toBe(200); + const parsed = frames(response.payload); + const terminal = parsed.at(-1); + expect(terminal?.event).toBe("response.failed"); + expect(terminal?.json["type"]).toBe("response.failed"); + const body = terminal?.json["response"] as ResponsePayload; + expect(body.status).toBe("failed"); + expect(body.error).toEqual({ + code: "upstream_error", + message: "The upstream completion ended with an error.", + }); + expect(body.output_text).toBe("partial"); + // The flat `error` frame is kept next to the spec-shaped terminal event. + expect(parsed.some((frame) => frame.event === "error")).toBe(true); + expect(parsed.map((frame) => frame.json.sequence_number)).toEqual(parsed.map((_, index) => index)); + }); + + it("keeps sequence numbers contiguous when the completion generator throws", async () => { + const app = await makeApp({}, async function* (request: InternalRequest): AsyncGenerator { + yield { + kind: "start", + sessionId: "ses_throw", + messageId: "msg_throw", + model: request.model, + agent: "build", + reusedSession: false, + reasoningEnabled: false, + }; + throw new ApiError(502, "upstream_error", "boom"); + }); + + const response = await app.inject({ + method: "POST", + url: "/v1/responses", + headers: AUTH, + payload: { model: "opencode/deepseek-v4.1-flash-free", input: "Go.", stream: true }, + }); + + expect(response.statusCode).toBe(200); + const parsed = frames(response.payload); + const numbers = parsed.map((frame) => frame.json.sequence_number); + expect(numbers).not.toContain(Number.MAX_SAFE_INTEGER); + expect(numbers).toEqual(numbers.map((_, index) => index)); + expect(parsed.at(-1)?.event).toBe("response.failed"); + }); + + it("keeps the live counter when the stream fails after its first frames", async () => { + // The first serialisation of this tool call throws, aborting + // `finaliseStream` and routing the failure through the outer stream catch; + // the second serialisation (of the `response.failed` payload) succeeds. + let serialisations = 0; + const flakyArguments = { + toJSON: (): string => { + serialisations += 1; + if (serialisations === 1) throw new Error("unserialisable frame"); + return "{}"; + }, + }; + const app = await makeApp({ + script: (request): CompletionEvent[] => [ + { kind: "start", sessionId: "ses_outer", messageId: "msg_outer", model: request.model, agent: "build", reusedSession: false, reasoningEnabled: false }, + { kind: "tool_calls", calls: [{ id: "call_1", name: "lookup", arguments: flakyArguments as unknown as string }] }, + { kind: "end", finishReason: "stop", usage: { ...EMPTY_USAGE }, messageId: "msg_outer" }, + ], + }); + + const response = await app.inject({ + method: "POST", + url: "/v1/responses", + headers: AUTH, + payload: { model: "opencode/deepseek-v4.1-flash-free", input: "Go.", stream: true }, + }); + + expect(response.statusCode).toBe(200); + const parsed = frames(response.payload); + const numbers = parsed.map((frame) => frame.json.sequence_number); + expect(numbers).not.toContain(Number.MAX_SAFE_INTEGER); + expect(numbers).toEqual(numbers.map((_, index) => index)); + expect(parsed.at(-1)?.event).toBe("response.failed"); + }); + it("surfaces a consolidated reasoning summary sent without deltas", async () => { const app = await makeApp({ script: (): CompletionEvent[] => { @@ -632,3 +899,64 @@ describe("POST /v1/responses (streaming)", () => { expect((response.json() as ResponsePayload).object).toBe("response"); }); }); + +describe("POST /v1/responses (media concurrency)", () => { + let server: http.Server; + let baseUrl: string; + + beforeAll(async () => { + server = http.createServer((_request, response) => { + // Every response is delayed, so resolving N parts serially costs N times + // the delay while resolving them concurrently costs roughly one delay. + setTimeout(() => { + response.writeHead(200, { "content-type": "image/png" }); + response.end(PNG_BUFFER); + }, MEDIA_DELAY_MS); + }); + await new Promise((resolve) => server.listen(0, "127.0.0.1", resolve)); + baseUrl = `http://127.0.0.1:${(server.address() as AddressInfo).port}`; + }); + + afterAll(async () => { + await new Promise((resolve) => server.close(() => resolve())); + }); + + it("resolves the media parts of one message concurrently, in declaration order", async () => { + let captured: InternalRequest | undefined; + const app = await makeApp({ + config: { allowPrivateMediaUrls: true }, + onRun: (request) => (captured = request), + }); + + const startedAt = Date.now(); + const response = await app.inject({ + method: "POST", + url: "/v1/responses", + headers: AUTH, + payload: { + model: "opencode/deepseek-v4.1-flash-free", + input: [ + { + role: "user", + content: [ + { type: "input_text", text: "two images" }, + { type: "input_image", image_url: `${baseUrl}/first.png` }, + { type: "input_image", image_url: `${baseUrl}/second.png` }, + ], + }, + ], + }, + }); + const elapsed = Date.now() - startedAt; + + expect(response.statusCode).toBe(200); + const attachments = captured?.messages.at(-1)?.attachments ?? []; + expect(attachments.map((attachment) => attachment.origin)).toEqual([ + `${baseUrl}/first.png`, + `${baseUrl}/second.png`, + ]); + expect(attachments.every((attachment) => attachment.mime === "image/png")).toBe(true); + // Serial resolution would need at least two full fixture delays. + expect(elapsed).toBeLessThan(MEDIA_DELAY_MS * 2 - 10); + }); +}); diff --git a/test/process.test.ts b/test/process.test.ts index d1cd142..da2036f 100644 --- a/test/process.test.ts +++ b/test/process.test.ts @@ -121,4 +121,39 @@ describe("UpstreamProcess", () => { expect(process.status().ready).toBe(false); expect(process.status().lastError).toContain("exited"); }); + + it("kills a stale spawned server and spawns a replacement on the next resolve", async () => { + const { process, children } = harness(); + + const first = await process.resolve(); + expect(process.status().ready).toBe(true); + + process.markStale("hung upstream"); + + // A hung spawned server used to keep `ready: true` and be reused forever. + expect(process.status().ready).toBe(false); + expect(process.status().lastError).toBe("hung upstream"); + + const second = await process.resolve(); + expect(children).toHaveLength(2); + expect(second.pid).not.toBe(first.pid); + expect(children[0]?.signals).toContain("SIGKILL"); + expect(process.status().ready).toBe(true); + expect(process.status().url).toBe(second.url); + }); + + it("does not report a late stale-server exit over the replacement", async () => { + const { process, children } = harness(); + await process.resolve(); + process.markStale("slow"); + const second = await process.resolve(); + await tick(); // the killed child reports its exit here + + // A successful resolve clears the error; the late exit of the killed child + // must not clear the tracking of the live replacement. + expect(process.status().ready).toBe(true); + expect(process.status().url).toBe(second.url); + await process.stop(); + expect(children[1]?.signals).toContain("SIGTERM"); + }); }); \ No newline at end of file diff --git a/test/reasoning.test.ts b/test/reasoning.test.ts index de77d99..1515859 100644 --- a/test/reasoning.test.ts +++ b/test/reasoning.test.ts @@ -116,6 +116,28 @@ describe("reasoning effort helpers", () => { expect(decision.note).toContain("does not expose"); }); + it("never selects a 'none' variant when reasoning was requested", () => { + // A model whose only effort variant is `none` cannot think at all. + expect(supportsReasoning(["default", "none"])).toBe(false); + const unsupported = resolveVariant({ + available: ["default", "none"], + reasoning: { enabled: true, effort: "minimal" }, + mode: "on-request", + }); + expect(unsupported.variant).toBeUndefined(); + expect(unsupported.reasoningEnabled).toBe(false); + + // With a real effort variant available, `none` must be skipped, not chosen + // just because it is the closest entry on the ladder. + const decision = resolveVariant({ + available: ["default", "none", "high"], + reasoning: { enabled: true, effort: "minimal" }, + mode: "on-request", + }); + expect(decision.variant).toBe("high"); + expect(decision.reasoningEnabled).toBe(true); + }); + it("forces medium when the server policy is 'always'", () => { const decision = resolveVariant({ available: FULL_LADDER, mode: "always" }); expect(decision.variant).toBe("medium"); diff --git a/test/regressions.test.ts b/test/regressions.test.ts index 0bb35f9..0b3635d 100644 --- a/test/regressions.test.ts +++ b/test/regressions.test.ts @@ -263,7 +263,9 @@ describe("OpenAI responses surface (scripted)", () => { expect(call?.["call_id"]).toBe("call_1"); const usage = body["usage"] as Record; expect(usage["input_tokens"]).toBe(10); - expect(usage["output_tokens"]).toBe(5); + // OpenAI semantics: reasoning tokens are a subset of output tokens. + expect(usage["output_tokens"]).toBe(8); + expect(usage["total_tokens"]).toBe(18); await app.close(); }); @@ -395,7 +397,7 @@ describe("Anthropic messages surface (scripted)", () => { expect((starts[1]?.json["content_block"] as Record)["type"]).toBe("text"); expect((starts[2]?.json["content_block"] as Record)["type"]).toBe("tool_use"); const deltas = frames.filter((frame) => frame.event === "content_block_delta").map((frame) => frame.json["delta"] as Record); - expect(deltas.map((delta) => delta["type"])).toEqual(["thinking_delta", "text_delta", "input_json_delta"]); + expect(deltas.map((delta) => delta["type"])).toEqual(["thinking_delta", "signature_delta", "text_delta", "input_json_delta"]); const messageDelta = frames.find((frame) => frame.event === "message_delta"); expect((messageDelta?.json["delta"] as Record)["stop_reason"]).toBe("tool_use"); await app.close(); @@ -718,4 +720,21 @@ describe("adversarial input handling", () => { expect(errorFrame?.json.retry_after_ms).toBe(30_000); await app.close(); }); +}); + +describe("HTTP metrics label cardinality", () => { + it("labels unmatched requests with a bounded sentinel instead of the raw URL", async () => { + const ctx = createTestContext(); + const app = await buildServer(ctx); + // Unauthenticated callers can choose any path; prom-client keeps one series + // per label set forever, so the raw path must never become a label. + await app.inject({ method: "GET", url: "/random-path-abc-123" }); + await app.inject({ method: "GET", url: "/another-path-zzz-456" }); + await app.close(); + + const exposition = await ctx.metrics.registry.metrics(); + expect(exposition).toContain('route="unmatched"'); + expect(exposition).not.toContain("random-path-abc-123"); + expect(exposition).not.toContain("another-path-zzz-456"); + }); }); \ No newline at end of file diff --git a/test/sessions.test.ts b/test/sessions.test.ts index bed0fe3..4df4390 100644 --- a/test/sessions.test.ts +++ b/test/sessions.test.ts @@ -1,4 +1,7 @@ -import { describe, expect, it } from "vitest"; +import fs from "node:fs"; +import os from "node:os"; +import path from "node:path"; +import { afterEach, describe, expect, it } from "vitest"; import { createLogger } from "../src/logger.js"; import { createMetrics } from "../src/metrics/registry.js"; import { SessionStore, deriveKey, hashMessages, hashTools } from "../src/upstream/sessions.js"; @@ -15,6 +18,24 @@ function store(overrides: Parameters[0] = {}): SessionStore { return new SessionStore(config, createLogger(config), createMetrics({ enabled: false })); } +const tempDirs: string[] = []; + +afterEach(() => { + while (tempDirs.length > 0) { + const dir = tempDirs.pop(); + if (dir) fs.rmSync(dir, { recursive: true, force: true }); + } +}); + +/** Construct a persistent store whose `sessions.json` contains `records`. */ +function persistedStore(records: Record): SessionStore { + const dataDir = fs.mkdtempSync(path.join(os.tmpdir(), "opencode-sessions-")); + tempDirs.push(dataDir); + fs.writeFileSync(path.join(dataDir, "sessions.json"), JSON.stringify(records), "utf8"); + const config = testConfig({ sessionPersist: true, dataDir }); + return new SessionStore(config, createLogger(config), createMetrics({ enabled: false })); +} + const BASE_INPUT = { model: "opencode/big-pickle", agent: "build", toolsHash: "none" } as const; describe("SessionStore", () => { @@ -151,6 +172,43 @@ describe("SessionStore", () => { expect(sessions.size()).toBe(0); }); + it("restores only valid persisted records and recovers a missing lastUsedAt", () => { + const now = Date.now(); + const base = { + model: "opencode/big-pickle", + agent: "build", + prefixHash: "hash", + createdAt: now, + busy: false, + reusedCount: 0, + }; + const sessions = persistedStore({ + "k-valid:ses_valid": { ...base, key: "k-valid", sessionId: "ses_valid", deliveredCount: 2, lastUsedAt: now }, + // Older records may predate `lastUsedAt`; it must be recovered from + // `createdAt` instead of leaving an entry that `sweep()` can never expire. + "k-recovered:ses_recovered": { ...base, key: "k-recovered", sessionId: "ses_recovered", deliveredCount: 1 }, + "k-zero:ses_zero": { + ...base, + key: "k-zero", + sessionId: "ses_zero", + deliveredCount: 0, + lastUsedAt: now, + }, + }); + + try { + const restored = sessions.list(); + expect(restored.map((record) => record.sessionId).sort()).toEqual(["ses_recovered", "ses_valid"]); + expect(restored.find((record) => record.sessionId === "ses_recovered")?.lastUsedAt).toBe(now); + expect(sessions.size()).toBe(2); + + expect(sessions.sweep(now + 3_600_000)).toBe(2); + expect(sessions.size()).toBe(0); + } finally { + sessions.stop(); + } + }); + it("evicts the least recently used session past the limit", () => { const sessions = store({ sessionMaxEntries: 2 }); for (const id of ["a", "b", "c"]) { diff --git a/test/shutdown.test.ts b/test/shutdown.test.ts new file mode 100644 index 0000000..0dcfde5 --- /dev/null +++ b/test/shutdown.test.ts @@ -0,0 +1,91 @@ +/** + * Bounded shutdown. + * + * A hung `app.close()` (an in-flight SSE, for example) must not stop the gateway + * from stopping its upstream child, and a second signal must not run the hooks + * again. + */ +import { describe, expect, it, vi } from "vitest"; +import { DEFAULT_DRAIN_MS, shutdown, type ShutdownApp, type ShutdownDeps } from "../src/http/shutdown.js"; + +interface Stub { + deps: ShutdownDeps; + events: ReturnType; + sessions: ReturnType; + upstream: ReturnType; + warnings: string[]; +} + +function stub(): Stub { + const events = vi.fn(async () => undefined); + const sessions = vi.fn(() => undefined); + const upstream = vi.fn(async () => undefined); + const warnings: string[] = []; + const log = { + info: () => undefined, + warn: (context: unknown, message?: unknown) => { + warnings.push(`${String(message)} ${JSON.stringify(context)}`); + }, + error: () => undefined, + } as unknown as ShutdownDeps["log"]; + return { + deps: { log, events: { stop: events }, sessions: { stop: sessions }, upstream: { stop: upstream } }, + events, + sessions, + upstream, + warnings, + }; +} + +function appWith(close: () => Promise, forceClose?: () => void): ShutdownApp { + const app: { close: () => Promise; server?: { closeAllConnections?: () => void } } = { close }; + if (forceClose) app.server = { closeAllConnections: forceClose }; + return app as ShutdownApp; +} + +describe("shutdown", () => { + it("resolves within the drain deadline when app.close() never settles", async () => { + const s = stub(); + const forceClose = vi.fn(); + const never = new Promise(() => undefined); + + const startedAt = Date.now(); + await shutdown(s.deps, appWith(() => never, forceClose), 25); + + expect(Date.now() - startedAt).toBeLessThan(1_000); + expect(forceClose).toHaveBeenCalledTimes(1); + expect(s.events).toHaveBeenCalledTimes(1); + expect(s.sessions).toHaveBeenCalledTimes(1); + expect(s.upstream).toHaveBeenCalledTimes(1); + }); + + it("does not run the stop hooks twice on a double invocation", async () => { + const s = stub(); + const app = appWith(async () => undefined); + + await shutdown(s.deps, app, 25); + await shutdown(s.deps, app, 25); + + expect(s.events).toHaveBeenCalledTimes(1); + expect(s.sessions).toHaveBeenCalledTimes(1); + expect(s.upstream).toHaveBeenCalledTimes(1); + }); + + it("stops the upstream even when closing the server fails", async () => { + const s = stub(); + const app = appWith(async () => { + throw new Error("close failed"); + }); + + await shutdown(s.deps, app, 25); + + expect(s.events).toHaveBeenCalledTimes(1); + expect(s.sessions).toHaveBeenCalledTimes(1); + expect(s.upstream).toHaveBeenCalledTimes(1); + expect(s.warnings.some((line) => line.includes("closing the HTTP server failed"))).toBe(true); + }); + + it("keeps a 10 second default drain", () => { + expect(DEFAULT_DRAIN_MS).toBe(10_000); + }); +}); \ No newline at end of file diff --git a/test/tools.test.ts b/test/tools.test.ts index 0921655..693e6e5 100644 --- a/test/tools.test.ts +++ b/test/tools.test.ts @@ -48,6 +48,16 @@ describe("tool bridge instructions", () => { expect(createToolBridge([WEATHER], { name: "get_weather" }).instructions).toContain("exactly one tool call"); expect(createToolBridge([WEATHER], { name: "unknown" }).instructions).toContain("unknown tool"); }); + + it("asks for at most one call when parallel tool calls are disabled", () => { + const single = createToolBridge([WEATHER], "auto", { parallelToolCalls: false }).instructions; + expect(single).toContain("at most one tool call block"); + + expect(createToolBridge([WEATHER], "auto").instructions).not.toContain("at most one tool call block"); + expect(createToolBridge([WEATHER], "auto", { parallelToolCalls: true }).instructions).not.toContain( + "at most one tool call block", + ); + }); }); describe("parseToolCallBody", () => { @@ -89,6 +99,25 @@ describe("parseToolCallBody", () => { expect(parseToolCallBody("")).toEqual([]); expect(parseToolCallBody('{"arguments":{}}')).toEqual([]); }); + + it("collects several adjacent JSON values from one envelope body", () => { + const calls = parseToolCallBody('{"name":"a","arguments":{}}\n{"name":"b","arguments":{}}'); + expect(calls.map((call) => call.name)).toEqual(["a", "b"]); + }); + + it("collects an object followed by an array from one envelope body", () => { + const calls = parseToolCallBody('{"name":"a","arguments":{}}\n[{"name":"b","arguments":{"x":1}}]'); + expect(calls.map((call) => call.name)).toEqual(["a", "b"]); + expect(calls[1]?.arguments).toBe('{"x":1}'); + }); + + it("keeps every call and no prose when an envelope holds adjacent values", () => { + const parsed = parseAssistantText( + `${TOOL_CALL_OPEN}{"name":"a","arguments":{}}\n{"name":"b","arguments":{}}${TOOL_CALL_CLOSE}`, + ); + expect(parsed.calls.map((call) => call.name)).toEqual(["a", "b"]); + expect(parsed.text).toBe(""); + }); }); describe("normaliseArguments", () => {