diff --git a/README.md b/README.md index 0c5197e..f3751b5 100644 --- a/README.md +++ b/README.md @@ -330,7 +330,9 @@ model actually offers. * OpenAI chat: `reasoning_effort` (or `reasoning.effort`) — `none`, `minimal`, `low`, `medium`, `high`, `xhigh`, `max`. Common aliases are accepted (`off`/`disabled` → `none`, `min`/`lowest` → `minimal`, - `default`/`normal`/`mid` → `medium`, `maximum`/`highest` → `max`). + `default`/`normal`/`mid` → `medium`, `maximum`/`highest` → `max`). A value + outside that set is rejected with `400 invalid_request` rather than silently + treated as `medium`. * OpenAI Responses: `reasoning.effort`. * Anthropic: `thinking: {type:"enabled", budget_tokens: N}` (bucketed: `<2k`→minimal, `<6k`→low, `<16k`→medium, `<40k`→high, `<80k`→xhigh, else max) @@ -436,13 +438,16 @@ JSON output is bridged through the prompt for the same reason function calling i | --- | --- | --- | | `/v1/chat/completions` | `response_format` | `{"type":"json_object"}`, `{"type":"json_schema","json_schema":{name,schema}}` | | `/v1/responses` | `text.format` | `{"type":"json_object"}`, `{"type":"json_schema",name,schema}` | +| `/v1/messages` | `output_config.format` | `{"type":"json_object"}`, `{"type":"json_schema",schema?}` | `{"type":"text"}` and an absent field leave the prompt unchanged. The gateway adds a `# Response format` prompt section asking for a single valid JSON value and, for a schema, for a value that validates against it. This is a model contract, not a server-enforced one: nothing validates the reply, so a model that ignores the instruction can still answer in prose. Validate the result on the -client when it matters. +client when it matters. For the same reason `strict: true` — which promises +server-enforced conformance — is rejected with `400 unsupported_parameter` +instead of accepted and ignored. ## Model naming diff --git a/docs/API.md b/docs/API.md index 5e85a67..2ec1d8a 100644 --- a/docs/API.md +++ b/docs/API.md @@ -21,7 +21,7 @@ operational; it is summarised at the end of this document and in the README. | Name | Kind | Meaning | | --- | --- | --- | -| `x_opencode` | response field | Non-standard object carried by every buffered completion payload and by the `response` object of the `/v1/responses` SSE events (`response.created`, `response.in_progress`, `response.completed`, `response.failed`): `session_id`, `agent`, `variant`, `reused_session`, and `native_tool_calls` (an array on the OpenAI surfaces, a count on the Anthropic surface) plus `reasoning: {enabled, note}` on the two OpenAI completion surfaces (`/v1/chat/completions`, `/v1/completions`). `unapplied` (array) names the generation knobs the request supplied that the gateway recorded but could not apply, in the fixed order `temperature, top_p, presence_penalty, frequency_penalty, seed, logit_bias, max_tokens, max_completion_tokens, max_output_tokens`; the key is omitted when none were supplied. The Anthropic streamed sequence and the two OpenAI streamed sequences do not carry `x_opencode`; one exception: the Anthropic `message_delta` of a cancelled turn carries `x_opencode: {"interrupted": true}`, because the stop reason alone cannot express the interruption. | +| `x_opencode` | response field | Non-standard object carried by every buffered completion payload and by the `response` object of the `/v1/responses` SSE events (`response.created`, `response.in_progress`, `response.completed`, `response.failed`): `session_id`, `agent`, `variant`, `reused_session`, and `native_tool_calls` (an array on the OpenAI surfaces, a count on the Anthropic surface) plus `reasoning: {enabled, note}` on the two OpenAI completion surfaces (`/v1/chat/completions`, `/v1/completions`). `unapplied` (array) names the generation knobs the request supplied that the gateway recorded but could not apply, in the fixed order `temperature, top_p, presence_penalty, frequency_penalty, seed, logit_bias, max_tokens, max_completion_tokens, max_output_tokens, service_tier`; the key is omitted when none were supplied. The Anthropic streamed sequence and the two OpenAI streamed sequences do not carry `x_opencode`; one exception: the Anthropic `message_delta` of a cancelled turn carries `x_opencode: {"interrupted": true}`, because the stop reason alone cannot express the interruption. | | `x-conversation-id` | request header | Explicit sticky-session key. Requests carrying the same value reuse the same upstream OpenCode session only while the model, agent, variant, tool set, permission profile and message prefix all still match. | | `x-opencode-agent` | request header | Run this request with a specific OpenCode agent instead of `OPENCODE_AGENT`. | | `x-request-id` | request/response header | Caller-supplied correlation id, echoed on every response (JSON and SSE). Accepted when it matches `[A-Za-z0-9._:-]{1,128}`; anything else is replaced by a generated id. The same value is used as the request id in the gateway logs. | @@ -54,9 +54,20 @@ with a `retry-after` header once that budget is spent. > streamed path). > * The generation knobs OpenCode's agent loop owns — `temperature`, `top_p`, > `presence_penalty`, `frequency_penalty`, `seed`, `logit_bias`, `max_tokens`, -> `max_completion_tokens`, `max_output_tokens` — are accepted and recorded for -> client compatibility but cannot be applied. Every response names them in -> `x_opencode.unapplied`, so a caller can detect it instead of guessing. +> `max_completion_tokens`, `max_output_tokens`, `service_tier` — are accepted +> and recorded for client compatibility but cannot be applied. Every response +> names them in `x_opencode.unapplied`, so a caller can detect it instead of +> guessing. +> * Token accounting is normalised per surface. `prompt_tokens` / +> `input_tokens` on the OpenAI surfaces is the **whole** prompt: the upstream +> reports cached input separately, and the gateway folds `cache_read` and +> `cache_write` into it, with `prompt_tokens_details.cached_tokens` (or +> `input_tokens_details.cached_tokens`) a subset that is never larger than the +> prompt. `/v1/messages` keeps the Anthropic convention instead, where +> `input_tokens` excludes `cache_read_input_tokens` and +> `cache_creation_input_tokens`. Thinking tokens are a subset of +> `completion_tokens` / `output_tokens` on every surface, so +> `total_tokens` is always `prompt + completion`. > * A field that would change the *shape* of the response and cannot be emulated > at all is rejected with `400 unsupported_parameter`, naming the field in > `param` (see the individual rows: `logprobs`/`top_logprobs`, non-text @@ -82,6 +93,7 @@ with a `retry-after` header once that budget is spent. | `messages[].content[].input_audio` | `{data, format}` | — | `format` is `wav`, `mp3`, `m4a`, `mp4`, `webm`, `ogg`, `opus`, `flac`, `aac`, `pcm` or a full MIME type. | | `messages[].content[].file` | `{filename?, file_data?, url?, mime_type?}` | — | `file_data` is base64 or a `data:` URI; `file_id` is rejected with `unsupported_file_reference`. | | `messages[].content[].document` | object | — | Accepts `{url}`, `{data}`, `{path}` or an Anthropic-style nested `{source:{media_type,data}}`. | +| media parts on a non-`user` role | — | — | Rejected with `400 invalid_request` (`param: "messages"`). OpenAI only allows image/audio/file parts on a user message, and the gateway forwards the attachments of user turns only, so accepting one would download and then silently drop the input. | | `messages[].tool_calls` | array | — | Assistant tool calls echoed back by the client. | | `messages[].tool_call_id` | string | — | Required on `role: "tool"` messages. | | `messages[].name` | string | — | Optional tool name on `role: "tool"`. | @@ -89,15 +101,15 @@ with a `retry-after` header once that budget is spent. | `stream_options.include_usage` | boolean | `false` | Append a usage-only chunk (with `choices: []`) before `[DONE]`. | | `tools` | array | *(none)* | OpenAI declarations `{type:"function",function:{name,description,parameters}}`. Bridged through the prompt. | | `tool_choice` | `auto` \| `none` \| `required` \| `{type:"function",function:{name}}` | `auto` | Rendered into the bridge instructions. `400 invalid_request` (`param: "tool_choice"`) when it requires a tool but `tools` is absent or empty, or when it names a function the request never declared. | -| `reasoning_effort` | string | *(unset)* | `none`, `minimal`, `low`, `medium`, `high`, `xhigh`, `max` plus aliases (`off`, `min`, `maximum`, ...). | +| `reasoning_effort` | string | *(unset)* | `none`, `minimal`, `low`, `medium`, `high`, `xhigh`, `max` plus aliases (`off`, `min`, `maximum`, ...). A non-empty value outside that set is `400 invalid_request` (`param: "reasoning_effort"`) instead of being silently folded into `medium`. | | `reasoning.effort` | string | *(unset)* | Used when `reasoning_effort` is absent. | | `max_tokens` / `max_completion_tokens` | number | *(unset)* | `max_completion_tokens` wins. Accepted and recorded, not enforced upstream: OpenCode's agent owns the generation budget. Listed in `x_opencode.unapplied` when supplied. | | `temperature`, `top_p` | number | *(unset)* | Accepted and recorded, but not forwarded: OpenCode's agent loop owns the sampling parameters. Listed in `x_opencode.unapplied` when supplied. | | `stop` | string \| string[] | *(unset)* | **Honoured on both paths**: the visible text is truncated at the first delimiter, empty strings are dropped. Generation upstream is not interrupted, so `usage` counts the full turn and `finish_reason` stays `stop`. | | `n` | number | `1` | **Only `1` is supported**; anything else returns `400 invalid_request`. | -| `user`, `metadata`, `service_tier` | — | — | Accepted; not forwarded and **not logged**. `metadata` is carried on the internal request so a future surface can use it, but nothing reads it today. | +| `user`, `metadata`, `service_tier` | — | — | Accepted; not forwarded and **not logged**. `metadata` is carried on the internal request so a future surface can use it, but nothing reads it today. `service_tier` is recorded and named in `x_opencode.unapplied` when supplied. | | `parallel_tool_calls` | boolean | `true` | `false` makes the tool bridge ask the model for at most one bridged tool call per turn; `true`/absent allows several. | -| `response_format` | object | *(unset)* | `{"type":"text"}`, `{"type":"json_object"}` or `{"type":"json_schema","json_schema":{name,schema}}`. OpenCode cannot receive an output schema, so the requirement is rendered into the prompt (see "JSON output mode" below); it is a model contract, not a server-enforced one. | +| `response_format` | object | *(unset)* | `{"type":"text"}`, `{"type":"json_object"}` or `{"type":"json_schema","json_schema":{name,schema}}`. OpenCode cannot receive an output schema, so the requirement is rendered into the prompt (see "JSON output mode" below); it is a model contract, not a server-enforced one. `json_schema.strict: true` therefore promises a guarantee the gateway cannot give and is rejected with `400 unsupported_parameter` (`param: "response_format.json_schema.strict"`); `strict: false` is accepted. | | `seed`, `logprobs`, `logit_bias`, `presence_penalty`, `frequency_penalty` | — | — | `seed`, `logit_bias`, `presence_penalty` and `frequency_penalty` are accepted and recorded, and named in `x_opencode.unapplied` when supplied. `logprobs`/`top_logprobs` are **rejected** with `400 unsupported_parameter` unless they are disabled (`logprobs: false`), because the gateway cannot produce token-level scores. | | `best_of`, `suffix` | — | — | Rejected with `400 unsupported_parameter` naming the field, like `/v1/completions`: the gateway produces exactly one candidate and does not echo a suffix. An explicit `null` is treated as unset. | | `messages[].content[].image_url.detail` | string | `auto` | Only `"auto"` is accepted; the gateway cannot downscale media, so any other value is `400 unsupported_parameter` with `param: "messages"`. | @@ -274,7 +286,7 @@ reasoning mapping and tool bridging with the chat endpoint. | Field | Type | Default | Notes | | --- | --- | --- | --- | -| `model` | string | — | Required. Same naming rules as chat. | +| `model` | string | — | Required and non-empty: `model: ""` is `400 invalid_request` with `param: "model"`. Same naming rules as chat. | | `input` | string \| array | — | Required, and a non-empty string or array: `input: []` is `400 invalid_request` with `param: "input"` rather than an empty prompt. Items: `message` (`{role, content}`, `type` optional), `function_call`, `function_call_output`, `reasoning`, `item_reference`. Roles: `user`, `assistant`, `system`, `developer`. | | `input[].content` parts | — | — | `input_text`, `output_text`, `summary_text` (text is used), `refusal` (the refusal text is used), `input_image`, `input_file`, `input_audio`, `video_url`. | | `instructions` | string | *(unset)* | Prepended as a `system` turn **and echoed** on the response object. | @@ -283,12 +295,14 @@ reasoning mapping and tool bridging with the chat endpoint. | `tool_choice` | `auto` \| `none` \| `required` \| `{type:"function",name}` | `auto` | Bridged into the prompt; echoed back as `auto`, `none`, `required` or `function:`. Anything else (for example `"bogus"` or the `allowed_tools` form) is `400 unsupported_parameter` with `param: "tool_choice"` instead of being silently ignored, and the echo always reflects the validated value. `400 invalid_request` (`param: "tool_choice"`) when it requires a tool but `tools` is absent or empty, or when it names a function the request never declared. | | `reasoning.effort` | string | *(unset)* | Same ladder as `reasoning_effort`. `reasoning.summary` is echoed only. | | `max_output_tokens`, `temperature`, `top_p`, `metadata`, `truncation` | — | — | Accepted and echoed back; `truncation` defaults to `"disabled"` and is **not applied** (the gateway never trims history), and the other four are echoed but not forwarded to the provider. `metadata` is not logged. `max_output_tokens`, `temperature` and `top_p` are named in `x_opencode.unapplied` when supplied. | +| `service_tier` | string | *(unset)* | Accepted and recorded but **not echoed**; named in `x_opencode.unapplied` when supplied. | | `parallel_tool_calls` | boolean | `true` | Echoed; `false` makes the tool bridge ask for at most one bridged tool call per turn. | | `previous_response_id` | string | *(unset)* | **Rejected** with `400 unsupported_parameter`: the gateway keeps no response store, so resend the full `input`. The successful response echoes it as `null`. | | `store` | boolean | `false` | `store: false` is accepted and echoed (nothing is persisted); `store: true` is rejected with `400 unsupported_parameter`. | -| `text.format` | object | *(unset)* | `{"type":"text"}`, `{"type":"json_object"}` or `{"type":"json_schema",name,schema}`. Rendered into the prompt like the chat `response_format`; see "JSON output mode". | +| `text.format` | object | *(unset)* | `{"type":"text"}`, `{"type":"json_object"}` or `{"type":"json_schema",name,schema}`. Rendered into the prompt like the chat `response_format`; see "JSON output mode". The effective format is **echoed** on the response object as `text.format`, defaulting to `{"type":"text"}`. `strict: true` promises server-enforced conformance the gateway cannot give and is rejected with `400 unsupported_parameter` (`param: "text.format.strict"`). | | `include`, `top_logprobs`, `modalities`, `audio`, `prediction`, `web_search_options`, `functions`, `function_call`, `seed`, `presence_penalty`, `frequency_penalty`, `logit_bias` | — | — | The generation knobs (`seed`, penalties, `logit_bias`) are accepted and recorded, and named in `x_opencode.unapplied` when supplied. Everything else in this row is rejected with `400 unsupported_parameter` naming the field: `include` must be empty, `logprobs`/`top_logprobs` cannot be produced, an audio modality cannot be answered, and the legacy `functions`/`function_call` shape is not emulated. `function_call: "none"`, `store: false`, `logprobs: false` and `include: []` are accepted as no-ops. | | `input[].content[].detail` | string | `auto` | Only `"auto"` is accepted; the gateway cannot downscale media, so any other value is `400 unsupported_parameter` with `param: "input"`. | +| media parts on a non-`user` input message | — | — | Rejected with `400 invalid_request` (`param: "input"`). Media is accepted on a `user` message and inside a `function_call_output` (re-homed onto the enclosing user turn); any other role would have its media downloaded and then dropped, because only user turns carry attachments upstream. | `item_reference` items are skipped (they point at stored responses the gateway does not keep). `reasoning` items are accepted and ignored: a caller may resend a @@ -341,6 +355,7 @@ leaving a `[image: ]` / `[document: ]` marker in the tool text "tools": [], "temperature": null, "top_p": null, + "text": { "format": { "type": "text" } }, "reasoning": { "effort": null, "summary": null }, "metadata": {}, "incomplete_details": null, @@ -368,6 +383,9 @@ leaving a `[image: ]` / `[document: ]` marker in the tool text failure. * The `reasoning` output item is emitted only when reasoning was surfaced; both `summary` and `content` carry the same text. +* `text.format` echoes the effective output format (`{"type":"text"}` when the + request supplied none), so a client reading the typed response object can + always see which contract was requested. * Bridged tool calls are appended as output items in order: ```json @@ -484,14 +502,14 @@ the wire format. Use `/v1/chat/completions` for anything new. | 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. | +| `prompt` | string \| string[] | — | Required. One element is accepted and becomes the user message; more than one is `400 unsupported_parameter` with `param: "prompt"`, because the gateway produces exactly one candidate and silently joining them would return a completion that matches none of the prompts. | | `n` | number | `1` | Only `1` is supported; any other value is `400 invalid_request`. | | `stream` | boolean | `false` | Emit `text_completion` SSE chunks terminated by `data: [DONE]`. | | `stream_options.include_usage` | boolean | `false` | Adds a final usage-only chunk (`choices: []`). | -| `max_tokens`, `temperature` | — | *(unset)* | Accepted and recorded; the OpenCode agent owns the generation budget and the sampling parameters, so they are not applied. Both are named in `x_opencode.unapplied` when supplied. | +| `max_tokens`, `temperature`, `top_p` | — | *(unset)* | Accepted and recorded; the OpenCode agent owns the generation budget and the sampling parameters, so they are not applied. All are named in `x_opencode.unapplied` when supplied. | | `stop` | string \| string[] | *(unset)* | **Honoured on both paths**: the visible text is truncated at the first delimiter and `finish_reason` stays `stop`. Generation upstream is not interrupted. | | `presence_penalty`, `frequency_penalty`, `seed`, `logit_bias` | — | *(unset)* | Accepted and recorded, not applied; named in `x_opencode.unapplied` when supplied. | -| `user` | string | — | Accepted and ignored (correlation is done with `x-request-id`). | +| `service_tier`, `user` | string | — | Accepted and ignored (`user` correlation is done with `x-request-id`); `service_tier` is named in `x_opencode.unapplied` when supplied. | | `echo` | boolean | `false` | `true` is rejected with `400 unsupported_parameter` (the prompt is rewritten before it reaches the model). | | `suffix`, `best_of` | — | — | Rejected with `400 unsupported_parameter` naming the field. | | `logprobs`, `top_logprobs` | — | — | Rejected with `400 unsupported_parameter` unless disabled (`logprobs: false` or `0`), because the gateway cannot produce token-level scores. | @@ -579,7 +597,8 @@ Anthropic Messages API. | `system` | string \| array | *(unset)* | Array form accepts `{type:"text",text}` blocks. Joined with blank lines. | | `stream` | boolean | `false` | Emit the Anthropic SSE sequence. | | `thinking` | object | *(unset)* | `{type:"enabled",budget_tokens}` or `{type:"disabled"}`. `budget_tokens` must be an **integer ≥ 1**, and `type:"enabled"` without it is `400 invalid_request` with `param: "thinking.budget_tokens"`, matching the Anthropic contract. (The non-standard `effort` key is accepted and mapped exactly like the top-level `reasoning_effort`; a request using only `effort` does not need a budget.) | -| `reasoning_effort` | string | *(unset)* | Extension: OpenAI-style alias for `thinking`. Ignored when `thinking` is present. | +| `reasoning_effort` | string | *(unset)* | Extension: OpenAI-style alias for `thinking`. Ignored when `thinking` is present. An unrecognised non-empty value is `400 invalid_request` (`param: "reasoning_effort"`). | +| `output_config` | object | *(unset)* | `{effort?, format?}`. `effort` selects the thinking level exactly like `reasoning_effort` but only when `thinking` is absent, and `format` (`{type:"text"}` \| `{type:"json_object"}` \| `{type:"json_schema",schema?}`) becomes the internal response format, rendered into the prompt like `response_format`. `null` is treated as unset. | | `tools` | array | *(none)* | `{name,description,input_schema}`. Bridged through the prompt. | | `tool_choice` | `{type:"auto"}` \| `{type:"any"}` \| `{type:"none"}` \| `{type:"tool",name}` | auto | `any` maps to a required call, `tool` to a named call. Any of `auto`, `any` and `tool` additionally accepts `disable_parallel_tool_use: true`, which caps the turn at one tool call. `400 invalid_request` (`param: "tool_choice"`) when it requires a tool but `tools` is absent or empty, or when a named tool was never declared. | | `temperature`, `top_p`, `metadata.user_id` | — | *(unset)* | Accepted and recorded; not forwarded to the provider (the OpenCode agent owns sampling), and `metadata` is **not** logged. | @@ -625,8 +644,11 @@ Anthropic Messages API. `usage.output_tokens` still reports every token the turn produced, which can exceed the visible (truncated) text. * A `thinking` block is emitted only when reasoning was requested and surfaced. - Its `signature` is `base64("opencode-api:")` — a deterministic - placeholder, not a cryptographic attestation. + Its `signature` is `base64("opencode-api:")` — a + deterministic placeholder derived from the response id, not a cryptographic + attestation. Both paths key it on the same gateway id (`message.id`), so a + streamed turn and the buffered form of the same turn always agree; two separate + requests are different messages and therefore sign differently. * `x_opencode.native_tool_calls` is a **count** on this surface. * A turn the upstream reports as failed is **not** a normal response: a buffered request answers `502 api_error` with the Anthropic error body, and a streamed @@ -985,7 +1007,7 @@ body; a request that never finishes is disconnected. It does not apply to a | `session_cache_entries` | gauge | `state` ∈ `entries` \| `busy` | | `event_stream_connected` | gauge | — | | `event_stream_reconnects_total` | counter | `reason` ∈ `idle` \| `ended` \| `rejected` | -| `event_frames_dropped_total` | counter | `reason` ∈ `no_session` \| `no_subscriber` \| `malformed` | +| `event_frames_dropped_total` | counter | `reason` ∈ `no_session` \| `no_subscriber` \| `malformed` \| `stale` | | `rate_limit_rejections_total` | counter | `scope` ∈ `api` \| `admin` | `completions_total` counts **every** exit, including failures: diff --git a/docs/ARCHITECTURE.md b/docs/ARCHITECTURE.md index 692bd63..d18e297 100644 --- a/docs/ARCHITECTURE.md +++ b/docs/ARCHITECTURE.md @@ -142,6 +142,18 @@ Event types the gateway consumes: `finish` is one of `stop | length | tool-calls | content-filter | error | unknown`. `tokens` is `{ input, output, reasoning, cache: { read, write } }`. +The stream is per **session**, not per turn, so a completion scopes the frames it +consumes: the subscription opens before the prompt is issued, and a turn this +gateway interrupted keeps its record committed for reuse while its terminal +frames are still in flight. `execute()` records the instant it is about to issue +the prompt and drops any frame whose envelope `created` predates it (counted as +`event_frames_dropped_total{reason="stale"}`), because accepting one finalised a +fresh turn with no output — an empty answer reported as a normal `stop`. +`created` is only used for ordering when it is recognisably epoch milliseconds +(`EPOCH_MS_FLOOR`), so a seconds-based or duration-like value can never drop a +turn's frames; an assistant message id cannot scope a turn at all, since one +agent turn spans one assistant message per step. + 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 through `onReconnect`. In-flight completions do **not** @@ -220,6 +232,9 @@ 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. +`InternalRequest.serviceTier?: string` is the latest additive field: the OpenAI +surfaces accept `service_tier` for client compatibility, record it there and name +it in `x_opencode.unapplied`, because no OpenCode equivalent exists. `InternalRequest.stop`, `maxTokens`, `temperature` and `topP` were write-only for a while. `stop` is now consumed by the Anthropic surface and by the OpenAI chat @@ -494,10 +509,16 @@ embedded in the upstream `data:` URI only when it matches the RFC 6838 `application/octet-stream`. A value carrying a comma would otherwise turn the payload into a non-base64 body the receiver never decodes. -`isPrivateHost()` normalises the address itself before classifying it: any IPv6 +`isPrivateHost()` normalises the address itself before classifying it: an IPv6 +zone identifier (`%en0`, `%25en0`) is stripped, any IPv6 spelling (full, compressed, IPv4-mapped, IPv4-compatible, dotted tail) is expanded first, then IPv4 is canonicalised, then loopback, RFC1918, link-local, unique-local, -multicast, `0.0.0.0`, `100.64/10` and the cloud-metadata ranges are matched. +multicast, `0.0.0.0`, `100.64/10` and the cloud-metadata ranges are matched. A +colon-containing host that `net.isIP` rejects, and an otherwise unrecognised IPv6 +literal whose last 32 bits decode to a private IPv4, are treated as private; a +single trailing dot is stripped before the hostname table is consulted, so +`localhost.` is loopback. A remote attachment stores `${host}${pathname}` in +`origin` — never a credential or a query string. `isWithinRoots()` compares resolved real paths, so a caller must `realpath` the candidate first. Both are exported for the media path and for tests; the media code never relies on `new URL()` having canonicalised the hostname. @@ -598,6 +619,13 @@ tests can substitute a scripted runner (`test/helpers/context.ts`). * All code, comments, JSDoc, log messages, error messages, tests and docs are in **English**. * Validation uses `zod` (`z.object({...}).safeParse(body)`), and on failure throw `ApiError.badRequest(message, { code: "invalid_request", param })`. +* Route classification — public paths, `/admin/*` versus `/metrics`, the + rate-limit bucket and the Anthropic error envelope — goes through + `classifyPath()` (`src/auth.ts`), which prefers the matched route pattern over + `request.url`. The router matches on the percent-decoded path while the raw URL + keeps the caller's bytes, so comparing `request.url` against a route literal + let `/%61dmin/config` reach an admin route as a general request; never classify + on the raw URL again. * Never call `fetch` to the OpenCode server directly; use `ctx.client`. * Never call the model provider directly; use `runCompletion`/`collectCompletion`. * Streaming handlers must: @@ -631,11 +659,16 @@ tests can substitute a scripted runner (`test/helpers/context.ts`). `OPENCODE_REASONING_FIELD=both` (read from `Config.reasoningField`). * 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`; 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. + `thinking.effort` / top-level `reasoning_effort` / `output_config.effort` as a + convenience (`output_config.format` maps onto `InternalRequest.responseFormat` + when `text(format)` is absent; `thinking` wins over `output_config.effort`). + Reasoning becomes a `thinking` content block with a deterministic `signature` + keyed on the **gateway** message id: the streamed form emits it as + `signature_delta` before the block stops and the buffered form signs with the + same value, while the upstream assistant id is not available when the streamed + block closes (it only arrives with `reasoning_end` / `text_end`). Keying on the + upstream id made the two paths disagree, because the buffered aggregate always + has it and the streamed path usually does not. * Anthropic `stop_sequences` is honoured by an adapter-local filter over assistant text only, shared by both paths (`truncateAtStopSequence`): the visible text is truncated at the first match, `stop_reason` becomes `stop_sequence` and @@ -646,15 +679,24 @@ tests can substitute a scripted runner (`test/helpers/context.ts`). adapters honour `stop` the same way and keep their documented `finish_reason`. * Fields the gateway cannot honour are never silently ignored: the OpenAI surfaces accept the generation knobs (`temperature`, `top_p`, `max_tokens`, - `max_completion_tokens`, `max_output_tokens`, `presence_penalty`, - `frequency_penalty`, `seed`, `logit_bias`) for client compatibility and list - them in `x_opencode.unapplied` on the final payload, and they reject every field - that would change the shape of the response (`logprobs`/`top_logprobs` when - requested, non-text `modalities`, `audio`, `prediction`, `store: true`, - `web_search_options`, legacy `functions`/`function_call`, - `previous_response_id`, non-empty `include`, `best_of`, `suffix`, and any - `detail` other than `"auto"`) with `400 unsupported_parameter` naming the field - in `param`. + `max_completion_tokens`, `max_output_tokens`, `service_tier`, + `presence_penalty`, `frequency_penalty`, `seed`, `logit_bias`) for client + compatibility and list them in `x_opencode.unapplied` on the final payload, and + they reject every field that would change the shape of the response + (`logprobs`/`top_logprobs` when requested, non-text `modalities`, `audio`, + `prediction`, `store: true`, `web_search_options`, legacy + `functions`/`function_call`, `previous_response_id`, non-empty `include`, + `best_of`, `suffix`, `json_schema`/`text.format` with `strict: true`, media parts + on a role that cannot carry them, and any `detail` other than `"auto"`) with + `400 unsupported_parameter` naming the field in `param`. An invalid + `reasoning_effort` is `400 invalid_request` (`param: "reasoning_effort"`) rather + than a silent fold into `medium`. +* Token accounting is per surface: the upstream reports cached input separately + (`input` is the non-cached count), so the OpenAI `prompt_tokens` / + `input_tokens` fold `cache_read` and `cache_write` into the prompt and expose + them as the `cached_tokens` subset, while `/v1/messages` keeps Anthropic's + convention where `input_tokens` excludes them. Thinking tokens are a subset of + the completion/output count on every surface. * `/v1/responses` reports a filtered turn as `status: "incomplete"` with `incomplete_details.reason: "content_filter"`, keeps `created_at` constant for the whole response, echoes `instructions`, announces the reasoning item with @@ -694,15 +736,18 @@ tests can substitute a scripted runner (`test/helpers/context.ts`). * JSON output is bridged through the prompt, exactly like tool calling: `response_format` (chat) and `text.format` (responses) become a `# Response format` prompt section (`InternalRequest.responseFormat`). Nothing - validates the reply server-side. + validates the reply server-side, so `strict: true` is rejected rather than + accepted-and-ignored, and `/v1/responses` echoes the effective `text.format` + (`{"type":"text"}` by default) on the response object. * 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 + array) 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. + verbatim by the agent, and so is a `prompt` array with more than one element — + silently joining them returned a completion that matched none of the prompts. * `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 diff --git a/docs/CONFIGURATION.md b/docs/CONFIGURATION.md index 23b496a..dd85bc4 100644 --- a/docs/CONFIGURATION.md +++ b/docs/CONFIGURATION.md @@ -145,6 +145,9 @@ way: the default (`on-request`, `info`) is kept and a warning naming the variabl is logged. The warning never echoes the value, because an operator can paste a secret into the wrong variable. +`OPENCODE_REASONING_FIELD` follows the same rule: an unrecognised value falls back +to `reasoning_content` and logs the same warning naming the variable. + ## Environment variables read by other libraries `dotenv` loads `.env` from the project root and then the working directory. The diff --git a/docs/VERIFICATION.md b/docs/VERIFICATION.md index cc22b2b..162ddc4 100644 --- a/docs/VERIFICATION.md +++ b/docs/VERIFICATION.md @@ -1,5 +1,11 @@ # OpenCode API — independent verification report +> **This document is a layered record.** Sections 1–5 and the first two addenda +> below describe the 2026-12-02 audit and the remediation passes that followed, in +> their own numbers. The **last addendum** ("current state after the +> audit-and-fix pass of 2026-12-05") is the authoritative current state: where any +> earlier count or line reference disagrees with it, the last addendum is correct. + * **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` at audit time; the released package is `1.0.0`), working tree as of 16:05 local time @@ -323,3 +329,53 @@ Still unresolved at the time of writing: none of the P-01 … P-25 items were le open; the P-14/P-15/P-16/P-17/P-19 documentation, Docker and CI items and the P-18 image smoke test are covered above, and the remaining source-level items are covered by the regression tests named in the proposals file. + +### Addendum — current state after the audit-and-fix pass of 2026-12-05 + +The body and the two earlier addenda above are the historical record of the +2026-12-02 audit and the remediation passes that followed. This addendum is the +authoritative **current** state; where a number above disagrees with this table, +this one is correct. + +| Command | Result | +| --- | --- | +| `pnpm typecheck` | **PASS** — `$ tsc -p tsconfig.json --noEmit`, exit 0 | +| `pnpm build` | **PASS** — `tsc -p tsconfig.build.json`, exit 0, **78** files emitted into `dist/` (39 modules + 39 source maps) | +| `pnpm test` | **PASS** — **30** files, **767 passed**, 2 skipped (769) | +| `pnpm exec vitest run test/docs-consistency.test.ts` | **PASS** — 1 file, **16** tests | +| `pnpm smoke:dist` | **PASS** — `dist/index.js answered /health with version 1.0.0`, then a clean SIGTERM shutdown | + +Numbers quoted earlier in this document that have since changed: + +* `src/config.ts` now reads **51** environment variables (was 49), and all 51 are + listed in `.env.example`, `docs/CONFIGURATION.md` and `README.md`. +* The `GET /` index in `docs/API.md` lists **19** entries; together with `GET /` + itself that is exactly the **20** routes `src/` registers. +* The unit suite is **30 files / 767 passed / 2 skipped**, up from 25 files and + 657 passed; the guards in `test/docs-consistency.test.ts` are now 16. + +This pass fixed, with a regression test for each (details in the commit and in +`IMPROVEMENT_PROPOSALS.md` until that working file is removed): + +* **High** — the admin credential tier was bypassable with a percent-encoded path + (`/%61dmin/config`): classification now uses the matched route, not `request.url` + (`test/auth-surface.test.ts`); OpenAI `prompt_tokens`/`input_tokens` now fold + the cache buckets in, so `cached_tokens` can no longer exceed the prompt + (`test/parity.test.ts`, `test/openai-chat.test.ts`, `test/openai-responses.test.ts`, + `test/regressions.test.ts`); a terminal event left in flight by a previous turn + can no longer finalise the next turn on a sticky session + (`test/completion.test.ts`). +* **Medium** — media on a non-`user` message is rejected instead of downloaded + and dropped; a multi-element `/v1/completions` prompt is rejected instead of + silently joined; an empty or non-object 2xx upstream body is an + `upstream_invalid_json` failure instead of a `500`; a non-object SSE frame no + longer tears down the shared event stream; an abort during upstream resolution + now stops the request before it is issued; Anthropic `output_config` is mapped. +* **Low / hardening** — `json_schema.strict` and invalid `reasoning_effort` are + rejected instead of silently ignored; `/v1/responses` echoes `text.format` and + rejects an empty `model`; `/v1/completions` accepts `top_p`; `service_tier` is + recorded and named in `x_opencode.unapplied`; the Anthropic thinking signature is + keyed on the gateway message id on both paths; SSE field values are CR/LF-safe; + `isPrivateHost()` handles zone ids, unmapped IPv6 literals and trailing-dot + names; `OPENCODE_REASONING_FIELD` warns on a typo; the docs-consistency guard + also pins the documented `service`/`version`. diff --git a/src/adapter/anthropic/messages.ts b/src/adapter/anthropic/messages.ts index 75aff73..ea2afda 100644 --- a/src/adapter/anthropic/messages.ts +++ b/src/adapter/anthropic/messages.ts @@ -184,6 +184,24 @@ const thinkingSchema = z.object({ effort: z.string().optional(), }); +/** + * Anthropic `output_config`: the current shape of a thinking-effort request. + * + * `effort` is mapped through `reasoningFromEffort()` only when `thinking` is + * absent, so the older `thinking` spelling keeps winning exactly as before; + * `format` becomes the same `InternalRequest.responseFormat` the OpenAI + * surfaces use, which renders a JSON-output section into the prompt. + */ +const outputConfigSchema = z.object({ + effort: z.string().optional(), + format: z + .object({ + type: z.enum(["text", "json_object", "json_schema"]), + schema: z.record(z.string(), z.unknown()).optional(), + }) + .optional(), +}); + /** Request schema of `POST /v1/messages`. */ const anthropicMessageBaseSchema = z.object({ model: z.string().min(1), @@ -202,6 +220,12 @@ const anthropicMessageBaseSchema = z.object({ tools: z.array(toolSchema).optional(), tool_choice: toolChoiceSchema.optional(), thinking: thinkingSchema.optional(), + /** + * Current Anthropic spelling for a thinking-effort request. `effort` is + * mapped through `reasoningFromEffort()` when `thinking` is absent, and + * `format` (with an optional `schema`) becomes `InternalRequest.responseFormat`. + */ + output_config: outputConfigSchema.optional(), /** * OpenAI-style convenience alias for `thinking`: `"low"`, `"high"`, `"max"`, … * It is mapped with `reasoningFromEffort()` and ignored when `thinking` is @@ -337,6 +361,7 @@ const NULL_MEANS_UNSET_FIELDS: ReadonlySet = new Set([ "tools", "tool_choice", "thinking", + "output_config", "reasoning_effort", "service_tier", "container", @@ -522,14 +547,35 @@ function mapToolChoice(choice: AnthropicRequestInput["tool_choice"]): InternalRe } } +/** + * Map `output_config.format` onto the internal JSON output request. + * + * `type: "text"` requests nothing, exactly like the OpenAI `text` format; a + * `json_schema` format carries the caller's schema, which the prompt builder + * renders into the `# Response format` section. The gateway cannot enforce it, + * which is why `docs/API.md` documents it as best-effort. + */ +function mapOutputFormat( + config: AnthropicRequestInput["output_config"], +): InternalRequest["responseFormat"] { + const format = config?.format; + if (format === undefined || format.type === "text") return undefined; + if (format.type === "json_object") return { type: "json_object" }; + return { + type: "json_schema", + ...(format.schema !== undefined ? { schema: format.schema } : {}), + }; +} + /** * Normalise a validated Anthropic body into the internal request model. * * Media blocks are resolved through `resolveAttachment()`; `tool_use` blocks * become assistant `toolCalls`; `tool_result` blocks become `role: "tool"` - * messages; `system` text becomes a leading `system` message. Fields the - * gateway cannot honour (`top_k`, `service_tier`, `container`, `mcp_servers`) - * are accepted and ignored. + * messages; `system` text becomes a leading `system` message; `output_config` + * contributes the thinking effort (when `thinking` is absent) and the JSON + * output format. Fields the gateway cannot honour (`top_k`, `service_tier`, + * `container`, `mcp_servers`) are accepted and ignored. */ export async function toInternalRequest( body: AnthropicRequestInput, @@ -687,7 +733,13 @@ export async function toInternalRequest( return definition; }); - const reasoning = reasoningFromThinking(body.thinking) ?? reasoningFromEffort(body.reasoning_effort); + // Precedence is unchanged: the documented `thinking` object wins, then the + // current `output_config.effort` spelling, then the non-standard top-level + // `reasoning_effort` convenience alias. + const reasoning = + reasoningFromThinking(body.thinking) ?? + reasoningFromEffort(body.output_config?.effort) ?? + reasoningFromEffort(body.reasoning_effort); const request: InternalRequest = { surface: ANTHROPIC_MESSAGES_SURFACE, @@ -701,6 +753,8 @@ export async function toInternalRequest( if (options.conversationKey !== undefined) request.conversationKey = options.conversationKey; if (options.agent !== undefined) request.agent = options.agent; if (reasoning !== undefined) request.reasoning = reasoning; + const responseFormat = mapOutputFormat(body.output_config); + if (responseFormat !== undefined) request.responseFormat = responseFormat; if (body.temperature !== undefined) request.temperature = body.temperature; if (body.top_p !== undefined) request.topP = body.top_p; if (body.max_tokens !== undefined) request.maxTokens = body.max_tokens; @@ -788,20 +842,21 @@ function newMessageId(): string { return `msg_${randomBytes(12).toString("hex")}`; } -/** Deterministic base64 signature for the gateway-generated thinking block. */ -function thinkingSignature(id: string): string { - return Buffer.from(`opencode-api:${id}`).toString("base64"); -} - /** - * Subject of the gateway thinking signature. + * Deterministic base64 signature for the gateway-generated thinking block. * - * 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. + * The subject is the **gateway** message id, on both paths. The upstream + * assistant message id is not usable as a shared subject: the streamed path has + * to close the thinking block (`signature_delta` + `content_block_stop`) as soon + * as the first text or tool block starts, and `runCompletion()` yields `start` + * with an empty `messageId` before the upstream has reported one, so at that + * point the id may still be unknown while the buffered aggregate always has it. + * Signing with the upstream id therefore made the two paths disagree (P11); the + * gateway id exists before the turn starts in both paths and is a property of + * the response, not of the upstream, so it is the one subject both can agree on. */ -function thinkingSignatureSubject(assistantMessageId: string, messageId: string): string { - return assistantMessageId.length > 0 ? assistantMessageId : messageId; +function thinkingSignature(id: string): string { + return Buffer.from(`opencode-api:${id}`).toString("base64"); } function usagePayload(usage: Usage): AnthropicUsagePayload { @@ -988,7 +1043,7 @@ export function renderAnthropicMessage( content.push({ type: "thinking", thinking: collected.reasoning, - signature: thinkingSignature(thinkingSignatureSubject(collected.messageId, id)), + signature: thinkingSignature(id), }); } if (collected.text.length > 0) { @@ -1057,7 +1112,6 @@ async function streamAnthropicMessage( try { const id = newMessageId(); let model = request.model; - let assistantMessageId = ""; /** Next content-block index; blocks are announced in arrival order. */ let index = 0; let openIndex = -1; @@ -1092,7 +1146,7 @@ async function streamAnthropicMessage( index: openIndex, delta: { type: "signature_delta", - signature: thinkingSignature(thinkingSignatureSubject(assistantMessageId, id)), + signature: thinkingSignature(id), }, }, "content_block_delta", @@ -1171,7 +1225,6 @@ async function streamAnthropicMessage( switch (event.kind) { case "start": { model = event.model.length > 0 ? event.model : model; - assistantMessageId = event.messageId; reasoningEnabled = reasoningEnabled || event.reasoningEnabled; send( { @@ -1207,12 +1260,7 @@ async function streamAnthropicMessage( } case "reasoning_end": { // 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; - } + // block stays open until another kind starts or the turn ends. // The provider may deliver the consolidated summary instead of (or // in addition to) deltas; adopt it only when it is longer, exactly // like `collectCompletion()` and the buffered route. @@ -1230,12 +1278,7 @@ async function streamAnthropicMessage( } case "text_end": { // 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; - } + // stays open until another kind starts or the turn ends. // A consolidated `text_end` is adopted only when it is longer than // what the deltas produced; only its unseen suffix is streamed. if (event.text.length <= textLength) break; @@ -1258,9 +1301,6 @@ 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": { diff --git a/src/adapter/common/reasoning.ts b/src/adapter/common/reasoning.ts index 68cb643..56616b8 100644 --- a/src/adapter/common/reasoning.ts +++ b/src/adapter/common/reasoning.ts @@ -2,6 +2,7 @@ * Mapping between OpenAI `reasoning_effort` / Anthropic `thinking.budget_tokens` * and the thinking-effort variants OpenCode exposes per model. */ +import { ApiError } from "../../errors.js"; import type { ReasoningRequest } from "../../types/internal.js"; /** Ordered thinking-effort ladder, weakest first. */ @@ -223,12 +224,27 @@ export function resolveVariant(input: ResolveVariantInput): VariantDecision { }; } -/** Build a normalised reasoning request from an OpenAI `reasoning_effort` value. */ +/** + * Build a normalised reasoning request from an OpenAI `reasoning_effort` value. + * + * A non-empty value `normaliseEffort()` does not know is rejected with + * `400 invalid_request` naming `reasoning_effort`: the previous behaviour + * returned `{ enabled: true, effort: "banana" }`, which `resolveVariant()` + * silently bucketed to `medium`, so a typo quietly turned thinking on. Every + * other adapter field is validated the same way (see `assertHonouredParameters`). + * An empty value still means "unset", exactly as before. + */ export function reasoningFromEffort(effort: string | undefined | null): ReasoningRequest | undefined { - if (effort === undefined || effort === null || effort === "") return undefined; + if (effort === undefined || effort === null || effort.trim() === "") return undefined; const normalised = normaliseEffort(effort); + if (normalised === undefined) { + throw ApiError.badRequest( + `\`reasoning_effort\` must be one of ${EFFORT_ORDER.join(", ")} (received \`${effort}\`).`, + { code: "invalid_request", param: "reasoning_effort" }, + ); + } if (normalised === "none") return { enabled: false, effort: "none", disabled: true }; - return { enabled: true, effort: normalised ?? effort.toLowerCase() }; + return { enabled: true, effort: normalised }; } /** Build a normalised reasoning request from an Anthropic `thinking` object. */ diff --git a/src/adapter/openai/chat.ts b/src/adapter/openai/chat.ts index 82c1f2f..a3beefa 100644 --- a/src/adapter/openai/chat.ts +++ b/src/adapter/openai/chat.ts @@ -291,6 +291,9 @@ export function isTextOnlyModalities(modalities: readonly string[]): boolean { * OpenCode's agent loop owns the sampling parameters and the generation budget, * so these values never reach the model; they are echoed back through * `x_opencode.unapplied` instead of being silently dropped or rejected. + * `service_tier` has no OpenCode equivalent either, and it is listed here for + * the same reason: a caller that asks for a tier must be able to see that the + * gateway did not select one. */ const UNAPPLIED_ORDER = [ "temperature", @@ -302,6 +305,7 @@ const UNAPPLIED_ORDER = [ "max_tokens", "max_completion_tokens", "max_output_tokens", + "service_tier", ] as const; /** @@ -387,6 +391,30 @@ function assertImageDetail(detail: string | undefined): void { }); } +/** + * Reject media content parts on a role that cannot carry them. + * + * OpenAI chat messages only forward attachments for `role: "user"`; a `tool` + * message's `content` is text-only, and `system` / `developer` / `assistant` + * turns have no attachment slot either. The Responses adapter applies the same + * rule to non-user input messages (see `messageDraft()` in `responses.ts`). + * + * `param` names the request field the caller has to change: `messages` on the + * chat surface, `input` on the Responses surface, matching the `file_id` and + * `detail` rejections of each. + */ +export function assertMediaRole( + role: InternalMessage["role"], + mediaCount: number, + param: string = "messages", +): void { + if (mediaCount === 0 || role === "user") return; + throw ApiError.badRequest( + `Media content parts are only supported on \`user\` messages (received a \`${role}\` message).`, + { code: "invalid_request", param }, + ); +} + /** `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)); @@ -403,6 +431,38 @@ function hasText(value: string | undefined): boolean { return value !== undefined && value.length > 0; } +/** + * True when a content part carries media rather than text. + * + * The role rule below is what matters here; `mediaPartCount()` is the only + * consumer and the Responses adapter applies the same rule to its own part + * vocabulary through `assertMediaRole()`. + */ +function isMediaPart(part: ChatContentPart): boolean { + return part.type !== "text"; +} + +/** Count the media content parts of one message body. */ +function mediaPartCount(content: ChatMessage["content"]): number { + if (content === undefined || content === null || typeof content === "string") return 0; + return content.filter(isMediaPart).length; +} + +/** + * Reject media on a role that cannot carry it, before the model is resolved. + * + * P5: the only consumer of attachments upstream is the user turn, so media on a + * `tool` / `system` / `developer` / `assistant` message used to be downloaded, + * charged to the request's media budget and then silently dropped as an empty + * message. The rejection is a `400 invalid_request` naming `messages`, matching + * the existing `file_id` / `detail` rejections. + */ +function assertMediaRoles(messages: ChatMessage[]): void { + for (const message of messages) { + assertMediaRole(message.role, mediaPartCount(message.content)); + } +} + // ----------------------------------------------------------------- routes --- export function registerOpenAiChatRoutes(app: FastifyInstance, ctx: AppContext): void { @@ -410,6 +470,9 @@ export function registerOpenAiChatRoutes(app: FastifyInstance, ctx: AppContext): const body = parseChatRequest(request.body); assertToolCallIds(body.messages); assertHonouredParameters(body); + // Media stays legal on `user` only; a `tool` message's `content` is + // text-only and the other roles have no attachment slot at all. + assertMediaRoles(body.messages); // Generation knobs stay accepted: they are recorded on the internal request // and echoed back as `x_opencode.unapplied`. const unapplied = unappliedParameters(body); @@ -495,6 +558,7 @@ async function buildRequest( // the caller which of them the turn could not apply. if (typeof body.temperature === "number") internal.temperature = body.temperature; if (typeof body.top_p === "number") internal.topP = body.top_p; + if (typeof body.service_tier === "string") internal.serviceTier = body.service_tier; const maxTokens = body.max_completion_tokens ?? body.max_tokens; if (typeof maxTokens === "number") internal.maxTokens = maxTokens; @@ -524,7 +588,8 @@ export interface MessageMediaDraft { /** * Build a message without resolving its media. * - * Validation of the media parts happens here, so an invalid part is reported + * Validation of the media parts happens here (and in `assertMediaRoles()`, which + * the route runs before the model is resolved), so an invalid part is reported * before any download starts. */ function toInternalMessageDraft(message: ChatMessage): MessageMediaDraft { @@ -660,11 +725,21 @@ function toToolCalls(calls: ChatMessage["tool_calls"]): ToolCall[] { })); } -/** Map OpenAI `response_format` onto the internal JSON output request. */ +/** + * Map OpenAI `response_format` onto the internal JSON output request. + * + * `json_schema.strict: true` promises server-enforced conformance the gateway + * cannot provide — the schema is rendered into the prompt like any other + * (see `docs/ARCHITECTURE.md` §6) — so it is rejected instead of silently + * dropped, exactly like `logprobs`. + */ function toResponseFormat(format: ChatRequest["response_format"]): ResponseFormat | undefined { if (format === undefined || format.type === "text") return undefined; if (format.type === "json_object") return { type: "json_object" }; const spec = format.json_schema; + if (spec?.strict === true) { + rejectUnsupported("response_format.json_schema.strict", "the gateway cannot enforce a JSON schema"); + } return { type: "json_schema", ...(spec?.name !== undefined ? { name: spec.name } : {}), @@ -843,10 +918,18 @@ export function openCodeExtension( * `total = prompt + completion` always holds; `usage.totalTokens` is ignored * because it is the same sum and cannot disagree. * + * `prompt_tokens` is the **whole** prompt the provider charged for: the + * upstream reports `input` as the non-cached bucket only and carries the cache + * hits in `cache.read` / `cache.write`, so summing all three is the only way + * `prompt_tokens_details.cached_tokens` can stay a subset of `prompt_tokens` + * (it used to exceed it) and `total_tokens` can count the cached prompt at all. + * `/v1/messages` is deliberately different: Anthropic's `input_tokens` excludes + * the cache buckets. + * * Shared with the legacy completions surface (`completions.ts`). */ export function openAiUsage(usage: Usage): Record { - const prompt = usage.inputTokens; + const prompt = usage.inputTokens + usage.cacheReadTokens + usage.cacheWriteTokens; const completion = usage.outputTokens + usage.reasoningTokens; return { prompt_tokens: prompt, diff --git a/src/adapter/openai/completions.ts b/src/adapter/openai/completions.ts index 16df4ba..a3756b9 100644 --- a/src/adapter/openai/completions.ts +++ b/src/adapter/openai/completions.ts @@ -7,9 +7,9 @@ * 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. + * Only one completion per request is supported (`n` must be `1`, and an array + * `prompt` may hold exactly one element), 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"; @@ -55,6 +55,11 @@ const completionRequestSchema = z.object({ // reported through `x_opencode.unapplied` (see `chat.ts`). max_tokens: z.number().optional(), temperature: z.number().optional(), + // Declared like the other OpenAI surfaces: without a schema entry zod + // stripped `top_p`, so the only silent generation-knob drop left in the + // gateway was on this surface. + top_p: z.number().optional(), + service_tier: z.string().optional(), stop: z.union([z.string(), z.array(z.string())]).optional(), user: z.string().optional(), // Generation knobs: accepted and recorded, reported through @@ -113,12 +118,16 @@ export function registerOpenAiCompletionRoutes(app: FastifyInstance, ctx: AppCon }); } - // 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", - }); + // An array `prompt` is only accepted when it holds exactly one element: the + // gateway produces one completion per request (`n` must be 1), so a longer + // array has no `index` a caller could map back to its own prompt. It used to + // be joined with "\n" into one merged turn, which answered 200 while + // returning something the caller never asked for. + if (Array.isArray(body.prompt) && body.prompt.length > 1) { + throw ApiError.badRequest( + "An array `prompt` must contain exactly one element: this gateway produces one completion per request.", + { code: "unsupported_parameter", param: "prompt" }, + ); } // Resolve before running so an unknown/disabled model fails with an HTTP @@ -159,7 +168,10 @@ export function registerOpenAiCompletionRoutes(app: FastifyInstance, ctx: AppCon // ------------------------------------------------------- request translation --- function buildRequest(body: CompletionRequest, resolved: ResolvedModel): InternalRequest { - const text = Array.isArray(body.prompt) ? body.prompt.join("\n") : body.prompt; + // The route already rejected an array with more than one element, so this + // only unwraps a one-element array — it never merges prompts. + const prompt = body.prompt; + const text = Array.isArray(prompt) ? (prompt[0] ?? "") : prompt; const messages: InternalMessage[] = [{ role: "user", text }]; const internal: InternalRequest = { @@ -175,7 +187,9 @@ function buildRequest(body: CompletionRequest, resolved: ResolvedModel): Interna // sampling parameters and the generation budget; `x_opencode.unapplied` names // every such field the caller supplied. if (typeof body.temperature === "number") internal.temperature = body.temperature; + if (typeof body.top_p === "number") internal.topP = body.top_p; if (typeof body.max_tokens === "number") internal.maxTokens = body.max_tokens; + if (typeof body.service_tier === "string") internal.serviceTier = body.service_tier; const stop = normaliseStop(body.stop); if (stop !== undefined && stop.length > 0) internal.stop = stop; diff --git a/src/adapter/openai/responses.ts b/src/adapter/openai/responses.ts index 0492962..c43ca28 100644 --- a/src/adapter/openai/responses.ts +++ b/src/adapter/openai/responses.ts @@ -34,8 +34,10 @@ * resend a previous response's `output` verbatim, but provider-side thinking * state cannot be replayed. * - `service_tier` 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"). + * effect on the completion; `service_tier` is recorded and listed in + * `x_opencode.unapplied` like the other generation knobs. `text.format` is + * rendered into the prompt like the chat `response_format` (see "JSON + * output mode") and echoed back as `text: { format: … }`. */ import { randomUUID } from "node:crypto"; import type { FastifyInstance, FastifyReply, FastifyRequest } from "fastify"; @@ -45,6 +47,7 @@ import { normaliseArguments } from "../common/tools.js"; import { EMPTY_USAGE } from "../common/usage.js"; import { assertHonouredParameters, + assertMediaRole, rejectUnsupported, resolveMessageMedia, unappliedParameters, @@ -230,7 +233,9 @@ const toolChoice = z.union([ const responsesRequest = z .object({ - model: z.string(), + // `.min(1)` matches the chat surface: an empty model used to reach + // `ModelRegistry.resolve()` and answer 404 instead of 400. + model: z.string().min(1), // The real API requires at least one input item: an empty array used to run // the upstream turn with an empty prompt and answer 200. input: z.union([z.string().trim().min(1), z.array(inputItem).min(1)]), @@ -384,6 +389,20 @@ interface ResponseUsage { output_tokens_details: { reasoning_tokens: number }; } +/** + * The `text.format` object echoed back on every response payload. + * + * The real API echoes the format the caller asked for and defaults it to + * `{ type: "text" }`; the gateway used to omit the field entirely, so a caller + * could not tell whether its `text.format` had been read (see P9). `strict` is + * deliberately absent: it is rejected before a response exists. + */ +interface TextFormatEcho { + type: "text" | "json_object" | "json_schema"; + name?: string; + schema?: Record; +} + interface ResponseBody { id: string; object: "response"; @@ -398,6 +417,7 @@ interface ResponseBody { tools: Array>; temperature: number | null; top_p: number | null; + text: TextFormatEcho; reasoning: { effort: string | null; summary: string | null }; metadata: Record; incomplete_details: { reason: string } | null; @@ -428,6 +448,8 @@ interface ResponseEcho { parallelToolCalls: boolean; truncation: string; store: boolean; + /** `text.format` the caller sent, echoed back like the real API does. */ + text: TextFormatEcho; reasoningEffort: string | null; reasoningSummary: string | null; /** `instructions` the caller sent, echoed back like the real API does. */ @@ -497,6 +519,30 @@ function assertSupportedRequest(body: ResponsesRequest): void { } } +/** + * Reject media content parts on an input message role that cannot carry them, + * before the model is resolved and before any byte is fetched. + * + * P5: media is legal on a `user` input message and inside a + * `function_call_output` (which re-homes it onto a synthetic user turn); an + * `assistant` / `system` / `developer` message used to keep its media, have it + * downloaded and budget-charged, and then lose it, because the orchestrator + * forwards user-turn attachments only. The rejection mirrors the chat surface. + */ +function assertInputMediaRoles(input: ResponsesRequest["input"]): void { + if (typeof input === "string") return; + for (const item of input) { + if (item.type === "function_call" || item.type === "function_call_output" || item.type === "item_reference") { + // `function_call_output` handles its own media (see `mapInputItems`). + continue; + } + if (typeof item.role !== "string" || !Array.isArray(item.content)) continue; + const role = item.role as InternalMessage["role"]; + const parts = item.content as ContentPart[]; + assertMediaRole(role, parts.filter(isMediaPart).length, "input"); + } +} + /** Unix time in seconds, the unit OpenAI uses for `created_at` / `created`. */ function unixSeconds(): number { return Math.floor(Date.now() / 1000); @@ -528,6 +574,7 @@ export function registerOpenAiResponsesRoutes(app: FastifyInstance, ctx: AppCont const body = parsed.data; assertSupportedRequest(body); + assertInputMediaRoles(body.input); // The response is created here: `created_at` is a property of the response, // not of the frame or of the moment the turn happens to finish. const createdAt = unixSeconds(); @@ -639,6 +686,7 @@ async function prepare( ...(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.service_tier !== undefined ? { serviceTier: body.service_tier } : {}), ...(body.parallel_tool_calls !== undefined ? { parallelToolCalls: body.parallel_tool_calls } : {}), ...(conversationKey !== undefined ? { conversationKey } : {}), ...(agent !== undefined ? { agent } : {}), @@ -661,6 +709,7 @@ async function prepare( parallelToolCalls: body.parallel_tool_calls !== false, truncation: body.truncation ?? "disabled", store: body.store === true, + text: echoTextFormat(body.text?.format), reasoningEffort: reasoning?.effort ?? null, reasoningSummary: body.reasoning?.summary ?? null, instructions: body.instructions ?? null, @@ -753,6 +802,13 @@ async function mapInputItems( * * Validation stays here (a `file_id` reference is rejected before any fetch * starts); the actual resolution happens once for the whole request. + * + * Media is only legal on a `user` input message or inside a + * `function_call_output` (which re-homes it onto a synthetic user turn, see + * `mapInputItems`). Media on an `assistant` / `system` / `developer` message + * would be downloaded, billed against the request budget and then dropped, + * because the orchestrator forwards user-turn attachments only, so it is + * rejected with the same `400 invalid_request` the chat surface returns. */ function messageDraft( role: "user" | "assistant" | "system" | "developer", @@ -809,13 +865,15 @@ function messageDraft( } } + assertMediaRole(role, media.length); + return { message: { role, text: text.join("\n") }, sources: media }; } /** A content part that carries media rather than text. */ type MediaContentPart = Extract; -/** Narrow a `function_call_output.output` entry to the parts the media pool can resolve. */ +/** Narrow a content part to the media-carrying subset the media pool can resolve. */ function isMediaPart(part: ContentPart): part is MediaContentPart { return ( part.type === "input_image" || part.type === "input_file" || part.type === "input_audio" || part.type === "video_url" @@ -907,6 +965,13 @@ function contentToText(value: string | ContentPart[] | undefined): string { function mapResponseFormat(format: z.infer | undefined): ResponseFormat | undefined { if (format === undefined || format.type === "text") return undefined; if (format.type === "json_object") return { type: "json_object" }; + // `strict: true` promises server-enforced schema conformance the gateway + // cannot provide: the schema is rendered into the prompt, exactly like the + // chat `response_format`. Rejected rather than silently dropped, following + // the `logprobs` policy. + if (format.strict === true) { + rejectUnsupported("text.format.strict", "the gateway cannot enforce a JSON schema"); + } return { type: "json_schema", ...(format.name !== undefined ? { name: format.name } : {}), @@ -914,6 +979,19 @@ function mapResponseFormat(format: z.infer | undefined): Resp }; } +/** Render the validated `text.format` back into the wire shape of the response. */ +function echoTextFormat(format: z.infer | undefined): TextFormatEcho { + if (format === undefined) return { type: "text" }; + if (format.type === "json_schema") { + return { + type: "json_schema", + ...(format.name !== undefined ? { name: format.name } : {}), + ...(format.schema !== undefined ? { schema: format.schema } : {}), + }; + } + return { type: format.type }; +} + /** The name of a named-function `tool_choice`, whichever SDK spelling it used. */ function namedToolChoice(value: ResponsesRequest["tool_choice"]): string { if (value !== undefined && typeof value !== "string") { @@ -958,11 +1036,18 @@ function toResponseUsage(usage: Usage): ResponseUsage { // 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. + // + // `input_tokens` is the whole prompt: the upstream reports `input` as the + // non-cached bucket and carries the cache hits in `cache.read` / `cache.write`, + // so summing all three is what keeps + // `input_tokens_details.cached_tokens` a subset of `input_tokens` and + // `total_tokens` honest (P4). The Anthropic surface is deliberately different. + const inputTokens = usage.inputTokens + usage.cacheReadTokens + usage.cacheWriteTokens; const outputTokens = usage.outputTokens + usage.reasoningTokens; return { - input_tokens: usage.inputTokens, + input_tokens: inputTokens, output_tokens: outputTokens, - total_tokens: usage.inputTokens + outputTokens, + total_tokens: inputTokens + outputTokens, input_tokens_details: { cached_tokens: usage.cacheReadTokens }, output_tokens_details: { reasoning_tokens: usage.reasoningTokens }, }; @@ -1073,6 +1158,7 @@ function baseResponse(prepared: Prepared, state: ResponseState): ResponseBody { tools: prepared.echo.tools, temperature: prepared.echo.temperature, top_p: prepared.echo.topP, + text: prepared.echo.text, reasoning: { effort: prepared.echo.reasoningEffort, summary: prepared.echo.reasoningSummary }, metadata: prepared.echo.metadata, incomplete_details: incompleteReasonForTurn !== null ? { reason: incompleteReasonForTurn } : null, diff --git a/src/auth.ts b/src/auth.ts index c9177de..696564c 100644 --- a/src/auth.ts +++ b/src/auth.ts @@ -72,6 +72,24 @@ export function isPublicPath(path: string): boolean { return PUBLIC_PATHS.has(path); } +/** + * Path a request is classified by: what the router will actually dispatch. + * + * `request.url` keeps the bytes the caller sent, while Fastify's router matches + * on the percent-decoded path. Classifying on the raw URL let `/%61dmin/config` + * be authenticated as a general route (and charged to the api rate-limit bucket) + * while the dispatcher still ran `GET /admin/config`, so a general key reached + * every admin route. `request.routeOptions.url` is the matched route pattern and + * is populated before the `onRequest` hooks run, so it cannot disagree with the + * dispatcher; a request that matched no route (a 404 on its way to the + * not-found handler) falls back to the canonical raw path. + */ +export function classifyPath(request: FastifyRequest): string { + const route = request.routeOptions?.url; + if (typeof route === "string" && route.length > 0) return route; + return requestPath(request); +} + /** * API key extraction. * @@ -222,7 +240,8 @@ function authRejection(limiters: RateLimiters, request: FastifyRequest, message? */ export function requireApiKey(config: Config, limiters: RateLimiters) { return async function authenticate(request: FastifyRequest, _reply: FastifyReply): Promise { - const path = requestPath(request); + // The matched route, not the raw URL: see `classifyPath`. + const path = classifyPath(request); if (isPublicPath(path)) return; const presented = extractApiKey(request); diff --git a/src/config.ts b/src/config.ts index ed7d468..acdb70e 100644 --- a/src/config.ts +++ b/src/config.ts @@ -295,6 +295,26 @@ function envLogLevel(name: string, fallback: string): string { return fallback; } +/** + * Parse a closed-set environment value. + * + * A typo in an enum used to fold silently into the fallback — + * `OPENCODE_REASONING_FIELD=boht` produced `reasoning_content` with nothing in + * the log — so the operator could not tell the setting had been ignored. + * Matching is case-insensitive, like `envLogLevel()`, and an unrecognised value + * warns through `warnInvalidEnv()` (the variable name, never the value) before + * the fallback is returned. + */ +function envEnum(name: string, allowed: readonly T[], fallback: T): T { + const raw = env(name); + if (raw === undefined) return fallback; + const normalised = raw.toLowerCase(); + const match = allowed.find((value) => value.toLowerCase() === normalised); + if (match !== undefined) return match; + warnInvalidEnv(name, fallback); + return fallback; +} + /** Resolve a possibly-relative path against the current working directory. */ export function resolvePath(value: string): string { const expanded = value.startsWith("~") ? path.join(os.homedir(), value.slice(1)) : value; @@ -379,6 +399,15 @@ function parseAliases(): Record | undefined { return Object.fromEntries(entries); } +/** + * The closed sets the reasoning environment variables accept. + * + * Kept next to `LOG_LEVELS` because all three are validated before `Config` + * takes their value; anything outside the set warns and falls back. + */ +const REASONING_DEFAULTS: readonly Config["reasoningDefault"][] = ["off", "on-request", "always"]; +const REASONING_FIELDS: readonly Config["reasoningField"][] = ["reasoning_content", "both"]; + let cached: Config | undefined; export function loadConfig(overrides: Partial = {}): Config { if (cached && Object.keys(overrides).length === 0) return cached; @@ -491,18 +520,13 @@ export function loadConfig(overrides: Partial = {}): Config { maxAttachments: envInt("OPENCODE_MAX_ATTACHMENTS", 16, 1), mediaFetchTimeoutMs: envInt("OPENCODE_MEDIA_FETCH_TIMEOUT_MS", 15_000, 100), - reasoningDefault: (() => { - const raw = env("OPENCODE_REASONING_DEFAULT"); - if (raw === undefined) return "on-request"; - const normalised = raw.toLowerCase(); - if (normalised === "off" || normalised === "on-request" || normalised === "always") return normalised; - warnInvalidEnv("OPENCODE_REASONING_DEFAULT", "on-request"); - return "on-request"; - })(), + reasoningDefault: ((): Config["reasoningDefault"] => + envEnum("OPENCODE_REASONING_DEFAULT", REASONING_DEFAULTS, "on-request"))(), exposeNativeTools: envBool("OPENCODE_EXPOSE_NATIVE_TOOLS", false), toolBridgeDenyNativeTools: envBool("OPENCODE_TOOL_BRIDGE_DENY_NATIVE_TOOLS", true), nativeToolEventName: envStr("OPENCODE_NATIVE_TOOL_EVENT", "opencode.tool_call"), - reasoningField: envStr("OPENCODE_REASONING_FIELD", "reasoning_content").toLowerCase() === "both" ? "both" : "reasoning_content", + reasoningField: ((): Config["reasoningField"] => + envEnum("OPENCODE_REASONING_FIELD", REASONING_FIELDS, "reasoning_content"))(), logLevel: envLogLevel("OPENCODE_LOG_LEVEL", "info"), logPretty: envBool("OPENCODE_LOG_PRETTY", process.stdout.isTTY === true), diff --git a/src/http/rateLimit.ts b/src/http/rateLimit.ts index 4263a24..50666b1 100644 --- a/src/http/rateLimit.ts +++ b/src/http/rateLimit.ts @@ -17,7 +17,7 @@ */ import { createHash } from "node:crypto"; import type { FastifyReply, FastifyRequest } from "fastify"; -import { extractApiKey, isPublicPath, requestPath } from "../auth.js"; +import { classifyPath, extractApiKey, isPublicPath } from "../auth.js"; import type { Config } from "../config.js"; import { ApiError } from "../errors.js"; @@ -285,7 +285,9 @@ export function requireRateLimit(config: Config, limiters: RateLimiters, onRejec const keySet = configuredKeySet(config); return async function rateLimit(request: FastifyRequest, _reply: FastifyReply): Promise { if (!limiters.api.enabled) return; - const path = requestPath(request); + // The matched route, so an encoded spelling of an admin path is charged to + // the admin bucket exactly like the plain one (see `classifyPath`). + const path = classifyPath(request); if (isPublicPath(path) || request.method === "OPTIONS") return; const scope = path === "/admin" || path.startsWith("/admin/") ? "admin" : "api"; diff --git a/src/http/sse.ts b/src/http/sse.ts index 13b89f2..af67a5e 100644 --- a/src/http/sse.ts +++ b/src/http/sse.ts @@ -96,13 +96,31 @@ export class SseWriter { raw.on("error", () => this.#handleClose()); } - /** Write a `data:` frame, optionally with a named event. */ + /** + * Write a `data:` frame, optionally with a named event. + * + * CR and LF terminate an SSE field, so a caller-supplied value carrying either + * could otherwise inject a frame of its own (a bogus `event:` line, a second + * `data:` payload, a `retry:`) into the stream the client parses. Both fields + * are therefore normalised instead of emitted verbatim: + * + * - one or more `\r\n` / `\r` / `\n` line terminators in `data` split it into + * multiple `data:` lines, exactly like a lone `\n` already did. SSE strips + * one optional space after the colon, so a payload is reproduced line for + * line and joining the lines with `\n` restores it; + * - a line terminator in `event` would create a second field, so it becomes a + * single space: the frame keeps one `event:` line and the name stays + * readable instead of silently truncating the event for the client. + * + * These are pure frame-construction rules: every wire byte a current call site + * produces (no CR/LF in the event, payload split on `\n`) is unchanged. + */ send(data: string | object, event?: string): void { if (this.#closed) return; const payload = typeof data === "string" ? data : JSON.stringify(data); let frame = ""; - if (event) frame += `event: ${event}\n`; - for (const line of payload.split("\n")) frame += `data: ${line}\n`; + if (event) frame += `event: ${sanitiseEventName(event)}\n`; + for (const line of splitSseLines(payload)) frame += `data: ${line}\n`; frame += "\n"; this.#write(frame); } @@ -224,4 +242,27 @@ export class SseWriter { if (!this.#closedController.signal.aborted) this.#closedController.abort(); this.#options.onClose?.(); } +} + +/** + * Split a `data` payload into the lines one SSE frame carries. + * + * SSE ends a line at CRLF, a lone CR or a lone LF, so all three are terminators + * here; splitting on `\n` alone let a payload with a lone CR smuggle framing + * into the stream. Splitting (rather than rejecting) keeps a multi-line payload + * byte-identical to the historical `\n`-only behaviour. + */ +function splitSseLines(payload: string): string[] { + return payload.split(/\r\n|\r|\n/); +} + +/** + * Remove the line terminators that would end the `event:` field early. + * + * A replacement rather than a rejection: `event` is often operator-configured + * (`OPENCODE_NATIVE_TOOL_EVENT`), and throwing would fail a live stream over a + * configuration typo. A space keeps the name on one line and readable. + */ +function sanitiseEventName(event: string): string { + return event.replace(/[\r\n]/g, " "); } \ No newline at end of file diff --git a/src/media/resolve.ts b/src/media/resolve.ts index e14e170..e1b646d 100644 --- a/src/media/resolve.ts +++ b/src/media/resolve.ts @@ -695,7 +695,12 @@ async function resolveUrl( const headerMime = normaliseMimeType(headerValue(response.headers["content-type"]) ?? ""); const name = source.name ?? deriveName(current, headerMime); const mime = sniffOrDeclare(buffer, headerMime ?? source.mime, name); - return toAttachment(buffer, mime, name, field, current.toString()); + // `origin` follows the same policy as `describeUrl()`: host plus + // pathname only. `URL.toString()` would keep a `user:password@` userinfo + // component (which the request never sends, so recording it would leak a + // secret the download never used) and the query string (a signed URL's + // credential), and the attachment travels on into prompts and logs. + return toAttachment(buffer, mime, name, field, describeUrl(current)); } if (hop === MAX_REDIRECTS) { @@ -1375,6 +1380,13 @@ const MIME_SAMPLE_EXTENSIONS: Record = { export function isPrivateHost(hostname: string): boolean { let host = hostname.replace(/^\[|\]$/g, "").toLowerCase(); + // A zone identifier (`fe80::1%eth0`, and the `%25eth0` spelling a WHATWG URL + // may still carry) selects a local interface: strip it *before* anything + // classifies the address, because `net.isIP()` and every parser below reject + // the `%zone` suffix and used to call a link-local address public. + const zone = host.indexOf("%"); + if (zone !== -1) host = host.slice(0, zone); + // IPv4-mapped IPv6, in either the dotted form (`::ffff:127.0.0.1`) or the // normalised hex form WHATWG URL produces (`::ffff:7f00:1`). const mapped = embeddedIpv4(host); @@ -1414,6 +1426,8 @@ function embeddedIpv4(host: string): string | undefined { * fully written `0:0:0:0:0:ffff:7f00:1`, a compressed `::ffff:7f00:1` and a * dotted tail (`::ffff:127.0.0.1`). Normalising here is what makes * `isPrivateHost()` correct for input that has not been through `new URL()`. + * A `%zone` suffix is stripped by the caller first: it is interface metadata, + * not part of the literal, and no parser below accepts it. */ function expandIpv6(host: string): number[] | undefined { let value = host; @@ -1452,8 +1466,13 @@ function expandIpv6(host: string): number[] | undefined { function isPrivateHostname(host: string): boolean { if (host === "") return false; - if (host === "localhost" || host.endsWith(".localhost")) return true; - if (host.endsWith(".local") || host.endsWith(".internal") || host.endsWith(".home.arpa")) return true; + // A trailing dot is the absolute form of a DNS name (`localhost.`); it names + // the same host, so exactly one is removed before the name table is consulted. + // Without this an attacker-supplied absolute name slipped past every + // name-based rule here and was only caught by the later address check. + const name = host.endsWith(".") ? host.slice(0, -1) : host; + if (name === "localhost" || name.endsWith(".localhost")) return true; + if (name.endsWith(".local") || name.endsWith(".internal") || name.endsWith(".home.arpa")) return true; const octets = parseIpv4(host); return octets !== undefined && isPrivateIpv4(octets); } @@ -1481,7 +1500,10 @@ function isPrivateIpv4(octets: readonly [number, number, number, number]): boole } function isPrivateIpv6(host: string): boolean { - if (net.isIP(host) !== 6) return false; + // Anything with a colon that is not an address `net` accepts is meaningless + // as a hostname (more than one colon cannot be a port suffix either), so it is + // classified private rather than allowed through unclassified. + if (net.isIP(host) !== 6) return true; if (host === "::" || host === "::1") return true; // Unique-local fc00::/7 and link-local fe80::/10. if (host.startsWith("fc") || host.startsWith("fd")) return true; @@ -1492,6 +1514,16 @@ function isPrivateIpv6(host: string): boolean { // Transition mechanisms that can carry another address family: NAT64 // (64:ff9b::/96) and 6to4 (2002::/16). if (host.startsWith("64:ff9b:") || host.startsWith("2002:")) return true; + // The last 32 bits of a literal that is not caught above can still be an + // IPv4 address (an IPv4-mapped or IPv4-compatible form the prefix checks do + // not cover): classify it through the IPv4 rules instead of trusting the + // outer spelling. `embeddedIpv4()` only returns a value when the whole + // literal is such a form, so a plain `2001:db8::1` stays public. + const embedded = embeddedIpv4(host); + if (embedded !== undefined) { + const octets = parseIpv4(embedded); + if (octets !== undefined) return isPrivateIpv4(octets); + } return false; } diff --git a/src/metrics/registry.ts b/src/metrics/registry.ts index b1ebfc9..4b231d9 100644 --- a/src/metrics/registry.ts +++ b/src/metrics/registry.ts @@ -113,7 +113,7 @@ export function createMetrics(options: { enabled: boolean; prefix?: string } = { const eventFramesDropped = new Counter({ name: `${prefix}event_frames_dropped_total`, - help: "Upstream event frames the hub could not deliver, by reason: no_session, no_subscriber or malformed.", + help: "Upstream event frames the hub could not deliver, by reason: no_session, no_subscriber, malformed or stale.", labelNames: ["reason"] as const, registers: [registry], }); diff --git a/src/server.ts b/src/server.ts index 0c5f064..f01e59c 100644 --- a/src/server.ts +++ b/src/server.ts @@ -11,7 +11,7 @@ import { registerOpenAiModelRoutes } from "./adapter/openai/models.js"; import { registerOpenAiResponsesRoutes } from "./adapter/openai/responses.js"; import { registerAnthropicCountTokenRoutes } from "./adapter/anthropic/countTokens.js"; import { registerAnthropicMessageRoutes } from "./adapter/anthropic/messages.js"; -import { canonicalPath, requireApiKey } from "./auth.js"; +import { classifyPath, requireApiKey } from "./auth.js"; import type { AppContext } from "./context.js"; import type { Config } from "./config.js"; import { ApiError, toAnthropicError, toApiError, toOpenAiError } from "./errors.js"; @@ -31,7 +31,9 @@ import { SERVICE_NAME, VERSION } from "./version.js"; const ANTHROPIC_SURFACE_PATHS: ReadonlySet = new Set(["/v1/messages", "/v1/messages/count_tokens"]); function isAnthropicSurface(request: FastifyRequest): boolean { - return ANTHROPIC_SURFACE_PATHS.has(canonicalPath(request.url)); + // `classifyPath` prefers the matched route, so an encoded spelling of + // `/v1/messages` gets the Anthropic error envelope the dispatcher will use. + return ANTHROPIC_SURFACE_PATHS.has(classifyPath(request)); } /** diff --git a/src/types/internal.ts b/src/types/internal.ts index 83e723b..5821cc1 100644 --- a/src/types/internal.ts +++ b/src/types/internal.ts @@ -113,6 +113,14 @@ export interface InternalRequest { temperature?: number; topP?: number; maxTokens?: number; + /** + * OpenAI `service_tier` (`"auto"` / `"default"` / `"flex"` / …). + * + * Recorded so the OpenAI surfaces can report it through + * `x_opencode.unapplied`: the OpenCode agent loop selects the upstream tier, + * so the gateway cannot honour the caller's choice. + */ + serviceTier?: string; stop?: string[]; /** Explicit conversation key (`x-conversation-id` header). */ conversationKey?: string; diff --git a/src/upstream/client.ts b/src/upstream/client.ts index 75c948a..6d14184 100644 --- a/src/upstream/client.ts +++ b/src/upstream/client.ts @@ -104,13 +104,27 @@ export class OpencodeClient { timedOut = true; controller.abort(new Error("upstream timeout")); }, timeoutMs); - const onAbort = (): void => controller.abort(options.signal?.reason); - options.signal?.addEventListener("abort", onAbort, { once: true }); + // `AbortSignal.any()` instead of a listener on `options.signal`: a caller + // signal that aborted while `resolve()` was pending never emits another + // "abort" event, so a listener attached after the fact would miss it, while + // the composed signal is already aborted when `fetch()` observes it. It also + // covers the synchronous window between the check below and `fetch()`. + const signal = + options.signal === undefined ? controller.signal : AbortSignal.any([controller.signal, options.signal]); const startedAt = process.hrtime.bigint(); let outcome = "success"; try { + // A caller that disconnected while `resolve()` was still cold-starting or + // re-probing the child must not reach the upstream at all: `prompt()` would + // otherwise run a real, billed turn nobody is left to read. This is checked + // before `fetch()`, so the request is never issued. + if (options.signal?.aborted === true) { + outcome = "aborted"; + throw new ApiError(499, "timeout_error", "Client closed the request."); + } + const response = await fetch(url, { method, headers: { @@ -119,7 +133,7 @@ export class OpencodeClient { accept: "application/json", }, body: options.body === undefined ? undefined : JSON.stringify(options.body), - signal: controller.signal, + signal, }); if (response.status === 401) { @@ -151,9 +165,15 @@ export class OpencodeClient { }); } - if (text.length === 0) return undefined as T; - const parsed = safeParse(text); - if (parsed === undefined) { + const parsed: unknown = safeParse(text); + + // A 2xx body must be the `{ data: ... }` envelope every caller dereferences. + // An empty body used to return `undefined`, and `JSON.parse` also accepts a + // literal `null`, a bare string/number and an array, so all of them reached + // `response.data` as a bare `TypeError` — an HTTP 500 outside the ApiError + // taxonomy — instead of an upstream failure. A syntax error already took + // this branch and keeps its outcome. + if (text.length === 0 || parsed === undefined || !isJsonObject(parsed)) { outcome = "invalid_json"; throw ApiError.unavailable("OpenCode returned a malformed JSON response.", { code: "upstream_invalid_json", @@ -161,7 +181,7 @@ export class OpencodeClient { upstreamBody: text.slice(0, 500), }); } - return parsed; + return parsed as T; } catch (error) { if (error instanceof ApiError) { this.#metrics.upstreamRequests.inc({ operation: options.operation, outcome }); @@ -194,7 +214,6 @@ 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); @@ -336,6 +355,16 @@ function safeParse(text: string): T | undefined { } } +/** + * Whether a parsed 2xx body can carry the `{ data: ... }` envelope callers read. + * + * `JSON.parse` accepts `null`, a bare string/number and an array, none of which + * has a `data` field; dereferencing them used to escape as a bare `TypeError`. + */ +function isJsonObject(value: unknown): value is Record { + return typeof value === "object" && value !== null && !Array.isArray(value); +} + function duration(metrics: Metrics, operation: string, startedAt: bigint): void { const seconds = Number(process.hrtime.bigint() - startedAt) / 1e9; metrics.upstreamDuration.observe({ operation }, seconds); diff --git a/src/upstream/completion.ts b/src/upstream/completion.ts index 31f679e..d3d3791 100644 --- a/src/upstream/completion.ts +++ b/src/upstream/completion.ts @@ -443,6 +443,17 @@ const STREAM_GAP_GRACE_MS = 5_000; */ export const MAX_QUEUED_EVENTS = 10_000; +/** + * Lowest value that can plausibly be an epoch-millisecond stamp. + * + * The envelope's `created` is optional and its unit is not part of the frozen + * contract, so it is only used for ordering when it is recognisably epoch + * milliseconds. A seconds-based or duration-like value must never be compared + * against `Date.now()`, or every frame of a turn would look like it predates the + * turn and be dropped. + */ +const EPOCH_MS_FLOOR = 1_000_000_000_000; + async function* execute( prepared: Prepared, deps: CompletionDeps, @@ -515,6 +526,12 @@ async function* execute( ...(prepared.decision.note ? { note: prepared.decision.note } : {}), }; + // The turn boundary: every event the upstream creates after this instant + // belongs to this turn. The subscription above was opened before the prompt, + // so a leftover frame from the previous turn on the same sticky session can + // already be sitting in the queue (see the staleness check in the loop). + const turnFloor = Date.now(); + await client.prompt(sessionId, prepared.promptText, prepared.promptFiles, { ...(options.signal ? { signal: options.signal } : {}), }); @@ -605,6 +622,28 @@ async function* execute( const event = next; const data = event.data as Record; const eventMessageId = typeof data["assistantMessageID"] === "string" ? data["assistantMessageID"] : undefined; + + // A frame the upstream created before this turn's prompt belongs to an + // earlier turn of the same session. This is reachable: the subscription + // opens before `prompt()`, and a turn this gateway interrupted keeps its + // record committed for reuse while its terminal frames are still in flight. + // Accepting one would finalise this turn with no output — an empty answer + // reported as a normal `stop`, exactly the silent truncation the grace + // window below exists to prevent. + // + // Ordering uses the envelope stamp only, never the assistant message id: a + // single agent turn spans one assistant message per step, so an id change + // is normal and cannot scope a turn. `created` is likewise only used when + // it is recognisably epoch milliseconds (see `EPOCH_MS_FLOOR`), which + // assumes the upstream shares this process's clock — true for the spawned + // child this gateway supervises, and for any host running NTP. + const stale = + typeof event.created === "number" && event.created >= EPOCH_MS_FLOOR && event.created < turnFloor; + if (stale) { + metrics.eventFramesDropped.inc({ reason: "stale" }); + log.debug({ sessionId, type: event.type }, "dropping an event frame from an earlier turn"); + continue; + } if (eventMessageId && messageId === "") messageId = eventMessageId; switch (event.type) { diff --git a/src/upstream/events.ts b/src/upstream/events.ts index aff1902..8f6aa53 100644 --- a/src/upstream/events.ts +++ b/src/upstream/events.ts @@ -329,9 +329,13 @@ export class EventHub { } } } catch (error) { - // Only the idle watchdog rejects here; a `stop()`-aborted read settles - // through `reader.cancel()` below. - if (this.#isCurrentLoop(generation)) this.#dropReason = "idle"; + // Only the idle watchdog may be reported as "idle". A read can also reject + // because the transport failed, and mislabelling that a missed heartbeat + // hid the real trigger in the reconnect metric; anything else is the + // stream ending, which still reconnects through `#loop`. + if (this.#isCurrentLoop(generation)) { + this.#dropReason = error instanceof IdleReadTimeoutError ? "idle" : "ended"; + } throw error; } finally { // Release the response body on every exit path; without this a stop() or @@ -369,15 +373,28 @@ export class EventHub { if (dataLines.length === 0) return; - let parsed: OpencodeEvent; + let value: unknown; try { - parsed = JSON.parse(dataLines.join("\n")) as OpencodeEvent; + value = JSON.parse(dataLines.join("\n")); } catch { this.#metrics.eventFramesDropped.inc({ reason: "malformed" }); this.#log.debug({ frame: frame.slice(0, 200) }, "ignoring malformed event frame"); return; } + // `JSON.parse` succeeds for `null`, a bare string/number and an array. Those + // used to reach `parsed.type` below: on `null` the property read threw a + // TypeError that escaped `#handleFrame` into the read loop, tore down the + // shared stream (failing every in-flight completion with + // `event_stream_lost`), dropped every frame queued behind it and was not + // counted as malformed. Only a JSON object can be a frame. + if (typeof value !== "object" || value === null || Array.isArray(value)) { + this.#metrics.eventFramesDropped.inc({ reason: "malformed" }); + this.#log.debug({ frame: frame.slice(0, 200) }, "ignoring malformed event frame"); + return; + } + + const parsed = value as OpencodeEvent; if (!parsed.type && eventName) parsed.type = eventName; if (!parsed.type) return; @@ -431,11 +448,24 @@ function delay(ms: number): Promise { }); } +/** + * Rejection raised by the idle watchdog alone. + * + * The read loop classifies the reconnect reason from the rejection type: every + * rejection used to be reported as `"idle"`, which hid a transport failure behind + * a missed heartbeat. A plain `Error` is indistinguishable from anything else + * `read()` can reject with. + */ +class IdleReadTimeoutError extends Error {} + /** 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); + timer = setTimeout( + () => reject(new IdleReadTimeoutError(`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. diff --git a/test/anthropic.test.ts b/test/anthropic.test.ts index e8deefc..7fc853c 100644 --- a/test/anthropic.test.ts +++ b/test/anthropic.test.ts @@ -358,7 +358,9 @@ describe("POST /v1/messages", () => { 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`]); + // `Attachment.origin` stores `host + pathname` only, so a remote URL can + // never leak its scheme, userinfo or query string (P16). + expect(origins).toEqual([`127.0.0.1:${address.port}/first.png`, `127.0.0.1:${address.port}/second.png`]); // Serial resolution would need at least 120 ms for two 60 ms responses. expect(elapsed).toBeLessThan(110); } finally { @@ -401,6 +403,84 @@ describe("POST /v1/messages", () => { expect(body.stop_reason).toBe("tool_use"); }); + it("maps output_config onto the internal reasoning and response format", async () => { + // P10: `output_config` is the current Anthropic spelling for a + // thinking-effort request plus a structured-output format. It used to be + // silently ignored (no schema entry), so a caller got neither. + const captures: InternalRequest[] = []; + const { app } = await serverWith({ onRun: (request) => captures.push(request) }); + const send = async (output_config: unknown): Promise => { + const response = await post(app, "/v1/messages", { + model: MODEL, + max_tokens: 64, + messages: [{ role: "user", content: "Answer" }], + output_config, + }); + return response.statusCode; + }; + + expect( + await send({ effort: "high", format: { type: "json_schema", schema: { type: "object", properties: {} } } }), + ).toBe(200); + expect(captures[0]?.reasoning).toEqual({ enabled: true, effort: "high" }); + expect(captures[0]?.responseFormat).toEqual({ + type: "json_schema", + schema: { type: "object", properties: {} }, + }); + + // `json_object` bridges to the same internal shape the OpenAI surfaces use. + expect(await send({ format: { type: "json_object" } })).toBe(200); + expect(captures[1]?.reasoning).toBeUndefined(); + expect(captures[1]?.responseFormat).toEqual({ type: "json_object" }); + + // `type: "text"` requests no format; an empty object requests neither. + expect(await send({ format: { type: "text" } })).toBe(200); + expect(captures[2]?.responseFormat).toBeUndefined(); + expect(await send({})).toBe(200); + expect(captures[3]?.reasoning).toBeUndefined(); + expect(captures[3]?.responseFormat).toBeUndefined(); + + // Effort aliases keep working (the same table `reasoning_effort` uses). + expect(await send({ effort: "extra-high" })).toBe(200); + expect(captures[4]?.reasoning).toEqual({ enabled: true, effort: "xhigh" }); + }); + + it("lets the documented thinking object win over output_config", async () => { + // P10: `output_config.effort` is only consulted when `thinking` is absent, + // so an existing caller that sends both keeps its previous behaviour. + const captures: InternalRequest[] = []; + const { app } = await serverWith({ onRun: (request) => captures.push(request) }); + + const response = await post(app, "/v1/messages", { + model: MODEL, + max_tokens: 64, + messages: [{ role: "user", content: "Answer" }], + thinking: { type: "enabled", budget_tokens: 30_000 }, + output_config: { effort: "low", format: { type: "json_object" } }, + }); + + expect(response.statusCode).toBe(200); + expect(captures[0]?.reasoning).toEqual({ enabled: true, budgetTokens: 30_000 }); + // The non-reasoning half of `output_config` is still applied. + expect(captures[0]?.responseFormat).toEqual({ type: "json_object" }); + }); + + it("treats output_config: null as unset", async () => { + const captures: InternalRequest[] = []; + const { app } = await serverWith({ onRun: (request) => captures.push(request) }); + + const response = await post(app, "/v1/messages", { + model: MODEL, + max_tokens: 64, + messages: [{ role: "user", content: "Answer" }], + output_config: null, + }); + + expect(response.statusCode).toBe(200); + expect(captures[0]?.reasoning).toBeUndefined(); + expect(captures[0]?.responseFormat).toBeUndefined(); + }); + it("emits a thinking block with a deterministic signature when thinking is enabled", async () => { const events: CompletionEvent[] = [ { @@ -432,12 +512,17 @@ describe("POST /v1/messages", () => { expect(body.content[0]?.["thinking"]).toBe("Weighing the options."); const signature = body.content[0]?.["signature"]; expect(typeof signature).toBe("string"); - // 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"); + // The signature subject is the gateway message id of the response: the + // streamed path has to sign before the upstream id is known, so both paths + // key on the one id they both already have (P11). Pinned to the response id + // so a signature that stopped being derived from it cannot pass. + expect(Buffer.from(String(signature), "base64").toString("utf8")).toBe( + `opencode-api:${body.id}`, + ); expect(body.content[1]).toEqual({ type: "text", text: "Answer." }); }); - it("streams a signature_delta before the thinking block stop, matching the buffered signature", async () => { + it("streams a signature_delta before the thinking block stop", async () => { const events: CompletionEvent[] = [ { kind: "start", @@ -477,11 +562,20 @@ describe("POST /v1/messages", () => { expect(signatureAt).toBeGreaterThan(-1); expect(thinkingStopAt).toBeGreaterThan(signatureAt); + // The signature is derived from the gateway message id of its own response + // (P11). It cannot equal the buffered response's signature: that is a + // different HTTP request with its own `msg_…` id, which is exactly why the + // subject is the gateway id rather than the upstream one. 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"); + expect(Buffer.from(String(bufferedSignature), "base64").toString("utf8")).toBe( + `opencode-api:${bufferedBody.id}`, + ); + const streamedId = payloads.find((frame) => frame.type === "message_start")?.message?.id; + expect(Buffer.from(String(payloads[signatureAt]?.delta?.signature), "base64").toString("utf8")).toBe( + `opencode-api:${streamedId}`, + ); // Anthropic's streaming reference opens the thinking block with an empty // `signature` field and delivers the real value in the signature_delta; the @@ -538,7 +632,13 @@ describe("POST /v1/messages", () => { expect(textDeltas.map((frame) => frame.index)).toEqual([1, 1]); }); - it("uses the assistant id reported by the end event for the thinking signature", async () => { + it("keys the thinking signature on the gateway message id when the upstream id arrives late", async () => { + // P11 regression. `start` carries no upstream assistant id and the id only + // arrives on the step-scoped `reasoning_end`: the streamed path closes the + // thinking block (signature_delta + content_block_stop) at that point in + // real turns before the id is known, so it used to sign with the gateway id + // while the buffered path signed with the upstream id — the two paths + // disagreed for the same turn. Both now use the gateway message id. const events: CompletionEvent[] = [ { kind: "start", @@ -554,24 +654,39 @@ describe("POST /v1/messages", () => { { kind: "end", finishReason: "stop", usage: usage(4, 1), messageId: "msg_late" }, ]; const { app } = await serverWith({ script: () => events }); - - const streamed = await post(app, "/v1/messages", { + const payload = (stream: boolean) => ({ model: MODEL, max_tokens: 64, - stream: true, + stream, thinking: { type: "enabled", budget_tokens: 2_048 }, messages: [{ role: "user", content: "Think only" }], }); + + const streamed = await post(app, "/v1/messages", payload(true)); + const buffered = await post(app, "/v1/messages", payload(false)); 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; + const streamedId = payloads.find((frame) => frame.type === "message_start")?.message?.id; - expect(Buffer.from(String(signature), "base64").toString("utf8")).toBe("opencode-api:msg_late"); + const bufferedBody = JSON.parse(buffered.body) as AnthropicResponseBody; + const bufferedSignature = bufferedBody.content[0]?.["signature"]; + expect(typeof streamedId).toBe("string"); + expect(typeof bufferedSignature).toBe("string"); + // Both signatures are derived from the id of their own response… + expect(Buffer.from(String(signature), "base64").toString("utf8")).toBe(`opencode-api:${streamedId}`); + expect(Buffer.from(String(bufferedSignature), "base64").toString("utf8")).toBe( + `opencode-api:${bufferedBody.id}`, + ); + // …and neither uses the upstream id, which the streamed path cannot know + // when it has to close the thinking block. + expect(Buffer.from(String(signature), "base64").toString("utf8")).not.toContain("msg_late"); }); - it("matches the buffered signature when the assistant id only arrives on step events", async () => { + it("signs with the gateway id 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. + // reports it on the step-scoped end events; the thinking block closes before + // that on the streamed path, so both adapters key the signature on the + // gateway message id they both already hold (P11). const events: CompletionEvent[] = [ { kind: "start", @@ -611,8 +726,16 @@ describe("POST /v1/messages", () => { 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); + expect(Buffer.from(String(bufferedSignature), "base64").toString("utf8")).toBe( + `opencode-api:${bufferedBody.id}`, + ); + // Each path signs with the gateway id of its own response (P11), so the two + // signatures are equal in form and never keyed on the upstream id that only + // one of the two paths can know at signing time. + const streamedId = payloads.find((frame) => frame.type === "message_start")?.message?.id; + expect(Buffer.from(String(payloads[signatureAt]?.delta?.signature), "base64").toString("utf8")).toBe( + `opencode-api:${streamedId}`, + ); }); it("maps a length finish reason to max_tokens", async () => { diff --git a/test/auth-surface.test.ts b/test/auth-surface.test.ts new file mode 100644 index 0000000..681e58b --- /dev/null +++ b/test/auth-surface.test.ts @@ -0,0 +1,186 @@ +/** + * Route classification regression tests (proposal P1). + * + * `request.url` keeps the bytes the caller sent while Fastify's router matches + * on the percent-decoded path, so classifying on the raw URL let a general API + * key reach every `/admin/*` route through an encoded spelling such as + * `/%61dmin/config`. These tests drive the real app through `app.inject()` and + * pin the classification that the dispatcher actually uses. + */ +import { describe, expect, it } from "vitest"; +import { classifyPath } from "../src/auth.js"; +import { buildServer } from "../src/server.js"; +import { createTestContext } from "./helpers/context.js"; + +const GENERAL = "general-key"; +const ADMIN = "admin-key"; + +function build() { + return createTestContext({ + config: { apiKeys: [GENERAL], adminApiKeys: [ADMIN], usingDefaultApiKey: false, metricsEnabled: false }, + }); +} + +describe("route classification", () => { + it("classifies on the matched route rather than the raw encoded URL", () => { + const matched = { routeOptions: { url: "/admin/config" }, url: "/%61dmin/config" }; + expect(classifyPath(matched as never)).toBe("/admin/config"); + + // An unmatched path has no route pattern and falls back to the canonical + // raw URL, so an unknown encoded path is still not treated as an admin route. + const unmatched = { routeOptions: {}, url: "/%61dmin/nothing" }; + expect(classifyPath(unmatched as never)).toBe("/%61dmin/nothing"); + }); + + it("rejects a general key on the plain admin route", async () => { + const app = await buildServer(build()); + try { + const response = await app.inject({ + method: "GET", + url: "/admin/config", + headers: { authorization: `Bearer ${GENERAL}` }, + }); + expect(response.statusCode).toBe(401); + } finally { + await app.close(); + } + }); + + it("accepts an admin key on the plain admin route", async () => { + const app = await buildServer(build()); + try { + const response = await app.inject({ + method: "GET", + url: "/admin/config", + headers: { authorization: `Bearer ${ADMIN}` }, + }); + expect(response.statusCode).toBe(200); + } finally { + await app.close(); + } + }); + + it("rejects a general key on a percent-encoded admin route", async () => { + const app = await buildServer(build()); + try { + for (const url of ["/%61dmin/config", "/%61%64%6d%69%6e/config", "/admin/%63onfig"]) { + const response = await app.inject({ + method: "GET", + url, + headers: { authorization: `Bearer ${GENERAL}` }, + }); + // Either the encoded spelling reaches the admin route (401) or it does + // not match one at all (404); it must never answer with admin data. + expect([401, 404]).toContain(response.statusCode); + expect(response.body).not.toContain("\"host\""); + } + } finally { + await app.close(); + } + }); + + it("accepts an admin key on a percent-encoded admin route", async () => { + const app = await buildServer(build()); + try { + const response = await app.inject({ + method: "GET", + url: "/%61dmin/config", + headers: { authorization: `Bearer ${ADMIN}` }, + }); + expect(response.statusCode).toBe(200); + } finally { + await app.close(); + } + }); + + it("rejects a general key on an encoded admin mutation", async () => { + const app = await buildServer(build()); + try { + for (const [method, url] of [ + ["DELETE", "/%61dmin/sessions"], + ["POST", "/%61dmin/models/refresh"], + ["POST", "/%61dmin/upstream/restart"], + ] as const) { + const response = await app.inject({ + method, + url, + headers: { authorization: `Bearer ${GENERAL}` }, + }); + expect(response.statusCode).toBe(401); + } + } finally { + await app.close(); + } + }); + + it("still answers every admin route for an admin key", async () => { + const app = await buildServer(build()); + try { + for (const [method, url] of [ + ["GET", "/admin/status"], + ["GET", "/admin/config"], + ["GET", "/admin/sessions"], + ["POST", "/admin/models/refresh"], + ] as const) { + const response = await app.inject({ + method, + url, + headers: { authorization: `Bearer ${ADMIN}` }, + }); + expect(response.statusCode).toBe(200); + } + } finally { + await app.close(); + } + }); + + it("uses the Anthropic error envelope for an encoded Anthropic path", async () => { + const app = await buildServer(build()); + try { + const response = await app.inject({ + method: "POST", + url: "/v1/%6dessages", + headers: { authorization: `Bearer ${GENERAL}`, "content-type": "application/json" }, + payload: { model: "opencode/big-pickle" }, + }); + expect(response.statusCode).toBe(400); + const body = response.json() as { type?: string; error?: unknown }; + expect(body.type).toBe("error"); + expect(body.error).toBeDefined(); + } finally { + await app.close(); + } + }); + + it("keeps the OpenAI error envelope for a non-Anthropic path", async () => { + const app = await buildServer(build()); + try { + const response = await app.inject({ + method: "POST", + url: "/v1/messagesfoo", + headers: { authorization: `Bearer ${GENERAL}`, "content-type": "application/json" }, + payload: {}, + }); + expect(response.statusCode).toBe(404); + const body = response.json() as { type?: string; error?: unknown }; + expect(body.type).toBeUndefined(); + expect(body.error).toBeDefined(); + } finally { + await app.close(); + } + }); + + it("still authenticates a general key on a general route", async () => { + const app = await buildServer(build()); + try { + const response = await app.inject({ + method: "GET", + url: "/v1/models", + headers: { authorization: `Bearer ${GENERAL}` }, + }); + expect(response.statusCode).toBe(200); + } finally { + await app.close(); + } + }); +}); diff --git a/test/client.test.ts b/test/client.test.ts index 89d9b67..9a978b3 100644 --- a/test/client.test.ts +++ b/test/client.test.ts @@ -119,12 +119,21 @@ async function rejectingUpstream(): Promise { } /** A client over a scripted `UpstreamProcess` that records lifecycle calls. */ -function stubUpstream(url: string, upstreamRequestTimeoutMs = 5_000): FakeUpstream { +function stubUpstream( + url: string, + upstreamRequestTimeoutMs = 5_000, + options: { resolveDelayMs?: number } = {}, +): FakeUpstream { const config = testConfig({ upstreamRequestTimeoutMs }); const stale: string[] = []; const reprobe: string[] = []; const upstream = { - resolve: async () => ({ url, password: undefined, source: "env" as const }), + resolve: async () => { + // A cold start (spawn + readiness) or a re-probe can take seconds; the + // delay models a caller that disconnects while `resolve()` is still busy. + if (options.resolveDelayMs !== undefined) await delay(options.resolveDelayMs); + return { url, password: undefined, source: "env" as const }; + }, markStale: (reason: string) => { stale.push(reason); }, @@ -132,16 +141,62 @@ function stubUpstream(url: string, upstreamRequestTimeoutMs = 5_000): FakeUpstre reprobe.push(reason); }, } as unknown as UpstreamProcess; + // The client and the fixture share one registry: `metricValues()` reads this + // instance, so a second one would observe nothing the client recorded. + const metrics = createMetrics({ enabled: false }); return { url, - client: new OpencodeClient(upstream, config, createLogger(config), createMetrics({ enabled: false })), - metrics: createMetrics({ enabled: false }), + client: new OpencodeClient(upstream, config, createLogger(config), metrics), + metrics, stale, reprobe, close: async () => undefined, }; } +/** A real HTTP listener that answers every request with the same `200` body. */ +async function respondingUpstream(body: string): Promise { + const server = http.createServer((_request, response) => { + response.writeHead(200, { "content-type": "application/json" }); + response.end(body); + }); + await new Promise((resolve) => server.listen(0, "127.0.0.1", resolve)); + const { port } = server.address() as AddressInfo; + const item = stubUpstream(`http://127.0.0.1:${port}`, 5_000); + item.close = async () => { + server.closeAllConnections(); + await new Promise((resolve) => server.close(() => resolve())); + }; + open.push(item); + return item; +} + +/** A real HTTP listener that answers `200 {"data":{"id":"ses_1"}}` and counts requests. */ +async function countingUpstream(options: { resolveDelayMs?: number } = {}): Promise<{ + item: FakeUpstream; + requests: () => number; +}> { + let requests = 0; + const server = http.createServer((_request, response) => { + requests += 1; + response.writeHead(200, { "content-type": "application/json" }); + response.end('{"data":{"id":"ses_1"}}'); + }); + await new Promise((resolve) => server.listen(0, "127.0.0.1", resolve)); + const { port } = server.address() as AddressInfo; + const item = stubUpstream(`http://127.0.0.1:${port}`, 5_000, options); + item.close = async () => { + server.closeAllConnections(); + await new Promise((resolve) => server.close(() => resolve())); + }; + open.push(item); + return { item, requests: () => requests }; +} + +function delay(ms: number): Promise { + return new Promise((resolve) => setTimeout(resolve, ms)); +} + describe("OpencodeClient", () => { it("reports its own request timeout as a 504", async () => { const upstream = await hangingUpstream(150, { catalogueTimeoutMs: 150 }); @@ -229,6 +284,79 @@ describe("OpencodeClient", () => { expect(requests.map((value) => value.labels?.["outcome"])).toEqual(["aborted", "aborted"]); expect(requests.map((value) => value.labels?.["operation"])).toEqual(["session.create", "session.prompt"]); }); + + it("rejects a 2xx body that is empty or not a JSON object", async () => { + for (const body of ["", "null"]) { + const upstream = await respondingUpstream(body); + const expected = { + status: 503, + kind: "overloaded_error", + code: "upstream_invalid_json", + upstreamStatus: 200, + }; + + // Pre-fix an empty body returned `undefined` and a literal `null` passed + // `safeParse`, so both reached `response.data` as a bare `TypeError` — + // outside the ApiError taxonomy, i.e. HTTP 500 for `/ready`, + // `/v1/models` and every `ModelRegistry.resolve()`. + await expect(upstream.client.listModels()).rejects.toMatchObject(expected); + await expect( + upstream.client.createSession({ model: { providerID: "opencode", id: "m" }, agent: "build" }), + ).rejects.toMatchObject(expected); + + // Both cases are the same invalid-JSON outcome as a syntax error. + const requests = await metricValues(upstream, "opencode_api_upstream_requests_total"); + expect(requests.map((value) => value.labels?.["outcome"])).toEqual(["invalid_json", "invalid_json"]); + } + }); + + it("does not issue the upstream call when the caller aborts during resolve()", async () => { + // `resolve()` (cold start + readiness) is bounded by 30 s, so it is exactly + // where a client disconnect is most likely and was least visible. + const { item, requests } = await countingUpstream({ resolveDelayMs: 50 }); + const controller = new AbortController(); + const creating = item.client.createSession( + { model: { providerID: "opencode", id: "m" }, agent: "build" }, + { signal: controller.signal }, + ); + setTimeout(() => controller.abort(), 10); + + // Pre-fix the signal was only observed after `resolve()`, so the request ran + // against a live upstream the caller had already abandoned — for `prompt()` + // that is a real, billed turn nobody is left to read. + await expect(creating).rejects.toMatchObject({ + status: 499, + kind: "timeout_error", + message: "Client closed the request.", + }); + expect(requests()).toBe(0); + + const values = await metricValues(item, "opencode_api_upstream_requests_total"); + expect(values).toHaveLength(1); + expect(values[0]?.value).toBe(1); + expect(values[0]?.labels?.["operation"]).toBe("session.create"); + expect(values[0]?.labels?.["outcome"]).toBe("aborted"); + }); + + it("does not issue the upstream call for a signal aborted before the call", async () => { + const { item, requests } = await countingUpstream(); + const controller = new AbortController(); + controller.abort(); + + // An already-aborted signal never emits another "abort" event, so a listener + // attached after the fact used to miss it entirely and the call proceeded. + await expect( + item.client.createSession( + { model: { providerID: "opencode", id: "m" }, agent: "build" }, + { signal: controller.signal }, + ), + ).rejects.toMatchObject({ status: 499, kind: "timeout_error", message: "Client closed the request." }); + expect(requests()).toBe(0); + + const values = await metricValues(item, "opencode_api_upstream_requests_total"); + expect(values).toHaveLength(1); + expect(values[0]?.labels?.["outcome"]).toBe("aborted"); + }); }); // ------------------------------------------------------------------- COR-09 --- diff --git a/test/completion.test.ts b/test/completion.test.ts index 9b22cd3..1dffa57 100644 --- a/test/completion.test.ts +++ b/test/completion.test.ts @@ -1512,3 +1512,119 @@ describe("tool_choice that requires a tool", () => { expect(createSessionCalls).toHaveLength(1); }); }); + +/** + * Turn scoping (proposal P2). + * + * The per-session subscription opens before `prompt()`, and a turn this gateway + * interrupted keeps its record committed for reuse while its terminal frames are + * still in flight. A frame from the previous turn must therefore not be able to + * end the next one: without the scope check it finalised the new turn with no + * output and reported an empty answer as a normal `stop`. + */ +describe("turn-scoped event handling", () => { + /** An envelope the upstream created at `createdAt` (epoch milliseconds). */ + function stamped(type: string, createdAt: number, data: Record = {}): OpencodeEvent { + return { id: `evt_${type}_${createdAt}`, type, created: createdAt, data: { sessionID: "ses_test", ...data } }; + } + + /** A stamp no turn running now can have produced. */ + const BEFORE_THIS_TURN = 1_700_000_000_000; + + it("ignores a terminal frame the previous turn left in flight", async () => { + const { deps, sessions, promptCalls } = harness((_sessionId, call) => + call === 0 + ? simpleTurn("First") + : [ + stamped("session.idle", BEFORE_THIS_TURN, { outcome: "success" }), + ...simpleTurn("Second"), + ], + ); + + const first = await collectCompletion(request(), deps); + expect(first.text).toBe("First"); + expect(sessions.size()).toBe(1); + + const second = await collectCompletion(request(), deps); + expect(promptCalls[1]?.sessionId).toBe("ses_test"); + expect(second.text).toBe("Second"); + expect(second.finishReason).toBe("stop"); + }); + + it("keeps every step of a multi-step turn, whose assistant message id changes", async () => { + // One agent turn spans one assistant message per step, so an id change is + // normal: scoping a turn by `data.assistantMessageID` would drop the later + // steps of every tool-using turn. + const { deps } = harness((_sessionId, call) => + call === 0 + ? simpleTurn("First") + : [ + event("session.step.started", { + assistantMessageID: "msg_s1", + agent: "build", + model: { providerID: "opencode", id: "seaglass-alpha-free" }, + started: 0, + }), + event("session.step.ended", { assistantMessageID: "msg_s1", finish: "tool-calls" }), + event("session.step.started", { + assistantMessageID: "msg_s2", + agent: "build", + model: { providerID: "opencode", id: "seaglass-alpha-free" }, + started: 0, + }), + event("session.text.delta", { assistantMessageID: "msg_s2", ordinal: 0, delta: "Second" }), + event("session.step.ended", { assistantMessageID: "msg_s2", finish: "stop" }), + event("session.execution.succeeded", { assistantMessageID: "msg_s2" }), + ], + ); + + await collectCompletion(request(), deps); + const second = await collectCompletion(request(), deps); + expect(second.text).toBe("Second"); + expect(second.finishReason).toBe("stop"); + }); + + it("counts a dropped pre-turn frame as stale", async () => { + const { deps, metrics } = harness((_sessionId, call) => + call === 0 + ? simpleTurn("First") + : [stamped("session.execution.succeeded", BEFORE_THIS_TURN), ...simpleTurn("Second")], + ); + + await collectCompletion(request(), deps); + await collectCompletion(request(), deps); + + const series = await metricSeries(metrics, "opencode_api_event_frames_dropped_total"); + expect(series.some((entry) => matches(entry.labels, { reason: "stale" }) && entry.value >= 1)).toBe(true); + }); + + it("never treats a seconds-based stamp as a pre-turn stamp", async () => { + // `created` is optional and unverified: a seconds-based value is smaller than + // every epoch-millisecond turn floor, so using it for ordering would drop + // every frame of the turn. Only recognisable epoch-millisecond stamps order. + const { deps } = harness((_sessionId, call) => + call === 0 + ? simpleTurn("First") + : [ + stamped("session.step.started", 1_700_000_000, { + assistantMessageID: "msg_b1", + agent: "build", + model: { providerID: "opencode", id: "seaglass-alpha-free" }, + started: 0, + }), + stamped("session.text.delta", 1_700_000_000, { + assistantMessageID: "msg_b1", + ordinal: 0, + delta: "Second", + }), + event("session.step.ended", { assistantMessageID: "msg_b1", finish: "stop" }), + event("session.execution.succeeded", { assistantMessageID: "msg_b1" }), + ], + ); + + await collectCompletion(request(), deps); + const second = await collectCompletion(request(), deps); + expect(second.text).toBe("Second"); + expect(second.finishReason).toBe("stop"); + }); +}); diff --git a/test/config.test.ts b/test/config.test.ts index f124630..8f3af48 100644 --- a/test/config.test.ts +++ b/test/config.test.ts @@ -568,4 +568,57 @@ describe("logger redaction (A4)", () => { expect(output).not.toContain(secret); } }); -}); \ No newline at end of file +}); +// --------------------------------------------------------------------- P3a --- + +describe("P3a: OPENCODE_REASONING_FIELD is validated like the other enums", () => { + it("accepts both documented values, case-insensitively", () => { + const warn = vi.spyOn(console, "warn").mockImplementation(() => undefined); + + setEnv("OPENCODE_REASONING_FIELD", "both"); + expect(config().reasoningField).toBe("both"); + setEnv("OPENCODE_REASONING_FIELD", "BOTH"); + expect(config().reasoningField).toBe("both"); + setEnv("OPENCODE_REASONING_FIELD", "reasoning_content"); + expect(config().reasoningField).toBe("reasoning_content"); + + expect(warn).not.toHaveBeenCalled(); + }); + + it("warns and falls back to reasoning_content for a typo instead of swallowing it", () => { + const warn = vi.spyOn(console, "warn").mockImplementation(() => undefined); + setEnv("OPENCODE_REASONING_FIELD", "boht"); + + expect(config().reasoningField).toBe("reasoning_content"); + expect(warn).toHaveBeenCalledTimes(1); + const message = String(warn.mock.calls[0]?.[0]); + expect(message).toContain("OPENCODE_REASONING_FIELD"); + // The existing warning style names the variable and the default it used. + expect(message).toContain("reasoning_content"); + // The value is never echoed: an operator can paste a secret into any variable. + expect(message).not.toContain("boht"); + }); + + it("keeps the documented default when the variable is unset", () => { + const warn = vi.spyOn(console, "warn").mockImplementation(() => undefined); + setEnv("OPENCODE_REASONING_FIELD", undefined); + + expect(config().reasoningField).toBe("reasoning_content"); + expect(warn).not.toHaveBeenCalled(); + }); + + it("still validates OPENCODE_REASONING_DEFAULT through the same helper", () => { + const warn = vi.spyOn(console, "warn").mockImplementation(() => undefined); + + for (const value of ["off", "on-request", "always"]) { + setEnv("OPENCODE_REASONING_DEFAULT", value); + expect(config().reasoningDefault, value).toBe(value); + } + expect(warn).not.toHaveBeenCalled(); + + setEnv("OPENCODE_REASONING_DEFAULT", "alway"); + expect(config().reasoningDefault).toBe("on-request"); + expect(warn).toHaveBeenCalledTimes(1); + expect(String(warn.mock.calls[0]?.[0])).toContain("OPENCODE_REASONING_DEFAULT"); + }); +}); diff --git a/test/docs-consistency.test.ts b/test/docs-consistency.test.ts index a62a403..51b0414 100644 --- a/test/docs-consistency.test.ts +++ b/test/docs-consistency.test.ts @@ -23,6 +23,7 @@ import path from "node:path"; import { fileURLToPath } from "node:url"; import { describe, expect, it } from "vitest"; import { buildServer } from "../src/server.js"; +import { SERVICE_NAME, VERSION } from "../src/version.js"; import { createTestContext } from "./helpers/context.js"; const repoRoot = path.resolve(path.dirname(fileURLToPath(import.meta.url)), ".."); @@ -36,7 +37,7 @@ function read(relativePath: string): string { * suffix is optional so the plain `env()` reads count too, and `\b` plus the * lowercase spelling keeps `warnInvalidEnv("...")` out of the set. */ -const ENV_READ = /\benv(?:Str|OptStr|Int|Bool|List|LogLevel)?\(\s*"([A-Z][A-Z0-9_]*)"/g; +const ENV_READ = /\benv(?:Str|OptStr|Int|Bool|List|LogLevel|Enum)?\(\s*"([A-Z][A-Z0-9_]*)"/g; /** A token that reads as an environment-variable name in documentation. */ const DOCUMENTED_NAME = /\b(?:OPENCODE_[A-Z0-9_]+|HOST|PORT)\b/g; @@ -211,6 +212,32 @@ describe("the GET / endpoint index (docs/API.md)", () => { expect(entry, `the index entry "${entry}" is not canonical`).toMatch(/^[A-Z]+ \/\S*$/); } }); + + it("documents the service name and version the gateway actually reports", async () => { + // The example block is the machine-readable identity of the deployment, so + // its `service`/`version` must match both the live body and the compiled-in + // constants: comparing only `endpoints` let a version bump leave the + // documented example stale with a green suite. + const documented = JSON.parse(documentedIndexBlock(read("docs/API.md"))) as { + service?: unknown; + version?: unknown; + }; + const ctx = createTestContext(); + const app = await buildServer(ctx); + try { + await app.ready(); + const live = (await app.inject({ method: "GET", url: "/" })).json() as { + service: string; + version: string; + }; + expect(documented.service).toBe(live.service); + expect(documented.version).toBe(live.version); + expect(live.service).toBe(SERVICE_NAME); + expect(live.version).toBe(VERSION); + } finally { + await app.close(); + } + }); }); // ------------------------------------------------------------------- P-15 --- diff --git a/test/events.test.ts b/test/events.test.ts index a0dd6c6..5e7425c 100644 --- a/test/events.test.ts +++ b/test/events.test.ts @@ -194,6 +194,64 @@ describe("EventHub", () => { expect(received[0]?.type).toBe("session.text.delta"); }); + it("drops a non-object JSON frame without tearing down the stream", async () => { + const item = await fixture((response) => { + response.write(frame({ id: "e0", type: "server.connected", data: {} })); + // `data: null` is valid JSON but not a frame. It used to make `parsed.type` + // throw inside `#handleFrame`; the TypeError escaped into the read loop, + // tore the shared stream down and — because the valid frame shares this + // chunk — the frame after it was lost as well, so every in-flight + // completion saw a gap. + response.write( + `data: null\n\n${frame({ id: "e1", type: "session.text.delta", data: { sessionID: "ses_1", delta: "ok" } })}`, + ); + return () => undefined; + }); + active.push(item); + + const deltas: unknown[] = []; + item.hub.subscribe("ses_1", (event) => deltas.push((event.data as { delta?: unknown }).delta)); + item.hub.start(); + + await waitFor(() => deltas.length === 1); + // Let a reconnect (and any duplicate delivery) land before asserting. + await delay(80); + + expect(deltas).toEqual(["ok"]); + expect( + await counterValue(item.metrics, "opencode_api_event_frames_dropped_total", { reason: "malformed" }), + ).toBe(1); + // The stream must survive: no reconnect at all, and none labelled "idle". + expect(item.connectionCount()).toBe(1); + expect(item.closedCount()).toBe(0); + expect(item.hub.connected).toBe(true); + expect( + await counterValue(item.metrics, "opencode_api_event_stream_reconnects_total", { reason: "idle" }), + ).toBe(0); + }); + + it("labels a failed read as ended instead of idle", async () => { + const item = await fixture((response) => { + response.write(frame({ id: "e0", type: "server.connected", data: {} })); + // Destroy the socket: a transport failure, not a missed heartbeat. The read + // loop used to set `#dropReason = "idle"` for every rejection, so this + // reconnect was counted as if the upstream had gone silent. + const timer = setTimeout(() => response.socket?.destroy(), 100); + return () => clearTimeout(timer); + }); + active.push(item); + + item.hub.start(); + expect(await item.hub.ensureConnected(2_000)).toBe(true); + + await waitForAsync( + async () => + (await counterValue(item.metrics, "opencode_api_event_stream_reconnects_total", { reason: "ended" })) >= 1, + 3_000, + ); + expect(await counterValue(item.metrics, "opencode_api_event_stream_reconnects_total", { reason: "idle" })).toBe(0); + }); + it("releases every concurrent ensureConnected waiter", async () => { const item = await fixture((response) => { const timer = setTimeout(() => response.write(frame({ id: "e0", type: "server.connected", data: {} })), 120); diff --git a/test/http-proposals.test.ts b/test/http-proposals.test.ts index d12b14d..2fd6d3d 100644 --- a/test/http-proposals.test.ts +++ b/test/http-proposals.test.ts @@ -9,12 +9,14 @@ * spy, because the property under test is not visible on the wire. */ import { readFileSync } from "node:fs"; +import { EventEmitter } from "node:events"; import os from "node:os"; -import type { FastifyRequest } from "fastify"; +import type { FastifyReply, FastifyRequest } from "fastify"; import { afterEach, describe, expect, it, vi } from "vitest"; import { extractApiKey, isAuthorized, requestPath } from "../src/auth.js"; import { loadConfig, resetConfigCache, type Config } from "../src/config.js"; import { chargeFailedAuth, createRateLimiters } from "../src/http/rateLimit.js"; +import { SseWriter } from "../src/http/sse.js"; import { appendVary, buildServer } from "../src/server.js"; import { createTestContext } from "./helpers/context.js"; @@ -401,4 +403,82 @@ describe("D1-D3 the documentation matches the code", () => { expect(documentation, String(pattern)).toMatch(pattern); } }); -}); \ No newline at end of file +}); +// --------------------------------------------------------------------- P3b --- + +/** Minimal `ServerResponse` double: records every frame the writer emits. */ +class RecordingRaw extends EventEmitter { + readonly written: string[] = []; + ended = false; + + write(chunk: string): boolean { + this.written.push(chunk); + return true; + } + + writeHead(..._args: unknown[]): void { + /* no-op */ + } + + flushHeaders(): void { + /* no-op */ + } + + end(): void { + this.ended = true; + } + + destroy(): void { + /* no-op */ + } +} + +/** Frames emitted by one `send()` call on a fresh writer. */ +function framesFrom(data: string | object, event?: string): string[] { + const raw = new RecordingRaw(); + const reply = { + raw, + getHeaders: () => ({}), + hijack: () => undefined, + } as unknown as FastifyReply; + const writer = new SseWriter(reply, { heartbeatMs: 0 }); + writer.open(); + writer.send(data, event); + writer.close(); + return raw.written; +} + +describe("P3b: SseWriter.send() cannot be used to inject SSE framing", () => { + it("splits a lone CR into its own data line", () => { + // SSE ends a line at a lone CR as well as at LF: emitting it verbatim let a + // payload open a field of its own inside the frame. + expect(framesFrom("a\rb")).toEqual(["data: a\ndata: b\n\n"]); + }); + + it("normalises CRLF into two data lines without emitting a bare CR", () => { + const frames = framesFrom("a\r\nb"); + expect(frames).toEqual(["data: a\ndata: b\n\n"]); + expect(frames.join("")).not.toContain("\r\n"); + }); + + it("keeps a line terminator in the event name inside the event field", () => { + // An `event` value with a newline used to end the `event:` line and inject a + // `data:` frame the client would parse as a second event. + const frames = framesFrom("payload", "message\r\ndata: injected"); + const frame = frames.join(""); + expect(frame.split("\n").filter((line) => line.startsWith("event:"))).toHaveLength(1); + expect(frame).not.toContain("\r"); + expect(frame).toContain("event: message data: injected\n"); + expect(frame).toContain("data: payload\n"); + }); + + it("keeps a normal multi-line data payload frame-identical to before", () => { + // The documented contract: a payload split on `\n` becomes one `data:` line + // per line, and an object payload is JSON-serialised on a single line. + expect(framesFrom("first\nsecond\nthird", "message")).toEqual([ + "event: message\ndata: first\ndata: second\ndata: third\n\n", + ]); + expect(framesFrom({ ok: true })).toEqual(['data: {"ok":true}\n\n']); + expect(framesFrom("", "message")).toEqual(["event: message\ndata: \n\n"]); + }); +}); diff --git a/test/media-proposals.test.ts b/test/media-proposals.test.ts index 51cbf5d..34565f1 100644 --- a/test/media-proposals.test.ts +++ b/test/media-proposals.test.ts @@ -16,6 +16,7 @@ import { loadConfig, resetConfigCache, type Config } from "../src/config.js"; import { ApiError } from "../src/errors.js"; import { createMediaBudget, + isPrivateHost, resolveAttachment, resolveAttachments, setMediaLogger, @@ -61,7 +62,9 @@ function config(overrides: Partial = {}): Config { /** Serve one PNG on loopback and return its base URL. */ async function servePng(): Promise { const server = http.createServer((request, response) => { - if (request.url === "/a.png") { + // Routed on the path only: a test may add a query string, which the URL + // parser keeps in `request.url`. + if (new URL(request.url ?? "/", "http://127.0.0.1").pathname === "/a.png") { response.writeHead(200, { "content-type": "image/png", "content-length": String(PNG_BUFFER.byteLength) }); response.end(PNG_BUFFER); return; @@ -271,4 +274,113 @@ describe("M6: ENXIO and ENODEV map to the 400 path", () => { openSpy.mockRestore(); } }); +}); + +describe("P15: the private-host guard normalises a zone suffix, an unparsed literal and an absolute name", () => { + it("strips an IPv6 zone identifier before classifying", () => { + // `net.isIP()` rejects `%zone`, so those literals used to fall through as + // public even though the address they qualify is loopback or link-local. + expect(isPrivateHost("::ffff:127.0.0.1%en0")).toBe(true); + expect(isPrivateHost("fe80::1%eth0")).toBe(true); + // The `%25` spelling a caller may hand over undecoded is the same suffix. + expect(isPrivateHost("::ffff:127.0.0.1%25en0")).toBe(true); + expect(isPrivateHost("[fe80::1%eth0]")).toBe(true); + // A zone selects an interface, never a different host: a public literal + // stays public with or without one. + expect(isPrivateHost("2001:db8::1%en0")).toBe(false); + }); + + it("classifies a colon-containing host that net.isIP rejects as private", () => { + // A hostname cannot contain a colon; one that does and is not an address is + // unclassifiable, so it is refused rather than allowed through. + expect(isPrivateHost("127.0.0.1:8080")).toBe(true); + expect(isPrivateHost("::ffff:127.0.0.1:80")).toBe(true); + expect(isPrivateHost("evil:host")).toBe(true); + }); + + it("classifies the embedded last 32 bits of an IPv6 literal", () => { + // An IPv4-compatible form (`::7f00:1`) and a fully written mapped form carry + // a private IPv4 address the 16-bit prefix checks alone did not catch. + expect(isPrivateHost("::7f00:1")).toBe(true); + expect(isPrivateHost("::a00:1")).toBe(true); + expect(isPrivateHost("::ffff:a9fe:a9fe")).toBe(true); + expect(isPrivateHost("0:0:0:0:0:ffff:a9fe:a9fe")).toBe(true); + // A public IPv4 address stays public in the same encodings. + expect(isPrivateHost("::ffff:808:808")).toBe(false); + expect(isPrivateHost("::808:808")).toBe(false); + }); + + it("strips exactly one trailing dot before the name lookup", () => { + expect(isPrivateHost("localhost.")).toBe(true); + expect(isPrivateHost("metadata.google.internal.")).toBe(true); + expect(isPrivateHost("api.local.")).toBe(true); + // A public name stays public in its absolute form too. + expect(isPrivateHost("api.openai.com.")).toBe(false); + // Only one dot is removed: `..` is not a name. + expect(isPrivateHost("..")).toBe(false); + }); + + it("keeps every previously public control case public", () => { + for (const host of ["8.8.8.8", "93.184.216.34", "api.openai.com", "2001:0db8:0:0:0:0:0:1", "0:0:0:0:0:ffff:808:808"]) { + expect(isPrivateHost(host), host).toBe(false); + } + for (const host of ["localhost", "127.0.0.1", "10.1.2.3", "::1", "fd00::1", "169.254.169.254"]) { + expect(isPrivateHost(host), host).toBe(true); + } + }); +}); + +describe("P16: a remote attachment origin drops credentials and the query string", () => { + it("stores host plus pathname only", async () => { + const base = await servePng(); + const authority = new URL(base).host; + + const attachment = await resolveAttachment( + // A credential in the userinfo and a signed token in the query: neither is + // sent by `requestMedia()`, so neither may be retained. + { url: `http://user:sekret@${authority}/a.png?token=s3cret#frag` }, + config({ allowRemoteMediaUrls: true, allowPrivateMediaUrls: true }), + ); + + expect(attachment.origin).toBe(`${authority}/a.png`); + expect(attachment.origin).not.toContain("sekret"); + expect(attachment.origin).not.toContain("user:"); + expect(attachment.origin).not.toContain("token"); + }); + + it("keeps the reader-visible origin policy through /v1/chat/completions", async () => { + const base = await servePng(); + const authority = new URL(base).host; + const captured: InternalRequest[] = []; + const ctx = createTestContext({ + config: { allowRemoteMediaUrls: true, allowPrivateMediaUrls: true }, + onRun: (request) => captured.push(request), + }); + const app = await buildServer(ctx); + + try { + const response = await app.inject({ + method: "POST", + url: "/v1/chat/completions", + headers: AUTH, + payload: { + model: "opencode/deepseek-v4.1-flash-free", + messages: [ + { + role: "user", + content: [ + { type: "text", text: "describe" }, + { type: "image_url", image_url: { url: `${base}/a.png?token=s3cret` } }, + ], + }, + ], + }, + }); + + expect(response.statusCode).toBe(200); + expect(captured[0]?.messages[0]?.attachments?.[0]?.origin).toBe(`${authority}/a.png`); + } finally { + await app.close(); + } + }); }); \ No newline at end of file diff --git a/test/media.test.ts b/test/media.test.ts index 8a05dd7..92f6543 100644 --- a/test/media.test.ts +++ b/test/media.test.ts @@ -437,7 +437,8 @@ describe("resolveAttachment", () => { config({ allowRemoteMediaUrls: true, allowPrivateMediaUrls: true }), ); expect(attachment.mime).toBe("image/png"); - expect(attachment.origin).toBe(`${baseUrl}/image.png`); + // `origin` is host plus pathname only (P16); the scheme is not retained. + expect(attachment.origin).toBe(`${new URL(baseUrl).host}/image.png`); expect(attachment.size).toBe(PNG_BUFFER.byteLength); }); @@ -642,7 +643,7 @@ describe("resolveAttachment", () => { 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(attachment.origin).toBe(`media.example.test:${port}/image.png`); expect(lookup).toHaveBeenCalledTimes(2); const options = captured[0]; @@ -678,10 +679,13 @@ describe("resolveAttachment", () => { }); expect(result.attachments).toHaveLength(3); + // `origin` is host plus pathname only (P16): the query string and the + // scheme are not retained, so three distinct URLs report the same origin. + const originBase = new URL(baseUrl).host; expect(result.attachments.map((attachment) => attachment.origin)).toEqual([ - `${baseUrl}/image.png?i=0`, - `${baseUrl}/image.png?i=1`, - `${baseUrl}/image.png?i=2`, + `${originBase}/image.png`, + `${originBase}/image.png`, + `${originBase}/image.png`, ]); expect(result.omitted).toHaveLength(37); expect(result.omitted[0]).toEqual({ index: 3, reason: "count" }); diff --git a/test/openai-chat.test.ts b/test/openai-chat.test.ts index e355728..fc744ec 100644 --- a/test/openai-chat.test.ts +++ b/test/openai-chat.test.ts @@ -105,6 +105,72 @@ describe("response_format", () => { }); expect(captured[2]?.responseFormat).toBeUndefined(); }); + + it("rejects json_schema.strict: true instead of silently dropping it", async () => { + // P7: `strict: true` promises server-enforced conformance the gateway cannot + // provide (the schema is rendered into the prompt), so it is a 400 naming the + // field — the same policy `logprobs` follows. `strict: false` keeps working. + const app = await buildServer(createTestContext()); + const rejected = await app.inject({ + method: "POST", + url: "/v1/chat/completions", + headers: AUTH, + payload: { + model: MODEL, + messages: [{ role: "user", content: "Hi" }], + response_format: { + type: "json_schema", + json_schema: { name: "answer", schema: { type: "object" }, strict: true }, + }, + }, + }); + + expect(rejected.statusCode).toBe(400); + const error = (rejected.json() as { error: { code: string; param: string | null } }).error; + expect(error.code).toBe("unsupported_parameter"); + expect(error.param).toBe("response_format.json_schema.strict"); + + const accepted = await app.inject({ + method: "POST", + url: "/v1/chat/completions", + headers: AUTH, + payload: { + model: MODEL, + messages: [{ role: "user", content: "Hi" }], + response_format: { + type: "json_schema", + json_schema: { name: "answer", schema: { type: "object" }, strict: false }, + }, + }, + }); + expect(accepted.statusCode).toBe(200); + }); + + it("rejects an unmapped reasoning_effort instead of coercing it to medium", async () => { + // P8: `reasoning_effort: "banana"` used to reach the orchestrator as + // `{enabled: true, effort: "banana"}`, which `resolveVariant()` bucketed to + // `medium`, silently turning thinking on. Aliases keep working. + const app = await buildServer(createTestContext()); + const rejected = await app.inject({ + method: "POST", + url: "/v1/chat/completions", + headers: AUTH, + payload: { model: MODEL, messages: [{ role: "user", content: "Hi" }], reasoning_effort: "banana" }, + }); + + expect(rejected.statusCode).toBe(400); + const error = (rejected.json() as { error: { code: string; param: string | null } }).error; + expect(error.code).toBe("invalid_request"); + expect(error.param).toBe("reasoning_effort"); + + const accepted = await app.inject({ + method: "POST", + url: "/v1/chat/completions", + headers: AUTH, + payload: { model: MODEL, messages: [{ role: "user", content: "Hi" }], reasoning_effort: "x-high" }, + }); + expect(accepted.statusCode).toBe(200); + }); }); describe("POST /v1/chat/completions (non-streaming)", () => { @@ -170,8 +236,10 @@ describe("POST /v1/chat/completions (non-streaming)", () => { expect(response.statusCode).toBe(200); const body = response.json() as ChatBody; expect(body.choices[0]?.message.content).toBe("Hello world"); - // Nothing unapplied was supplied, so the key stays absent. - expect(body.x_opencode["unapplied"]).toBeUndefined(); + // `service_tier` is the one field among these that is accepted but cannot be + // applied (OpenCode picks the upstream tier), so it is named in + // `x_opencode.unapplied` instead of being echoed as honoured (P9). + expect(body.x_opencode["unapplied"]).toEqual(["service_tier"]); await app.close(); }); @@ -291,6 +359,52 @@ describe("POST /v1/chat/completions (non-streaming)", () => { await app.close(); }); + it("rejects media content parts on a role that cannot carry them", async () => { + // P5: the orchestrator forwards attachments for user turns only, so media on + // a `tool` / `system` / `developer` / `assistant` message used to be + // downloaded, charged to the request budget and then dropped as an empty + // message. The rejection happens before any fetch, so a `data:` URI is used + // here only to keep the fixture offline — the point is the role. + const app = await buildServer(createTestContext()); + const media = [{ type: "image_url", image_url: { url: `data:image/png;base64,${PNG_BASE64}` } }]; + const cases: Array<{ role: string; extra: Record }> = [ + { role: "tool", extra: { tool_call_id: "call_1" } }, + { role: "system", extra: {} }, + { role: "developer", extra: {} }, + { role: "assistant", extra: {} }, + ]; + + for (const { role, extra } of cases) { + const response = await app.inject({ + method: "POST", + url: "/v1/chat/completions", + headers: AUTH, + payload: { + model: MODEL, + messages: [ + { role: "user", content: "look" }, + { role, content: media, ...extra }, + ], + }, + }); + expect(response.statusCode, `${role} must be rejected`).toBe(400); + const body = response.json() as { error: { code: string; param: string | null } }; + expect(body.error.code, `${role} must be invalid_request`).toBe("invalid_request"); + expect(body.error.param, `${role} must name the messages field`).toBe("messages"); + } + + // The same media on a `user` turn still works: text-only fixtures need no + // network because the attachment is inline. + const accepted = await app.inject({ + method: "POST", + url: "/v1/chat/completions", + headers: AUTH, + payload: { model: MODEL, messages: [{ role: "user", content: media }] }, + }); + expect(accepted.statusCode).toBe(200); + await app.close(); + }); + it("rejects a tool_choice naming an undeclared tool", async () => { // The real `runCompletion` builds the shared tool bridge; the scripted test // runner replaces it, so invoke the same assertion the orchestrator runs. @@ -740,8 +854,11 @@ describe("POST /v1/chat/completions (non-streaming)", () => { 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`); + // `Attachment.origin` is `host + pathname` only (P16), so the scheme is + // deliberately absent from the recorded value. + const fixtureHost = new URL(fixture.origin).host; + expect(attachments[0]?.origin).toBe(`${fixtureHost}/first.png`); + expect(attachments[1]?.origin).toBe(`${fixtureHost}/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. @@ -779,9 +896,11 @@ describe("POST /v1/chat/completions (non-streaming)", () => { expect(response.statusCode).toBe(200); const attachments = captured[0]?.messages.flatMap((message) => message.attachments ?? []) ?? []; + // `Attachment.origin` is `host + pathname` only (P16). + const fixtureHost = new URL(fixture.origin).host; expect(attachments.map((attachment) => attachment.origin)).toEqual([ - `${fixture.origin}/first.png`, - `${fixture.origin}/second.png`, + `${fixtureHost}/first.png`, + `${fixtureHost}/second.png`, ]); // Resolving message by message serialises the pools: two fixture delays. expect(elapsed).toBeLessThan(DELAY_MS * 2 - 40); @@ -1083,6 +1202,76 @@ describe("usage accounting", () => { await app.close(); }); + + it("counts the cache buckets inside prompt_tokens so cached_tokens stays a subset", async () => { + // P4 regression. The upstream reports `input` as the non-cached bucket only + // and carries the cache hits in `cache.read` / `cache.write`, so with + // `prompt_tokens = inputTokens` the payload claimed 100 cached tokens out of + // 5 prompt tokens and `total_tokens` ignored the cached prompt entirely. + const cacheUsage: Usage = { + ...EMPTY_USAGE, + inputTokens: 5, + cacheReadTokens: 100, + cacheWriteTokens: 7, + outputTokens: 2, + totalTokens: 114, + }; + const script = (request: InternalRequest): CompletionEvent[] => [ + { + kind: "start", + sessionId: "ses_cache", + messageId: "msg_cache", + model: request.model, + agent: "build", + reusedSession: false, + reasoningEnabled: false, + }, + { kind: "text_delta", text: "Cached", ordinal: 0 }, + { kind: "usage", usage: cacheUsage }, + { kind: "end", finishReason: "stop", usage: cacheUsage, messageId: "msg_cache" }, + ]; + const app = await buildServer(createTestContext({ script })); + + const buffered = await app.inject({ + method: "POST", + url: "/v1/chat/completions", + headers: AUTH, + payload: { model: MODEL, messages: [{ role: "user", content: "Hi" }] }, + }); + expect(buffered.statusCode).toBe(200); + const usage = (buffered.json() as ChatBody).usage; + expect(usage).toEqual({ + prompt_tokens: 112, + completion_tokens: 2, + total_tokens: 114, + completion_tokens_details: { reasoning_tokens: 0 }, + prompt_tokens_details: { cached_tokens: 100 }, + }); + expect((usage["prompt_tokens_details"] as { cached_tokens: number }).cached_tokens).toBeLessThanOrEqual( + usage["prompt_tokens"] as number, + ); + expect((usage["prompt_tokens"] as number) + (usage["completion_tokens"] as number)).toBe( + usage["total_tokens"], + ); + + const streamed = await app.inject({ + method: "POST", + url: "/v1/chat/completions", + headers: AUTH, + payload: { + model: MODEL, + messages: [{ role: "user", content: "Hi" }], + stream: true, + stream_options: { include_usage: true }, + }, + }); + const streamedUsage = parseSseJson(streamed.payload) + .map((frame) => frame.json) + .find((chunk) => chunk.usage !== undefined)?.usage ?? {}; + expect(streamedUsage).toEqual(usage); + + await app.close(); + }); }); describe("POST /v1/chat/completions (streaming)", () => { diff --git a/test/openai-completions.test.ts b/test/openai-completions.test.ts index 9cc2971..f547723 100644 --- a/test/openai-completions.test.ts +++ b/test/openai-completions.test.ts @@ -115,6 +115,30 @@ describe("POST /v1/completions (non-streaming)", () => { await app.close(); }); + it("accepts top_p and service_tier, records them and names them in x_opencode.unapplied", async () => { + // P9: this was the only surface that silently dropped `top_p` (no schema + // entry, so zod stripped it), and `service_tier` was accepted without any + // diagnostic. Both are now recorded and listed like the chat surface does. + 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", top_p: 0.9, temperature: 0.2, service_tier: "flex" }, + }); + + expect(response.statusCode).toBe(200); + const body = response.json() as CompletionBody; + expect(captured[0]?.topP).toBe(0.9); + expect(captured[0]?.temperature).toBe(0.2); + expect(captured[0]?.serviceTier).toBe("flex"); + expect(body.x_opencode["unapplied"]).toEqual(["temperature", "top_p", "service_tier"]); + await app.close(); + }); + it("rejects every field that changes the response shape with 400 unsupported_parameter", async () => { const ctx = createTestContext({ script: textScript }); const app = await buildCompletionServer(ctx); @@ -197,7 +221,10 @@ describe("POST /v1/completions (non-streaming)", () => { await app.close(); }); - it("joins an array prompt into one user turn with n: 1", async () => { + it("accepts a one-element array prompt with the default n and never merges prompts", async () => { + // P6. A one-element array is the spec-valid way to name a single prompt, so + // it is accepted with the default `n`; the single element is unwrapped, not + // joined, so `index: 0` keeps mapping to that prompt. const captured: InternalRequest[] = []; const ctx = createTestContext({ onRun: (request) => captured.push(request) }); @@ -207,11 +234,11 @@ describe("POST /v1/completions (non-streaming)", () => { method: "POST", url: "/v1/completions", headers: AUTH, - payload: { model: MODEL, prompt: ["first", "second"], n: 1 }, + payload: { model: MODEL, prompt: ["first"] }, }); expect(response.statusCode).toBe(200); - expect(captured[0]?.messages).toEqual([{ role: "user", text: "first\nsecond" }]); + expect(captured[0]?.messages).toEqual([{ role: "user", text: "first" }]); await app.close(); }); @@ -231,10 +258,12 @@ describe("POST /v1/completions (non-streaming)", () => { await app.close(); }); - it("rejects an array prompt without n: 1", async () => { + it("rejects an array prompt with more than one element", async () => { const ctx = createTestContext(); const app = await buildCompletionServer(ctx); + // Omitted `n` means the default of 1: the array itself is the problem, not + // the missing `n`, and the field named is `prompt`. const missingN = await app.inject({ method: "POST", url: "/v1/completions", @@ -242,7 +271,21 @@ describe("POST /v1/completions (non-streaming)", () => { payload: { model: MODEL, prompt: ["a", "b"] }, }); expect(missingN.statusCode).toBe(400); - expect((missingN.json() as { error: { param: string } }).error.param).toBe("prompt"); + const missingNError = (missingN.json() as { error: { code: string; param: string } }).error; + expect(missingNError.param).toBe("prompt"); + expect(missingNError.code).toBe("unsupported_parameter"); + + // Explicit `n: 1` does not make a multi-element array legal. + const explicitN = await app.inject({ + method: "POST", + url: "/v1/completions", + headers: AUTH, + payload: { model: MODEL, prompt: ["a", "b"], n: 1 }, + }); + expect(explicitN.statusCode).toBe(400); + expect((explicitN.json() as { error: { code: string; param: string } }).error.code).toBe( + "unsupported_parameter", + ); const nIsTwo = await app.inject({ method: "POST", diff --git a/test/openai-responses.test.ts b/test/openai-responses.test.ts index 0688282..bed0673 100644 --- a/test/openai-responses.test.ts +++ b/test/openai-responses.test.ts @@ -102,6 +102,7 @@ interface ResponsePayload { tools: Array>; temperature: number | null; top_p: number | null; + text: { type: string; name?: string; schema?: Record }; max_output_tokens: number | null; reasoning: { effort: string | null; summary: string | null }; incomplete_details: { reason: string } | null; @@ -240,6 +241,125 @@ describe("POST /v1/responses (non-streaming)", () => { expect(captured[1]?.responseFormat).toEqual({ type: "json_schema", name: "answer", schema: { type: "object" } }); }); + it("echoes text.format on the payload, defaulting to text, on both paths", async () => { + // P9: every other request field was echoed, but `text` was omitted, so a + // caller could not tell whether its `text.format` had been read. + const app = await makeApp(); + const payload = (text?: Record, stream = false): Record => ({ + model: "opencode/deepseek-v4.1-flash-free", + input: "hi", + stream, + ...(text !== undefined ? { text } : {}), + }); + + const defaulted = await app.inject({ method: "POST", url: "/v1/responses", headers: AUTH, payload: payload() }); + expect((defaulted.json() as ResponsePayload).text).toEqual({ type: "text" }); + + const jsonObject = await app.inject({ + method: "POST", + url: "/v1/responses", + headers: AUTH, + payload: payload({ format: { type: "json_object" } }), + }); + expect((jsonObject.json() as ResponsePayload).text).toEqual({ type: "json_object" }); + + const jsonSchema = await app.inject({ + method: "POST", + url: "/v1/responses", + headers: AUTH, + payload: payload({ format: { type: "json_schema", name: "answer", schema: { type: "object" } } }), + }); + expect((jsonSchema.json() as ResponsePayload).text).toEqual({ + type: "json_schema", + name: "answer", + schema: { type: "object" }, + }); + + const plainText = await app.inject({ + method: "POST", + url: "/v1/responses", + headers: AUTH, + payload: payload({ format: { type: "text" } }), + }); + expect((plainText.json() as ResponsePayload).text).toEqual({ type: "text" }); + + // The streamed response object carries the same echo. + const streamed = await app.inject({ + method: "POST", + url: "/v1/responses", + headers: AUTH, + payload: payload({ format: { type: "json_object" } }, true), + }); + const streamedBody = frames(streamed.payload).at(-1)?.json["response"] as ResponsePayload; + expect(streamedBody.text).toEqual({ type: "json_object" }); + }); + + it("records service_tier and names it in x_opencode.unapplied", async () => { + // P9: the field was accepted and neither echoed nor listed, so a caller that + // asked for a tier had no way to see it was not applied. + 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", input: "hi", service_tier: "flex" }, + }); + + expect(response.statusCode).toBe(200); + expect(captured?.serviceTier).toBe("flex"); + expect((response.json() as ResponsePayload).x_opencode.unapplied).toEqual(["service_tier"]); + }); + + it("counts the cache buckets inside input_tokens", async () => { + // P4: `input_tokens` must include `cache.read` / `cache.write`, otherwise + // `input_tokens_details.cached_tokens` can exceed `input_tokens`. + const cacheUsage: Usage = { + ...EMPTY_USAGE, + inputTokens: 5, + cacheReadTokens: 100, + cacheWriteTokens: 7, + outputTokens: 2, + totalTokens: 114, + }; + const app = await makeApp({ + script: (request): CompletionEvent[] => [ + { + kind: "start", + sessionId: "ses_cache", + messageId: "msg_cache", + model: request.model, + agent: "build", + reusedSession: false, + reasoningEnabled: false, + }, + { kind: "text_delta", text: "Cached", ordinal: 0 }, + { kind: "usage", usage: cacheUsage }, + { kind: "end", finishReason: "stop", usage: cacheUsage, messageId: "msg_cache" }, + ], + }); + + for (const stream of [false, true]) { + const response = await app.inject({ + method: "POST", + url: "/v1/responses", + headers: AUTH, + payload: { model: "opencode/deepseek-v4.1-flash-free", input: "hi", stream }, + }); + const body = stream + ? (frames(response.payload).at(-1)?.json["response"] as ResponsePayload) + : (response.json() as ResponsePayload); + expect(body.usage).toEqual({ + input_tokens: 112, + output_tokens: 2, + total_tokens: 114, + input_tokens_details: { cached_tokens: 100 }, + output_tokens_details: { reasoning_tokens: 0 }, + }); + expect(body.usage?.input_tokens_details.cached_tokens).toBeLessThanOrEqual(body.usage?.input_tokens ?? 0); + } + }); + it("rejects an input_file that only carries a file_id", async () => { const app = await makeApp(); @@ -1767,9 +1887,11 @@ describe("POST /v1/responses (media concurrency)", () => { expect(response.statusCode).toBe(200); const attachments = captured?.messages.at(-1)?.attachments ?? []; + // `Attachment.origin` stores `host + pathname` only (P16). + const mediaHost = new URL(baseUrl).host; expect(attachments.map((attachment) => attachment.origin)).toEqual([ - `${baseUrl}/first.png`, - `${baseUrl}/second.png`, + `${mediaHost}/first.png`, + `${mediaHost}/second.png`, ]); expect(attachments.every((attachment) => attachment.mime === "image/png")).toBe(true); // Serial resolution would need at least two full fixture delays. @@ -1801,9 +1923,11 @@ describe("POST /v1/responses (media concurrency)", () => { expect(response.statusCode).toBe(200); const attachments = captured?.messages.flatMap((message) => message.attachments ?? []) ?? []; + // `Attachment.origin` stores `host + pathname` only (P16). + const mediaHost = new URL(baseUrl).host; expect(attachments.map((attachment) => attachment.origin)).toEqual([ - `${baseUrl}/first.png`, - `${baseUrl}/second.png`, + `${mediaHost}/first.png`, + `${mediaHost}/second.png`, ]); // Resolving item by item would serialise two pools and cost two delays. expect(elapsed).toBeLessThan(MEDIA_DELAY_MS * 2 - 10); @@ -1981,4 +2105,105 @@ describe("POST /v1/responses (input validation)", () => { { name: "lookup" }, ]); }); + + it("rejects an empty model with 400 instead of resolving it and answering 404", async () => { + // P9: `model: ""` used to pass `z.string()` and reach `ModelRegistry.resolve()`, + // which reported `404 model_not_found`. It is a malformed body, not an + // unknown model, and the chat surface already answered 400. + const app = await makeApp(); + const response = await app.inject({ + method: "POST", + url: "/v1/responses", + headers: AUTH, + payload: { model: "", input: "hi" }, + }); + + expect(response.statusCode).toBe(400); + const body = response.json() as { error: { code: string; param: string | null } }; + expect(body.error.code).toBe("invalid_request"); + expect(body.error.param).toBe("model"); + }); + + it("rejects media content parts on a non-user input message", async () => { + // P5: only a `user` message and `function_call_output` may carry media; the + // other roles used to keep it, pay the download and lose it. + const app = await makeApp({ config: { allowPrivateMediaUrls: true } }); + for (const role of ["assistant", "system", "developer"] as const) { + const response = await app.inject({ + method: "POST", + url: "/v1/responses", + headers: AUTH, + payload: { + model: "opencode/deepseek-v4.1-flash-free", + input: [ + { role: "user", content: "look" }, + { role, content: [{ type: "input_image", image_url: PNG_DATA_URI }] }, + ], + }, + }); + expect(response.statusCode, `${role} must be rejected`).toBe(400); + const body = response.json() as { error: { code: string; param: string | null } }; + expect(body.error.code, `${role} must be invalid_request`).toBe("invalid_request"); + expect(body.error.param, `${role} must name the input field`).toBe("input"); + } + + // The same part on a `user` message is still resolved into an attachment. + let captured: InternalRequest | undefined; + const acceptedApp = await makeApp({ config: { allowPrivateMediaUrls: true }, onRun: (request) => (captured = request) }); + const accepted = await acceptedApp.inject({ + method: "POST", + url: "/v1/responses", + headers: AUTH, + payload: { + model: "opencode/deepseek-v4.1-flash-free", + input: [{ role: "user", content: [{ type: "input_image", image_url: PNG_DATA_URI }] }], + }, + }); + expect(accepted.statusCode).toBe(200); + expect(captured?.messages.at(-1)?.attachments).toHaveLength(1); + }); + + it("rejects text.format.strict: true instead of silently dropping it", async () => { + // P7, same policy as the chat `response_format.json_schema.strict`. + const app = await makeApp(); + const rejected = await app.inject({ + method: "POST", + url: "/v1/responses", + headers: AUTH, + payload: { + model: "opencode/deepseek-v4.1-flash-free", + input: "hi", + text: { format: { type: "json_schema", name: "answer", schema: { type: "object" }, strict: true } }, + }, + }); + + expect(rejected.statusCode).toBe(400); + const error = (rejected.json() as { error: { code: string; param: string | null } }).error; + expect(error.code).toBe("unsupported_parameter"); + expect(error.param).toBe("text.format.strict"); + }); + + it("rejects an unmapped reasoning.effort instead of coercing it to medium", async () => { + // P8: the value used to reach the orchestrator and be bucketed to `medium`. + const app = await makeApp(); + const rejected = await app.inject({ + method: "POST", + url: "/v1/responses", + headers: AUTH, + payload: { model: "opencode/deepseek-v4.1-flash-free", input: "hi", reasoning: { effort: "banana" } }, + }); + + expect(rejected.statusCode).toBe(400); + const error = (rejected.json() as { error: { code: string; param: string | null } }).error; + expect(error.code).toBe("invalid_request"); + expect(error.param).toBe("reasoning_effort"); + + const accepted = await app.inject({ + method: "POST", + url: "/v1/responses", + headers: AUTH, + payload: { model: "opencode/deepseek-v4.1-flash-free", input: "hi", reasoning: { effort: "x-high" } }, + }); + expect(accepted.statusCode).toBe(200); + }); }); diff --git a/test/parity.test.ts b/test/parity.test.ts index 46b76a4..3ded3a4 100644 --- a/test/parity.test.ts +++ b/test/parity.test.ts @@ -213,9 +213,12 @@ const CHAT: SurfaceCase = { expectsToolCalls: true, expectedFinishReason: "tool_calls", expectedUsage: { - prompt_tokens: 21, + // `prompt_tokens` folds in the cache buckets (P4): the upstream's `input` + // bucket is the non-cached part only, so 21 + 3 (cache read) + 1 (cache + // write) is the whole prompt. `cached_tokens` stays the read subset. + prompt_tokens: 25, completion_tokens: 13, - total_tokens: 34, + total_tokens: 38, completion_tokens_details: { reasoning_tokens: 4 }, prompt_tokens_details: { cached_tokens: 3 }, }, @@ -307,9 +310,10 @@ const RESPONSES: SurfaceCase = { expectsToolCalls: true, expectedFinishReason: "completed", expectedUsage: { - input_tokens: 21, + // Same cache-inclusive prompt accounting as the chat surface (P4). + input_tokens: 25, output_tokens: 13, - total_tokens: 34, + total_tokens: 38, input_tokens_details: { cached_tokens: 3 }, output_tokens_details: { reasoning_tokens: 4 }, }, @@ -357,9 +361,11 @@ const COMPLETIONS: SurfaceCase = { expectsToolCalls: false, expectedFinishReason: "tool_calls", expectedUsage: { - prompt_tokens: 21, + // The legacy surface shares `openAiUsage()`, so the cache buckets are part + // of `prompt_tokens` here too (P4). + prompt_tokens: 25, completion_tokens: 13, - total_tokens: 34, + total_tokens: 38, completion_tokens_details: { reasoning_tokens: 4 }, prompt_tokens_details: { cached_tokens: 3 }, }, @@ -436,7 +442,11 @@ function anthropicTurn( type: block.type, text: block.text, thinking: block.thinking, - signature: block.signature, + // The signature is derived from the gateway message id, which is random + // per response (P11), so only its shape is comparable across two HTTP + // requests. The streamed and buffered signatures of one turn are already + // asserted equal inside `test/anthropic.test.ts`. + signature: block.signature === "" ? "" : "", toolId: block.toolId, toolName: block.toolName, input: block.input, diff --git a/test/reasoning.test.ts b/test/reasoning.test.ts index 4f48df0..5e8c23c 100644 --- a/test/reasoning.test.ts +++ b/test/reasoning.test.ts @@ -1,4 +1,5 @@ import { describe, expect, it } from "vitest"; +import { ApiError } from "../src/errors.js"; import { EFFORT_ORDER, budgetFromEffort, @@ -214,8 +215,11 @@ describe("reasoning effort helpers", () => { it("builds reasoning requests from OpenAI and Anthropic inputs", () => { expect(reasoningFromEffort("high")).toEqual({ enabled: true, effort: "high" }); + // Every spelling in the alias table normalises to the same internal value. + expect(reasoningFromEffort("EXTRA-HIGH")).toEqual({ enabled: true, effort: "xhigh" }); expect(reasoningFromEffort("none")).toMatchObject({ enabled: false, disabled: true }); expect(reasoningFromEffort(undefined)).toBeUndefined(); + expect(reasoningFromEffort("")).toBeUndefined(); expect(reasoningFromThinking({ type: "enabled", budget_tokens: 4_000 })).toEqual({ enabled: true, budgetTokens: 4_000, @@ -224,4 +228,24 @@ describe("reasoning effort helpers", () => { expect(reasoningFromThinking({ type: "enabled" })).toMatchObject({ enabled: true, effort: "medium" }); expect(reasoningFromThinking(undefined)).toBeUndefined(); }); + + it("rejects a non-empty effort the alias table does not know", () => { + // P8: the value used to be passed through, and `resolveVariant()` bucketed + // it to `medium`, so `reasoning_effort: "banana"` silently enabled + // thinking. It is now a 400 naming the field, exactly like the other + // validated adapter fields. + expect(() => reasoningFromEffort("banana")).toThrowError(ApiError); + try { + reasoningFromEffort(" Banana "); + expect.unreachable("an unmapped effort must be rejected"); + } catch (error) { + expect(error).toBeInstanceOf(ApiError); + const apiError = error as ApiError; + expect(apiError.status).toBe(400); + expect(apiError.code).toBe("invalid_request"); + expect(apiError.param).toBe("reasoning_effort"); + } + // Whitespace-only is still "unset", not an invalid value. + expect(reasoningFromEffort(" ")).toBeUndefined(); + }); }); \ No newline at end of file diff --git a/test/regressions.test.ts b/test/regressions.test.ts index 8869f43..422bda4 100644 --- a/test/regressions.test.ts +++ b/test/regressions.test.ts @@ -268,10 +268,13 @@ describe("OpenAI responses surface (scripted)", () => { expect(call?.["arguments"]).toBe('{"city":"Hanoi"}'); expect(call?.["call_id"]).toBe("call_1"); const usage = body["usage"] as Record; - expect(usage["input_tokens"]).toBe(10); + // `input_tokens` is the whole prompt, and the cache buckets are a subset of + // it (`input_tokens_details.cached_tokens`) rather than additional to it. + expect(usage["input_tokens"]).toBe(12); + expect((usage["input_tokens_details"] as Record)["cached_tokens"]).toBe(2); // OpenAI semantics: reasoning tokens are a subset of output tokens. expect(usage["output_tokens"]).toBe(8); - expect(usage["total_tokens"]).toBe(18); + expect(usage["total_tokens"]).toBe(20); await app.close(); });