diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index af6e8f0..0d720e3 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -28,9 +28,9 @@ jobs: - name: Set up pnpm uses: pnpm/action-setup@v6 with: - # Pinned to the version that generated pnpm-lock.yaml; `allowBuilds` - # in pnpm-workspace.yaml is a pnpm 10+ feature. - version: 12.21.0 + # Pinned to the version in `packageManager`; `allowBuilds` in + # pnpm-workspace.yaml is a pnpm 10+ feature. Bump both together. + version: 12.25.1 - name: Set up Node.js uses: actions/setup-node@v7 @@ -96,7 +96,7 @@ jobs: - name: Set up pnpm uses: pnpm/action-setup@v6 with: - version: 12.21.0 + version: 12.25.1 - name: Set up Node.js ${{ matrix.node }} uses: actions/setup-node@v7 @@ -115,3 +115,11 @@ jobs: - name: Test run: pnpm test + + # `pnpm test` runs the TypeScript sources through vitest, so nothing above + # proves that the emitted `dist/` actually boots. Start it and probe /health. + - name: Smoke the built output + run: pnpm smoke:dist + + - name: Audit the production dependencies + run: pnpm audit --prod diff --git a/AGENTS.md b/AGENTS.md index 3953836..1c9aef7 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -73,8 +73,9 @@ These were verified against `opencode serve` 2.3.2; re-read `http(s)` URLs are rejected, so remote media must be fetched and inlined. * `/api/event` is a single global SSE stream; frames are `data: {json}` with the discriminator **inside** the JSON (`type`), plus `: heartbeat` comments. The - stream is volatile — handle reconnects by reconciling from - `GET /api/session/{id}/message`. + stream is volatile. A mid-turn reconnect is **not** reconciled from + `GET /api/session/{id}/message`: `runCompletion` keeps a 5 s grace window for + the terminal event and otherwise fails the turn with `503 event_stream_lost`. * `time.released` is in **milliseconds**; OpenAI's `created` is in seconds. * The free tier answers `429 provider.free-limit` with `retryAfterMs`. A live test failing with 429 is an environment problem, not a code defect — do not "fix" diff --git a/README.md b/README.md index da19f2d..543bc2e 100644 --- a/README.md +++ b/README.md @@ -49,7 +49,10 @@ Both print the resulting key; edit `.env` directly to set a specific value. Run `pnpm setup -- --random --force` to rotate an existing custom key. With no `.env` at all the gateway still starts and logs a warning that the default -key is in use. `OPENCODE_ALLOW_NO_AUTH=true` disables authentication entirely on a +key is in use. The same warning is logged when `.env` lists the published key +explicitly, which is what `.env.example` and `pnpm setup` do — `GET /admin/config` +reports `auth.usingDefaultApiKey: true` in both cases. +`OPENCODE_ALLOW_NO_AUTH=true` disables authentication entirely on a trusted loopback host. Health check: @@ -403,9 +406,13 @@ Limitations, stated plainly: `patch`, `task`, `skill`) for that session, so the model cannot "answer" your request by running its own shell or web tools instead of emitting a bridged call. This is controlled by `OPENCODE_TOOL_BRIDGE_DENY_NATIVE_TOOLS` (default - `true`); the deny rules are merged on top of `OPENCODE_AGENT_PERMISSIONS`. + `true`); the deny rules are merged on top of `OPENCODE_AGENT_PERMISSIONS`. The + rules apply whenever `tools` is non-empty — even with `tool_choice: "none"`, + which disables the bridge instructions but never the containment. * `tool_choice: "none"` disables the bridge; `"required"` and a named tool are - rendered as instructions, not as a hard guarantee. + rendered as instructions, not as a hard guarantee. A `tool_choice` that requires + a tool while `tools` is absent or empty is rejected with + `400 invalid_request` (`param: "tool_choice"`). * **Native** OpenCode tool activity (the `build` agent reading files, running commands) is *not* part of the OpenAI or Anthropic contract. It is reported as the non-standard `x_opencode.native_tool_calls` field of the final payload (an @@ -509,9 +516,12 @@ Every variable, with types, defaults and security notes: hashed and compared, so reuse can never change semantics: on any mismatch the gateway starts a fresh session and replays. The cache holds `OPENCODE_SESSION_MAX` entries for `OPENCODE_SESSION_TTL_MS` and is keyed by - model + agent + variant + tool-set hash + conversation root. Pass + model + agent + variant + tool-set hash + permission profile + conversation + root. Pass `x-conversation-id` to control the key explicitly, or set - `OPENCODE_SESSION_CACHE=false` for fully stateless routing. + `OPENCODE_SESSION_CACHE=false` for fully stateless routing. An explicit key is + still only reused while the message prefix, the model, the agent, the variant, + the tool set and the permission profile match. * **Free-tier rate limits.** The bundled free models are limited per model and per window upstream. The gateway answers `429` with a `retry-after` header in seconds and repeats the upstream message; back off for that long. A stream diff --git a/docs/API.md b/docs/API.md index 703ce9e..1ea6232 100644 --- a/docs/API.md +++ b/docs/API.md @@ -21,8 +21,8 @@ operational; it is summarised at the end of this document and in the README. | Name | Kind | Meaning | | --- | --- | --- | -| `x_opencode` | response field | Non-standard object attached to the buffered completion payload of every surface and to the terminal response object of the OpenAI SSE streams: `session_id`, `agent`, `variant`, `reused_session`, and `native_tool_calls` (an array on the OpenAI surfaces, a count on the Anthropic surface) plus `reasoning: {enabled, note}` on `/v1/chat/completions`. The Anthropic **streamed** sequence does not carry it (Anthropic's event schema has no place for extra message fields); use `stream: false` when you need it. | -| `x-conversation-id` | request header | Explicit sticky-session key. Requests carrying the same value reuse the same upstream OpenCode session while their message prefix still matches. | +| `x_opencode` | 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.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 `/v1/chat/completions`. The `/v1/chat/completions`, `/v1/completions` and Anthropic **streamed** sequences do not carry it (their event schemas have no place for extra message fields); use `stream: false`, or the Responses stream, when you need it. | +| `x-conversation-id` | request header | Explicit sticky-session key. Requests carrying the same value reuse the same upstream OpenCode session only while the model, agent, variant, tool set, permission profile and message prefix all still match. | | `x-opencode-agent` | request header | Run this request with a specific OpenCode agent instead of `OPENCODE_AGENT`. | | `x-request-id` | request/response header | Caller-supplied correlation id, echoed on every response (JSON and SSE). Accepted when it matches `[A-Za-z0-9._:-]{1,128}`; anything else is replaced by a generated id. The same value is used as the request id in the gateway logs. | | `reasoning_effort` | request field | Non-standard on `/v1/messages`: an OpenAI-style alias for `thinking`. Ignored when `thinking` is present. | @@ -38,9 +38,12 @@ when `OPENCODE_METRICS_PUBLIC=true`). > **Reading this reference.** Request fields are validated with `zod`; unknown > JSON fields are ignored, matching the permissive behaviour of the OpenAI and -> Anthropic servers. Every field listed below is one the adapters actually -> honour. A malformed body is rejected with `400 invalid_request_error` naming -> the offending field in `param`. +> Anthropic servers. Every field listed below is one the adapters accept and +> validate. Fields the adapters cannot forward to OpenCode — sampling knobs +> (`temperature`, `top_p`, `max_tokens`, `stop`), attribution fields and +> stored-response references — say so explicitly in their row, because OpenCode's +> agent loop owns the generation budget. A malformed body is rejected with +> `400 invalid_request_error` naming the offending field in `param`. ## 1. `POST /v1/chat/completions` @@ -62,14 +65,14 @@ when `OPENCODE_METRICS_PUBLIC=true`). | `stream` | boolean | `false` | Emit SSE frames instead of one JSON body. | | `stream_options.include_usage` | boolean | `false` | Append a usage-only chunk (with `choices: []`) before `[DONE]`. | | `tools` | array | *(none)* | OpenAI declarations `{type:"function",function:{name,description,parameters}}`. Bridged through the prompt. | -| `tool_choice` | `auto` \| `none` \| `required` \| `{type:"function",function:{name}}` | `auto` | Rendered into the bridge instructions. | +| `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. | | `reasoning_effort` | string | *(unset)* | `none`, `minimal`, `low`, `medium`, `high`, `xhigh`, `max` plus aliases (`off`, `min`, `maximum`, ...). | | `reasoning.effort` | string | *(unset)* | Used when `reasoning_effort` is absent. | | `max_tokens` / `max_completion_tokens` | number | *(unset)* | `max_completion_tokens` wins. Recorded, not enforced upstream: OpenCode's agent owns the generation budget. | | `temperature`, `top_p` | number | *(unset)* | Accepted and recorded, but not forwarded: OpenCode's agent loop owns the sampling parameters (same as `max_tokens`). | -| `stop` | string \| string[] | *(unset)* | Accepted. Empty strings are dropped. | +| `stop` | string \| string[] | *(unset)* | Accepted and recorded; empty strings are dropped. **Not enforced upstream**: generation is not truncated, so the delimiter can appear in the answer 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. `metadata` is carried on the internal request for logging. | +| `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. | | `parallel_tool_calls` | boolean | `true` | `false` makes the tool bridge ask the model for at most one bridged tool call per turn; `true`/absent allows several. | | `response_format` | object | *(unset)* | `{"type":"text"}`, `{"type":"json_object"}` or `{"type":"json_schema","json_schema":{name,schema}}`. OpenCode cannot receive an output schema, so the requirement is rendered into the prompt (see "JSON output mode" below); it is a model contract, not a server-enforced one. | | `seed`, `logprobs`, `logit_bias`, `presence_penalty`, `frequency_penalty` | — | — | Accepted and deliberately ignored. | @@ -118,11 +121,14 @@ when `OPENCODE_METRICS_PUBLIC=true`). With `OPENCODE_REASONING_FIELD=both` an identical `reasoning` field is emitted alongside it (read from `Config.reasoningField`, so two gateways in one process cannot share the setting). -* `finish_reason` is `stop`, `length`, `tool_calls` or `content_filter`; the - internal `error`/`cancelled` reasons are reported as `stop`. +* `finish_reason` is `stop`, `length`, `tool_calls` or `content_filter`. A turn + the upstream ended with `error` is a failure, not a completion: the buffered + form answers `502 api_error` / `upstream_error`, and the streamed form ends + with the error frame below instead of a finish chunk or `[DONE]`. Only + `cancelled` (client disconnect) is reported as `stop`. * `x_opencode.native_tool_calls` lists native OpenCode tool activity as - `{id, name, status, input?, error?}` with `status` in `started`, `called`, - `succeeded`, `failed`. + `{id, name, status, input?, error?}` with `status` in `started`, `input`, + `called`, `succeeded`, `failed`. ### Streaming (`stream: true`) @@ -173,10 +179,14 @@ data: {"type":"opencode.tool_call","activity":{"id":"toolu_01J...","name":"read" The stream head is written lazily. A failure raised before the first frame is reported with a real HTTP status; after that the status is already `200`, so -errors must be read from the final frame: +errors must be read from the final frame. A turn the upstream ends with `error` +is such a failure — the stream closes with the error frame below +(`code: "upstream_error"`, `message: "The upstream completion ended with an +error."`) and emits neither a finish chunk nor `[DONE]`: ``` data: {"error":{"message":"OpenCode did not finish the request in time.","type":"api_error","code":"timeout_error","param":null}} +data: {"error":{"message":"The upstream completion ended with an error.","type":"api_error","code":"upstream_error","param":null}} ``` ### Errors @@ -194,7 +204,7 @@ data: {"error":{"message":"OpenCode did not finish the request in time.","type": | Status | `type` | Typical `code` | | --- | --- | --- | -| `400` | `invalid_request_error` | `invalid_request`, `model_disabled`, `unsupported_modality`, `unsupported_file_reference`, `invalid_attachment`, `attachment_too_large`, `attachment_download_failed`, `local_files_disabled`, `attachment_not_found`, `attachment_path_forbidden`, `remote_media_disabled`, `private_media_blocked` | +| `400` | `invalid_request_error` | `invalid_request` (including a `tool_choice` that requires a tool but declares none), `model_disabled`, `unsupported_modality`, `unsupported_file_reference`, `invalid_attachment`, `attachment_too_large`, `attachment_download_failed`, `local_files_disabled`, `attachment_not_found`, `attachment_path_forbidden`, `remote_media_disabled`, `private_media_blocked` | | `401` | `invalid_request_error` | `authentication_error` | | `403` | `invalid_request_error` | `permission_error` | | `404` | `invalid_request_error` | `model_not_found` | @@ -202,7 +212,7 @@ data: {"error":{"message":"OpenCode did not finish the request in time.","type": | `499` | — | client disconnected before the response started | | `501` | `invalid_request_error` | `not_implemented_error` | | `502` | `api_error` | `upstream_error`, `upstream_unauthorized`, `upstream_invalid_json` | -| `503` | `api_error` | `overloaded_error`, `upstream_unavailable`, `upstream_unreachable`, `event_stream_unavailable` | +| `503` | `api_error` | `overloaded_error`, `upstream_unavailable`, `upstream_unreachable`, `event_stream_unavailable`, `event_stream_lost` (a mid-turn event-stream reconnect; the answer would have been incomplete) | | `504` | `api_error` | `timeout_error`, `upstream_timeout` | | `500` | `api_error` | `internal_error` — an unexpected gateway failure; the message never contains credentials | @@ -235,14 +245,14 @@ reasoning mapping and tool bridging with the chat endpoint. | Field | Type | Default | Notes | | --- | --- | --- | --- | | `model` | string | — | Required. Same naming rules as chat. | -| `input` | string \| array | — | Required. A plain string, or items: `message` (`{role, content}`, `type` optional), `function_call`, `function_call_output`, `item_reference`. Roles: `user`, `assistant`, `system`, `developer`. | +| `input` | string \| array | — | Required. A plain string, or 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. | | `stream` | boolean | `false` | Emit the typed SSE sequence. | | `tools` | array | *(none)* | Flat function tools `{type:"function",name,description,parameters}`. | -| `tool_choice` | `auto` \| `none` \| `required` \| `{type:"function",name}` | `auto` | Bridged into the prompt; echoed back as `auto`, `none`, `required` or `function:`. | +| `tool_choice` | `auto` \| `none` \| `required` \| `{type:"function",name}` | `auto` | Bridged into the prompt; echoed back as `auto`, `none`, `required` or `function:`. `400 invalid_request` (`param: "tool_choice"`) when it requires a tool but `tools` is absent or empty. | | `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"`. | +| `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. | | `parallel_tool_calls` | boolean | `true` | Echoed; `false` makes the tool bridge ask for at most one bridged tool call per turn. | | `previous_response_id` | string | *(unset)* | Accepted and ignored — the gateway keeps no response store, so callers must resend the full `input`. Echoed as `null`. | | `store` | boolean | `false` | Accepted and ignored; nothing is persisted. Echoed as given. | @@ -250,7 +260,10 @@ reasoning mapping and tool bridging with the chat endpoint. | `include`, `service_tier`, `top_logprobs`, `user` | — | — | Accepted for compatibility; no effect. | `item_reference` items are skipped (they point at stored responses the gateway -does not keep). `function_call` items become assistant tool calls; +does not keep). `reasoning` items are accepted and ignored: a caller may resend a +previous response's `output` verbatim, but provider-side thinking state cannot be +replayed (same policy as `thinking`/`redacted_thinking` on `/v1/messages`). +`function_call` items become assistant tool calls; `function_call_output` items become `role: "tool"` turns. An `input_file` part accepts `file_data`/`file_url`; a reference carrying only `file_id` is rejected with `400 unsupported_file_reference` instead of being silently dropped. @@ -366,8 +379,10 @@ event: response.completed data: {"type":"response.completed","sequence_number":8,"response":{"id":"resp_...","object":"response","status":"completed","model":"opencode/deepseek-v4.1-flash-free","output":[...],"output_text":"Hello! How can I help?","usage":{"input_tokens":12,"output_tokens":9,"total_tokens":21,"input_tokens_details":{"cached_tokens":0},"output_tokens_details":{"reasoning_tokens":6}},"x_opencode":{...}}} ``` -* `response.created` and `response.in_progress` are always the first two frames, - even before the upstream turn has been assigned a session. +* `response.created` and `response.in_progress` are the first two frames of a + stream that starts at all. A failure known before the first event (for example + an unavailable upstream event stream) is reported with a real HTTP status and a + JSON error body, so no frame is written. * Reasoning deltas use `response.reasoning_summary_part.added`, `response.reasoning_summary_text.delta`, `response.reasoning_summary_text.done` and `response.reasoning_summary_part.done`; the closing item then appears as @@ -472,8 +487,10 @@ data: [DONE] `finish_reason` is `stop`, `length` or `content_filter`; reasoning, tool calls and native tool activity have no representation in this legacy wire format and are -not streamed. Errors use the same OpenAI error shape and status table as -`/v1/chat/completions`. +not streamed. A turn the upstream ended with `error` answers `502 upstream_error` +(buffered) or closes the stream with the error frame and neither a finish chunk +nor `[DONE]` (streamed). Errors use the same OpenAI error shape and status table +as `/v1/chat/completions`. ### curl @@ -500,16 +517,17 @@ Anthropic Messages API. | `audio` block (extension) | `{source:{type:"base64",media_type,data}}` | — | Non-standard; base64 sources only. | | `video` block (extension) | `{source}` | — | Non-standard; base64 or url sources. | | `tool_use` block | `{id,name,input}` | — | Assistant messages only; `input` is serialised to the argument string. | -| `tool_result` block | `{tool_use_id, content?, is_error?}` | — | User messages only. `content` is a string or `text`/`image`/`document` blocks (non-text blocks are noted as omitted). | +| `tool_result` block | `{tool_use_id, content?, is_error?}` | — | User messages only. `content` is a string or `text`/`image`/`document` blocks. Inline-text documents are folded into the tool text; `image`/`document` bytes are resolved like any other media and attached to the enclosing user turn, leaving a `[image: ]` / `[document: ]` marker in the tool text. `is_error: true` prefixes the tool text with `[tool error]`. | | `thinking` / `redacted_thinking` blocks | — | — | Accepted for multi-turn replay compatibility and ignored: the gateway cannot store provider-side thinking state. | | `max_tokens` | number ≥ 1 | — | Required by the Anthropic schema and validated; recorded but not enforced upstream (the OpenCode agent owns the generation budget), so a reply can exceed it. | +| `stop_sequences` | array of string | *(none)* | Honoured on this surface, on both paths: the visible text is truncated at the first match, `stop_reason` becomes `stop_sequence` and `stop_sequence` names the matched entry. Empty strings are dropped. Only assistant text is matched — never `thinking` output or tool arguments. Generation upstream is **not** interrupted, so `usage.output_tokens` still counts the whole turn and the sticky session is not disturbed. | | `system` | string \| array | *(unset)* | Array form accepts `{type:"text",text}` blocks. Joined with blank lines. | | `stream` | boolean | `false` | Emit the Anthropic SSE sequence. | | `thinking` | object | *(unset)* | `{type:"enabled",budget_tokens}` or `{type:"disabled"}`. (The adapter validates `budget_tokens`; use the top-level `reasoning_effort` for a named effort.) | | `reasoning_effort` | string | *(unset)* | Extension: OpenAI-style alias for `thinking`. Ignored when `thinking` is present. | | `tools` | array | *(none)* | `{name,description,input_schema}`. Bridged through the prompt. | -| `tool_choice` | `{type:"auto"}` \| `{type:"any"}` \| `{type:"none"}` \| `{type:"tool",name}` | auto | `any` maps to a required call, `tool` to a named call. | -| `temperature`, `top_p`, `stop_sequences`, `metadata.user_id` | — | *(unset)* | Accepted and recorded; `temperature`/`top_p`/`stop_sequences` are not forwarded to the provider (the OpenCode agent owns sampling), and `metadata` is carried for logging. | +| `tool_choice` | `{type:"auto"}` \| `{type:"any"}` \| `{type:"none"}` \| `{type:"tool",name}` | auto | `any` maps to a required call, `tool` to a named call. `400 invalid_request` (`param: "tool_choice"`) when it requires a tool but `tools` is absent or empty. | +| `temperature`, `top_p`, `metadata.user_id` | — | *(unset)* | Accepted and recorded; not forwarded to the provider (the OpenCode agent owns sampling), and `metadata` is **not** logged. | | `top_k`, `service_tier`, `container`, `mcp_servers` | — | — | Accepted and ignored. | | `cache_control` | object | — | Accepted on text/image/document/tool blocks and ignored. | @@ -544,10 +562,13 @@ Anthropic Messages API. ``` * `stop_reason` in the final payload is `end_turn`, `max_tokens` (length limit), - `tool_use` (tool calls were offered and produced) or `refusal` (content filter); - `message_start` carries `null` because the turn has not finished yet. A matched - `stop_sequences` entry cannot be detected upstream, so `stop_sequence` is always - `null`. + `tool_use` (tool calls were offered and produced), `refusal` (content filter) or + `stop_sequence` (a `stop_sequences` entry matched); `message_start` carries + `null` because the turn has not finished yet. `stop_sequence` names the matched + entry, otherwise it is `null`. The identical filter runs on both paths, so the + buffered and streamed text agree. Generation upstream is not stopped, so + `usage.output_tokens` still reports every token the turn produced, which can + exceed the visible (truncated) text. * A `thinking` block is emitted only when reasoning was requested and surfaced. Its `signature` is `base64("opencode-api:")` — a deterministic placeholder, not a cryptographic attestation. @@ -564,7 +585,7 @@ event: message_start data: {"type":"message_start","message":{"id":"msg_...","type":"message","role":"assistant","model":"opencode/deepseek-v4.1-flash-free","content":[],"stop_reason":null,"stop_sequence":null,"usage":{"input_tokens":0,"output_tokens":0}}} event: content_block_start -data: {"type":"content_block_start","index":0,"content_block":{"type":"thinking","thinking":""}} +data: {"type":"content_block_start","index":0,"content_block":{"type":"thinking","thinking":"","signature":""}} event: content_block_delta data: {"type":"content_block_delta","index":0,"delta":{"type":"thinking_delta","thinking":"The user greeted me."}} @@ -604,8 +625,9 @@ event: content_block_stop data: {"type":"content_block_stop","index":2} ``` -Anthropic always carries a text block, so a tool-only turn streams an empty text -block (`content_block_start` + `content_block_stop`) before the tool block. +A tool-only turn has no text block on either path: the `tool_use` block opens at +index 0, or index 1 when a `thinking` block precedes it. No empty text block is +emitted, and a turn that produced nothing streams no content block at all. Errors after the stream starts are delivered as an `error` event, and a failure raised before the first frame is reported with a real HTTP status: @@ -636,7 +658,7 @@ Anthropic shape, selected by the request path (`/v1/messages*`): | `404` | `not_found_error` | | `429` | `rate_limit_error` (with `retry-after` header; mid-stream the hint travels as `retry_after_ms` in the error frame) | | `502` | `api_error` | -| `503` | `overloaded_error` | +| `503` | `overloaded_error` (including `event_stream_lost`, a mid-turn event-stream reconnect: the message says the answer may be incomplete) | | `504` | `timeout_error` | ### curl @@ -664,12 +686,13 @@ is still resolved, so an unknown model returns `404`. ```json { "input_tokens": 42, - "x_opencode": { "estimated": true, "method": "chars/4" } + "x_opencode": { "estimated": true, "method": "mixed" } } ``` The number is an **approximation**: OpenCode exposes no tokenizer endpoint, so -the gateway estimates `characters / 4` over every message, the system prompt, the +the gateway estimates one token per CJK character and `characters / 4` for the +rest over every message, the system prompt, the tool-bridge instructions that will be prepended to the real prompt, and the tool JSON schemas, plus a small per-message overhead, and never reports less than `1`. Media blocks are not downloaded for this endpoint; they contribute a short diff --git a/docs/ARCHITECTURE.md b/docs/ARCHITECTURE.md index abd2425..58644c2 100644 --- a/docs/ARCHITECTURE.md +++ b/docs/ARCHITECTURE.md @@ -105,7 +105,8 @@ server normalises attachments to `{data, mime, source}` internally. with no agent prompt and no tools (≈100 input tokens) but it does not stream, has no multi-turn memory and accepts no attachments. `OpencodeClient.generate()` wraps it as an escape hatch, but the gateway does not use it on any request path: -`count_tokens` returns a documented `chars / 4` estimate instead, because a real +`count_tokens` returns the mixed estimate documented in `docs/API.md` §5 (one +token per CJK character, `characters / 4` for the rest) instead, because a real count would cost a provider round trip per call. ### 2.4 Event stream @@ -138,7 +139,12 @@ Event types the gateway consumes: The stream is documented as volatile: a slow consumer overflows and fails it, and events during a disconnect are lost. `EventHub` reconnects with backoff and -notifies subscribers so in-flight completions can reconcile. A half-open socket +notifies subscribers through `onReconnect`. In-flight completions do **not** +reconcile from `GET /api/session/{id}/message`: `runCompletion` records the gap, +keeps consuming for a 5 s grace window (bounded by the remaining request budget) +so a terminal event that arrives in time still completes the turn, and otherwise +interrupts the session and fails the turn with `503 event_stream_lost` instead of +returning a silently truncated answer. A half-open socket never rejects `read()`, so every read is bounded by an idle watchdog (three documented heartbeats, overridable through `EventHubOptions.idleTimeoutMs` in tests); expiry fails the connection so the loop reconnects. `stop()` and every @@ -195,6 +201,10 @@ 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.stop`, `maxTokens`, `temperature` and `topP` were write-only for +a while. `stop` is now consumed by the Anthropic surface (see §6); the other three +stay recorded-but-not-forwarded, and every reference doc says so per surface. + ### 4.2 `src/errors.ts` (frozen) ```ts @@ -212,7 +222,7 @@ toApiError(value, fallbackMessage?): ApiError ### 4.3 `src/upstream/*` (frozen) ```ts -class UpstreamProcess { resolve(): Promise; status(); invalidate(reason); stop(); markStale(reason) } +class UpstreamProcess { resolve(): Promise; status(); invalidate(reason); stop(); shutdown(); markStale(reason) } class OpencodeClient { request(path, options): Promise; listModels(); listProviders(); listAgents(); createSession(payload); getSession(id); getMessages(id); prompt(id, text, files); interrupt(id); deleteSession(id); generate(id, prompt, opts); ping() } @@ -225,8 +235,15 @@ class SessionStore { acquire(input): AcquireResult; commit(key, sessionId, in runCompletion(request, deps, options?): AsyncGenerator collectCompletion(request, deps, options?): Promise hashTools(tools): string +BRIDGE_DENIED_ACTIONS: readonly string[] ``` +The session identity covers the model, agent, variant, tool-set hash and +permission profile: `AcquireInput.permissionProfile` and `SessionRecord.toolsHash` +are part of `deriveKey` and are compared when a candidate is reused, so a cached +session is never handed to a request that needs a different set of native-tool +permissions — even through an explicit `x-conversation-id`. + `markStale(reason)` always drops the cached endpoint; when it was a spawned child it also kills and forgets the process, so the next `resolve()` spawns a replacement instead of retrying a dead URL. Catalogue calls (`listModels`, @@ -236,6 +253,20 @@ replacement instead of retrying a dead URL. Catalogue calls (`listModels`, candidates while keeping the conversation key, so a stale-session replay caches its replacement where the next turn of that conversation will find it. +`stop()` is deliberately **non-terminal**: `POST /admin/upstream/restart` and the +retry paths call `stop()`/`invalidate()` and then `resolve()` again, and +`test/process.test.ts` pins that. `shutdown()` is the terminal variant, used only +by the process-exit path (`src/http/shutdown.ts`): it awaits an in-flight start, +SIGKILLs every child that never reached `#child`, and makes any later `resolve()` +reject with `503 upstream_unavailable`. + +`/sessions.json` is an envelope `{ version, fingerprint, records }` where +`fingerprint` is `Config.instanceId`. A `ses_*` id only exists inside the upstream +process that created it, so on load the store ignores records written by another +gateway instance instead of replaying prompts against a dead session id. Because +the default instance id contains the pid, an unpinned `OPENCODE_INSTANCE_ID` +means a restart starts with an empty persisted cache. + ### 4.4 `src/adapter/common/*` (frozen) ```ts @@ -251,6 +282,10 @@ parseAssistantText(text): {text, calls}, parseToolCallBody(body): ToolCall[], normaliseArguments(args): string, renderTranscript(messages): string, renderToolResult(message): string, class ToolCallFilter +// `createToolBridge` throws `ApiError.badRequest(..., { code: "invalid_request", +// param: "tool_choice" })` when the choice requires a tool call but `tools` is +// absent or empty, so the check runs once for every surface. + // usage.ts EMPTY_USAGE, toUsage(tokens), addUsage(a, b), estimateTokens(text), estimateConversationTokens(parts) ``` @@ -261,13 +296,24 @@ EMPTY_USAGE, toUsage(tokens), addUsage(a, b), estimateTokens(text), estimateConv // resolve.ts export interface MediaSource { url?: string; dataUri?: string; base64?: string; mime?: string; path?: string; name?: string; } -export function resolveAttachment(source: MediaSource, config: Config, opts?: { signal?: AbortSignal }): - Promise; -export function kindFromMime(mime: string): AttachmentKind; -export function sniffMime(buffer: Buffer, fallback?: string): string; +export interface MediaBudgetLimits { maxCount: number; maxBytes: number } +export interface MediaBudget extends MediaBudgetLimits { + usedCount: number; usedBytes: number; claimSlot(): boolean; releaseSlot(): void; admit(bytes: number): boolean; +} +export function createMediaBudget(limits: MediaBudgetLimits): MediaBudget; +export class AttachmentOmittedError extends ApiError { reason: "count" | "bytes" } +export function resolveAttachment(source: MediaSource, config: Config, + opts?: { field?: string; signal?: AbortSignal; budget?: MediaBudget }): Promise; +export function resolveAttachments(sources: readonly MediaSource[], config: Config, + opts?: { field?: string; signal?: AbortSignal; budget?: MediaBudget; concurrency?: number; + onOmit?: (omission: OmittedAttachment) => void } +): Promise<{ attachments: Attachment[]; omitted: OmittedAttachment[] }>; +export function formatOmissionNote(omitted: readonly OmittedAttachment[], limits: MediaBudgetLimits): string; export function buildDataUri(attachment: Pick): string; // mime.ts +export function kindFromMime(mime: string): AttachmentKind; +export function sniffMime(buffer: Buffer, fallback?: string): string; export function isImage(mime: string): boolean; export function isAudio(mime: string): boolean; export function isVideo(mime: string): boolean; @@ -286,6 +332,31 @@ download is dialled with `node:http`/`node:https` and a `lookup` callback pinned to the validated address, so the guard and the connection cannot disagree (DNS rebinding); redirects are followed manually with per-hop re-validation. +A local file is read through **one** handle: `realpath` → roots check → +`fsp.open` with `O_NOFOLLOW` where the platform has it → `fstat` → `read`, so the +bytes cannot come from a path that was swapped after the check. `ENOENT`/`ENOTDIR` +map to 400 `attachment_not_found` and `EACCES`/`EPERM`/`ELOOP`/`EISDIR`/`EBUSY` +to 400 `invalid_attachment`; hard links inside a root, a swapped parent directory +and Windows reparse points remain outside the guarantee. + +Attachment caps are enforced **before** anything is fetched. Each request creates +one `MediaBudget` (from `config.maxAttachments` and `config.maxAttachmentBytes`) +and every adapter resolves its media against it: the count slot is claimed +synchronously, so a burst of blocks cannot all take the last slot, and a source +the budget cannot fit is reported through `OmittedAttachment` / +`formatOmissionNote` instead of being downloaded. Downloads run in a bounded pool +(4 by default, 8 maximum) and the first hard failure aborts the request-level +controller, which is also chained to the caller's disconnect signal — without +that, a rejected `Promise.all` left its siblings running to +`config.mediaFetchTimeoutMs`. The bounds are the same ones the prompt builder +applies later, so a request inside the caps behaves byte-identically. + +Tool-result media: `tool_result.content` `image`/`document` blocks are resolved +through the same `resolveMediaBlock` path and attached to the enclosing **user** +turn, because `collectAttachments` forwards user-turn attachments only. The tool +message keeps a `[: ]` marker; `is_error: true` adds a `[tool error]` +prefix. + ### 4.6 Surface adapters Each module exports exactly one registration function and owns its whole file. @@ -326,8 +397,12 @@ Shared helpers each adapter may use: right shape — Anthropic shape for `/v1/messages*`, OpenAI shape otherwise) * `resolveAttachment` from `src/media/resolve.ts` * `shutdown(deps, app, drainMs?)` from `src/http/shutdown.ts` — bounded drain used - by the SIGINT/SIGTERM handler (`forceCloseConnections: true` on the Fastify - instance is the first line of defence) + by the SIGINT/SIGTERM handler. The Fastify instance is built with + `forceCloseConnections: "idle"`: idle keep-alive sockets are closed at once, + in-flight requests keep running until the deadline, and only then does the + helper call `server.closeAllConnections()` — including any hijacked SSE socket. + The upstream hook is `deps.upstream.shutdown?.() ?? deps.upstream.stop()`, so + the process-exit path is terminal while the admin restart route keeps `stop()`. **Never import `runCompletion` directly.** Always go through `ctx.completion`, so tests can substitute a scripted runner (`test/helpers/context.ts`). @@ -365,13 +440,23 @@ tests can substitute a scripted runner (`test/helpers/context.ts`). 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. +* 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 + `stop_sequence` names the entry. Generation is not interrupted, so a sticky + session shared with concurrent work is untouched and `usage` still counts the + full upstream turn; a client that replays the truncated answer sends a different + prefix and therefore gets a fresh session. * When a request declares client `tools`, the created session is given `deny` permission rules for OpenCode's built-in actions (`bash`, `webfetch`, `websearch`, `edit`, `write`, `patch`, `task`, `skill`), merged on top of `OPENCODE_AGENT_PERMISSIONS`. Verified live: without the rules the agent loops through its own tools and never emits a bridged call; with them the model answers with the tool-call envelope. Controlled by - `OPENCODE_TOOL_BRIDGE_DENY_NATIVE_TOOLS` (default `true`). + `OPENCODE_TOOL_BRIDGE_DENY_NATIVE_TOOLS` (default `true`). The rules are applied + whenever `tools` is non-empty — **including `tool_choice: "none"`**, which only + disables the bridge instructions, never the containment. A request that declares + no tools keeps the unrestricted agent. * Bridged tool calls always set `finish_reason: "tool_calls"` / `stop_reason: "tool_use"`, even when the upstream turn finished with `stop`, because the envelope is plain assistant text. diff --git a/docs/CONFIGURATION.md b/docs/CONFIGURATION.md index 7d5089b..6db3d40 100644 --- a/docs/CONFIGURATION.md +++ b/docs/CONFIGURATION.md @@ -25,13 +25,13 @@ variable. (Discovery and the spawned CLI read the variables listed in | `PORT` | integer 1–65535 | `20123` | TCP port to listen on. | — | | `OPENCODE_MAX_BODY_BYTES` | integer ≥ 1024 | `67108864` (64 MiB) | Maximum request body size. | Raising it widens the memory-exhaustion surface; base64 media inflates bodies by ~33%. | | `OPENCODE_TRUST_PROXY` | boolean | `false` | Trust `x-forwarded-*` headers for the client address. | Enable only when a proxy you control terminates the connection; otherwise clients can spoof their address in logs and metrics. | -| `OPENCODE_CORS_ORIGINS` | CSV list | *(empty)* | Allowed browser origins; `*` allows all. | `*` lets any web page call the gateway with a user's key. Prefer an explicit list. | +| `OPENCODE_CORS_ORIGINS` | CSV list | *(empty)* | Allowed browser origins; `*` allows all. An allowed origin receives `access-control-allow-headers` covering this gateway's headers plus the ones the official OpenAI and Anthropic SDKs send (`openai-organization`, `openai-project`, `x-stainless-*`, `anthropic-dangerous-direct-browser-access`), and `access-control-expose-headers: x-request-id`. | `*` lets any web page call the gateway with a user's key. Prefer an explicit list. | ## Authentication | Variable | Type | Default | Description | Security implication | | --- | --- | --- | --- | --- | -| `OPENCODE_API_KEYS` | CSV list | `sk-dummy-123` | Keys accepted from callers. When unset, the built-in development key `sk-dummy-123` is used and a warning is logged at startup. When set but empty (`OPENCODE_API_KEYS=","`) the gateway refuses to start instead of silently accepting the public default. | The default key is public knowledge (it ships in `.env.example` and the README). Set your own secret before exposing the port; rotate by listing old and new keys together. | +| `OPENCODE_API_KEYS` | CSV list | `sk-dummy-123` | Keys accepted from callers. When unset, the built-in development key `sk-dummy-123` is used. When the published key is among the accepted keys — either because nothing was configured or because it is listed explicitly, as `.env.example` ships it — a warning is logged at startup and `GET /admin/config` reports `auth.usingDefaultApiKey: true`. When set but empty (`OPENCODE_API_KEYS=","`) the gateway refuses to start instead of silently accepting the public default. | The default key is public knowledge (it ships in `.env.example` and the README). Set your own secret before exposing the port; rotate by listing old and new keys together. | | `OPENCODE_API_KEY` | string | *(unset)* | Single-key alias appended to `OPENCODE_API_KEYS`. | Same as above; convenient for local use only. | | `OPENCODE_ALLOW_NO_AUTH` | boolean | `false` | Accept every caller, ignoring keys. | Full unauthenticated access to every model and to the OpenCode agent. Use only on a trusted loopback host. | | `OPENCODE_METRICS_PUBLIC` | boolean | `false` | Exempt `GET /metrics` from authentication. | Metrics expose model names, route traffic and token volumes. | @@ -76,7 +76,7 @@ existing custom key. | `OPENCODE_SESSION_CACHE` | boolean | `true` | Reuse the OpenCode session that already holds the conversation prefix. | Reuse is strictly prefix-checked; a mismatch replays the conversation on a fresh session. Disable for fully stateless routing. | | `OPENCODE_SESSION_TTL_MS` | integer ≥ 1000 | `1800000` (30 min) | Idle lifetime of a cached session. | Longer lifetimes keep session state in memory longer. | | `OPENCODE_SESSION_MAX` | integer ≥ 1 | `500` | Maximum cached sessions (least recently used are evicted). | — | -| `OPENCODE_SESSION_PERSIST` | boolean | `false` | Persist the session cache to `/sessions.json`. | The file records session ids and message prefixes; keep the data directory private. | +| `OPENCODE_SESSION_PERSIST` | boolean | `false` | Persist the session cache to `/sessions.json`. | The file records session ids, message prefixes and the `OPENCODE_INSTANCE_ID` of the writer. A `ses_*` id is only valid inside the upstream server that created it, so a file written by another instance is ignored on load; because the default instance id contains the gateway pid, a restart starts with an empty cache. Pin `OPENCODE_INSTANCE_ID` to keep the cache across restarts — only correct for a long-lived upstream (`OPENCODE_SERVER_URL`). Keep the data directory private. | | `OPENCODE_MODEL_CACHE_TTL_MS` | integer ≥ 1000 | `300000` (5 min) | Model catalog cache lifetime. | — | | `OPENCODE_MODEL_ALIASES` | JSON object | *(unset)* | Alias map applied before resolution, e.g. `{"gpt-4o":"opencode/big-pickle"}`. | Aliases can silently redirect a familiar name to another provider model. Must be a JSON object of string values or the gateway refuses to start. | @@ -84,12 +84,12 @@ existing custom key. | Variable | Type | Default | Description | Security implication | | --- | --- | --- | --- | --- | -| `OPENCODE_ALLOW_LOCAL_FILES` | boolean | `false` | Allow attachments addressed by local file path. | Reading local files on behalf of a remote caller is a file-disclosure primitive. Keep it off unless callers are trusted. | -| `OPENCODE_ALLOWED_FILE_ROOTS` | CSV list of paths | `OPENCODE_WORKDIR` | Roots a local path must resolve inside (after `realpath`). | Widen this only to directories that are safe to read. | +| `OPENCODE_ALLOW_LOCAL_FILES` | boolean | `false` | Allow attachments addressed by local file path. The file is read through one `O_NOFOLLOW` handle after the roots check, and an unreadable file answers 400 `invalid_attachment`. | Reading local files on behalf of a remote caller is a file-disclosure primitive. Keep it off unless callers are trusted, and make sure the allowed roots contain no untrusted writers (hard links inside a root and a swapped parent directory are not closed by `realpath`). | +| `OPENCODE_ALLOWED_FILE_ROOTS` | CSV list of paths | `OPENCODE_WORKDIR` | Roots a local path must resolve inside (after `realpath`). The read itself uses one `O_NOFOLLOW` handle, but hard links inside a root and a swapped parent directory are not closed. | Widen this only to directories that are safe to read, with no untrusted writers. | | `OPENCODE_ALLOW_REMOTE_MEDIA_URLS` | boolean | `true` | Fetch `http(s)://` media server-side and inline it as a data URI. | The gateway performs the request, so it can reach hosts the caller cannot. | | `OPENCODE_ALLOW_PRIVATE_MEDIA_URLS` | boolean | `true` | Allow remote media on private, loopback and link-local addresses. | **Set to `false` on any multi-user deployment.** Leaving it `true` is an SSRF primitive against the host network and cloud metadata endpoints. | -| `OPENCODE_MAX_ATTACHMENT_BYTES` | integer ≥ 1 | `20971520` (20 MiB) | Maximum decoded size of one attachment and of all attachments combined in a request. | Bounds memory per request. | -| `OPENCODE_MAX_ATTACHMENTS` | integer ≥ 1 | `16` | Maximum attachments forwarded per request. | — | +| `OPENCODE_MAX_ATTACHMENT_BYTES` | integer ≥ 1 | `20971520` (20 MiB) | Maximum decoded size of one attachment and of all attachments combined in a request, enforced while media is resolved and again before it is forwarded. | Bounds memory per request. | +| `OPENCODE_MAX_ATTACHMENTS` | integer ≥ 1 | `16` | Maximum attachments resolved and forwarded per request. Media beyond the cap is never fetched, and the prompt records what was dropped. | — | | `OPENCODE_MEDIA_FETCH_TIMEOUT_MS` | integer ≥ 100 | `15000` | Timeout for one remote media download. | — | Media accept only `data:` URIs, `http(s)://` URLs and (opt-in) local paths; @@ -106,9 +106,9 @@ uploads are always inlined for OpenCode as a `data:` URI. See the README section | `OPENCODE_NATIVE_TOOL_EVENT` | string | `opencode.tool_call` | SSE event name used for native tool activity. | — | | `OPENCODE_REASONING_FIELD` | `reasoning_content` \| `both` | `reasoning_content` | `POST /v1/chat/completions` only: when `both`, the adapter emits an extra `reasoning` alias next to `reasoning_content` on messages and deltas. Read into `Config.reasoningField`. | — | | `OPENCODE_LOG_LEVEL` | string | `info` | Pino level: `fatal`, `error`, `warn`, `info`, `debug`, `trace`. | `debug`/`trace` may log prompts and upstream payloads. | -| `OPENCODE_LOG_PRETTY` | boolean | `true` when stdout is a TTY | Pretty-print logs instead of JSON lines. | — | +| `OPENCODE_LOG_PRETTY` | boolean | `true` when stdout is a TTY | Pretty-print logs instead of JSON lines. | Needs `pino-pretty`, which is a dev dependency; without it the gateway falls back to JSON instead of failing. | | `OPENCODE_METRICS_ENABLED` | boolean | `true` | Enable Prometheus collection; when false, `GET /metrics` answers `404`. | — | -| `OPENCODE_INSTANCE_ID` | string | `opencode-api-` | Identifier for this gateway instance. | — | +| `OPENCODE_INSTANCE_ID` | string | `opencode-api-` | Identifier for this gateway instance. Also the fingerprint of the persisted session cache (`OPENCODE_SESSION_PERSIST`). | Changing it invalidates the persisted session cache. | Boolean values accept `1/true/yes/on/enabled` and `0/false/no/off/disabled` (case-insensitive). Any other value falls back to the default. @@ -139,8 +139,11 @@ The gateway exits with code 1 (before it listens) when: A missing key is **not** fatal: with neither `OPENCODE_API_KEYS` nor `OPENCODE_API_KEY` set, the gateway starts with the built-in development key -`sk-dummy-123` and logs a warning. Every variable is otherwise clamped to its -documented bounds, and an unrecognised boolean/integer falls back to the default. +`sk-dummy-123` and logs a warning. The same warning is logged when the published +key is configured explicitly — including the `.env.example` default that +`pnpm setup` copies — because in that case the port is just as unprotected. +Every variable is otherwise clamped to its documented bounds, and an unrecognised +boolean/integer falls back to the default. ## Recommended hardening for a reachable deployment diff --git a/docs/VERIFICATION.md b/docs/VERIFICATION.md index 7ba474c..eb0e1ac 100644 --- a/docs/VERIFICATION.md +++ b/docs/VERIFICATION.md @@ -119,16 +119,17 @@ leak with operational impact) / **minor** (incorrect behaviour in an edge case o | **F-14** | minor | The completion event queue is unbounded and the SSE writer ignores backpressure (`raw.write()` return value discarded), so a slow client cannot throttle the producer; exposure is limited in practice by the upstream output size. | `src/upstream/completion.ts:755-786`; `src/http/sse.ts:87-93` | Code inspection (not reproduced: the free-tier quota prevents long live streams). | | **F-15** | minor | Responses `input_file` silently drops `file_id` (the OpenAI chat adapter rejects it explicitly with `unsupported_file_reference`), producing a generic “Attachment has no source” 400 and masking the real problem. | `src/adapter/openai/responses.ts:58-65,467-477` vs `src/adapter/openai/chat.ts:325-330` | Live: `input_file` with only `file_id` → `400 invalid_attachment "Attachment has no source…"`. | | **F-16** | minor | Upstream request timeouts are reported as `503 upstream_unreachable`/`upstream_error` rather than `504 timeout_error`, because the client’s abort controller is not distinguished from a client-side abort; the error table documents 504. | `src/upstream/client.ts:137-153`; `docs/API.md:196,535` | Code inspection; the abort timer rejects `fetch`, `options.signal?.aborted` is false, so the `unavailable` branch is taken. | -| **F-17** | nit | Dead/unused public surface: `SSE_HEADERS`, `bootstrapLogger`, `newRequestId`, `budgetFromEffort`, `buildDataUri`, `renderToolResult` are never referenced; `void supported;` is a dead local. (`getSession`/`getMessages`/`generate`/`ping` are unused too but are declared frozen API in `docs/ARCHITECTURE.md`.) | `src/http/sse.ts:105`; `src/logger.ts:49`; `src/upstream/process.ts:374`; `src/adapter/common/reasoning.ts:77`; `src/media/resolve.ts:78`; `src/adapter/common/tools.ts:350`; `src/upstream/completion.ts:622-633` | `grep -rn "" src/` shows only the definition. | -| **F-18** | nit | Docker reproducibility: `package.json` has no `packageManager` field while the Dockerfile relies on `corepack enable`, so the image installed pnpm **12.25.1** although this workspace uses **12.21.0**; the lockfile (`lockfileVersion: '9.0'`) still resolved, and the build succeeded. | `Dockerfile:20,24`; `package.json` | Build log: `Done in 179ms using pnpm v12.25.1`. | +| **F-17** | nit | Dead/unused public surface: `SSE_HEADERS`, `bootstrapLogger`, `newRequestId`, `budgetFromEffort`, `renderToolResult` are never referenced; `void supported;` is a dead local. `buildDataUri` was on this list and is now used by `toPromptAttachment()` in `src/upstream/completion.ts`, so it is live. (`getSession`/`getMessages`/`generate`/`ping` are unused too but are declared frozen API in `docs/ARCHITECTURE.md`.) | `src/http/sse.ts:105`; `src/logger.ts:49`; `src/upstream/process.ts:374`; `src/adapter/common/reasoning.ts:77`; `src/adapter/common/tools.ts:350`; `src/upstream/completion.ts:622-633` | `grep -rn "" src/` shows only the definition. | +| **F-18** | fixed | Docker reproducibility: `package.json` now declares `packageManager: pnpm@12.25.1`, the CI jobs install that version, and the Dockerfile's `corepack enable` derives the same one, so the image, CI and the workspace agree. | `package.json`; `Dockerfile:20,24`; `.github/workflows/ci.yml` | Resolved in the improvement pass. | | **F-19** | nit | `docker-compose.yml` sets `OPENCODE_BIN=/usr/local/bin/opencode` while the corresponding volume mount is commented out, so a default `docker compose up` starts a gateway whose every completion fails with `503 upstream_unavailable` (documented in the comments, but the default is not runnable). | `docker-compose.yml:31,42-43` | Code inspection. | | **F-20** | nit | The `created` example in `docs/API.md:627` shows a millisecond value (`1792195200000`) while the explanation at `docs/API.md:657-659` states the field is converted to seconds; the live response is `1792195200`. | `docs/API.md:627` vs `docs/API.md:657-659` | Live `GET /v1/models` shows `"created":1792195200`. | ### Not reported (checked and found correct) -* Auth: every non-public route is behind the global `preHandler`; `/health`, `/ready`, `/healthz` are the only public paths; `/metrics` is public only with `OPENCODE_METRICS_PUBLIC=true`; unknown paths return 404 through the (unauthenticated) not-found handler without exposing data; OPTIONS preflight returns 204 before auth and never touches data. +* Auth: every non-public route is behind the global `preHandler`; `/health`, `/ready`, `/healthz` are the only public paths; `/metrics` is public only with `OPENCODE_METRICS_PUBLIC=true`; unknown paths return 404 through the (unauthenticated) not-found handler without exposing data; OPTIONS preflight returns 204 before auth and never touches data. A disallowed origin receives the same 204 without any `access-control-*` header, so the browser blocks the response and never sends the real request. An allowed origin additionally receives `access-control-allow-headers` covering the official OpenAI and Anthropic SDK headers and `access-control-expose-headers: x-request-id`. * Constant-time comparison is used for keys (`timingSafeEqual` with a length guard). -* Local paths: `realpath` is applied **before** the `allowedFileRoots` check, and only the OpenAI `document` part exposes a path field — symlink escape and traversal are correctly blocked (a TOCTOU window remains between `stat`/`realpath` and `readFile`, not reproduced and not separately reported). +* Local paths: `realpath` is applied **before** the `allowedFileRoots` check, and only the OpenAI `document` part exposes a path field — symlink escape and traversal are correctly blocked. The file is now read through one handle (`fsp.open` with `O_NOFOLLOW` where the platform has it, then `fstat` and `read`), so a final-component swap after the check cannot redirect the read, and an unreadable or vanished file returns 400 `invalid_attachment` / `attachment_not_found` instead of a 500. Residual risks, not closed by `realpath` + `O_NOFOLLOW`: hard links created inside an allowed root, a swapped parent directory, and Windows reparse points (Node exposes no `openat2`/`RESOLVE_BENEATH`). +* Attachment caps: `OPENCODE_MAX_ATTACHMENTS` and `OPENCODE_MAX_ATTACHMENT_BYTES` are enforced while media is resolved, not only when it is forwarded. One budget per request covers every message and every nested `tool_result` block, the count slot is claimed before the first `await`, downloads run in a bounded pool, and the first hard failure aborts the in-flight siblings instead of letting them run to the fetch timeout. * Remote downloads are streamed with a hard `maxAttachmentBytes` cap and a fetch timeout, and an oversized `content-length` is rejected before reading. * SSE framing: `[DONE]` is emitted only by `/v1/chat/completions`; Anthropic block indexes are contiguous `0,1,2…` with matching `content_block_start/stop`; Responses `sequence_number` is strictly increasing and unique (verified: `[0..15]`, strictly increasing `true`); in-stream error frames were observed on all three surfaces. * `content: null` is emitted by the chat adapter exactly when a tool call exists and no text was produced; `finish_reason`/`stop_reason` mapping matches the documented tables (`length`→`max_tokens`, `content_filter`→`refusal`, bridged calls→`tool_calls`/`tool_use`). diff --git a/package.json b/package.json index 14270e0..88fe765 100644 --- a/package.json +++ b/package.json @@ -29,6 +29,7 @@ ], "type": "module", "license": "MIT", + "packageManager": "pnpm@12.25.1", "engines": { "node": ">=20.11.0" }, @@ -52,7 +53,8 @@ "test:watch": "vitest --exclude 'test/integration/**'", "test:integration": "vitest run test/integration", "test:all": "vitest run", - "smoke": "node scripts/smoke.mjs" + "smoke": "node scripts/smoke.mjs", + "smoke:dist": "node scripts/smoke-dist.mjs" }, "dependencies": { "dotenv": "^17.2.3", @@ -65,6 +67,7 @@ "@commitlint/cli": "^20.5.3", "@commitlint/config-conventional": "^20.5.3", "@types/node": "^24.10.1", + "pino-pretty": "^13.2.0", "tsx": "^4.20.6", "typescript": "^5.9.3", "vitest": "^3.2.4" diff --git a/pnpm-lock.yaml b/pnpm-lock.yaml index bd23dad..b561386 100644 --- a/pnpm-lock.yaml +++ b/pnpm-lock.yaml @@ -1,3 +1,180 @@ +--- +lockfileVersion: '9.0' + +importers: + + .: + configDependencies: {} + packageManagerDependencies: + pnpm: + specifier: 12.25.1 + version: 12.25.1 + +packages: + + '@pnpm/exe.android-arm64@12.25.1': + resolution: {integrity: sha512-QHXIyWMsuntq05xq9twYS6upQZS2TYeJIfmBWDFw1Xyi8XQxiaD06DSTWwZYjR38GwOP/dveeMC2jk2Y68IAAg==} + cpu: [arm64] + os: [android] + + '@pnpm/exe.android-x64@12.25.1': + resolution: {integrity: sha512-bOJZTzi5c0MrI8xn6qU+0QzYu3gHMUtwLxb8ZRzuk/by7u6XhGXpn+gfppw7BF3te+rxpqK/mSR2PXb40d/7kg==} + cpu: [x64] + os: [android] + + '@pnpm/exe.darwin-arm64@12.25.1': + resolution: {integrity: sha512-NXG2kaXA7ui3T7aznhAmG8AwWZ/BmKkxqT9DIIQJ0jU1jLKkRhGce1gbyJ+RAeGKx0HcRHAJbRi38lcHgpCteA==} + cpu: [arm64] + os: [darwin] + + '@pnpm/exe.darwin-x64@12.25.1': + resolution: {integrity: sha512-cDnnUeocsg6ESvgjxTs9az5SUt9MEaINaMKGzAEqrfFMCRvaYgkC+0Ct7eYb/41i9WYPvd9DFv8H29LHECwcVA==} + cpu: [x64] + os: [darwin] + + '@pnpm/exe.freebsd-x64@12.25.1': + resolution: {integrity: sha512-LEDM+BE5BdYEetfEHKSD9f5IhOWmMAHix9bMqhds6dn3cMICNQeJZQaoimwUDeVVAR8yMtvaDwRZGuWXOq5gJw==} + cpu: [x64] + os: [freebsd] + + '@pnpm/exe.linux-arm64-musl@12.25.1': + resolution: {integrity: sha512-LtURUp1sJoS0ENQtKLk+oTI7oSlcEDHl3SOxxS8AUD/FTmP1AM1htwYwxi+91J+MTinOYqcUFrgb1f87Zn1Vfw==} + cpu: [arm64] + os: [linux] + libc: [musl] + + '@pnpm/exe.linux-arm64@12.25.1': + resolution: {integrity: sha512-55Ni6+zebnL2zdvKq23tZCEWbtPSMKeQ1MwJAwqDqS/VjD/Z6hT0BlJSTFvHKUgrWOBxnH501iTIyQgLVD+Cfw==} + cpu: [arm64] + os: [linux] + libc: [glibc] + + '@pnpm/exe.linux-loong64@12.25.1': + resolution: {integrity: sha512-52Fzal3IdcqsJ1kChNZC00JoFcwA9tDem/qTuZxpeJcc0KTALXTI5U/LbVF1+OXBfn72ADjS0Hxewkng7Q1iBA==} + cpu: [loong64] + os: [linux] + libc: [glibc] + + '@pnpm/exe.linux-ppc64@12.25.1': + resolution: {integrity: sha512-x3b9VQyrmHi1IIejDGqZWrdmgbtTV/qgE3Sca0NVYmY6gT1cAvkKFq6tQvHJEgeEdny7hGKl+1sk6YkKRs1Sfg==} + cpu: [ppc64] + os: [linux] + libc: [glibc] + + '@pnpm/exe.linux-riscv64@12.25.1': + resolution: {integrity: sha512-lPQ5PjYog/N07VsOBEZr661GgZ7y39wQLRCviHcL4RfpMBpe4XeJKK3W7YKl9NJz6+5/nzMYYfTcvZPFLWuMvA==} + cpu: [riscv64] + os: [linux] + libc: [glibc] + + '@pnpm/exe.linux-s390x@12.25.1': + resolution: {integrity: sha512-5kdJeOXns1O/PYqdR2Zk/0ci/0mCz1LhaJDIA6NiqNdgFxwCC6ufRTBiu9u4FB/F2MWBLPDtyHxwzpcbBFCP9Q==} + cpu: [s390x] + os: [linux] + libc: [glibc] + + '@pnpm/exe.linux-x64-musl@12.25.1': + resolution: {integrity: sha512-GRsFj54bSmdhceZwrA+zReMfGJw6X6qpC4pJh6iLaUcy3p0fG7A7Zqr70AKmtzvW1Zm2VGkeeIzja6QSkN09Vw==} + cpu: [x64] + os: [linux] + libc: [musl] + + '@pnpm/exe.linux-x64@12.25.1': + resolution: {integrity: sha512-Db2T6CtSNO8hjG6FISkOaZ2PW/OpynoXcT+jWEh44xDgSBt68rgbjGIbzjXSKJ+vH2mkoUxaUZCcLLusBVqelw==} + cpu: [x64] + os: [linux] + libc: [glibc] + + '@pnpm/exe.netbsd-x64@12.25.1': + resolution: {integrity: sha512-2hU5yNM/C8FT5eqbrNzB+0yGw/SS3oMJ1afk8pXEDsGU4vWdiiWxSqQ0kM8GHIvCDa/qRyw9ns98XWu5KZxxiA==} + cpu: [x64] + os: [netbsd] + + '@pnpm/exe.win32-arm64@12.25.1': + resolution: {integrity: sha512-v7YduE+TgEid1AiIThVBmYBnF0dj6vtk3ymcCkcM5FvanAM8MXoZhSiQYayQruh8xDwTXf5n8Zgn1OOi8WtqDg==} + cpu: [arm64] + os: [win32] + + '@pnpm/exe.win32-x64@12.25.1': + resolution: {integrity: sha512-cMfLsOE4zxSYBZYWyK1tr6BvCKVDyC81CnZg953t/6MEL592D8gk0eGdHQilEcd+yO+o6Ey1W9LLQdjl7pglsQ==} + cpu: [x64] + os: [win32] + + pnpm@12.25.1: + resolution: {integrity: sha512-psZ31wNNPXmvE28z2zPNbUEz1z+lZaBr1kqPCW0lN92HoI1o4Y/zd3cf9RwY4uwxvgO0RnDrGeJBiQ6uOu0Bag==} + engines: {node: '>=18'} + hasBin: true + +snapshots: + + '@pnpm/exe.android-arm64@12.25.1': + optional: true + + '@pnpm/exe.android-x64@12.25.1': + optional: true + + '@pnpm/exe.darwin-arm64@12.25.1': + optional: true + + '@pnpm/exe.darwin-x64@12.25.1': + optional: true + + '@pnpm/exe.freebsd-x64@12.25.1': + optional: true + + '@pnpm/exe.linux-arm64-musl@12.25.1': + optional: true + + '@pnpm/exe.linux-arm64@12.25.1': + optional: true + + '@pnpm/exe.linux-loong64@12.25.1': + optional: true + + '@pnpm/exe.linux-ppc64@12.25.1': + optional: true + + '@pnpm/exe.linux-riscv64@12.25.1': + optional: true + + '@pnpm/exe.linux-s390x@12.25.1': + optional: true + + '@pnpm/exe.linux-x64-musl@12.25.1': + optional: true + + '@pnpm/exe.linux-x64@12.25.1': + optional: true + + '@pnpm/exe.netbsd-x64@12.25.1': + optional: true + + '@pnpm/exe.win32-arm64@12.25.1': + optional: true + + '@pnpm/exe.win32-x64@12.25.1': + optional: true + + pnpm@12.25.1: + optionalDependencies: + '@pnpm/exe.android-arm64': 12.25.1 + '@pnpm/exe.android-x64': 12.25.1 + '@pnpm/exe.darwin-arm64': 12.25.1 + '@pnpm/exe.darwin-x64': 12.25.1 + '@pnpm/exe.freebsd-x64': 12.25.1 + '@pnpm/exe.linux-arm64': 12.25.1 + '@pnpm/exe.linux-arm64-musl': 12.25.1 + '@pnpm/exe.linux-loong64': 12.25.1 + '@pnpm/exe.linux-ppc64': 12.25.1 + '@pnpm/exe.linux-riscv64': 12.25.1 + '@pnpm/exe.linux-s390x': 12.25.1 + '@pnpm/exe.linux-x64': 12.25.1 + '@pnpm/exe.linux-x64-musl': 12.25.1 + '@pnpm/exe.netbsd-x64': 12.25.1 + '@pnpm/exe.win32-arm64': 12.25.1 + '@pnpm/exe.win32-x64': 12.25.1 + +--- lockfileVersion: '9.0' settings: @@ -33,6 +210,9 @@ importers: '@types/node': specifier: ^24.10.1 version: 24.19.4 + pino-pretty: + specifier: ^13.2.0 + version: 13.2.0 tsx: specifier: ^4.20.6 version: 4.23.15 @@ -582,6 +762,9 @@ packages: color-name@1.1.4: resolution: {integrity: sha512-dOy+3AuW3a2wNbZHIuMZpTcgjGuLU/uBL/ubcZF9OXbDo8ff4O8yVp5Bf0efS8uEoYo5q4Fx7dY9OgQGXgAsQA==} + colorette@2.0.20: + resolution: {integrity: sha512-IfEDxwoWIjkeXL1eXcDiow4UbKjhLdq6/EuSVR9GMN7KVH3r9gQ83e73hsz1Nd1T3ijd5xv1wcWRYO+D6kCI2w==} + compare-func@2.0.0: resolution: {integrity: sha512-zHig5N+tPWARooBnb0Zx1MFcdfpyJrfTJ3Y5L+IFvUm8rM74hHz66z0gw0x4tijh5CorKkKUCnW82R2vmpeCRA==} @@ -619,6 +802,9 @@ packages: typescript: optional: true + dateformat@4.6.3: + resolution: {integrity: sha512-2P0p0pFGzHS5EMnhdxQi7aJN+iMheud0UhG4dlE1DLAlvL8JHjJJTX/CSm4JXwV0Ka5nGk3zC5mcb5bUQUxxMA==} + debug@4.4.3: resolution: {integrity: sha512-RGwwWnwQvkVfavKVt22FGLw+xYSdzARwm0ru6DhTVA3umU5hZc28V3kO4stgYryrTlLpuvgI9GiijltAjNbcqA==} engines: {node: '>=6.0'} @@ -647,6 +833,9 @@ packages: emoji-regex@8.0.0: resolution: {integrity: sha512-MSjYzcWNOA0ewAHpz0MxpYFvwg6yjy1NG3xteoqz644VCo/RPgnr1/GGt+ic3iJTzQ8Eu3TdM14SawnVUmGE6A==} + end-of-stream@1.4.5: + resolution: {integrity: sha512-ooEGc6HP26xXq/N+GCGOT0JKCLDGrq2bQUZrQ7gyrJiZANJ/8YDTxTpQBXGMn+WbIQXNVpyWymm7KYVICQnyOg==} + env-paths@2.2.1: resolution: {integrity: sha512-+h1lkLKhZMTYjog1VEpJNG7NZJWcuc2DDk/qsqSTRRCOXiLjeQ1d1/udrUGhqMxUgAlwKNZ0cf2uqan5GLuS2A==} engines: {node: '>=6'} @@ -676,6 +865,9 @@ packages: resolution: {integrity: sha512-KfYbmpRm0VbLjEvVa9yGwCi9GI34xvi7A/HXYWQO65CSD2u3MczUJSuwXKFIxlGsgBQizV9q5J9NHj4VG0n+pA==} engines: {node: '>=12.0.0'} + fast-copy@4.3.4: + resolution: {integrity: sha512-o+7Dj5GG97OeQdPAVAo9EQE3O8YmRqUjCg0iqk9P2xH3IXI7rQPRyanWdoqK1QIzGje1oKF+kQudEStF93atyw==} + fast-decode-uri-component@1.0.1: resolution: {integrity: sha512-WKgKWg5eUxvRZGwW8FvfbaH7AXSh2cL+3j5fMGzUMCxWBJ3dV3a7Wz8y2f/uQ0e3B6WmodD3oS54jTQ9HVTIIg==} @@ -688,6 +880,9 @@ packages: fast-querystring@1.1.2: resolution: {integrity: sha512-g6KuKWmFXc0fID8WWH0jit4g0AGBoJhCkJMb1RmbsSEUNvQ+ZC8D6CUZ+GtF8nMzSPXnhiePyyqqipzNNEnHjg==} + fast-safe-stringify@2.1.1: + resolution: {integrity: sha512-W+KJc2dmILlPplD/H4K9l9LcAHAfPtP6BY84uVLXQ6Evcz9Lcg33Y2z1IVblT6xdY54PXYVHEv+0Wpq8Io6zkA==} + fast-uri@3.1.9: resolution: {integrity: sha512-hS/0Wt3Ya043oKXs0sIxrMpKQITXhMLIrVAKKXi4gozGC9v7YRWVnXIZzjNPTO02M9BdxLCWqK1yRXgNziVyJQ==} @@ -732,6 +927,9 @@ packages: resolution: {integrity: sha512-1pgFdhK3J2LeM+dVf2Pd424yHx2ou338lC0ErNP2hPx4j8eW1Sp0XqSjNxtk6Tc4Kr5wlWtSvz8cn2yb7/SG/w==} engines: {node: '>=20'} + help-me@5.0.0: + resolution: {integrity: sha512-7xgomUX6ADmcYzFik0HzAxh/73YlKR9bmFzf51CZwR+b6YtzU2m0u49hQCqV6SvlqIqsaxovfwdvbnsw3b/zpg==} + import-fresh@3.3.1: resolution: {integrity: sha512-TR3KfrTZTYLPB6jUjfx6MF9WcWrHL9su5TObK4ZkYgBdWKPOFoSoQIdEuTuR82pmtxH2spWG9h6etwfr1pLBqQ==} engines: {node: '>=6'} @@ -766,6 +964,10 @@ packages: resolution: {integrity: sha512-ekilCSN1jwRvIbgeg/57YFh8qQDNbwDb9xT/qu2DAHbFFZUicIl4ygVaAvzveMhMVr3LnpSKTNnwt8PoOfmKhQ==} hasBin: true + joycon@3.1.1: + resolution: {integrity: sha512-34wB/Y7MW7bzjKRjUKTa46I2Z7eV62Rkhva+KkopW7Qvv/OSWBqvkSY7vusOPrNuZcUG3tApvdVgNB8POj3SPw==} + engines: {node: '>=10'} + js-tokens@4.0.0: resolution: {integrity: sha512-RdJUflcE3cUzKiMqQgsCu06FPu9UdIJO0beYbPhHN4k6apgJtifcoCtT9bcxOpYBtpD2kCM6Sbzg4CausW/PKQ==} @@ -816,6 +1018,9 @@ packages: resolution: {integrity: sha512-0eJJY6hXLGf1udHwfNftBqH+g73EU4B504nZeKpz1sYRKafAghwxEJunB2O7rDZkL4PGfsMVnTXZ2EjibbqcsA==} engines: {node: '>=14.0.0'} + once@1.4.0: + resolution: {integrity: sha512-lNaJgI+2Q5URQBkccEKHTQOPaXdUxnZZElQTZY0MFUAuaEqe1E+Nyvgdz/aIyNi6Z9MzO5dv1H8n58/GELp3+w==} + parent-module@1.0.1: resolution: {integrity: sha512-GQ2EWRpQV8/o+Aw8YqtfZZPfNRWZYkbidE9k5rpl/hC3vtHHBfGm2Ifi6qWV+coDGkrUKZAxE3Lot5kcsRlh+g==} engines: {node: '>=6'} @@ -841,6 +1046,10 @@ packages: pino-abstract-transport@3.0.0: resolution: {integrity: sha512-wlfUczU+n7Hy/Ha5j9a/gZNy7We5+cXp8YL+X+PG8S0KXxw7n/JXA3c46Y0zQznIJ83URJiwy7Lh56WLokNuxg==} + pino-pretty@13.2.0: + resolution: {integrity: sha512-jjghD1ML+Di/WxjJDz6j6Y4FT7hIXOlb8h27AyJ+ohtAXJXH4PS/xkv7si+RCCIW59HMgZsMKTDgzdr0RhuRrg==} + hasBin: true + pino-std-serializers@7.1.0: resolution: {integrity: sha512-BndPH67/JxGExRgiX1dX0w1FvZck5Wa4aal9198SrRhZjH3GxKQUKIBnYJTdj2HDN3UQAS06HlfcSbQj2OHmaw==} @@ -860,6 +1069,9 @@ packages: engines: {node: ^16 || ^18 || >=20} deprecated: prom-client has been replaced by @prometheus-io/client + pump@3.0.4: + resolution: {integrity: sha512-VS7sjc6KR7e1ukRFhQSY5LM2uBWAUPiOPa/A3mkKmiMwSmRFUITt0xuj+/lesgnCv+dPIEYlkzrcyXgquIHMcA==} + quick-format-unescaped@4.0.4: resolution: {integrity: sha512-tYC1Q1hgyRuHgloV/YXs2w15unPVh8qfu/qCTfhTYamaw7fyhumKa2yGpdSo87vY32rIclj+4fWYQXUMs9EHvg==} @@ -923,6 +1135,9 @@ packages: sonic-boom@4.2.1: resolution: {integrity: sha512-w6AxtubXa2wTXAUsZMMWERrsIRAdrK0Sc+FUytWvYAhBJLyuI4llrMIC1DtlNSdI99EI86KZum2MMq3EAZlF9Q==} + sonic-boom@5.0.2: + resolution: {integrity: sha512-/JEruzo6yhNVhsLblTRchgTQHIt7SsdJP0YyrfWaNKjIOQDfrdZv9gwYraYCAsmKV39/LAdV31FLL5NCDpoL/A==} + source-map-js@1.3.0: resolution: {integrity: sha512-pdUVfIWcK0kCgK831ibqkZDcL7I9zljjOu0TQFnA+fiQ6y1CYqYB7RkTOHHO45FGMg5P/Mvk/+4ToQ7gAYAL5Q==} engines: {node: '>=6.0.0'} @@ -945,6 +1160,10 @@ packages: resolution: {integrity: sha512-Y38VPSHcqkFrCpFnQ9vuSXmquuv5oXOKpGeT6aGrr3o3Gc9AlVa6JBfUSOCnbxGGZF+/0ooI7KrPuUSztUdU5A==} engines: {node: '>=8'} + strip-json-comments@5.1.0: + resolution: {integrity: sha512-ErcwpJBYr8EfX/Br7JauOIGXoRE92w0hVtuS9j92UFgbATxA+WRSIZksSUDzEeItfWB/0QCEprTZT55RSINUHQ==} + engines: {node: '>=22'} + strip-literal@3.1.0: resolution: {integrity: sha512-8r3mkIM/2+PpjHoOtiAW8Rg3jJLHaV7xPwG+YRGrv6FP0wwk/toTpATxWYOW0BKdWwl82VT2tFYi5DlROa0Mxg==} @@ -1080,6 +1299,9 @@ packages: resolution: {integrity: sha512-YVGIj2kamLSTxw6NsZjoBxfSwsn0ycdesmc4p+Q21c5zPuZ1pl+NfxVdxPtdHvmNVOQ6XSYG4AUtyt/Fi7D16Q==} engines: {node: '>=10'} + wrappy@1.0.2: + resolution: {integrity: sha512-l4Sp/DRseor9wL6EvV2+TuQn63dMkPjZ/sp9XkghTEbV9KlPS1xUsZ3u7/IQO4wxtcFB4bgpQPRcR3QCvezPcQ==} + y18n@5.0.8: resolution: {integrity: sha512-0pfFzegeDWJHJIAmTLRP2DwHjdF5s7jo9tuztdQxAhINCdvS+3nGINqPd00AphqJR/0LhANUS6/+7SCb98YOfA==} engines: {node: '>=10'} @@ -1531,6 +1753,8 @@ snapshots: color-name@1.1.4: {} + colorette@2.0.20: {} + compare-func@2.0.0: dependencies: array-ify: 1.0.0 @@ -1567,6 +1791,8 @@ snapshots: optionalDependencies: typescript: 5.9.3 + dateformat@4.6.3: {} + debug@4.4.3: dependencies: ms: 2.1.3 @@ -1583,6 +1809,10 @@ snapshots: emoji-regex@8.0.0: {} + end-of-stream@1.4.5: + dependencies: + once: 1.4.0 + env-paths@2.2.1: {} error-ex@1.3.4: @@ -1630,6 +1860,8 @@ snapshots: expect-type@1.4.0: {} + fast-copy@4.3.4: {} + fast-decode-uri-component@1.0.1: {} fast-deep-equal@3.1.3: {} @@ -1647,6 +1879,8 @@ snapshots: dependencies: fast-decode-uri-component: 1.0.1 + fast-safe-stringify@2.1.1: {} + fast-uri@3.1.9: {} fast-uri@4.2.4: {} @@ -1700,6 +1934,8 @@ snapshots: dependencies: ini: 6.0.0 + help-me@5.0.0: {} + import-fresh@3.3.1: dependencies: parent-module: 1.0.1 @@ -1721,6 +1957,8 @@ snapshots: jiti@2.6.1: {} + joycon@3.1.1: {} + js-tokens@4.0.0: {} js-tokens@9.0.1: {} @@ -1762,6 +2000,10 @@ snapshots: on-exit-leak-free@2.1.2: {} + once@1.4.0: + dependencies: + wrappy: 1.0.2 + parent-module@1.0.1: dependencies: callsites: 3.1.0 @@ -1785,6 +2027,22 @@ snapshots: dependencies: split2: 4.2.0 + pino-pretty@13.2.0: + dependencies: + colorette: 2.0.20 + dateformat: 4.6.3 + fast-copy: 4.3.4 + fast-safe-stringify: 2.1.1 + help-me: 5.0.0 + joycon: 3.1.1 + minimist: 1.2.8 + on-exit-leak-free: 2.1.2 + pino-abstract-transport: 3.0.0 + pump: 3.0.4 + secure-json-parse: 4.1.1 + sonic-boom: 5.0.2 + strip-json-comments: 5.1.0 + pino-std-serializers@7.1.0: {} pino@10.4.0: @@ -1814,6 +2072,11 @@ snapshots: '@opentelemetry/api': 1.10.0 tdigest: 0.1.3 + pump@3.0.4: + dependencies: + end-of-stream: 1.4.5 + once: 1.4.0 + quick-format-unescaped@4.0.4: {} real-require@1.0.0: {} @@ -1882,6 +2145,10 @@ snapshots: dependencies: atomic-sleep: 1.0.0 + sonic-boom@5.0.2: + dependencies: + atomic-sleep: 1.0.0 + source-map-js@1.3.0: {} split2@4.2.0: {} @@ -1900,6 +2167,8 @@ snapshots: dependencies: ansi-regex: 5.0.1 + strip-json-comments@5.1.0: {} + strip-literal@3.1.0: dependencies: js-tokens: 9.0.1 @@ -2028,6 +2297,8 @@ snapshots: string-width: 4.2.3 strip-ansi: 6.0.1 + wrappy@1.0.2: {} + y18n@5.0.8: {} yargs-parser@21.1.1: {} diff --git a/scripts/smoke-dist.mjs b/scripts/smoke-dist.mjs new file mode 100644 index 0000000..4ec6736 --- /dev/null +++ b/scripts/smoke-dist.mjs @@ -0,0 +1,85 @@ +#!/usr/bin/env node +/** + * Boot the built gateway and probe its public liveness endpoint. + * + * This is the only check that exercises `dist/` exactly as it ships: `pnpm test` + * runs the TypeScript sources through vitest, so a broken emit, a missing `.js` + * extension at runtime or a bad ESM interop would reach production unnoticed. + * It needs no OpenCode CLI and no network beyond loopback: + * + * - `OPENCODE_AUTOSTART=false` stops the gateway from spawning `opencode serve`, + * and `OPENCODE_SERVER_URL` stays unset, so startup never touches upstream. + * - `/health` is public and unauthenticated by design. + * + * Exits 0 when `/health` answers 200, 1 otherwise. + */ +import { spawn } from "node:child_process"; +import path from "node:path"; +import { fileURLToPath } from "node:url"; + +const projectRoot = path.resolve(path.dirname(fileURLToPath(import.meta.url)), ".."); +const port = Number(process.env["SMOKE_PORT"] ?? 20199); +const timeoutMs = Number(process.env["SMOKE_TIMEOUT_MS"] ?? 20_000); + +const child = spawn(process.execPath, [path.join(projectRoot, "dist", "index.js")], { + cwd: projectRoot, + env: { + ...process.env, + HOST: "127.0.0.1", + PORT: String(port), + OPENCODE_API_KEYS: "smoke-test-key", + OPENCODE_AUTOSTART: "false", + OPENCODE_LOG_LEVEL: "silent", + OPENCODE_METRICS_ENABLED: "false", + OPENCODE_DATA_DIR: path.join(projectRoot, ".opencode-api", "smoke"), + OPENCODE_WORKDIR: path.join(projectRoot, ".opencode-api", "smoke-workspace"), + }, + stdio: ["ignore", "inherit", "inherit"], +}); + +let stopRequested = false; + +/** + * Resolve when the liveness endpoint answers, reject on a timeout. + * + * @returns {Promise} + */ +async function waitForHealth() { + const deadline = Date.now() + timeoutMs; + let lastError = "no attempt made"; + while (!stopRequested && Date.now() < deadline) { + if (child.exitCode !== null) { + throw new Error(`the gateway exited with code ${child.exitCode} before becoming healthy`); + } + try { + const response = await fetch(`http://127.0.0.1:${port}/health`, { signal: AbortSignal.timeout(2_000) }); + if (response.ok) return response; + lastError = `HTTP ${response.status}`; + } catch (error) { + lastError = error instanceof Error ? error.message : String(error); + } + await new Promise((resolve) => setTimeout(resolve, 250)); + } + throw new Error(`/health did not answer 200 within ${timeoutMs} ms (last attempt: ${lastError})`); +} + +/** Ask the child to shut down; the process exits when its own drain finishes. */ +function stopChild() { + stopRequested = true; + if (child.exitCode === null) child.kill("SIGTERM"); +} + +try { + const response = await waitForHealth(); + const body = await response.json(); + if (body.service !== "opencode-api" || typeof body.version !== "string") { + throw new Error(`unexpected /health body: ${JSON.stringify(body)}`); + } + console.log(`smoke: dist/index.js answered /health with version ${body.version}`); + process.exitCode = 0; +} catch (error) { + process.exitCode = 1; + console.error(`smoke: ${error instanceof Error ? error.message : String(error)}`); +} finally { + stopChild(); +} diff --git a/src/adapter/anthropic/countTokens.ts b/src/adapter/anthropic/countTokens.ts index b25756e..19b4d32 100644 --- a/src/adapter/anthropic/countTokens.ts +++ b/src/adapter/anthropic/countTokens.ts @@ -4,13 +4,14 @@ * IMPORTANT — the count is an approximation. OpenCode exposes no tokenizer * endpoint (`POST /api/session/{id}/generate` is the closest thing and still * requires a live session), so the gateway cannot reproduce Anthropic's exact - * tokenizer. Instead it reports `characters / 4` (see `estimateTokens` and - * `estimateConversationTokens` in `src/adapter/common/usage.ts`) over the + * tokenizer. Instead it reports a mixed estimate — one token per CJK character + * and `characters / 4` for the rest (see `estimateTokens` and + * `estimateConversationTokens` in `src/adapter/common/usage.ts`) — over the * rendered text of every message, the system prompt and the tool JSON schemas, * plus a small per-message overhead. * * Every response carries a non-standard `x_opencode` object that marks the value - * as an estimate (`estimated: true`, `method: "chars/4"`) so callers can decide + * as an estimate (`estimated: true`, `method: "mixed"`) so callers can decide * whether an approximate budget check is good enough for them. */ import type { FastifyInstance } from "fastify"; @@ -75,7 +76,7 @@ export function registerAnthropicCountTokenRoutes(app: FastifyInstance, ctx: App return reply.status(200).send({ input_tokens: estimateRequestTokens(internal), - x_opencode: { estimated: true, method: "chars/4" }, + x_opencode: { estimated: true, method: "mixed" }, }); }); } diff --git a/src/adapter/anthropic/messages.ts b/src/adapter/anthropic/messages.ts index 6a4d63c..e9c7ac2 100644 --- a/src/adapter/anthropic/messages.ts +++ b/src/adapter/anthropic/messages.ts @@ -20,7 +20,12 @@ import { completionDeps, type AppContext } from "../../context.js"; import { ApiError, toAnthropicError, toApiError } from "../../errors.js"; import { createDisconnectSignal } from "../../http/disconnect.js"; import { SseWriter } from "../../http/sse.js"; -import { resolveAttachment } from "../../media/resolve.js"; +import { + AttachmentOmittedError, + createMediaBudget, + resolveAttachment, + type MediaBudget, +} from "../../media/resolve.js"; import type { CollectedCompletion } from "../../upstream/completion.js"; import type { Attachment, @@ -213,6 +218,9 @@ export type AnthropicRequestInput = AnthropicCountTokensBody; type ContentBlock = z.infer; type MediaBlock = Extract; type ToolResultContent = z.infer; +/** Image/document blocks nested in a `tool_result` content array. */ +type ToolResultMediaBlock = Extract; +type ToolResultBlock = Extract; // ------------------------------------------------------------ response --- @@ -284,6 +292,12 @@ export interface ToInternalOptions { * short placeholder instead. Used by `count_tokens`, which only needs text. */ resolveMedia?: boolean; + /** + * Request-level media budget. Every media block of the request (including the + * `image`/`document` blocks nested in a `tool_result`) shares it, so the + * attachment caps bound the work before anything is fetched. + */ + budget?: MediaBudget; } function parseOrThrow(schema: S, body: unknown, label: string): z.output { @@ -326,18 +340,46 @@ function argumentsFromInput(input: unknown): string { } } -function toolResultText(content: ToolResultContent | undefined): string { +/** Image and document blocks carried by a `tool_result` content array. */ +function toolResultMediaBlocks(content: ToolResultContent | undefined): ToolResultMediaBlock[] { + if (content === undefined || typeof content === "string") return []; + return content.filter( + (block): block is ToolResultMediaBlock => block.type === "image" || block.type === "document", + ); +} + +/** + * Render the textual part of a `tool_result`. + * + * `resolved` holds one entry per media block, in declaration order: a resolved + * `Attachment` contributes its MIME placeholder (the bytes themselves ride on the + * user turn), and a string — an inline-text document, or the placeholder used + * when resolution is switched off — contributes its own text. + */ +function toolResultText(content: ToolResultContent | undefined, resolved: readonly (Attachment | string)[]): string { if (content === undefined) return ""; if (typeof content === "string") return content; const parts: string[] = []; + let cursor = 0; for (const block of content) { - if (block.type === "text") parts.push(block.text); - else if (block.type === "image") parts.push("[image content omitted]"); - else parts.push("[document content omitted]"); + if (block.type === "text") { + parts.push(block.text); + continue; + } + const value = resolved[cursor]; + cursor += 1; + if (typeof value === "string") parts.push(value); + else parts.push(mediaPlaceholder(block)); } return parts.join("\n"); } +/** Prefix a failed `tool_result` so the model can tell a failure from a success. */ +function withToolError(label: boolean, text: string): string { + if (!label) return text; + return text.length > 0 ? `[tool error]\n${text}` : "[tool error]"; +} + function mediaPlaceholder(block: MediaBlock): string { const source = block.source; const hint = source.type === "url" ? source.url : (source.media_type ?? ""); @@ -359,17 +401,26 @@ async function resolveMediaBlock(block: MediaBlock, options: ToInternalOptions): if (options.resolveMedia === false) return mediaPlaceholder(block); const source = block.source; - if (source.type === "base64") { - return await resolveAttachment({ base64: source.data, mime: source.media_type }, options.ctx.config, { - field: "messages", - signal: options.signal, - }); - } - if (source.type === "url") { - return await resolveAttachment({ url: source.url }, options.ctx.config, { - field: "messages", - signal: options.signal, - }); + try { + if (source.type === "base64") { + return await resolveAttachment({ base64: source.data, mime: source.media_type }, options.ctx.config, { + field: "messages", + signal: options.signal, + ...(options.budget !== undefined ? { budget: options.budget } : {}), + }); + } + if (source.type === "url") { + return await resolveAttachment({ url: source.url }, options.ctx.config, { + field: "messages", + signal: options.signal, + ...(options.budget !== undefined ? { budget: options.budget } : {}), + }); + } + } catch (error) { + // A block the request budget cannot fit is announced, not fetched: the model + // still learns that something was there, and the turn continues. + if (error instanceof AttachmentOmittedError) return mediaPlaceholder(block); + throw error; } return mediaPlaceholder(block); } @@ -408,6 +459,16 @@ export async function toInternalRequest( if (systemText.length > 0) messages.push({ role: "system", text: systemText }); const toolNames = new Map(); + // One budget for the whole request: every media block — including the nested + // tool_result ones — shares the attachment caps, and the count slot is claimed + // synchronously so concurrent blocks can never all take the last slot. + const budget = + options.budget ?? + createMediaBudget({ + maxCount: options.ctx.config.maxAttachments, + maxBytes: options.ctx.config.maxAttachmentBytes, + }); + const scoped: ToInternalOptions = { ...options, budget }; for (const message of body.messages) { if (typeof message.content === "string") { @@ -419,16 +480,29 @@ export async function toInternalRequest( const attachments: Attachment[] = []; const toolCalls: ToolCall[] = []; const toolResults: InternalMessage[] = []; + // Media carried by a tool_result rides on the user turn: that is the only + // turn `collectAttachments` forwards upstream. + const toolResultAttachments: Attachment[] = []; - // Media resolution is the only asynchronous part of a message. The blocks are - // independent, so resolve them concurrently and re-assemble the results in - // declaration order; the attachment caps still bound the work. + // Media resolution is the only asynchronous part of a message. The top-level + // blocks and the image/document blocks nested in a tool_result are resolved + // concurrently and re-assembled in declaration order. const mediaBlocks = message.content.filter( (block): block is MediaBlock => block.type === "image" || block.type === "document" || block.type === "audio" || block.type === "video", ); - const resolvedMedia = await Promise.all(mediaBlocks.map((block) => resolveMediaBlock(block, options))); + const toolResultBlocks = message.content.filter( + (block): block is ToolResultBlock => block.type === "tool_result", + ); + const nestedToolResultMedia = toolResultBlocks.map((block) => toolResultMediaBlocks(block.content)); + const [resolvedMedia, resolvedToolResultMedia] = await Promise.all([ + Promise.all(mediaBlocks.map((block) => resolveMediaBlock(block, scoped))), + Promise.all( + nestedToolResultMedia.map((blocks) => Promise.all(blocks.map((block) => resolveMediaBlock(block, scoped)))), + ), + ]); let mediaCursor = 0; + let toolResultCursor = 0; for (const block of message.content) { switch (block.type) { @@ -471,9 +545,14 @@ export async function toInternalRequest( param: "messages", }); } + const nested = resolvedToolResultMedia[toolResultCursor] ?? []; + toolResultCursor += 1; + for (const value of nested) { + if (typeof value !== "string") toolResultAttachments.push(value); + } const result: InternalMessage = { role: "tool", - text: toolResultText(block.content), + text: withToolError(block.is_error === true, toolResultText(block.content, nested)), toolCallId: block.tool_use_id, }; const name = toolNames.get(block.tool_use_id); @@ -494,9 +573,11 @@ export async function toInternalRequest( if (toolCalls.length > 0) assistant.toolCalls = toolCalls; messages.push(assistant); } - } else if (text.length > 0 || attachments.length > 0) { + } else if (text.length > 0 || attachments.length > 0 || toolResultAttachments.length > 0) { const user: InternalMessage = { role: "user", text }; - if (attachments.length > 0) user.attachments = attachments; + // Top-level media first, then tool-result media, both in declaration order. + const carried = [...attachments, ...toolResultAttachments]; + if (carried.length > 0) user.attachments = carried; messages.push(user); } @@ -526,7 +607,10 @@ export async function toInternalRequest( 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; - if (body.stop_sequences !== undefined && body.stop_sequences.length > 0) request.stop = body.stop_sequences; + // An empty sequence would match at position 0 and truncate every turn, so + // empty entries are dropped before the value reaches the internal request. + const stopSequences = (body.stop_sequences ?? []).filter((sequence) => sequence.length > 0); + if (stopSequences.length > 0) request.stop = stopSequences; const toolChoice = mapToolChoice(body.tool_choice); if (toolChoice !== undefined) request.toolChoice = toolChoice; if (body.metadata !== undefined) request.metadata = { ...body.metadata }; @@ -597,6 +681,126 @@ function mapStopReason(finishReason: FinishReason, calls: ToolCall[], toolsOffer } } +/** + * Terminal stop reason. + * + * A caller-supplied sequence that ended the visible answer wins over the upstream + * finish reason, so the streamed and buffered paths always agree. + */ +function stopReasonFor( + matched: string | undefined, + finishReason: FinishReason, + calls: ToolCall[], + toolsOffered: boolean, +): AnthropicStopReason { + if (matched !== undefined) return "stop_sequence"; + return mapStopReason(finishReason, calls, toolsOffered); +} + +/** + * Streaming filter for `stop_sequences`. + * + * Text deltas arrive in arbitrary chunks, so a sequence can straddle a delta + * boundary ("hello E" + "ND world"). The filter emits everything that cannot be + * part of a sequence and withholds the longest suffix that is still a proper + * prefix of one; when a sequence completes it records the match and suppresses + * every later delta. `flush()` releases a withheld suffix that never completed, + * so text is never lost. Only assistant text is filtered: reasoning and tool + * arguments are never truncated. + */ +class StopSequenceFilter { + readonly #sequences: readonly string[]; + #pending = ""; + #matched: string | undefined; + + constructor(sequences: readonly string[]) { + this.#sequences = sequences.filter((sequence) => sequence.length > 0); + } + + /** The sequence that ended the turn, once one has matched. */ + get matched(): string | undefined { + return this.#matched; + } + + /** Feed a text delta; returns the text that is safe to emit. */ + push(delta: string): string { + if (this.#matched !== undefined || delta.length === 0) return ""; + this.#pending += delta; + + const hit = this.#earliestMatch(); + if (hit !== undefined) { + const safe = this.#pending.slice(0, hit.index); + this.#pending = ""; + this.#matched = hit.sequence; + return safe; + } + + const held = this.#heldSuffixLength(); + if (held === 0) { + const safe = this.#pending; + this.#pending = ""; + return safe; + } + const safe = this.#pending.slice(0, this.#pending.length - held); + this.#pending = this.#pending.slice(this.#pending.length - held); + return safe; + } + + /** Release what is still withheld; a matched sequence itself is never emitted. */ + flush(): string { + const tail = this.#matched === undefined ? this.#pending : ""; + this.#pending = ""; + return tail; + } + + /** Earliest match; the longest sequence breaks a tie so the match is specific. */ + #earliestMatch(): { index: number; sequence: string } | undefined { + let best: { index: number; sequence: string } | undefined; + for (const sequence of this.#sequences) { + const index = this.#pending.indexOf(sequence); + if (index === -1) continue; + if ( + best === undefined || + index < best.index || + (index === best.index && sequence.length > best.sequence.length) + ) { + best = { index, sequence }; + } + } + return best; + } + + /** Length of the longest suffix that is a proper prefix of some sequence. */ + #heldSuffixLength(): number { + if (this.#sequences.length === 0) return 0; + let longest = 0; + for (const sequence of this.#sequences) longest = Math.max(longest, sequence.length); + const limit = Math.min(this.#pending.length, longest - 1); + for (let length = limit; length > 0; length -= 1) { + const suffix = this.#pending.slice(this.#pending.length - length); + if (this.#sequences.some((sequence) => sequence.length > length && sequence.startsWith(suffix))) { + return length; + } + } + return 0; + } +} + +/** + * Apply `stop_sequences` to a complete assistant text. + * + * Shared by the buffered route and the streaming filter so both paths truncate + * identically; when nothing matches the original text is returned unchanged. + */ +export function truncateAtStopSequence( + text: string, + sequences: readonly string[] | undefined, +): { text: string; stopSequence: string | null } { + const filter = new StopSequenceFilter(sequences ?? []); + const kept = `${filter.push(text)}${filter.flush()}`; + return { text: kept, stopSequence: filter.matched ?? null }; +} + /** Parse model-supplied tool arguments into the JSON object Anthropic expects. */ function parseToolInput(raw: string): Record { try { @@ -615,10 +819,17 @@ function reasoningRequested(request: InternalRequest, fromUpstream: boolean): bo return fromUpstream; } -/** Build the non-streaming Anthropic response payload. */ +/** + * Build the non-streaming Anthropic response payload. + * + * `stopSequence` is the sequence that truncated `collected.text` (the route + * applies the filter with `truncateAtStopSequence`), so the payload always agrees + * with the streamed one; `null` means no sequence matched. + */ export function renderAnthropicMessage( collected: CollectedCompletion, request: InternalRequest, + stopSequence: string | null = null, ): AnthropicMessageResponse { const id = newMessageId(); const content: AnthropicContentBlock[] = []; @@ -643,8 +854,13 @@ export function renderAnthropicMessage( role: "assistant", model: collected.model.length > 0 ? collected.model : request.model, content, - stop_reason: mapStopReason(collected.finishReason, collected.calls, request.tools.length > 0), - stop_sequence: null, + stop_reason: stopReasonFor( + stopSequence ?? undefined, + collected.finishReason, + collected.calls, + request.tools.length > 0, + ), + stop_sequence: stopSequence, usage: usagePayload(collected.usage), x_opencode: { session_id: collected.sessionId, @@ -689,11 +905,11 @@ async function streamAnthropicMessage( let index = 0; let openIndex = -1; let openKind: "thinking" | "text" | null = null; - let textStarted = false; let reasoningEnabled = request.reasoning?.enabled === true && request.reasoning.disabled !== true; let finishReason: FinishReason = "stop"; let usage: Usage = { ...EMPTY_USAGE }; const calls: ToolCall[] = []; + const stopFilter = new StopSequenceFilter(request.stop ?? []); const send = (payload: string | object, event: string): void => { if (!opened) { @@ -707,14 +923,13 @@ async function streamAnthropicMessage( openIndex = index; index += 1; openKind = "thinking"; - send({ type: "content_block_start", index: openIndex, content_block: { type: "thinking", thinking: "" } }, "content_block_start"); + send({ type: "content_block_start", index: openIndex, content_block: { type: "thinking", thinking: "", signature: "" } }, "content_block_start"); }; const openText = (): void => { openIndex = index; index += 1; openKind = "text"; - textStarted = true; send({ type: "content_block_start", index: openIndex, content_block: { type: "text", text: "" } }, "content_block_start"); }; @@ -738,6 +953,23 @@ async function streamAnthropicMessage( openIndex = -1; }; + /** + * Emit assistant text, opening the text block lazily. Text withheld by the + * stop-sequence filter never opens a block, so a truncated turn cannot emit + * an empty one. + */ + const sendText = (text: string): void => { + if (text.length === 0) return; + if (openKind !== "text") { + closeOpen(); + openText(); + } + send( + { type: "content_block_delta", index: openIndex, delta: { type: "text_delta", text } }, + "content_block_delta", + ); + }; + const stream = ctx.completion.run(request, completionDeps(ctx), { signal }); try { @@ -788,14 +1020,9 @@ async function streamAnthropicMessage( break; } case "text_delta": { - if (openKind !== "text") { - closeOpen(); - openText(); - } - send( - { type: "content_block_delta", index: openIndex, delta: { type: "text_delta", text: event.text } }, - "content_block_delta", - ); + // Only assistant text is subject to `stop_sequences`; the filter + // withholds a suffix that may still grow into a sequence. + sendText(stopFilter.push(event.text)); break; } case "text_end": { @@ -809,7 +1036,9 @@ async function streamAnthropicMessage( break; } case "tool_calls": { - calls.push(...event.calls); + // A stop sequence ended the visible answer, so no further tool block + // is emitted; calls collected before the match still are. + if (stopFilter.matched === undefined) calls.push(...event.calls); break; } case "usage": { @@ -839,12 +1068,12 @@ async function streamAnthropicMessage( return reply; } + // A withheld suffix that never completed a stop sequence is still real text, + // so it is flushed before the text block closes. A matched sequence is never + // emitted. No text block is opened for a turn that produced none: the + // buffered path contains no text block either. + sendText(stopFilter.flush()); closeOpen(); - // Anthropic always carries a text block; emit an empty one for tool-only turns. - if (!textStarted) { - openText(); - closeOpen(); - } for (const call of calls) { const blockIndex = index; @@ -872,8 +1101,8 @@ async function streamAnthropicMessage( { type: "message_delta", delta: { - stop_reason: mapStopReason(finishReason, calls, request.tools.length > 0), - stop_sequence: null, + stop_reason: stopReasonFor(stopFilter.matched, finishReason, calls, request.tools.length > 0), + stop_sequence: stopFilter.matched ?? null, }, usage: { // Anthropic counts thinking tokens inside `output_tokens`. @@ -917,7 +1146,13 @@ export function registerAnthropicMessageRoutes(app: FastifyInstance, ctx: AppCon } const collected = await ctx.completion.collect(internal, completionDeps(ctx), { signal: abort.signal }); - return reply.status(200).send(renderAnthropicMessage(collected, internal)); + // The same filter the streaming path uses, so both paths truncate + // identically. The upstream turn is not interrupted: `usage` still reports + // every token it produced, including the text after the stop sequence. + const truncated = truncateAtStopSequence(collected.text, internal.stop); + return reply + .status(200) + .send(renderAnthropicMessage({ ...collected, text: truncated.text }, internal, truncated.stopSequence)); } finally { abort.dispose(); } diff --git a/src/adapter/common/tools.ts b/src/adapter/common/tools.ts index 5d2f0e6..7a09c5f 100644 --- a/src/adapter/common/tools.ts +++ b/src/adapter/common/tools.ts @@ -14,6 +14,7 @@ * - the assistant text around a call is preserved. */ import { randomUUID } from "node:crypto"; +import { ApiError } from "../../errors.js"; import type { InternalMessage, ToolCall, ToolDefinition } from "../../types/internal.js"; export const TOOL_CALL_OPEN = "[[OPENCODE_TOOL_CALL]]"; @@ -69,6 +70,22 @@ function choiceInstruction(tools: ToolDefinition[], choice: ToolChoice | undefin return "Call a tool only when it is genuinely required to answer; otherwise answer directly in plain text."; } +/** + * Reject a `tool_choice` that asks for a tool the request never declared. + * + * Silently ignoring it would run the turn with the agent's own built-in tools + * and no bridged call, which is the opposite of what the caller asked for. + */ +function assertToolChoiceHasTools(tools: ToolDefinition[], choice: ToolChoice | undefined): void { + if (tools.length > 0) return; + if (choice === "required" || (choice !== undefined && typeof choice === "object")) { + throw ApiError.badRequest( + "`tool_choice` requires a tool call, but the request declared no `tools`.", + { code: "invalid_request", param: "tool_choice" }, + ); + } +} + /** * Build the prompt fragment that teaches the model the tool protocol. * Returns an inactive bridge when there is nothing to bridge. @@ -78,6 +95,8 @@ export function createToolBridge( choice?: ToolChoice, options: ToolBridgeOptions = {}, ): ToolBridge { + assertToolChoiceHasTools(tools, choice); + const active = tools.length > 0 && choice !== "none"; const instructions = active @@ -85,9 +104,9 @@ export function createToolBridge( "# Tool calling", "", "HARD RULE: for this turn the only tools that exist are the ones listed under", - "`## Available tools` below. You have no shell, no web access, no file access and no", - "sub-agents. Never call bash, webfetch, websearch, read, write, edit, glob, grep, task or", - "any other built-in tool. Do not explain that a tool is missing.", + "`## Available tools` below. You have no shell, no web access and no sub-agents.", + "Never call bash, webfetch, websearch, write, edit, task or any other built-in tool.", + "Do not explain that a tool is missing.", "", "Tool results are not available to you: the calling application executes the tool and", "returns the result in a later message.", @@ -269,7 +288,7 @@ function parseJsonValue(text: string): { value: unknown } | undefined { } catch { // The model may have emitted a trailing comma or an unquoted key; try a // light repair before giving up. - const repaired = text.replace(/,\s*([}\]])/g, "$1"); + const repaired = repairTrailingCommas(text); try { return { value: JSON.parse(repaired) }; } catch { @@ -278,6 +297,46 @@ function parseJsonValue(text: string): { value: unknown } | undefined { } } +/** + * Drop a comma that is followed only by whitespace and a closing object or array. + * + * A plain `/,\s*([}\]])/g` regex also rewrites a `,}` or `,]` that the model put + * *inside* a string value, silently corrupting the arguments. The walk below + * skips string literals the same way `scanTopLevelJsonValues` does, so only a + * genuine trailing comma is removed. + */ +function repairTrailingCommas(text: string): string { + let out = ""; + let inString = false; + let escaped = false; + + for (let index = 0; index < text.length; index += 1) { + const char = text.charAt(index); + if (inString) { + out += char; + if (escaped) escaped = false; + else if (char === "\\") escaped = true; + else if (char === '"') inString = false; + continue; + } + if (char === '"') { + inString = true; + out += char; + continue; + } + if (char === ",") { + let next = index + 1; + while (next < text.length && /\s/.test(text.charAt(next))) next += 1; + const following = text.charAt(next); + // Only a comma directly before a closing bracket is a trailing comma. + if (following === "}" || following === "]") continue; + } + out += char; + } + + return out; +} + /** * Extract every complete top-level JSON object/array from `text`. * diff --git a/src/adapter/common/usage.ts b/src/adapter/common/usage.ts index 878aefb..f8b4d03 100644 --- a/src/adapter/common/usage.ts +++ b/src/adapter/common/usage.ts @@ -36,16 +36,37 @@ export function addUsage(left: Usage, right: Usage): Usage { }; } +/** Characters of ordinary Latin text that fit in one token, on average. */ +const LATIN_CHARS_PER_TOKEN = 4; + +/** Matches one CJK ideograph, kana, Hangul syllable or CJK punctuation mark. */ +const CJK_CHARACTER = /[\u3000-\u303f\u3040-\u30ff\u3400-\u4dbf\u4e00-\u9fff\uf900-\ufaff\uff00-\uffef]/; + /** * Rough token estimate used by `count_tokens`. * * The OpenCode API exposes no tokenizer endpoint, so the gateway reports an - * approximation: characters / 4 with a floor of one token per message. The - * response is documented as an estimate. + * approximation. A character/4 rule badly under-counts scripts where one + * character is roughly one token — Japanese, Chinese and Korean prompts come out + * up to four times too small, exactly where a caller uses the count to check a + * budget — so the estimate splits the text: every CJK character counts as one + * token, everything else as `LATIN_CHARS_PER_TOKEN` characters per token, and an + * empty string is zero. The result is still documented as an estimate. */ export function estimateTokens(text: string): number { if (text.length === 0) return 0; - return Math.max(1, Math.ceil(text.length / 4)); + + let tokens = 0; + let latinCharacters = 0; + for (const character of text) { + if (CJK_CHARACTER.test(character)) { + tokens += 1; + continue; + } + latinCharacters += 1; + } + tokens += Math.ceil(latinCharacters / LATIN_CHARS_PER_TOKEN); + return Math.max(1, tokens); } /** Estimate the prompt size of a rendered conversation. */ diff --git a/src/adapter/openai/chat.ts b/src/adapter/openai/chat.ts index 2982b5a..4ffe53c 100644 --- a/src/adapter/openai/chat.ts +++ b/src/adapter/openai/chat.ts @@ -15,7 +15,13 @@ import { completionDeps, type AppContext } from "../../context.js"; import { ApiError, toApiError, toOpenAiError } from "../../errors.js"; import { createDisconnectSignal } from "../../http/disconnect.js"; import { SseWriter } from "../../http/sse.js"; -import { resolveAttachment, type MediaSource } from "../../media/resolve.js"; +import { + createMediaBudget, + formatOmissionNote, + resolveAttachments, + type MediaBudget, + type MediaSource, +} from "../../media/resolve.js"; import { EMPTY_USAGE, type Attachment, @@ -264,6 +270,7 @@ export function registerOpenAiChatRoutes(app: FastifyInstance, ctx: AppContext): const collected = await ctx.completion.collect(internal, completionDeps(ctx), { signal: abort.signal, }); + if (collected.finishReason === "error") throw failedTurnError(); return reply.send(chatCompletionBody(collected, ctx.config.reasoningField)); } @@ -288,8 +295,11 @@ async function buildRequest( signal: AbortSignal, ): Promise { const messages: InternalMessage[] = []; + // One budget for the whole request, so the attachment caps bound the work of + // every message together rather than each message separately. + const budget = createMediaBudget({ maxCount: config.maxAttachments, maxBytes: config.maxAttachmentBytes }); for (const message of body.messages) { - messages.push(await toInternalMessage(message, config, signal)); + messages.push(await toInternalMessage(message, config, signal, budget)); } const internal: InternalRequest = { @@ -333,9 +343,14 @@ async function buildRequest( return internal; } -async function toInternalMessage(message: ChatMessage, config: Config, signal: AbortSignal): Promise { +async function toInternalMessage( + message: ChatMessage, + config: Config, + signal: AbortSignal, + budget: MediaBudget, +): Promise { const texts: string[] = []; - const pending: Array> = []; + const sources: MediaSource[] = []; if (typeof message.content === "string") { texts.push(message.content); @@ -346,17 +361,26 @@ async function toInternalMessage(message: ChatMessage, config: Config, signal: A continue; } const source = mediaSourceOf(part); - if (source !== undefined) pending.push(resolveAttachment(source, config, { signal })); + if (source !== undefined) sources.push(source); } } - // Media parts are independent: resolve them concurrently and keep the - // declaration order, so N remote attachments cost max(latency), not the sum. - const attachments = pending.length > 0 ? await Promise.all(pending) : []; + // One request-level budget across every message: media parts are independent, + // so they are resolved concurrently in declaration order under the same caps, + // and a source beyond them is reported instead of being fetched. + const { attachments, omitted } = + sources.length > 0 + ? await resolveAttachments(sources, config, { signal, budget, field: "messages" }) + : { attachments: [], omitted: [] }; const internal: InternalMessage = { role: message.role, - text: texts.filter((text) => text.length > 0).join("\n"), + text: [ + texts.filter((text) => text.length > 0).join("\n"), + formatOmissionNote(omitted, { maxCount: config.maxAttachments, maxBytes: config.maxAttachmentBytes }), + ] + .filter((text) => text.length > 0) + .join("\n"), }; if (attachments.length > 0) internal.attachments = attachments; @@ -606,6 +630,7 @@ async function streamChat( let writer: SseWriter | undefined; let started = false; let finishReason: FinishReason = "stop"; + let failure: ApiError | undefined; let usage: Usage = { ...EMPTY_USAGE }; let toolIndex = 0; @@ -673,6 +698,7 @@ async function streamChat( case "end": finishReason = event.finishReason; + if (event.finishReason === "error") failure = failedTurnError(); usage = event.usage; break; @@ -686,6 +712,12 @@ async function streamChat( } } + // A turn the upstream ended with `error` is a failure, not a completion: + // route it through the same paths as `kind: "error"` so the caller gets a + // real HTTP status when nothing was sent yet, an in-band error frame once + // the head is committed, and never a finish chunk or `[DONE]`. + if (failure !== undefined) throw failure; + const active = ensure(); active.send({ ...base, @@ -756,6 +788,19 @@ function openAiErrorFrame(error: ApiError): Record { return body; } +/** + * Surrogate error for a turn the upstream ended with `finishReason: "error"`. + * + * The orchestrator does not carry the upstream error object on the terminal + * `end` event, so every surface reports this stable `502 upstream_error` + * surrogate — `/v1/responses` already does. Without it a failed turn renders as + * a successful `finish_reason: "stop"` (or an SSE stream that ends with + * `[DONE]`), which callers treat as a completed answer. + */ +function failedTurnError(): ApiError { + return new ApiError(502, "upstream_error", "The upstream completion ended with an error."); +} + function invalidRequestFromZod(error: z.ZodError): ApiError { const issue = error.issues[0]; if (issue === undefined) return ApiError.badRequest("Invalid request body.", { code: "invalid_request" }); diff --git a/src/adapter/openai/completions.ts b/src/adapter/openai/completions.ts index 85aad75..ce81679 100644 --- a/src/adapter/openai/completions.ts +++ b/src/adapter/openai/completions.ts @@ -108,6 +108,7 @@ export function registerOpenAiCompletionRoutes(app: FastifyInstance, ctx: AppCon const collected = await ctx.completion.collect(internal, completionDeps(ctx), { signal: abort.signal, }); + if (collected.finishReason === "error") throw failedTurnError(); return reply.send(completionBody(collected)); } @@ -193,6 +194,7 @@ async function streamCompletion( let writer: SseWriter | undefined; let startEmitted = false; let finishReason: FinishReason = "stop"; + let failure: ApiError | undefined; let usage: Usage = { ...EMPTY_USAGE }; // Headers are sent lazily so that a failure before the first event is still @@ -229,6 +231,7 @@ async function streamCompletion( case "end": finishReason = event.finishReason; + if (event.finishReason === "error") failure = failedTurnError(); usage = event.usage; break; @@ -244,6 +247,12 @@ async function streamCompletion( } } + // A turn the upstream ended with `error` is a failure, not a completion: + // route it through the same paths as `kind: "error"` so the caller gets a + // real HTTP status when nothing was sent yet, an in-band error frame once + // the head is committed, and never a finish chunk or `[DONE]`. + if (failure !== undefined) throw failure; + const active = ensure(); active.send(chunk("", mapFinishReason(finishReason))); if (options.includeUsage) { @@ -262,6 +271,19 @@ async function streamCompletion( // ------------------------------------------------------------------ helpers --- +/** + * Surrogate error for a turn the upstream ended with `finishReason: "error"`. + * + * The orchestrator does not carry the upstream error object on the terminal + * `end` event, so every surface reports this stable `502 upstream_error` + * surrogate — `/v1/responses` already does. Without it a failed turn renders as + * a successful `finish_reason: "stop"` (or an SSE stream that ends with + * `[DONE]`), which callers treat as a completed answer. + */ +function failedTurnError(): ApiError { + return new ApiError(502, "upstream_error", "The upstream completion ended with an error."); +} + /** * Build an in-stream OpenAI error frame. * diff --git a/src/adapter/openai/responses.ts b/src/adapter/openai/responses.ts index eb774e9..70535e3 100644 --- a/src/adapter/openai/responses.ts +++ b/src/adapter/openai/responses.ts @@ -14,8 +14,14 @@ * Not implemented, by design: * - `previous_response_id` is accepted and ignored; the gateway has no * server-side response store, so callers must resend the full `input`. - * - `store` is accepted and ignored; responses are never persisted, and the - * echoed response always reports `store: false`. + * - `store` is accepted and ignored; responses are never persisted. The value + * is echoed back as the caller sent it, so the field does not claim the + * response was stored. + * - `truncation` is accepted and echoed as given (default `"disabled"`) but + * never applied: the gateway does not trim history. + * - `reasoning` items in `input` are validated and ignored: a caller may + * resend a previous response's `output` verbatim, but provider-side thinking + * state cannot be replayed. * - `include`, `service_tier`, `top_logprobs` and `user` are accepted for API * compatibility and have no effect on the completion. `text.format` is not * in this list: it is rendered into the prompt like the chat @@ -31,7 +37,13 @@ import { completionDeps, type AppContext } from "../../context.js"; import { ApiError, toApiError } from "../../errors.js"; import { createDisconnectSignal } from "../../http/disconnect.js"; import { SseWriter } from "../../http/sse.js"; -import { resolveAttachment, type MediaSource } from "../../media/resolve.js"; +import { + createMediaBudget, + formatOmissionNote, + resolveAttachments, + type MediaBudget, + type MediaSource, +} from "../../media/resolve.js"; import type { ResolvedModel } from "../../upstream/models.js"; import type { CompletionEvent, @@ -118,7 +130,43 @@ const functionCallOutputItem = z const itemReference = z.object({ type: z.literal("item_reference"), id: z.string() }).passthrough(); -const inputItem = z.union([functionCallItemSchema, functionCallOutputItem, itemReference, messageItemSchema]); +/** + * One `summary`/`content` part of an echoed `reasoning` item. + * + * Only the shape matters: the item is validated and then ignored (see + * `mapInputItems`), exactly like the Anthropic surface's `thinking` and + * `redacted_thinking` blocks. + */ +const reasoningPart = z.object({ type: z.string(), text: z.string().optional() }).passthrough(); + +/** + * A `reasoning` item echoed back from a previous response's `output`. + * + * The real Responses API accepts these in `input`, and this gateway's own + * `output` contains them whenever reasoning was surfaced, so rejecting them + * broke the documented pattern of resending a previous `output` as `input`. + */ +const reasoningInputItem = z + .object({ + type: z.literal("reasoning"), + id: z.string().optional(), + summary: z.array(reasoningPart).optional(), + content: z.array(reasoningPart).optional(), + encrypted_content: z.string().nullable().optional(), + status: z.string().optional(), + }) + .passthrough(); + +const inputItem = z.union([ + functionCallItemSchema, + functionCallOutputItem, + itemReference, + // Before `messageItemSchema`: a reasoning item has no `role`/`content`, so it + // is recognised by its `type`, while the type-less message fallback in + // `mapInputItems` stays last. + reasoningInputItem, + messageItemSchema, +]); const reasoningOptions = z .object({ @@ -426,7 +474,12 @@ async function prepare( if (typeof body.input === "string") { messages.push({ role: "user", text: body.input }); } else { - messages.push(...(await mapInputItems(body.input, ctx, signal))); + // One budget for the whole request: the caps bound every input item together. + const budget = createMediaBudget({ + maxCount: ctx.config.maxAttachments, + maxBytes: ctx.config.maxAttachmentBytes, + }); + messages.push(...(await mapInputItems(body.input, ctx, signal, budget))); } const tools: ToolDefinition[] = (body.tools ?? []).map((tool) => ({ @@ -484,7 +537,12 @@ async function prepare( } /** Map the `input` array onto internal messages, preserving order. */ -async function mapInputItems(items: InputItem[], ctx: AppContext, signal: AbortSignal): Promise { +async function mapInputItems( + items: InputItem[], + ctx: AppContext, + signal: AbortSignal, + budget: MediaBudget, +): Promise { const messages: InternalMessage[] = []; for (const item of items) { @@ -505,9 +563,17 @@ async function mapInputItems(items: InputItem[], ctx: AppContext, signal: AbortS // References point at stored responses, which this gateway does not keep. continue; } + if (item.type === "reasoning") { + // Accepted for multi-turn replay compatibility and ignored: a `reasoning` + // item carries provider-side thinking state the gateway cannot store (the + // Anthropic surface does the same for `thinking`/`redacted_thinking`). + // Folding the text into the prompt would change token accounting and the + // sticky-session prefix hash. + continue; + } // `type` is optional on message items, so discriminate structurally here. if (typeof item.role !== "string" || item.content === undefined) continue; - messages.push(await mapMessageItem(item.role, item.content, ctx, signal)); + messages.push(await mapMessageItem(item.role, item.content, ctx, signal, budget)); } return messages; @@ -519,6 +585,7 @@ async function mapMessageItem( content: string | ContentPart[], ctx: AppContext, signal: AbortSignal, + budget: MediaBudget, ): Promise { if (typeof content === "string") return { role, text: content }; @@ -572,12 +639,19 @@ async function mapMessageItem( const message: InternalMessage = { role, text: text.join("\n") }; if (media.length > 0) { - // The parts of one message are independent, so they resolve concurrently; - // `Promise.all` preserves the declaration order of `media` in the result. - // The per-attachment and attachment-count caps still bound the work. - message.attachments = await Promise.all( - media.map((source) => resolveAttachment(source, ctx.config, { signal })), - ); + // One request-level budget, so the attachment caps bound the work of every + // item together: sources beyond it are reported in the text instead of fetched. + const { attachments, omitted } = await resolveAttachments(media, ctx.config, { + signal, + budget, + field: "input", + }); + if (attachments.length > 0) message.attachments = attachments; + const note = formatOmissionNote(omitted, { + maxCount: ctx.config.maxAttachments, + maxBytes: ctx.config.maxAttachmentBytes, + }); + if (note.length > 0) message.text = [message.text, note].filter((part) => part.length > 0).join("\n"); } return message; } @@ -972,9 +1046,12 @@ async function pipeEvents( // Pull the first event before committing the head. A failure raised while the // orchestrator prepares the turn (event stream unavailable, upstream refusal) - // must reach the caller as a real HTTP status, not as a 200 SSE body. + // reaches the adapter as a **yielded** `kind: "error"` event, so it must be + // inspected here: emitting the frames below would commit a 200 SSE head and + // report a pre-flight failure as an in-band `response.failed`. const iterator = events[Symbol.asyncIterator](); const first = await iterator.next(); + if (!first.done && first.value.kind === "error") throw first.value.error; emitFrame(writer, state, "response.created", (sequence) => ({ type: "response.created", diff --git a/src/config.ts b/src/config.ts index f4cd69d..e1969c4 100644 --- a/src/config.ts +++ b/src/config.ts @@ -16,7 +16,11 @@ export interface Config { /** API keys accepted from callers. Never empty: the built-in default applies. */ readonly apiKeys: readonly string[]; - /** True when no key was configured and the built-in development key is in use. */ + /** + * True when the published built-in development key is among the accepted keys + * — either because nothing was configured (so the default was installed) or + * because the caller listed it explicitly, as `.env.example` ships it. + */ readonly usingDefaultApiKey: boolean; readonly allowNoAuth: boolean; readonly metricsPublic: boolean; @@ -272,8 +276,14 @@ export function loadConfig(overrides: Partial = {}): Config { // The gateway always accepts at least one key, so it starts out of the box. // `sk-dummy-123` is a well-known development placeholder: anyone who can reach // the port can use it, so it must be replaced before exposing the gateway. - const usingDefaultApiKey = apiKeys.length === 0; - if (usingDefaultApiKey) apiKeys.push(DEFAULT_API_KEY); + if (apiKeys.length === 0) apiKeys.push(DEFAULT_API_KEY); + + // Installing the default is not the same as accepting it: `.env.example` + // ships `OPENCODE_API_KEYS=sk-dummy-123`, so the documented `pnpm setup` flow + // configures the published key explicitly. Both cases must warn, otherwise a + // caller probing a real installation never learns that the gateway accepts a + // key that ships with the project. + const usingDefaultApiKey = apiKeys.includes(DEFAULT_API_KEY); const config: Config = { host: envStr("HOST", "127.0.0.1"), diff --git a/src/http/shutdown.ts b/src/http/shutdown.ts index 91e351f..a52c4bd 100644 --- a/src/http/shutdown.ts +++ b/src/http/shutdown.ts @@ -18,7 +18,12 @@ export interface ShutdownDeps { readonly log: Pick; readonly events: { stop(): Promise }; readonly sessions: { stop(): void }; - readonly upstream: { stop(): Promise }; + /** + * `shutdown()` is the terminal variant: it forbids any further upstream spawn. + * The process-exit path uses it when available and falls back to `stop()`, + * which stays non-terminal for the admin restart route. + */ + readonly upstream: { stop(): Promise; shutdown?(): Promise }; } /** The app surface `shutdown` needs; structurally satisfied by `FastifyInstance`. */ @@ -52,7 +57,7 @@ export async function shutdown(deps: ShutdownDeps, app: ShutdownApp, drainMs = D await stop("sessions", async () => { deps.sessions.stop(); }, deps.log); - await stop("upstream", () => deps.upstream.stop(), deps.log); + await stop("upstream", () => deps.upstream.shutdown?.() ?? deps.upstream.stop(), deps.log); deps.log.info({ elapsedMs: Date.now() - startedAt }, "shutdown complete"); } diff --git a/src/index.ts b/src/index.ts index 15f4c2c..95d249e 100644 --- a/src/index.ts +++ b/src/index.ts @@ -21,6 +21,7 @@ import { ModelRegistry } from "./upstream/models.js"; import { UpstreamProcess } from "./upstream/process.js"; import { SessionStore } from "./upstream/sessions.js"; import { SERVICE_NAME, VERSION } from "./version.js"; +import { defaultApiKeyNote } from "./startup.js"; /** Directory holding this file: `/dist` when built, `/src` under tsx. */ const moduleDir = path.dirname(fileURLToPath(import.meta.url)); @@ -47,15 +48,8 @@ async function main(): Promise { if (config.usingDefaultApiKey) { // Readable on the terminal as well as in the structured log: a published // default key means anyone who can reach the port can use the gateway. - const note = - `Using the built-in default API key "${DEFAULT_API_KEY}" because OPENCODE_API_KEYS is not set.\n` + - `That key is public knowledge (it ships with the project), so replace it in ${path.join(projectRoot, ".env")} ` + - "before exposing this port to anything but localhost.\n" + - `Set OPENCODE_ALLOW_NO_AUTH=true to disable authentication entirely on a trusted host.`; - // The structured log never carries the key itself (AGENTS.md forbids logging - // credentials); the stderr note below is the operator-facing explanation. log.warn({ usingDefaultApiKey: true }, "using the built-in default API key"); - process.stderr.write(`\n${note}\n\n`); + process.stderr.write(`\n${defaultApiKeyNote(projectRoot)}\n\n`); } for (const key of config.apiKeys) { diff --git a/src/media/resolve.ts b/src/media/resolve.ts index 26734f5..2bc2fee 100644 --- a/src/media/resolve.ts +++ b/src/media/resolve.ts @@ -12,10 +12,22 @@ * All reads are bounded by `config.maxAttachmentBytes`, and remote fetches are * streamed with a hard cap so a hostile or accidental large response cannot * exhaust memory. + * + * Local-file containment (opt-in through `OPENCODE_ALLOW_LOCAL_FILES`) resolves + * the requested path with `realpath`, checks it against `allowedFileRoots`, and + * then reads through a single handle opened with `O_NOFOLLOW`, so a final + * component swapped for a symlink after the check cannot redirect the read. + * Residual risks that remain, by design: a hard link created inside an allowed + * root still reaches the outside inode, a parent directory can be swapped + * between `realpath` and `open`, and Windows has no `O_NOFOLLOW` equivalent + * (the flag is `0` there). Node exposes no `openat2`/`RESOLVE_BENEATH`, so the + * allowed roots must not contain untrusted writers. */ +import { constants as fsConstants } from "node:fs"; import type { LookupAddress } from "node:dns"; import dns from "node:dns/promises"; import fsp from "node:fs/promises"; +import type { FileHandle } from "node:fs/promises"; import http from "node:http"; import https from "node:https"; import net from "node:net"; @@ -45,10 +57,165 @@ export interface ResolveOptions { field?: string; /** Abort signal from the inbound request. */ signal?: AbortSignal; + /** + * Shared request budget (see `createMediaBudget`). The count slot is claimed + * synchronously before the first `await`; the byte side is checked once the + * payload size is known. + * + * A source the budget cannot fit never yields a partial attachment: it + * rejects with `AttachmentOmittedError` instead of returning truncated bytes. + * Prefer `resolveAttachments` when resolving more than one source: it reports + * the same situation as an `omitted` entry and admits in declaration order, + * which a bare loop of concurrent calls cannot guarantee. + */ + budget?: MediaBudget; +} + +/** Why a source was never fetched. */ +export type OmissionReason = "count" | "bytes"; + +/** Hard ceiling for one request's media. */ +export interface MediaBudgetLimits { + /** Maximum number of attachments the request may resolve. */ + readonly maxCount: number; + /** Maximum combined decoded bytes the request may retain. */ + readonly maxBytes: number; +} + +/** + * Request-level media budget. + * + * The count slot is claimed synchronously, before the first `await` of an + * attachment, so concurrent resolutions can never both take the last slot. The + * byte side is an admission ledger: bytes are booked only once the payload size + * is known, and a payload that does not fit is refused *whole* (nothing is + * booked and its buffer is dropped). Booking a fixed per-entry ceiling up front + * instead would let the first concurrent download reserve the entire budget and + * starve every sibling of a request that fits comfortably. + * + * The per-item read is bounded by `min(config.maxAttachmentBytes, maxBytes)`, so + * a single attachment may still use the whole request budget, while + * `usedBytes <= maxBytes` holds at all times. + */ +export interface MediaBudget extends MediaBudgetLimits { + /** Count slots claimed; released again by `releaseSlot`. */ + readonly usedCount: number; + /** Bytes admitted, i.e. actually retained. */ + readonly usedBytes: number; + /** Claim one of the `maxCount` slots; `false` when they are all taken. */ + claimSlot(): boolean; + /** Give a claimed slot back after a failed resolution. */ + releaseSlot(): void; + /** Book `bytes` when they still fit; `false` books nothing. */ + admit(bytes: number): boolean; +} + +/** The only budget implementation; `createMediaBudget` is the public factory. */ +class RequestMediaBudget implements MediaBudget { + readonly maxCount: number; + readonly maxBytes: number; + #usedCount = 0; + #usedBytes = 0; + + constructor(limits: MediaBudgetLimits) { + this.maxCount = Math.max(0, Math.trunc(limits.maxCount)); + this.maxBytes = Math.max(0, Math.trunc(limits.maxBytes)); + } + + get usedCount(): number { + return this.#usedCount; + } + + get usedBytes(): number { + return this.#usedBytes; + } + + claimSlot(): boolean { + if (this.#usedCount >= this.maxCount) return false; + this.#usedCount += 1; + return true; + } + + releaseSlot(): void { + this.#usedCount = Math.max(0, this.#usedCount - 1); + } + + admit(bytes: number): boolean { + const size = Math.max(0, Math.trunc(bytes)); + if (this.#usedBytes + size > this.maxBytes) return false; + this.#usedBytes += size; + return true; + } +} + +/** Create the per-request budget shared by every attachment of one request. */ +export function createMediaBudget(limits: MediaBudgetLimits): MediaBudget { + return new RequestMediaBudget(limits); +} + +/** + * Marker rejection for a source the request budget cannot fit. + * + * It is an `ApiError` (400 `attachment_omitted`) so it can never turn into a + * 500 if it escapes. Only direct callers of `resolveAttachment` see it; a batch + * that goes through `resolveAttachments` gets the same situation reported as an + * `omitted` entry instead. + */ +export class AttachmentOmittedError extends ApiError { + readonly reason: OmissionReason; + + constructor(reason: OmissionReason, field: string, budget: MediaBudgetLimits) { + super( + 400, + "invalid_request_error", + reason === "count" + ? `Attachment was not fetched: the request already claimed its ${budget.maxCount}-attachment limit.` + : `Attachment was not fetched: the request already filled its ${budget.maxBytes}-byte combined attachment budget.`, + { code: "attachment_omitted", param: field }, + ); + this.name = "AttachmentOmittedError"; + this.reason = reason; + } +} + +/** One source the budget refused, reported so the caller can tell the model. */ +export interface OmittedAttachment { + /** Declaration index in the source list. */ + readonly index: number; + /** Name hint, when the source carried one. */ + readonly name?: string; + readonly reason: OmissionReason; +} + +export interface ResolveAttachmentsOptions extends ResolveOptions { + /** In-flight downloads; clamped to 1..8. Default 4. */ + concurrency?: number; + /** Called for every omitted source (logging / metrics hook). */ + onOmit?: (omission: OmittedAttachment) => void; } +export interface ResolveAttachmentsResult { + /** Resolved attachments, in declaration order. */ + readonly attachments: Attachment[]; + /** Sources that were never fetched because the budget was spent. */ + readonly omitted: OmittedAttachment[]; +} + +/** Default worker-pool size for one request's attachments. */ +const DEFAULT_MEDIA_CONCURRENCY = 4; +/** Hard ceiling for the pool, whatever a caller asks for. */ +const MAX_MEDIA_CONCURRENCY = 8; + const DATA_URI_PATTERN = /^data:([^,]*?),(.*)$/s; +/** + * `O_NOFOLLOW` where the platform has it. + * + * Windows exposes no equivalent flag, so the final-component guarantee is + * POSIX-only and the value there is `0` (a plain `O_RDONLY` open). + */ +const OPEN_NOFOLLOW: number = process.platform === "win32" ? 0 : fsConstants.O_NOFOLLOW; + /** Resolve any supported media source into an attachment. */ export async function resolveAttachment( source: MediaSource, @@ -56,6 +223,208 @@ export async function resolveAttachment( options: ResolveOptions = {}, ): Promise { const field = options.field ?? "attachment"; + const budget = options.budget; + // The count slot is claimed synchronously, before the first `await`, so two + // concurrent resolutions can never both take the last slot. Byte admission + // happens once the payload size is known: booking a per-entry ceiling up front + // would let the first download reserve the whole budget and starve its + // siblings. + let limitBytes = config.maxAttachmentBytes; + if (budget !== undefined) { + if (!budget.claimSlot()) throw new AttachmentOmittedError("count", field, budget); + limitBytes = Math.min(config.maxAttachmentBytes, budget.maxBytes); + } + + try { + const attachment = await resolveSource(source, config, field, limitBytes, options.signal); + if (budget !== undefined && !budget.admit(retainedBytes(attachment))) { + throw new AttachmentOmittedError("bytes", field, budget); + } + return attachment; + } catch (error) { + // The slot is given back so a later source can still be tried; no bytes + // were admitted for this attachment. + if (budget !== undefined) budget.releaseSlot(); + throw error; + } +} + +/** + * Resolve many sources under one request budget and one abort controller. + * + * - At most `budget.maxCount` entries are fetched. A source is skipped without a + * fetch once no count slot is free or the byte budget is already spent, and it + * is reported in `omitted` — so its own validation errors no longer surface. + * - Admission is decided in declaration order (the pool hands out indexes + * monotonically and a small ledger admits them in order), so the accepted set + * is deterministic: `usedBytes <= budget.maxBytes` holds after every decision + * and a payload that does not fit is dropped whole rather than truncated. + * - Downloads run through a small worker pool (`concurrency`, default 4, hard + * ceiling 8) instead of one unbounded `Promise.all` per message. + * - The first hard failure aborts the request-level controller, so siblings stop + * immediately rather than running to `mediaFetchTimeoutMs`, and that error is + * rethrown once the pool settles. + * - The caller signal is chained to that controller, so a disconnect cancels + * every in-flight download. + * + * With no explicit budget the ceiling is `config.maxAttachments` entries and + * `config.maxAttachmentBytes` combined bytes — the same limits the prompt + * builder applies later, but enforced before anything is fetched. + */ +export async function resolveAttachments( + sources: readonly MediaSource[], + config: Config, + options: ResolveAttachmentsOptions = {}, +): Promise { + const field = options.field ?? "attachment"; + const budget = + options.budget ?? createMediaBudget({ maxCount: config.maxAttachments, maxBytes: config.maxAttachmentBytes }); + // One attachment may still use the whole request budget; the aggregate is + // enforced by admission below, not by shrinking this per-item read bound. + const limitBytes = Math.min(config.maxAttachmentBytes, budget.maxBytes); + + const controller = new AbortController(); + const callerSignal = options.signal; + const onAbort = (): void => controller.abort(callerSignal?.reason); + if (callerSignal?.aborted) controller.abort(callerSignal.reason); + else callerSignal?.addEventListener("abort", onAbort, { once: true }); + + type Decision = + | { readonly kind: "resolved"; readonly attachment: Attachment } + | { readonly kind: "omitted"; readonly reason: OmissionReason }; + + const decisions = new Map(); + const attachments: Attachment[] = []; + const omitted: OmittedAttachment[] = []; + let cursor = 0; + let nextAdmit = 0; + let failure: unknown; + + const recordOmission = (index: number, reason: OmissionReason): void => { + const name = sources[index]?.name; + const omission: OmittedAttachment = { index, reason, ...(name !== undefined ? { name } : {}) }; + omitted.push(omission); + options.onOmit?.(omission); + }; + + /** Admit every contiguous decision, oldest index first. */ + const drain = (): void => { + for (;;) { + const decision = decisions.get(nextAdmit); + if (decision === undefined) return; + decisions.delete(nextAdmit); + + if (decision.kind === "omitted") { + recordOmission(nextAdmit, decision.reason); + } else if (budget.admit(retainedBytes(decision.attachment))) { + // `drain()` walks indexes in order, so this array stays ordered. + attachments.push(decision.attachment); + } else { + recordOmission(nextAdmit, "bytes"); + } + nextAdmit += 1; + } + }; + + const worker = async (): Promise => { + for (;;) { + if (failure !== undefined) return; + const index = cursor; + cursor += 1; + if (index >= sources.length) return; + const source = sources[index]; + if (source === undefined) { + // A hole in the list is a caller bug, not user input: fail like an + // empty source would, and keep the admission ledger contiguous. + failure = ApiError.badRequest("Attachment has no source: provide dataUri, base64, url or path.", { + code: "invalid_attachment", + param: field, + }); + controller.abort(failure); + return; + } + + // Never dial a source that cannot be admitted: no count slot, or the byte + // budget is already fully spent. + if (!budget.claimSlot()) { + decisions.set(index, { kind: "omitted", reason: "count" }); + drain(); + continue; + } + if (budget.usedBytes >= budget.maxBytes) { + budget.releaseSlot(); + decisions.set(index, { kind: "omitted", reason: "bytes" }); + drain(); + continue; + } + + try { + const attachment = await resolveSource(source, config, field, limitBytes, controller.signal); + decisions.set(index, { kind: "resolved", attachment }); + drain(); + } catch (error) { + budget.releaseSlot(); + // The first hard failure wins: stop pulling work and abort the siblings. + if (failure === undefined) { + failure = error; + controller.abort(error); + } + return; + } + } + }; + + const requested = options.concurrency ?? DEFAULT_MEDIA_CONCURRENCY; + const poolSize = Math.min( + Math.max(1, Math.min(MAX_MEDIA_CONCURRENCY, Math.trunc(requested))), + Math.max(1, sources.length), + ); + + try { + await Promise.all(Array.from({ length: poolSize }, () => worker())); + } finally { + callerSignal?.removeEventListener("abort", onAbort); + } + + if (failure !== undefined) throw failure; + + drain(); + omitted.sort((left, right) => left.index - right.index); + return { attachments, omitted }; +} + +/** + * Render omissions as the prompt note the model reads, mirroring the wording + * the prompt builder uses for attachments it drops later. Empty when nothing + * was omitted, so a caller can append it unconditionally. + * + * Pass the limits the request budget was built from — `MediaBudgetLimits`, so + * an adapter can hand over its budget (or `{ maxCount: config.maxAttachments, + * maxBytes: config.maxAttachmentBytes }`) and the quoted numbers always match + * the enforced ones. + */ +export function formatOmissionNote(omitted: readonly OmittedAttachment[], limits: MediaBudgetLimits): string { + if (omitted.length === 0) return ""; + + const overByteBudget = omitted.some((entry) => entry.reason === "bytes"); + const labels = omitted.map((entry) => { + const label = entry.name ?? `attachment #${entry.index + 1}`; + return entry.reason === "count" ? `${label} (over the ${limits.maxCount}-file limit)` : label; + }); + const suffix = overByteBudget + ? ` - the request exceeded the ${limits.maxBytes}-byte combined attachment budget` + : ""; + return `[attachments omitted: ${labels.join(", ")}${suffix}]`; +} + +/** Validate the source shape and dispatch to the matching resolver. */ +async function resolveSource( + source: MediaSource, + config: Config, + field: string, + limitBytes: number, + signal: AbortSignal | undefined, +): Promise { const provided = [source.dataUri, source.base64, source.url, source.path].filter( (value): value is string => typeof value === "string" && value.length > 0, ); @@ -73,10 +442,10 @@ export async function resolveAttachment( }); } - if (source.dataUri) return resolveDataUri(source, config, field); - if (source.base64 !== undefined) return resolveBase64(source, config, field); - if (source.url) return resolveUrl(source, config, field, options.signal); - return resolveLocalFile(source, config, field); + if (source.dataUri) return resolveDataUri(source, config, field, limitBytes); + if (source.base64 !== undefined) return resolveBase64(source, config, field, limitBytes); + if (source.url) return resolveUrl(source, config, field, limitBytes, signal); + return resolveLocalFile(source, config, field, limitBytes); } /** Build a `data:` URI from an attachment payload. */ @@ -84,7 +453,7 @@ export function buildDataUri(attachment: Pick): str return `data:${attachment.mime};base64,${attachment.data}`; } -function resolveDataUri(source: MediaSource, config: Config, field: string): Attachment { +function resolveDataUri(source: MediaSource, config: Config, field: string, limitBytes: number): Attachment { const match = DATA_URI_PATTERN.exec(source.dataUri ?? ""); if (!match) { throw ApiError.badRequest("Malformed data URI in attachment.", { code: "invalid_attachment", param: field }); @@ -108,15 +477,15 @@ function resolveDataUri(source: MediaSource, config: Config, field: string): Att } } - assertWithinBudget(buffer.byteLength, config, field, source.name); + assertWithinBudget(buffer.byteLength, config, field, source.name, limitBytes); const mime = sniffOrDeclare(buffer, declaredMime ?? source.mime, source.name); return toAttachment(buffer, mime, source.name, field, "data-uri"); } -function resolveBase64(source: MediaSource, config: Config, field: string): Attachment { +function resolveBase64(source: MediaSource, config: Config, field: string, limitBytes: number): Attachment { const buffer = decodeBase64(source.base64 ?? "", field); - assertWithinBudget(buffer.byteLength, config, field, source.name); + assertWithinBudget(buffer.byteLength, config, field, source.name, limitBytes); const mime = sniffOrDeclare(buffer, source.mime, source.name); return toAttachment(buffer, mime, source.name, field, "base64"); } @@ -125,6 +494,7 @@ async function resolveUrl( source: MediaSource, config: Config, field: string, + limitBytes: number, signal: AbortSignal | undefined, ): Promise { if (!config.allowRemoteMediaUrls) { @@ -164,15 +534,15 @@ async function resolveUrl( } const declaredLength = Number(headerValue(response.headers["content-length"]) ?? "0"); - if (Number.isFinite(declaredLength) && declaredLength > config.maxAttachmentBytes) { + if (Number.isFinite(declaredLength) && declaredLength > limitBytes) { response.body.destroy(); throw ApiError.badRequest( - `Attachment is larger than the ${config.maxAttachmentBytes}-byte limit (content-length: ${declaredLength}).`, + `Attachment is larger than the ${limitBytes}-byte limit (content-length: ${declaredLength}).`, { code: "attachment_too_large", param: field }, ); } - const buffer = await readBounded(response.body, config.maxAttachmentBytes, field); + const buffer = await readBounded(response.body, limitBytes, field); const headerMime = normalise(headerValue(response.headers["content-type"]) ?? "") || undefined; const name = source.name ?? deriveName(current, headerMime); const mime = sniffOrDeclare(buffer, headerMime ?? source.mime, name); @@ -371,7 +741,12 @@ function parseHttpUrl(value: string | undefined, field: string): URL { return parsed; } -async function resolveLocalFile(source: MediaSource, config: Config, field: string): Promise { +async function resolveLocalFile( + source: MediaSource, + config: Config, + field: string, + limitBytes: number, +): Promise { if (!config.allowLocalFiles) { throw ApiError.badRequest( "Local file attachments are disabled on this server (OPENCODE_ALLOW_LOCAL_FILES=false).", @@ -399,30 +774,72 @@ async function resolveLocalFile(source: MediaSource, config: Config, field: stri ); } - const stats = await fsp.stat(realPath); - if (!stats.isFile()) { - throw ApiError.badRequest(`Attachment path is not a regular file: ${requested}`, { - code: "invalid_attachment", - param: field, - }); - } - if (stats.size > config.maxAttachmentBytes) { - throw ApiError.badRequest( - `Attachment is larger than the ${config.maxAttachmentBytes}-byte limit (${stats.size} bytes).`, - { code: "attachment_too_large", param: field }, - ); + // One handle owns the whole operation: the `stat` cannot disagree with the + // bytes, and `O_NOFOLLOW` refuses a final component that was swapped for a + // symlink between `realpath` and this open. Every failure is mapped to the + // documented 400 codes instead of escaping as a 500. + let handle: FileHandle | undefined; + let buffer: Buffer; + try { + handle = await fsp.open(realPath, fsConstants.O_RDONLY | OPEN_NOFOLLOW); + const stats = await handle.stat(); + if (!stats.isFile()) { + throw ApiError.badRequest(`Attachment path is not a regular file: ${requested}`, { + code: "invalid_attachment", + param: field, + }); + } + if (stats.size > limitBytes) { + throw ApiError.badRequest( + `Attachment is larger than the ${limitBytes}-byte limit (${stats.size} bytes).`, + { code: "attachment_too_large", param: field }, + ); + } + buffer = await handle.readFile(); + } catch (error) { + throw localFileError(error, requested, field); + } finally { + if (handle !== undefined) await handle.close().catch(() => undefined); } - const buffer = await fsp.readFile(realPath); const name = source.name ?? path.basename(realPath); // The pre-read `stat` can be stale (a file that grows between the two calls) // or meaningless (procfs reports size 0 for a regular file), so the bytes that // were actually read are checked against the same budget as well. - assertWithinBudget(buffer.byteLength, config, field, name); + assertWithinBudget(buffer.byteLength, config, field, name, limitBytes); const mime = sniffOrDeclare(buffer, source.mime, name); return toAttachment(buffer, mime, name, field, realPath); } +/** + * Map a filesystem failure on an allowed local file to the documented 400. + * + * `ENOENT`/`ENOTDIR` keep the historical `attachment_not_found`; the errno + * values a caller can trigger by making a file unreadable (`EACCES`, `EPERM`, + * `ELOOP` from `O_NOFOLLOW`, `EISDIR`, a Windows lock's `EBUSY`) become + * `invalid_attachment`. Anything else stays a 500 on purpose: an unexpected + * errno is an operational problem, not a caller error, and must keep surfacing + * in the logs. + */ +function localFileError(error: unknown, requested: string, field: string): ApiError { + if (error instanceof ApiError) return error; + const code = typeof error === "object" && error !== null ? (error as NodeJS.ErrnoException).code : undefined; + + if (code === "ENOENT" || code === "ENOTDIR") { + return ApiError.badRequest(`Attachment file does not exist or is not readable: ${requested}`, { + code: "attachment_not_found", + param: field, + }); + } + if (code === "EACCES" || code === "EPERM" || code === "ELOOP" || code === "EISDIR" || code === "EBUSY") { + return ApiError.badRequest(`Attachment file is not readable: ${requested}`, { + code: "invalid_attachment", + param: field, + }); + } + throw error; +} + function decodeBase64(payload: string, field: string): Buffer { const cleaned = payload.replace(/\s+/g, ""); if (cleaned.length === 0) { @@ -474,10 +891,27 @@ function toAttachment( }; } -function assertWithinBudget(bytes: number, config: Config, field: string, name: string | undefined): void { - if (bytes > config.maxAttachmentBytes) { +/** + * Decoded bytes an attachment retains. + * + * `Attachment.size` is optional in the frozen model even though this module + * always sets it; the base64 fallback keeps the budget honest if one ever + * arrives without it. + */ +function retainedBytes(attachment: Attachment): number { + return attachment.size ?? Math.floor((attachment.data.length * 3) / 4); +} + +function assertWithinBudget( + bytes: number, + config: Config, + field: string, + name: string | undefined, + limitBytes: number = config.maxAttachmentBytes, +): void { + if (bytes > limitBytes) { throw ApiError.badRequest( - `Attachment${name ? ` '${name}'` : ""} is ${bytes} bytes, above the ${config.maxAttachmentBytes}-byte limit.`, + `Attachment${name ? ` '${name}'` : ""} is ${bytes} bytes, above the ${limitBytes}-byte limit.`, { code: "attachment_too_large", param: field }, ); } diff --git a/src/server.ts b/src/server.ts index b5c074b..26407aa 100644 --- a/src/server.ts +++ b/src/server.ts @@ -52,10 +52,12 @@ export async function buildServer(ctx: AppContext): Promise { // Upstream calls are long; never let Fastify cut a streaming response short. requestTimeout: 0, connectionTimeout: 0, - // Shutdown must not wait for an in-flight SSE stream to finish: `close()` - // also tears down hijacked sockets, so SIGTERM cannot hang for the whole - // upstream timeout budget. - forceCloseConnections: true, + // Shutdown must not wait for an in-flight SSE stream to finish, and an + // in-flight buffered completion must not be cut off either. `"idle"` closes + // keep-alive sockets immediately but lets active requests run, so the + // bounded drain in `http/shutdown.ts` is what force-closes the remainder + // (including hijacked SSE sockets) once the deadline expires. + forceCloseConnections: "idle", }) as unknown as FastifyInstance; // Every response — JSON, error and SSE alike — carries the request id. @@ -66,17 +68,54 @@ export async function buildServer(ctx: AppContext): Promise { // ---------------------------------------------------------------- CORS --- const allowedOrigins = new Set(ctx.config.corsOrigins); const allowAnyOrigin = allowedOrigins.has("*"); + + /** + * Request headers a browser client is allowed to send. + * + * Beyond this gateway's own headers (`authorization`, `x-api-key`, + * `x-conversation-id`, `x-opencode-agent`) this lists what the official SDKs + * attach: the OpenAI SDKs send `openai-organization`/`openai-project` and + * `x-stainless-*` runtime tags, and the Anthropic SDK refuses to run in a + * browser unless the caller opts in with + * `anthropic-dangerous-direct-browser-access`. + */ + const ALLOWED_REQUEST_HEADERS = [ + "authorization", + "content-type", + "x-api-key", + "x-conversation-id", + "x-opencode-agent", + "anthropic-version", + "anthropic-beta", + "anthropic-dangerous-direct-browser-access", + "openai-beta", + "openai-organization", + "openai-project", + "x-stainless-arch", + "x-stainless-lang", + "x-stainless-os", + "x-stainless-package-version", + "x-stainless-runtime", + "x-stainless-runtime-version", + ].join(", "); + app.addHook("onRequest", async (request, reply) => { const origin = request.headers.origin; if (typeof origin !== "string" || origin.length === 0) return; if (allowAnyOrigin || allowedOrigins.has(origin)) { reply.header("access-control-allow-origin", allowAnyOrigin ? "*" : origin); - reply.header("access-control-allow-headers", "authorization, content-type, x-api-key, x-conversation-id, x-opencode-agent, anthropic-version, anthropic-beta, openai-beta"); + reply.header("access-control-allow-headers", ALLOWED_REQUEST_HEADERS); reply.header("access-control-allow-methods", "GET, POST, DELETE, OPTIONS"); reply.header("access-control-max-age", "86400"); + // `x-request-id` is set on every response; without this a browser cannot + // read it, although the reference documents it as the correlation id. + reply.header("access-control-expose-headers", "x-request-id"); reply.header("vary", "origin"); } if (request.method === "OPTIONS") { + // A disallowed origin still gets 204 without the CORS headers, so the + // browser blocks the response and never sends the real request. No + // gateway state or upstream work is involved. return reply.status(204).send(); } }); diff --git a/src/startup.ts b/src/startup.ts new file mode 100644 index 0000000..ddf2ab0 --- /dev/null +++ b/src/startup.ts @@ -0,0 +1,29 @@ +/** + * Operator-facing startup notes. + * + * Kept free of side effects so a unit test can assert what an operator is told + * without booting the gateway or loading `.env`. + */ +import path from "node:path"; +import { DEFAULT_API_KEY } from "./config.js"; + +/** + * Note printed when the gateway accepts the published development key. + * + * That is true both when nothing was configured (so the default was installed) + * and when `OPENCODE_API_KEYS` lists it explicitly — which is what + * `.env.example` ships and `pnpm setup` copies into `.env`. + * + * The structured log never carries the key itself (AGENTS.md forbids logging + * credentials); this note is written to stderr instead, and it names the key + * because it is already public knowledge. + */ +export function defaultApiKeyNote(projectRoot: string): string { + return ( + `Using the built-in default API key "${DEFAULT_API_KEY}": it is accepted because OPENCODE_API_KEYS ` + + "is unset or lists it explicitly.\n" + + `That key is public knowledge (it ships with the project), so replace it in ${path.join(projectRoot, ".env")} ` + + "before exposing this port to anything but localhost.\n" + + "Set OPENCODE_ALLOW_NO_AUTH=true to disable authentication entirely on a trusted host." + ); +} diff --git a/src/types/internal.ts b/src/types/internal.ts index 032652c..83e723b 100644 --- a/src/types/internal.ts +++ b/src/types/internal.ts @@ -119,8 +119,9 @@ export interface InternalRequest { /** OpenCode agent to run the turn with; defaults to the server configuration. */ agent?: string; /** - * Extra client-side correlation data echoed back in logs. Never forwarded to - * the upstream model provider. + * Extra client-side correlation data carried on the internal request for + * future use. It is never logged and never forwarded to the upstream model + * provider; the surfaces that accept it document it as accepted-and-ignored. */ metadata?: Record; } diff --git a/src/upstream/client.ts b/src/upstream/client.ts index 8e2eb0a..7f8d3ab 100644 --- a/src/upstream/client.ts +++ b/src/upstream/client.ts @@ -275,9 +275,10 @@ export class OpencodeClient { } /** - * Single-shot generation that bypasses the agent loop. Used by - * `count_tokens` estimates and by callers that explicitly request - * `x-opencode-raw-generation`. + * Single-shot generation that bypasses the agent loop. + * + * Available as an escape hatch; no request path uses it today (`count_tokens` + * reports an estimate instead, see `docs/ARCHITECTURE.md` §2.3). */ async generate( sessionId: string, diff --git a/src/upstream/completion.ts b/src/upstream/completion.ts index 8981a2b..e86198e 100644 --- a/src/upstream/completion.ts +++ b/src/upstream/completion.ts @@ -66,6 +66,8 @@ interface Prepared { promptText: string; promptFiles: OpencodePromptFileAttachment[]; key: string; + /** Permission profile the upstream session was created under. */ + permissionProfile: string; } /** Aggregated result of a non-streaming completion. */ @@ -213,6 +215,13 @@ async function prepare( const bridge = createToolBridge(request.tools, request.toolChoice, { parallelToolCalls: request.parallelToolCalls, }); + // Containment is a property of the request, not of the bridge: a caller that + // declares tools but disables them for this turn (`tool_choice: "none"`) still + // gets a session whose built-in tools are denied. A request that declares no + // tools keeps the unrestricted agent. + const denyNativeTools = request.tools.length > 0; + const permissionProfile = permissionProfileFor(config, denyNativeTools); + const permissions = permissionsFor(config, denyNativeTools); const toolsHash = hashTools(request.tools); const acquire = sessions.acquire({ key: request.conversationKey, @@ -222,6 +231,7 @@ async function prepare( variant: decision.variant, messages: request.messages, toolsHash, + permissionProfile, }); const key = acquire.key; @@ -240,7 +250,7 @@ async function prepare( title: deriveTitle(request.messages), location: { directory: config.workdir }, metadata: { gateway: "opencode-api", surface: request.surface }, - ...(permissionsFor(config, bridge.active) ? { permissions: permissionsFor(config, bridge.active) as never } : {}), + ...(permissions ? { permissions: permissions as never } : {}), }); sessionId = created.id; reused = false; @@ -261,6 +271,7 @@ async function prepare( promptText: text, promptFiles: files, key, + permissionProfile, }; } catch (error) { // `acquire()` already reserved the record when it reused a session. Anything @@ -271,6 +282,14 @@ async function prepare( } } +/** + * How long a turn keeps waiting for a terminal event after the upstream event + * stream reconnected. The frames inside the gap are gone for good, so the wait + * is bounded: a terminal event that arrives inside the window still completes + * the turn normally, and anything later fails the turn explicitly. + */ +const STREAM_GAP_GRACE_MS = 5_000; + async function* execute( prepared: Prepared, deps: CompletionDeps, @@ -281,6 +300,13 @@ async function* execute( const queue = new EventQueue(); const unsubscribe = events.subscribe(sessionId, (event) => queue.push(event)); + // A reconnect means the frames inside the gap were dropped, so this turn can no + // longer be trusted to reach a terminal event. Record the gap and bound the + // wait in the loop below; the same flag decides whether the turn fails. + let streamGap = false; + const offReconnect = events.onReconnect(() => { + streamGap = true; + }); let sessionSettled = false; try { @@ -321,9 +347,35 @@ async function* execute( let bridgedToolCalls = 0; const deadline = Date.now() + config.upstreamRequestTimeoutMs; let firstTokenDeadline = Date.now() + config.upstreamFirstTokenTimeoutMs; + let gapDeadline: number | undefined; for (;;) { const remaining = deadline - Date.now(); + if (streamGap) { + // Anchor the grace window once, on the first iteration that observes the + // gap: every frame inside it was lost, so waiting for the full request + // budget (default 10 min) would either 504 or, worse, report a truncated + // answer as a normal stop. `Math.min(remaining, …)` keeps a short global + // budget authoritative, and the specific error wins over a generic timeout. + const graceExpiry = gapDeadline ?? Date.now() + Math.min(Math.max(remaining, 0), STREAM_GAP_GRACE_MS); + gapDeadline = graceExpiry; + if (Date.now() >= graceExpiry) { + await safeInterrupt(client, sessionId, log); + metrics.completions.inc({ + surface: prepared.request.surface, + model: prepared.resolved.canonical, + stream: String(prepared.request.stream), + finish_reason: "event_stream_lost", + }); + yield { + kind: "error", + error: ApiError.unavailable("OpenCode event stream reconnected mid-turn; the response may be incomplete.", { + code: "event_stream_lost", + }), + }; + return; + } + } if (remaining <= 0) { await safeInterrupt(client, sessionId, log); yield { kind: "error", error: ApiError.timeout("OpenCode did not finish the request in time.") }; @@ -335,7 +387,8 @@ async function* execute( return; } - const next = await queue.next(Math.min(remaining, 1_000), options.signal); + const waitBudget = gapDeadline === undefined ? remaining : Math.min(remaining, gapDeadline - Date.now()); + const next = await queue.next(Math.min(Math.max(waitBudget, 0), 1_000), options.signal); if (next === "aborted") { await safeInterrupt(client, sessionId, log); yield { kind: "error", error: new ApiError(499, "timeout_error", "Client disconnected.") }; @@ -567,6 +620,7 @@ async function* execute( variant: prepared.decision.variant, messages: prepared.request.messages, toolsHash: hashTools(prepared.request.tools), + permissionProfile: prepared.permissionProfile, }); yield { @@ -580,6 +634,7 @@ async function* execute( } } finally { unsubscribe(); + offReconnect(); // The record is only cleared by `finalise()` when the turn completed. On any // other exit — abort, timeout, upstream failure, or the consumer abandoning // the generator — drop it, otherwise the record would stay `busy: true` and @@ -742,15 +797,31 @@ function modalityFor(kind: Attachment["kind"]): string | undefined { * Built-in OpenCode tool actions denied for sessions whose tools are bridged * through the prompt. Without this the model reaches for its own shell or web * tools instead of emitting a bridged tool call. + * + * Exported so the bridge prompt and the enforcement can be asserted against the + * same list. */ -const BRIDGE_DENIED_ACTIONS = ["bash", "webfetch", "websearch", "edit", "write", "patch", "task", "skill"] as const; +export const BRIDGE_DENIED_ACTIONS = ["bash", "webfetch", "websearch", "edit", "write", "patch", "task", "skill"] as const; + +/** + * Permission profile of the upstream session a request needs. + * + * A session is created with, or without, the bridge deny rules; that decision is + * part of its identity, so a session created under one profile is never handed + * to a request that needs the other. Derived from the effective decision rather + * than from `config.toolBridgeDenyNativeTools` alone: a request that declares no + * tools runs unrestricted even when the deny list is enabled. + */ +function permissionProfileFor(config: Config, denyNativeTools: boolean): string { + return denyNativeTools && config.toolBridgeDenyNativeTools ? "deny-native-tools" : "default"; +} function permissionsFor( config: Config, - bridgeActive: boolean, + denyNativeTools: boolean, ): { action: string; resource: string; effect: string }[] | undefined { const rules: { action: string; resource: string; effect: string }[] = [...(config.agentPermissions ?? [])]; - if (bridgeActive && config.toolBridgeDenyNativeTools) { + if (denyNativeTools && config.toolBridgeDenyNativeTools) { for (const action of BRIDGE_DENIED_ACTIONS) { rules.push({ action, resource: "*", effect: "deny" }); } diff --git a/src/upstream/events.ts b/src/upstream/events.ts index 6c302a6..418a45e 100644 --- a/src/upstream/events.ts +++ b/src/upstream/events.ts @@ -166,6 +166,10 @@ export class EventHub { this.#reconnectDelayMs = 250; const reader = response.body.getReader(); + // `decoder` and `buffer` are locals of this method ON PURPOSE: they hold + // half-received frame state, which must never survive into the next + // connection. Hoisting them would let a truncated frame from the previous + // connection prefix the first frame of the new one. const decoder = new TextDecoder(); let buffer = ""; diff --git a/src/upstream/process.ts b/src/upstream/process.ts index acb7846..39ffb55 100644 --- a/src/upstream/process.ts +++ b/src/upstream/process.ts @@ -30,6 +30,14 @@ export interface UpstreamProcessOptions { export type EndpointSource = "env" | "spawned" | "discovered"; +/** + * Message shapes that mean "this port is taken, try the next one". + * + * Deliberately narrow: `#spawn()` walks ten candidate ports, so a false positive + * multiplies a slow failure by ten. + */ +const PORT_IN_USE = /EADDRINUSE|address already in use/i; + export interface UpstreamEndpoint { url: string; password?: string; @@ -68,6 +76,20 @@ export class UpstreamProcess { #child?: SpawnedChild; #starting?: Promise; #stopping = false; + /** + * Set by `shutdown()` only. Unlike `#stopping` — which merely suppresses the + * crash report for a process the gateway killed itself — this state is + * permanent: once the process-exit path ran, no endpoint may be published and + * no new `opencode serve` may be started. + */ + #terminated = false; + /** + * Every child this instance ever spawned, including one that is still waiting + * for readiness and therefore not yet tracked by `#child`. The process `exit` + * hook and `shutdown()` iterate this set, so such a child cannot outlive the + * gateway and keep the internal port. + */ + readonly #liveChildren = new Set(); #lastError?: string; #lastStartedAt?: number; #binary?: string; @@ -117,6 +139,7 @@ export class UpstreamProcess { /** Return a live endpoint, spawning or discovering one when necessary. */ async resolve(): Promise { + this.#assertNotTerminated(); if (this.#endpoint && (this.#endpoint.source !== "spawned" || isProcessAlive(this.#endpoint.pid))) { return this.#endpoint; } @@ -161,6 +184,42 @@ export class UpstreamProcess { }); } + /** + * Terminal counterpart of `stop()` for the process-exit path. + * + * `stop()` stays deliberately non-terminal: `POST /admin/upstream/restart` + * (`src/routes/admin.ts`) and the retry paths call `stop()`/`invalidate()` and + * then `resolve()` again to get a replacement server, which + * `test/process.test.ts` pins. `shutdown()` marks the instance terminal first, + * so a `resolve()` that raced the shutdown can no longer start a server, and + * then terminates everything this instance spawned: + * + * * a start that is still waiting for readiness has not reached `#child` yet + * and is bounded only by `upstreamStartTimeoutMs` (30 s by default, longer + * than the 10 s drain), so its already-spawned children are killed now so + * the pending `resolve()` settles instead of outliving `process.exit(0)`; + * * the adopted child is then stopped exactly as `stop()` does. + * + * After it returns no child of this instance is alive and `resolve()` rejects. + */ + async shutdown(): Promise { + this.#terminated = true; + this.#stopping = true; + + const starting = this.#starting; + if (starting) { + // `stop()` handles the adopted child gracefully; every other child this + // instance has already spawned is killed here. + this.#killLiveChildren(this.#child); + await starting.catch(() => undefined); + } + + await this.stop(); + // `stop()` only knows `#child`: nothing else this instance started may + // survive a terminal shutdown, in-process or at `process.exit()`. + this.#killLiveChildren(); + } + /** * Take ownership of a freshly spawned server. * @@ -184,6 +243,7 @@ export class UpstreamProcess { async #resolveInternal(): Promise { this.#lastError = undefined; + this.#assertNotTerminated(); if (this.#config.upstreamUrl) { const endpoint: UpstreamEndpoint = { @@ -192,6 +252,7 @@ export class UpstreamProcess { source: "env", }; if (await this.#probe(endpoint)) { + this.#assertNotTerminated(); this.#endpoint = endpoint; return endpoint; } @@ -219,8 +280,13 @@ export class UpstreamProcess { } } + // A shutdown that arrived while the spawn was failing must not spend another + // probe budget on discovery, and must not publish an endpoint afterwards. + this.#assertNotTerminated(); + const discovered = await this.#discover(); if (discovered) { + this.#assertNotTerminated(); this.#endpoint = discovered; this.#log.info({ url: discovered.url, pid: discovered.pid }, "using discovered OpenCode service"); return discovered; @@ -269,6 +335,7 @@ export class UpstreamProcess { // A previous `stop()` set this flag so the exit of the process it killed is // not reported as a crash. A fresh spawn starts a new supervision cycle. this.#stopping = false; + this.#assertNotTerminated(); if (!this.#binary) { this.#binary = this.#findBinary(this.#config.upstreamBin); } @@ -277,6 +344,10 @@ export class UpstreamProcess { "OpenCode CLI executable not found. Set OPENCODE_BIN to the full path of the opencode binary.", ); } + // Installed before the first child exists, so a start that never reaches + // readiness is still covered when the gateway dies without running its + // shutdown handler. + this.#installExitHook(); const logDir = path.join(this.#config.dataDir, "logs"); fs.mkdirSync(logDir, { recursive: true }); @@ -289,14 +360,28 @@ export class UpstreamProcess { const port = this.#config.upstreamPort + attempt; try { const spawned = await this.#spawnOnPort(port, logDir); + // A `shutdown()` that arrived while the server was starting must not + // adopt it: the process-exit path has already cleared the handle it + // would look at, so the child would outlive the gateway. + if (this.#terminated) { + try { + spawned.child.kill("SIGKILL"); + } catch { + /* already gone */ + } + throw shuttingDownError(); + } // Track the child so `stop()` and shutdown can terminate it; without // this every restart would leak a server process and its port. this.#adopt(spawned.child); - this.#installExitHook(); return spawned; } catch (error) { lastError = error instanceof Error ? error.message : String(error); - if (!/EADDRINUSE|address already in use|port/i.test(lastError)) throw error; + // Only a port collision justifies the next candidate port. The check + // used to include a bare `port`, which also matched "did not report + // readiness" — a hung start was then retried ten times, spawning ten + // servers over five minutes, instead of failing once. + if (!PORT_IN_USE.test(lastError)) throw error; } } @@ -317,6 +402,13 @@ export class UpstreamProcess { const child = this.#spawnChild(this.#binary as string, args); + // Registered synchronously: from here on the child is a process that exists, + // even though it will only become `#child` once it reports readiness. + this.#liveChildren.add(child); + child.once("exit", () => { + this.#liveChildren.delete(child); + }); + const logStream = fs.createWriteStream(path.join(logDir, `opencode-${port}.log`), { flags: "a" }); return await new Promise((resolve, reject) => { @@ -401,19 +493,34 @@ export class UpstreamProcess { * Best-effort synchronous kill so the private server does not outlive the * gateway when the process is terminated without running the shutdown handler * (for example SIGKILL, or a task-manager kill on Windows). + * + * Every child this instance spawned is iterated, not only the adopted + * `#child`: a start that is still waiting for readiness has no handle there + * yet, and killing it at exit time is the last chance to release its port. */ #installExitHook(): void { if (this.#exitHookInstalled) return; this.#exitHookInstalled = true; process.once("exit", () => { - const child = this.#child; - if (!child || child.exitCode !== null) return; + this.#killLiveChildren(); + }); + } + + /** SIGKILL every child this instance spawned that is still alive, except `skip`. */ + #killLiveChildren(skip?: SpawnedChild): void { + for (const child of this.#liveChildren) { + if (child === skip || child.exitCode !== null) continue; try { child.kill("SIGKILL"); } catch { - /* nothing more we can do at exit time */ + /* already gone */ } - }); + } + } + + /** Terminal-state guard: nothing may resolve or spawn after `shutdown()`. */ + #assertNotTerminated(): void { + if (this.#terminated) throw shuttingDownError(); } /** @@ -462,6 +569,11 @@ export class UpstreamProcess { } } +/** The error every entry point throws once `shutdown()` made the instance terminal. */ +function shuttingDownError(): ApiError { + return ApiError.unavailable("upstream is shutting down", { code: "upstream_unavailable" }); +} + export function authHeaders(password: string | undefined): Record { if (!password) return {}; const token = Buffer.from(`opencode:${password}`, "utf8").toString("base64"); diff --git a/src/upstream/sessions.ts b/src/upstream/sessions.ts index a8888f6..6dc127a 100644 --- a/src/upstream/sessions.ts +++ b/src/upstream/sessions.ts @@ -24,12 +24,35 @@ import type { InternalMessage } from "../types/internal.js"; /** Maximum number of cached sessions sharing one conversation root. */ const MAX_CANDIDATES_PER_ROOT = 4; +/** + * Sentinel for a record whose permission profile is unknown. + * + * A record persisted before the profile existed cannot be proven to match a live + * request, so it is loaded (the sweeper still expires it) but never reused. No + * request ever produces this value: `permissionProfileFor()` returns either + * `"default"` or `"deny-native-tools"`. + */ +const UNKNOWN_PERMISSION_PROFILE = "unknown"; + +/** Sentinel for a record whose tool fingerprint is unknown. Never matches a request. */ +const UNKNOWN_TOOLS_HASH = "unknown"; + export interface SessionRecord { key: string; sessionId: string; model: string; agent: string; variant?: string; + /** + * Permission profile the upstream session was created under. + * + * The built-in tool deny rules are applied when the request declares tools, so + * a session created without them must never serve a request that needs them + * (and vice versa). + */ + permissionProfile: string; + /** Fingerprint of the tool definitions the session was created for. */ + toolsHash: string; /** Number of client messages already present in the upstream session. */ deliveredCount: number; /** Hash over the first `deliveredCount` client messages. */ @@ -48,6 +71,12 @@ export interface AcquireInput { messages: InternalMessage[]; /** Fingerprint of the tool definitions, so sessions are not shared across tool sets. */ toolsHash: string; + /** + * Permission profile the session needs. Compared against the stored profile so + * a session created with a different deny/open decision is never reused; this + * also covers the explicit `x-conversation-id` path, which bypasses `deriveKey`. + */ + permissionProfile: string; /** * Skip every cached candidate and start a new upstream session while keeping * the conversation key, so the replacement is cached under the same key (used @@ -144,6 +173,8 @@ export class SessionStore { let sawBusy = false; let sawModelChange = false; + let sawPermissionChange = false; + let sawToolChange = false; let sawShrink = false; for (const record of candidates) { @@ -155,6 +186,18 @@ export class SessionStore { sawModelChange = true; continue; } + // The session carries the permission set it was created with and the tool + // set it was created for. Reusing it for a request that needs either a + // different one would leave the agent unrestricted (or deny it tools + // nobody asked to deny), so both are part of the identity. + if (record.permissionProfile !== input.permissionProfile) { + sawPermissionChange = true; + continue; + } + if (record.toolsHash !== input.toolsHash) { + sawToolChange = true; + continue; + } if (record.deliveredCount > messages.length) { sawShrink = true; continue; @@ -186,9 +229,13 @@ export class SessionStore { ? "session-busy" : sawModelChange ? "model-or-agent-changed" - : sawShrink - ? "conversation-shrank" - : "prefix-mismatch"; + : sawPermissionChange + ? "permission-profile-changed" + : sawToolChange + ? "tool-set-changed" + : sawShrink + ? "conversation-shrank" + : "prefix-mismatch"; return { reused: false, pending: messages, messages, key, reason }; } @@ -204,6 +251,8 @@ export class SessionStore { model: input.model, agent: input.agent, variant: input.variant, + permissionProfile: input.permissionProfile, + toolsHash: input.toolsHash, deliveredCount: input.messages.length, prefixHash: hashMessages(input.messages), createdAt: existing?.createdAt ?? Date.now(), @@ -359,14 +408,45 @@ export class SessionStore { return path.join(this.#config.dataDir, "sessions.json"); } + /** + * Fingerprint of the process that owns the persisted `ses_*` ids. + * + * `OPENCODE_SESSION_PERSIST` is only meaningful while the upstream server that + * created those ids survives: they die with it, and the default configuration + * spawns a fresh `opencode serve` for every gateway run + * (`UpstreamProcess#spawn`). `Config.instanceId` defaults to + * `opencode-api-`, so a restart reads a different fingerprint and the + * stale cache is dropped instead of costing one wasted `prompt()` (404) and one + * discarded session per conversation. Pinning `OPENCODE_INSTANCE_ID` + * deliberately keeps the cache across restarts, which is only correct for a + * long-lived upstream (`OPENCODE_SERVER_URL`). + */ + #fingerprint(): string { + return this.#config.instanceId; + } + #load(): void { try { const raw = fs.readFileSync(this.#persistPath(), "utf8"); const parsed: unknown = JSON.parse(raw); if (typeof parsed !== "object" || parsed === null) return; + const envelope = parsed as Record; + const fingerprint = envelope["fingerprint"]; + // An unversioned file (written before this format) has no fingerprint and + // is treated like a foreign one: its ids cannot be proven to belong to the + // upstream this process is talking to. + if (envelope["version"] !== PERSIST_VERSION || fingerprint !== this.#fingerprint()) { + this.#log.info( + { persistedBy: typeof fingerprint === "string" ? fingerprint : "unknown" }, + "ignoring sticky sessions persisted by another gateway instance", + ); + return; + } + const records = envelope["records"]; + if (typeof records !== "object" || records === null) return; const now = Date.now(); let restored = 0; - for (const value of Object.values(parsed as Record)) { + for (const value of Object.values(records as Record)) { const record = restoreRecord(value, now, this.#config.sessionTtlMs); if (!record) continue; const candidates = this.#records.get(record.key) ?? []; @@ -391,10 +471,15 @@ export class SessionStore { if (!this.#config.sessionPersist) return; try { fs.mkdirSync(this.#config.dataDir, { recursive: true }); - const payload: Record = {}; + const records: Record = {}; for (const record of this.list()) { - payload[`${record.key}:${record.sessionId}`] = { ...record, busy: false }; + records[`${record.key}:${record.sessionId}`] = { ...record, busy: false }; } + const payload: PersistedSessions = { + version: PERSIST_VERSION, + fingerprint: this.#fingerprint(), + records, + }; fs.writeFileSync(this.#persistPath(), JSON.stringify(payload), "utf8"); } catch (error) { this.#log.warn({ err: error instanceof Error ? error.message : String(error) }, "could not persist sessions"); @@ -402,6 +487,23 @@ export class SessionStore { } } +/** + * Shape of `/sessions.json`. + * + * `fingerprint` identifies the process that owns the persisted `ses_*` ids, so a + * cache written by an earlier gateway run (whose upstream server is gone) is + * ignored on load. `version` is bumped whenever the record shape or the + * fingerprint rule changes; an older or unreadable file is dropped rather than + * migrated, because the cache is only an optimisation. + */ +interface PersistedSessions { + version: number; + fingerprint: string; + records: Record; +} + +const PERSIST_VERSION = 1; + function isNonEmptyString(value: unknown): value is string { return typeof value === "string" && value.length > 0; } @@ -445,12 +547,18 @@ function restoreRecord(value: unknown, now: number, ttlMs: number): SessionRecor const variant = candidate["variant"]; const reusedCount = candidate["reusedCount"]; + const permissionProfile = candidate["permissionProfile"]; + const toolsHash = candidate["toolsHash"]; return { key, sessionId, model, agent, variant: isNonEmptyString(variant) ? variant : undefined, + // A record written before these fields existed cannot be proven to match the + // request in flight, so it is kept but never reused. + permissionProfile: isNonEmptyString(permissionProfile) ? permissionProfile : UNKNOWN_PERMISSION_PROFILE, + toolsHash: isNonEmptyString(toolsHash) ? toolsHash : UNKNOWN_TOOLS_HASH, deliveredCount, prefixHash, createdAt, @@ -475,6 +583,7 @@ export function deriveKey(input: AcquireInput): string { agent: input.agent, variant: input.variant ?? null, tools: input.toolsHash, + permissions: input.permissionProfile, root: input.messages[0] ?? null, }), ) diff --git a/test/anthropic-count-tokens.test.ts b/test/anthropic-count-tokens.test.ts index 131dd45..94e4d51 100644 --- a/test/anthropic-count-tokens.test.ts +++ b/test/anthropic-count-tokens.test.ts @@ -10,12 +10,16 @@ import type { FastifyInstance } from "fastify"; import { afterEach, describe, expect, it } from "vitest"; import { createToolBridge } from "../src/adapter/common/tools.js"; +import { parseAnthropicCountTokensBody, toInternalRequest } from "../src/adapter/anthropic/messages.js"; import { buildServer } from "../src/server.js"; import type { ToolDefinition } from "../src/types/internal.js"; import { createTestContext } from "./helpers/context.js"; const AUTH = { authorization: "Bearer test-key" }; const MODEL = "deepseek-v4.1-flash-free"; +/** 1x1 PNG, matching the fixture used by the messages tests. */ +const PNG_1X1 = + "iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAYAAAAfFcSJAAAADUlEQVR42mP8z8BQDwAEhQGAhKmMIQAAAABJRU5ErkJggg=="; const apps: FastifyInstance[] = []; @@ -82,4 +86,36 @@ describe("POST /v1/messages/count_tokens estimate", () => { expect(disabled).toBeLessThan(auto); expect(createToolBridge([{ name: "noop", description: "Do nothing", parameters: { type: "object" } }], "none").instructions).toBe(""); }); + + it("keeps a media placeholder inside tool_result content without resolving it", async () => { + const body = parseAnthropicCountTokensBody({ + model: MODEL, + messages: [ + { role: "user", content: "Look it up" }, + { role: "assistant", content: [{ type: "tool_use", id: "toolu_1", name: "lookup", input: {} }] }, + { + role: "user", + content: [ + { + type: "tool_result", + tool_use_id: "toolu_1", + content: [{ type: "image", source: { type: "base64", media_type: "image/png", data: PNG_1X1 } }], + }, + ], + }, + ], + }); + + const internal = await toInternalRequest(body, { + ctx: createTestContext(), + model: `opencode/${MODEL}`, + resolveMedia: false, + }); + + const tool = internal.messages.at(-1); + expect(tool?.role).toBe("tool"); + expect(tool?.text).toBe("[image: image/png]"); + // `count_tokens` never fetches or decodes media, so nothing is attached. + expect(internal.messages.every((message) => (message.attachments ?? []).length === 0)).toBe(true); + }); }); diff --git a/test/anthropic.test.ts b/test/anthropic.test.ts index e8cc83e..3b6d408 100644 --- a/test/anthropic.test.ts +++ b/test/anthropic.test.ts @@ -9,6 +9,7 @@ import type { FastifyInstance } from "fastify"; import { afterEach, describe, expect, it } from "vitest"; import { ApiError } from "../src/errors.js"; +import { truncateAtStopSequence } from "../src/adapter/anthropic/messages.js"; import { buildServer } from "../src/server.js"; import { EMPTY_USAGE, type CompletionEvent, type InternalRequest, type Usage } from "../src/types/internal.js"; import { createTestContext, defaultScript, parseSse, type TestContextOptions } from "./helpers/context.js"; @@ -40,8 +41,23 @@ interface AnthropicErrorBody { interface StreamFrame { type: string; index?: number; - content_block?: { type?: string; id?: string; name?: string }; - delta?: { type?: string; stop_reason?: string | null; partial_json?: string; signature?: string }; + content_block?: { + type?: string; + id?: string; + name?: string; + thinking?: string; + text?: string; + signature?: string; + }; + delta?: { + type?: string; + stop_reason?: string | null; + stop_sequence?: string | null; + partial_json?: string; + signature?: string; + thinking?: string; + text?: string; + }; usage?: Record; message?: { id?: string; model?: string; role?: string }; } @@ -182,6 +198,120 @@ describe("POST /v1/messages", () => { expect(capture.request?.maxTokens).toBe(64); }); + it("resolves media inside tool_result content onto the user turn", async () => { + const capture: { request?: InternalRequest } = {}; + const { app } = await serverWith({ + onRun: (request) => { + capture.request = request; + }, + }); + + const response = await post(app, "/v1/messages", { + model: MODEL, + max_tokens: 64, + messages: [ + { role: "user", content: "What is the weather?" }, + { role: "assistant", content: [{ type: "tool_use", id: "toolu_shot", name: "screenshot", input: {} }] }, + { + role: "user", + content: [ + { + type: "tool_result", + tool_use_id: "toolu_shot", + content: [ + { type: "text", text: "15 degrees" }, + { type: "image", source: { type: "base64", media_type: "image/png", data: PNG_1X1 } }, + ], + }, + ], + }, + ], + }); + + expect(response.statusCode).toBe(200); + const messages = capture.request?.messages ?? []; + const tool = messages.at(-1); + expect(tool?.role).toBe("tool"); + expect(tool?.text).toContain("15 degrees"); + expect(tool?.text).not.toContain("[image content omitted]"); + + // The attachment must ride on the user turn: that is the only turn + // `collectAttachments` forwards upstream. + const user = messages.filter((message) => message.role === "user").at(-1); + expect(user?.attachments?.[0]?.mime).toBe("image/png"); + expect(user?.attachments?.[0]?.kind).toBe("image"); + }); + + it("merges an inline-text document in tool_result content into the tool text", async () => { + const capture: { request?: InternalRequest } = {}; + const { app } = await serverWith({ + onRun: (request) => { + capture.request = request; + }, + }); + + const response = await post(app, "/v1/messages", { + model: MODEL, + max_tokens: 64, + messages: [ + { role: "user", content: "Read the report" }, + { role: "assistant", content: [{ type: "tool_use", id: "toolu_doc", name: "read", input: {} }] }, + { + role: "user", + content: [ + { + type: "tool_result", + tool_use_id: "toolu_doc", + content: [ + { type: "text", text: "see" }, + { type: "document", source: { type: "text", media_type: "text/plain", data: "15 degrees" } }, + ], + }, + ], + }, + ], + }); + + expect(response.statusCode).toBe(200); + const messages = capture.request?.messages ?? []; + const tool = messages.at(-1); + expect(tool?.role).toBe("tool"); + expect(tool?.text).toContain("see"); + expect(tool?.text).toContain("15 degrees"); + expect(tool?.text).not.toContain("[document content omitted]"); + // An inline-text document carries no bytes, so nothing is forwarded. + expect(messages.every((message) => (message.attachments ?? []).length === 0)).toBe(true); + }); + + it("marks a failed tool_result in the tool text", async () => { + const capture: { request?: InternalRequest } = {}; + const { app } = await serverWith({ + onRun: (request) => { + capture.request = request; + }, + }); + + const response = await post(app, "/v1/messages", { + model: MODEL, + max_tokens: 64, + messages: [ + { role: "user", content: "Check the status" }, + { role: "assistant", content: [{ type: "tool_use", id: "toolu_err", name: "status", input: {} }] }, + { + role: "user", + content: [ + { type: "tool_result", tool_use_id: "toolu_err", is_error: true, content: "boom" }, + ], + }, + ], + }); + + expect(response.statusCode).toBe(200); + const tool = (capture.request?.messages ?? []).at(-1); + expect(tool?.role).toBe("tool"); + expect(tool?.text).toBe("[tool error]\nboom"); + }); + it("resolves the media blocks of one message concurrently, keeping declaration order", async () => { const fixture = createServer((_request, response) => { setTimeout(() => { @@ -343,6 +473,14 @@ describe("POST /v1/messages", () => { 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"); + + // Anthropic's streaming reference opens the thinking block with an empty + // `signature` field and delivers the real value in the signature_delta; the + // Python SDK types `ThinkingBlock.signature` as a required `str`. + const thinkingStart = payloads.find( + (frame) => frame.type === "content_block_start" && frame.content_block?.type === "thinking", + ); + expect(thinkingStart?.content_block).toEqual({ type: "thinking", thinking: "", signature: "" }); }); it("keeps one thinking and one text block across agent steps", async () => { @@ -681,6 +819,91 @@ describe("POST /v1/messages", () => { const payloads = parseSse(streamed.body).map((frame) => JSON.parse(frame.data) as StreamFrame); const inputDelta = payloads.find((frame) => frame.delta?.type === "input_json_delta"); expect(inputDelta?.delta?.partial_json).toBe("{}"); + + // A tool-only turn has no text block, so the streamed content must match the + // buffered array: one tool_use block at index 0 and no synthetic empty text. + const starts = payloads.filter((frame) => frame.type === "content_block_start"); + expect(starts.map((frame) => [frame.index, frame.content_block?.type])).toEqual([[0, "tool_use"]]); + expect(starts.some((frame) => frame.content_block?.type === "text")).toBe(false); + expect(starts.map((frame) => [frame.content_block?.type, frame.content_block?.name])).toEqual( + bufferedBody.content.map((block) => [block["type"], block["name"]]), + ); + }); + + it("keeps a thinking-plus-tool turn at matching block indexes on both paths", async () => { + const events: CompletionEvent[] = [ + { + kind: "start", + sessionId: "ses_think_tool", + messageId: "msg_think_tool", + model: CANONICAL_MODEL, + agent: "build", + reusedSession: false, + reasoningEnabled: true, + }, + { kind: "reasoning_delta", text: "Weighing.", ordinal: 0 }, + { kind: "reasoning_end", text: "Weighing.", ordinal: 0 }, + { kind: "tool_calls", calls: [{ id: "toolu_think", name: "lookup", arguments: "{}" }] }, + { kind: "usage", usage: usage(6, 3) }, + { kind: "end", finishReason: "tool_calls", usage: usage(6, 3), messageId: "msg_think_tool" }, + ]; + const { app } = await serverWith({ script: () => events }); + const payload = (stream: boolean) => ({ + model: MODEL, + max_tokens: 64, + stream, + thinking: { type: "enabled", budget_tokens: 2_048 }, + messages: [{ role: "user", content: "Think and look it up" }], + tools: [{ name: "lookup", input_schema: { type: "object" } }], + }); + + const buffered = await post(app, "/v1/messages", payload(false)); + const streamed = await post(app, "/v1/messages", payload(true)); + expect(buffered.statusCode).toBe(200); + expect(streamed.statusCode).toBe(200); + + const bufferedBody = JSON.parse(buffered.body) as AnthropicResponseBody; + expect(bufferedBody.content.map((block) => block["type"])).toEqual(["thinking", "tool_use"]); + + const payloads = parseSse(streamed.body).map((frame) => JSON.parse(frame.data) as StreamFrame); + const starts = payloads.filter((frame) => frame.type === "content_block_start"); + expect(starts.map((frame) => [frame.index, frame.content_block?.type])).toEqual([ + [0, "thinking"], + [1, "tool_use"], + ]); + }); + + it("emits no content block when the turn produced nothing", async () => { + const events: CompletionEvent[] = [ + { + kind: "start", + sessionId: "ses_empty", + messageId: "msg_empty", + model: CANONICAL_MODEL, + agent: "build", + reusedSession: false, + reasoningEnabled: false, + }, + { kind: "end", finishReason: "stop", usage: usage(2, 0), messageId: "msg_empty" }, + ]; + const { app } = await serverWith({ script: () => events }); + const payload = (stream: boolean) => ({ + model: MODEL, + max_tokens: 8, + stream, + messages: [{ role: "user", content: "hi" }], + }); + + const buffered = await post(app, "/v1/messages", payload(false)); + const body = JSON.parse(buffered.body) as AnthropicResponseBody; + expect(body.content).toEqual([]); + expect(body.stop_reason).toBe("end_turn"); + + const streamed = await post(app, "/v1/messages", payload(true)); + expect(streamed.statusCode).toBe(200); + const payloads = parseSse(streamed.body).map((frame) => JSON.parse(frame.data) as StreamFrame); + expect(payloads.some((frame) => frame.type === "content_block_start")).toBe(false); + expect(payloads.at(-1)?.type).toBe("message_stop"); }); it("emits an SSE error frame for a mid-stream failure", async () => { @@ -713,6 +936,208 @@ describe("POST /v1/messages", () => { expect(payload.error.type).toBe("overloaded_error"); expect(payload.error.message).toBe("Model is unavailable."); }); + + it("honours stop_sequences identically on the buffered and streamed paths", async () => { + // The sequence is split across deltas on purpose: "hello E" + "ND wor" + "ld". + // Session consequence: generation is *not* interrupted, so the upstream turn + // completes and the sticky record keeps the caller's input prefix. A client + // that replays the conversation containing the truncated assistant text sends + // a different prefix, which fails `acquire()`'s prefix check, so the session + // is not reused; concurrent work on that session is never disturbed. + const events: CompletionEvent[] = [ + { + kind: "start", + sessionId: "ses_stop", + messageId: "msg_stop", + model: CANONICAL_MODEL, + agent: "build", + reusedSession: false, + reasoningEnabled: false, + }, + { kind: "text_delta", text: "hello E", ordinal: 0 }, + { kind: "text_delta", text: "ND wor", ordinal: 0 }, + { kind: "text_delta", text: "ld", ordinal: 0 }, + { kind: "usage", usage: usage(5, 4) }, + { kind: "end", finishReason: "stop", usage: usage(5, 4), messageId: "msg_stop" }, + ]; + const { app } = await serverWith({ script: () => events }); + const payload = (stream: boolean) => ({ + model: MODEL, + max_tokens: 64, + stream, + stop_sequences: ["END"], + messages: [{ role: "user", content: "Say something" }], + }); + + const buffered = await post(app, "/v1/messages", payload(false)); + expect(buffered.statusCode).toBe(200); + const body = JSON.parse(buffered.body) as AnthropicResponseBody; + expect(body.content).toEqual([{ type: "text", text: "hello " }]); + expect(body.stop_reason).toBe("stop_sequence"); + expect(body.stop_sequence).toBe("END"); + // The upstream turn still ran to completion, so `usage` counts every token it + // produced, including the text after the stop sequence. + expect(body.usage.output_tokens).toBe(4); + + const streamed = await post(app, "/v1/messages", payload(true)); + expect(streamed.statusCode).toBe(200); + const payloads = parseSse(streamed.body).map((frame) => JSON.parse(frame.data) as StreamFrame); + const visible = payloads + .filter((frame) => frame.delta?.type === "text_delta") + .map((frame) => frame.delta?.text ?? "") + .join(""); + expect(visible).toBe("hello "); + expect(visible).not.toContain("END"); + const messageDelta = payloads.find((frame) => frame.type === "message_delta"); + expect(messageDelta?.delta?.stop_reason).toBe("stop_sequence"); + expect(messageDelta?.delta?.stop_sequence).toBe("END"); + // Shared-helper invariant: the streamed text equals the buffered text. + expect(visible).toBe(body.content[0]?.["text"]); + }); + + it("leaves text untouched when no stop sequence matches", async () => { + const events: CompletionEvent[] = [ + { + kind: "start", + sessionId: "ses_nostop", + messageId: "msg_nostop", + model: CANONICAL_MODEL, + agent: "build", + reusedSession: false, + reasoningEnabled: false, + }, + { kind: "text_delta", text: "hello ", ordinal: 0 }, + { kind: "text_delta", text: "world", ordinal: 0 }, + { kind: "usage", usage: usage(3, 2) }, + { kind: "end", finishReason: "stop", usage: usage(3, 2), messageId: "msg_nostop" }, + ]; + const { app } = await serverWith({ script: () => events }); + const payload = (stream: boolean) => ({ + model: MODEL, + max_tokens: 64, + stream, + stop_sequences: ["END"], + messages: [{ role: "user", content: "Say something" }], + }); + + const buffered = await post(app, "/v1/messages", payload(false)); + const body = JSON.parse(buffered.body) as AnthropicResponseBody; + expect(body.content).toEqual([{ type: "text", text: "hello world" }]); + expect(body.stop_reason).toBe("end_turn"); + expect(body.stop_sequence).toBeNull(); + + const streamed = await post(app, "/v1/messages", payload(true)); + const payloads = parseSse(streamed.body).map((frame) => JSON.parse(frame.data) as StreamFrame); + const visible = payloads + .filter((frame) => frame.delta?.type === "text_delta") + .map((frame) => frame.delta?.text ?? "") + .join(""); + // A withheld suffix that never completes a sequence must still be flushed. + expect(visible).toBe("hello world"); + expect(visible).toBe(body.content[0]?.["text"]); + }); + + it("shares one stop-sequence helper between both paths", () => { + // Unmatched: a suffix that never completes a sequence is released, so the + // text is unchanged. + expect(truncateAtStopSequence("hello E", ["END"])).toEqual({ text: "hello E", stopSequence: null }); + expect(truncateAtStopSequence("keep", [])).toEqual({ text: "keep", stopSequence: null }); + // Matched: everything from the sequence onwards is dropped. + expect(truncateAtStopSequence("hello END world", ["END"])).toEqual({ text: "hello ", stopSequence: "END" }); + expect(truncateAtStopSequence("a EN D", ["EN"])).toEqual({ text: "a ", stopSequence: "EN" }); + }); + + it("ignores an empty stop sequence", async () => { + const capture: { request?: InternalRequest } = {}; + const events: CompletionEvent[] = [ + { + kind: "start", + sessionId: "ses_empty_stop", + messageId: "msg_empty_stop", + model: CANONICAL_MODEL, + agent: "build", + reusedSession: false, + reasoningEnabled: false, + }, + { kind: "text_delta", text: "hello END world", ordinal: 0 }, + { kind: "usage", usage: usage(3, 4) }, + { kind: "end", finishReason: "stop", usage: usage(3, 4), messageId: "msg_empty_stop" }, + ]; + const { app } = await serverWith({ + script: () => events, + onRun: (request) => { + capture.request = request; + }, + }); + + const response = await post(app, "/v1/messages", { + model: MODEL, + max_tokens: 64, + stop_sequences: [""], + messages: [{ role: "user", content: "Say something" }], + }); + + expect(response.statusCode).toBe(200); + const body = JSON.parse(response.body) as AnthropicResponseBody; + expect(body.content).toEqual([{ type: "text", text: "hello END world" }]); + expect(body.stop_reason).toBe("end_turn"); + expect(body.stop_sequence).toBeNull(); + // The empty entry never reaches the internal request, so it cannot match at + // position 0. + expect(capture.request?.stop).toBeUndefined(); + }); + + it("never truncates reasoning or tool arguments at a stop sequence", async () => { + const events: CompletionEvent[] = [ + { + kind: "start", + sessionId: "ses_stop_scope", + messageId: "msg_stop_scope", + model: CANONICAL_MODEL, + agent: "build", + reusedSession: false, + reasoningEnabled: true, + }, + { kind: "reasoning_delta", text: "thinking END here", ordinal: 0 }, + { kind: "reasoning_end", text: "thinking END here", ordinal: 0 }, + { kind: "text_delta", text: "hello ", ordinal: 0 }, + { kind: "tool_calls", calls: [{ id: "toolu_arg", name: "lookup", arguments: '{"q":"END"}' }] }, + { kind: "usage", usage: usage(4, 5) }, + { kind: "end", finishReason: "tool_calls", usage: usage(4, 5), messageId: "msg_stop_scope" }, + ]; + const { app } = await serverWith({ script: () => events }); + const payload = (stream: boolean) => ({ + model: MODEL, + max_tokens: 64, + stream, + thinking: { type: "enabled", budget_tokens: 2_048 }, + stop_sequences: ["END"], + messages: [{ role: "user", content: "Think and look it up" }], + tools: [{ name: "lookup", input_schema: { type: "object" } }], + }); + + const buffered = await post(app, "/v1/messages", payload(false)); + const body = JSON.parse(buffered.body) as AnthropicResponseBody; + expect(body.content[0]?.["thinking"]).toBe("thinking END here"); + expect(body.content[1]).toEqual({ type: "text", text: "hello " }); + expect(body.content[2]).toEqual({ type: "tool_use", id: "toolu_arg", name: "lookup", input: { q: "END" } }); + expect(body.stop_reason).toBe("tool_use"); + expect(body.stop_sequence).toBeNull(); + + const streamed = await post(app, "/v1/messages", payload(true)); + const payloads = parseSse(streamed.body).map((frame) => JSON.parse(frame.data) as StreamFrame); + expect(payloads.find((frame) => frame.delta?.type === "thinking_delta")?.delta?.thinking).toBe( + "thinking END here", + ); + expect(payloads.find((frame) => frame.delta?.type === "input_json_delta")?.delta?.partial_json).toBe( + '{"q":"END"}', + ); + const visible = payloads + .filter((frame) => frame.delta?.type === "text_delta") + .map((frame) => frame.delta?.text ?? "") + .join(""); + expect(visible).toBe("hello "); + }); }); describe("POST /v1/messages/count_tokens", () => { @@ -736,7 +1161,7 @@ describe("POST /v1/messages/count_tokens", () => { const body = JSON.parse(response.body) as { input_tokens: number; x_opencode: Record }; expect(Number.isInteger(body.input_tokens)).toBe(true); expect(body.input_tokens).toBeGreaterThan(0); - expect(body.x_opencode).toEqual({ estimated: true, method: "chars/4" }); + expect(body.x_opencode).toEqual({ estimated: true, method: "mixed" }); }); it("does not require max_tokens", async () => { diff --git a/test/completion.test.ts b/test/completion.test.ts index 7771360..fcfa83a 100644 --- a/test/completion.test.ts +++ b/test/completion.test.ts @@ -2,12 +2,12 @@ import { describe, expect, it } from "vitest"; import { createLogger } from "../src/logger.js"; import { createMetrics } from "../src/metrics/registry.js"; import { ApiError } from "../src/errors.js"; -import { collectCompletion, runCompletion, type CompletionDeps } from "../src/upstream/completion.js"; +import { BRIDGE_DENIED_ACTIONS, collectCompletion, runCompletion, type CompletionDeps } from "../src/upstream/completion.js"; import { EventHub, type EventListener } from "../src/upstream/events.js"; import { ModelRegistry } from "../src/upstream/models.js"; import { SessionStore } from "../src/upstream/sessions.js"; -import { TOOL_CALL_CLOSE, TOOL_CALL_OPEN } from "../src/adapter/common/tools.js"; -import type { CompletionEvent, InternalRequest } from "../src/types/internal.js"; +import { TOOL_CALL_CLOSE, TOOL_CALL_OPEN, createToolBridge } from "../src/adapter/common/tools.js"; +import type { CompletionEvent, InternalRequest, ToolDefinition } from "../src/types/internal.js"; import type { OpencodeEvent } from "../src/types/opencode.js"; import type { OpencodeClient } from "../src/upstream/client.js"; import { defaultModels, testConfig } from "./helpers/context.js"; @@ -116,6 +116,18 @@ function simpleTurn(text: string, finish = "stop"): OpencodeEvent[] { ]; } +const WEATHER: ToolDefinition = { name: "get_weather", description: "weather", parameters: { type: "object" } }; + +/** The `permissions` array the harness captured for one `createSession` call. */ +function capturedPermissions( + createSessionCalls: Array>, + index = 0, +): Array<{ action: string; resource: string; effect: string }> | undefined { + return createSessionCalls[index]?.["permissions"] as + | Array<{ action: string; resource: string; effect: string }> + | undefined; +} + describe("collectCompletion", () => { it("aggregates text, usage and the finish reason", async () => { const { deps } = harness(() => simpleTurn("Hello world")); @@ -214,6 +226,33 @@ describe("collectCompletion", () => { expect(promptCalls[0]?.text).toContain("at most one tool call block"); }); + it("denies the native tools whenever the request declares tools, even with tool_choice none", async () => { + const { deps, createSessionCalls } = harness(() => simpleTurn("ok")); + await collectCompletion(request({ tools: [WEATHER], toolChoice: "none" }), deps); + + const permissions = capturedPermissions(createSessionCalls); + expect(permissions?.map((rule) => rule.action).sort()).toEqual([...BRIDGE_DENIED_ACTIONS].sort()); + expect(permissions?.every((rule) => rule.effect === "deny" && rule.resource === "*")).toBe(true); + }); + + it("leaves the agent unrestricted for a request that declares no tools", async () => { + const { deps, createSessionCalls } = harness(() => simpleTurn("ok")); + await collectCompletion(request({ toolChoice: "none" }), deps); + expect(capturedPermissions(createSessionCalls)).toBeUndefined(); + }); + + it("honours OPENCODE_TOOL_BRIDGE_DENY_NATIVE_TOOLS=false", async () => { + const { deps, createSessionCalls } = harness(() => simpleTurn("ok"), { toolBridgeDenyNativeTools: false }); + await collectCompletion(request({ tools: [WEATHER] }), deps); + expect(capturedPermissions(createSessionCalls)).toBeUndefined(); + }); + + it("bridges with the deny rules when tools are declared", async () => { + const { deps, createSessionCalls } = harness(() => simpleTurn("ok")); + await collectCompletion(request({ tools: [WEATHER] }), deps); + expect(capturedPermissions(createSessionCalls)).toHaveLength(BRIDGE_DENIED_ACTIONS.length); + }); + it("renders the requested JSON output format into the prompt", async () => { const { deps, promptCalls } = harness(() => simpleTurn('{"ok":true}')); await collectCompletion( @@ -579,8 +618,136 @@ describe("runCompletion streaming", () => { agent: "build", messages: [{ role: "user", text: "hang" }], toolsHash: "none", + permissionProfile: "default", }); expect(next.reason).not.toBe("session-busy"); expect(sessions.list().every((record) => !record.busy)).toBe(true); }); }); + +describe("session permission profiles", () => { + const MESSAGES: InternalRequest["messages"] = [{ role: "user", text: "Hello" }]; + const FOLLOW_UP: InternalRequest["messages"] = [ + { role: "user", text: "Hello" }, + { role: "assistant", text: "Hi there" }, + { role: "user", text: "How are you?" }, + ]; + + it("does not hand an unrestricted session to a turn that needs the deny rules", async () => { + const { deps, createSessionCalls } = harness(() => simpleTurn("Hi there")); + + // Turn 1 declares no tools, so its session has no deny rules. Turn 2 declares + // tools and must not inherit it: the session would keep its permissive + // permissions and the model could reach for its own shell and web tools. + await collectCompletion(request({ conversationKey: "profile-conv", messages: MESSAGES }), deps); + await collectCompletion(request({ conversationKey: "profile-conv", tools: [WEATHER], messages: FOLLOW_UP }), deps); + + expect(createSessionCalls).toHaveLength(2); + expect(capturedPermissions(createSessionCalls, 0)).toBeUndefined(); + expect(capturedPermissions(createSessionCalls, 1)).toHaveLength(BRIDGE_DENIED_ACTIONS.length); + }); + + it("does not hand a deny-listed session to a later tool-less turn", async () => { + const { deps, createSessionCalls } = harness(() => simpleTurn("Hi there")); + + await collectCompletion(request({ conversationKey: "profile-conv", tools: [WEATHER], messages: MESSAGES }), deps); + await collectCompletion(request({ conversationKey: "profile-conv", messages: FOLLOW_UP }), deps); + + expect(createSessionCalls).toHaveLength(2); + expect(capturedPermissions(createSessionCalls, 0)).toHaveLength(BRIDGE_DENIED_ACTIONS.length); + expect(capturedPermissions(createSessionCalls, 1)).toBeUndefined(); + }); + + it("still reuses a session created for the same tools and permission profile", async () => { + const { deps, createSessionCalls } = harness(() => simpleTurn("Hi there")); + + await collectCompletion(request({ conversationKey: "profile-conv", tools: [WEATHER], messages: MESSAGES }), deps); + await collectCompletion(request({ conversationKey: "profile-conv", tools: [WEATHER], messages: FOLLOW_UP }), deps); + + expect(createSessionCalls).toHaveLength(1); + }); + + it("does not share one x-conversation-id between two different tool sets", async () => { + const other: ToolDefinition = { name: "search", description: "search", parameters: { type: "object" } }; + const { deps, createSessionCalls } = harness(() => simpleTurn("Hi there")); + + // Same explicit key and the same conversation prefix, so only the tool + // fingerprint can keep the two turns apart. + await collectCompletion(request({ conversationKey: "shared-conv", tools: [WEATHER], messages: MESSAGES }), deps); + await collectCompletion(request({ conversationKey: "shared-conv", tools: [other], messages: FOLLOW_UP }), deps); + + expect(createSessionCalls).toHaveLength(2); + }); +}); + +describe("bridge prompt and enforcement", () => { + it("never names a built-in tool the deny list does not cover", () => { + const instructions = createToolBridge([WEATHER]).instructions; + const sentence = /Never call ([\s\S]+?) or\s+any other built-in tool/.exec(instructions); + expect(sentence).not.toBeNull(); + + const denied: readonly string[] = BRIDGE_DENIED_ACTIONS; + const named = (sentence?.[1] ?? "") + .split(/[,\s]+/) + .map((name) => name.trim()) + .filter((name) => name.length > 0); + expect(named.length).toBeGreaterThan(0); + for (const name of named) expect(denied).toContain(name); + + // The prompt must not promise file-read containment the deny rules cannot + // enforce: `read` (and the unenforced `glob`/`grep`) is not denied. + expect(instructions).not.toContain("no file access"); + expect(instructions).toContain("no shell"); + }); +}); + +describe("tool_choice that requires a tool", () => { + it("rejects required with no declared tools before contacting the upstream", async () => { + const { deps, createSessionCalls, promptCalls } = harness(() => simpleTurn("ok")); + + await expect(collectCompletion(request({ toolChoice: "required" }), deps)).rejects.toMatchObject({ + status: 400, + code: "invalid_request", + param: "tool_choice", + }); + + expect(createSessionCalls).toHaveLength(0); + expect(promptCalls).toHaveLength(0); + }); + + it("rejects a named tool_choice with an empty tools array on the Anthropic surface", async () => { + const { deps, createSessionCalls } = harness(() => simpleTurn("ok")); + + // `{type:"any"}` and `{type:"tool"}` both map onto these internal values, so + // the check covers `/v1/messages` as well as `/v1/chat/completions`. + await expect( + collectCompletion( + request({ surface: "anthropic.messages", tools: [], toolChoice: { name: "lookup" } }), + deps, + ), + ).rejects.toMatchObject({ status: 400, code: "invalid_request", param: "tool_choice" }); + + expect(createSessionCalls).toHaveLength(0); + }); + + it("fails a streaming turn before the first event instead of opening a stream", async () => { + const { deps } = harness(() => simpleTurn("ok")); + const events: CompletionEvent[] = []; + + await expect( + (async () => { + for await (const item of runCompletion(request({ stream: true, toolChoice: "required" }), deps)) { + events.push(item); + } + })(), + ).rejects.toMatchObject({ status: 400, code: "invalid_request" }); + + expect(events).toHaveLength(0); + }); + + it("still accepts a tool_choice that requires a declared tool", async () => { + const { deps, createSessionCalls } = harness(() => simpleTurn("ok")); + await collectCompletion(request({ tools: [WEATHER], toolChoice: "required" }), deps); + expect(createSessionCalls).toHaveLength(1); + }); +}); diff --git a/test/config.test.ts b/test/config.test.ts index e34e57d..bad6442 100644 --- a/test/config.test.ts +++ b/test/config.test.ts @@ -1,8 +1,11 @@ +import { readFileSync } from "node:fs"; import os from "node:os"; +import path from "node:path"; import { afterEach, describe, expect, it, vi } from "vitest"; import { isAuthorized } from "../src/auth.js"; import { DEFAULT_API_KEY, loadConfig, resetConfigCache, type Config } from "../src/config.js"; import { buildServer } from "../src/server.js"; +import { defaultApiKeyNote } from "../src/startup.js"; import { createTestContext } from "./helpers/context.js"; const KEY_VARS = ["OPENCODE_API_KEYS", "OPENCODE_API_KEY"] as const; @@ -192,6 +195,37 @@ describe("explicitly empty key configuration", () => { expect(() => config()).toThrow(/no usable key/); }); + it("is true when the published key is listed explicitly, as .env.example ships it", () => { + clearKeyEnv(); + process.env["OPENCODE_API_KEYS"] = DEFAULT_API_KEY; + const resolved = config(); + expect(resolved.apiKeys).toEqual([DEFAULT_API_KEY]); + expect(resolved.usingDefaultApiKey).toBe(true); + }); + + it("is true when the published key is listed next to a real secret", () => { + clearKeyEnv(); + process.env["OPENCODE_API_KEYS"] = `${DEFAULT_API_KEY},a-real-secret`; + const resolved = config(); + expect(resolved.apiKeys).toEqual([DEFAULT_API_KEY, "a-real-secret"]); + expect(resolved.usingDefaultApiKey).toBe(true); + }); + + it("is false when only other keys are configured", () => { + clearKeyEnv(); + process.env["OPENCODE_API_KEYS"] = "alpha,beta,gamma"; + const resolved = config(); + expect(resolved.usingDefaultApiKey).toBe(false); + expect(resolved.apiKeys).not.toContain(DEFAULT_API_KEY); + }); + + it("produces a startup note that names the published key and the remedy", () => { + const note = defaultApiKeyNote(path.join(os.tmpdir(), "opencode-api")); + expect(note).toContain(DEFAULT_API_KEY); + expect(note).toContain("OPENCODE_ALLOW_NO_AUTH"); + expect(note).not.toContain("because OPENCODE_API_KEYS is not set"); + }); + it("still uses the default key when the variable is unset", () => { setEnv("OPENCODE_API_KEYS", ""); setEnv("OPENCODE_API_KEY", undefined); @@ -199,4 +233,108 @@ describe("explicitly empty key configuration", () => { expect(resolved.apiKeys).toEqual([DEFAULT_API_KEY]); expect(resolved.usingDefaultApiKey).toBe(true); }); +}); + +describe(".env.example", () => { + const EXPECTED_ACTIVE = new Map([ + ["OPENCODE_API_KEYS", DEFAULT_API_KEY], + ["HOST", "127.0.0.1"], + ["PORT", "20123"], + ]); + + it("only activates assignments that match the built-in defaults", () => { + // `.env.example` documents that the values shown are the built-in defaults, + // and `pnpm setup` copies it verbatim into `.env`. An uncommented assignment + // that is NOT a default (for example a pinned OPENCODE_SERVER_URL) silently + // changes the documented quickstart behaviour, so pin the invariant here. + const file = readFileSync(new URL("../.env.example", import.meta.url), "utf8"); + const active = file + .split(/\r?\n/) + .map((line, index) => ({ line: line.trim(), number: index + 1 })) + .filter(({ line }) => /^[A-Z][A-Z0-9_]*=/.test(line)); + + expect(active.length).toBeGreaterThan(0); + for (const { line, number } of active) { + const [name = "", value = ""] = line.split("=", 2); + expect( + EXPECTED_ACTIVE.get(name), + `.env.example:${number} activates ${name}="${value}", which is not a documented built-in default`, + ).toBe(value); + } + }); +}); + +describe("HTTP server shutdown and CORS", () => { + it("closes idle connections without destroying in-flight requests", async () => { + // `true` would call server.closeAllConnections() inside Fastify's onClose + // hook, destroying active requests at t=0 and making the bounded drain in + // src/http/shutdown.ts dead code. `"idle"` is the documented pairing. + const ctx = createTestContext(); + const app = await buildServer(ctx); + expect(app.initialConfig.forceCloseConnections).toBe("idle"); + await app.close(); + }); + + it("answers an allowed preflight with the SDK headers and the request id exposed", async () => { + const ctx = createTestContext({ config: { corsOrigins: ["https://app.example"] } }); + const app = await buildServer(ctx); + + const response = await app.inject({ + method: "OPTIONS", + url: "/v1/chat/completions", + headers: { origin: "https://app.example", "access-control-request-method": "POST" }, + }); + + expect(response.statusCode).toBe(204); + expect(response.headers["access-control-allow-origin"]).toBe("https://app.example"); + const allowed = String(response.headers["access-control-allow-headers"]); + for (const header of [ + "authorization", + "x-api-key", + "x-conversation-id", + "anthropic-version", + "anthropic-dangerous-direct-browser-access", + "openai-organization", + "openai-project", + "x-stainless-lang", + ]) { + expect(allowed).toContain(header); + } + expect(String(response.headers["access-control-expose-headers"])).toContain("x-request-id"); + + await app.close(); + }); + + it("omits the CORS headers for an origin that is not allowed", async () => { + const ctx = createTestContext({ config: { corsOrigins: ["https://app.example"] } }); + const app = await buildServer(ctx); + + const response = await app.inject({ + method: "OPTIONS", + url: "/v1/chat/completions", + headers: { origin: "https://evil.example", "access-control-request-method": "POST" }, + }); + + expect(response.statusCode).toBe(204); + expect(response.headers["access-control-allow-origin"]).toBeUndefined(); + expect(response.headers["access-control-allow-headers"]).toBeUndefined(); + + await app.close(); + }); + + it("allows any origin when the allow-list is *", async () => { + const ctx = createTestContext({ config: { corsOrigins: ["*"] } }); + const app = await buildServer(ctx); + + const response = await app.inject({ + method: "GET", + url: "/health", + headers: { origin: "https://anything.example" }, + }); + + expect(response.headers["access-control-allow-origin"]).toBe("*"); + expect(response.headers["vary"]).toBe("origin"); + + await app.close(); + }); }); \ No newline at end of file diff --git a/test/events.test.ts b/test/events.test.ts index 60ae49b..867d36f 100644 --- a/test/events.test.ts +++ b/test/events.test.ts @@ -255,6 +255,63 @@ describe("EventHub", () => { // The abandoned connection is cancelled, not left open. await waitFor(() => item.closedCount() >= 1); }); + + it("does not carry a partial frame across a reconnect", async () => { + const item = await fixture((response, connection) => { + if (connection === 1) { + response.write(frame({ id: "e0", type: "server.connected", data: {} })); + // A frame cut in half: the terminating blank line never arrives before + // the connection drops, so its buffered bytes must be discarded rather + // than prefixed to the first frame of the next connection. + response.write('data: {"id":"e1","type":"session.text.delta","data":{"sessionID":"ses_1","delta":"stale'); + const timer = setTimeout(() => response.end(), 20); + return () => clearTimeout(timer); + } + response.write(frame({ id: "e2", type: "server.connected", data: {} })); + response.write(frame({ id: "e3", type: "session.text.delta", data: { sessionID: "ses_1", delta: "intact" } })); + return () => undefined; + }); + active.push(item); + + const received: OpencodeEvent[] = []; + item.hub.subscribe("ses_1", (event) => received.push(event)); + item.hub.start(); + + await waitFor(() => received.length >= 1, 8_000); + // Let any later dispatch land, so a cross-connection leak cannot hide. + await delay(80); + + expect(received.map((event) => event.id)).toEqual(["e3"]); + expect(received.map((event) => (event.data as { delta?: unknown }).delta)).toEqual(["intact"]); + }); + + it("decodes a multi-byte character split across two chunks", async () => { + const payload = frame({ + id: "e1", + type: "session.text.delta", + data: { sessionID: "ses_1", delta: "héllo ✓" }, + }); + const bytes = Buffer.from(payload, "utf8"); + // Split the two-byte "é" across two chunks: the streaming decoder must hold + // the partial code point until the second chunk completes it. + const splitAt = bytes.indexOf(Buffer.from("é", "utf8")) + 1; + expect(splitAt).toBeGreaterThan(0); + + const item = await fixture((response) => { + response.write(frame({ id: "e0", type: "server.connected", data: {} })); + response.write(bytes.subarray(0, splitAt)); + const timer = setTimeout(() => response.write(bytes.subarray(splitAt)), 20); + return () => clearTimeout(timer); + }); + 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); + expect(deltas).toEqual(["héllo ✓"]); + }); }); async function waitFor(predicate: () => boolean, timeoutMs = 3_000): Promise { diff --git a/test/media.test.ts b/test/media.test.ts index 60374c0..0df73f3 100644 --- a/test/media.test.ts +++ b/test/media.test.ts @@ -1,14 +1,25 @@ import http from "node:http"; import type { LookupAddress, LookupOptions } from "node:dns"; import dns from "node:dns/promises"; +import { constants as fsConstants } from "node:fs"; import fsp from "node:fs/promises"; +import type { FileHandle } from "node:fs/promises"; import type { AddressInfo } from "node:net"; import os from "node:os"; import path from "node:path"; import { afterAll, afterEach, beforeAll, describe, expect, it, vi } from "vitest"; import { loadConfig, resetConfigCache, type Config } from "../src/config.js"; import { ApiError } from "../src/errors.js"; -import { buildDataUri, isPrivateHost, isWithinRoots, resolveAttachment } from "../src/media/resolve.js"; +import { + buildDataUri, + createMediaBudget, + formatOmissionNote, + isPrivateHost, + isWithinRoots, + resolveAttachment, + resolveAttachments, + type MediaSource, +} from "../src/media/resolve.js"; import { extensionToMime, isAudio, isImage, isPdf, isTextual, isVideo, kindFromMime, sniffMime } from "../src/media/mime.js"; /** 1x1 transparent PNG. */ @@ -16,6 +27,23 @@ const PNG_BASE64 = "iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAYAAAAfFcSJAAAADUlEQVR42mP8z8BQDwAEhQGAhKmMIQAAAABJRU5ErkJggg=="; const PNG_BUFFER = Buffer.from(PNG_BASE64, "base64"); +/** + * POSIX mode bits are the only portable way to make a file unreadable here. + * Windows ACLs do not map onto `chmod` and uid 0 bypasses the mode, so the + * assertion is skipped there instead of pretending to test it. + */ +const canEnforceFileModes = process.platform !== "win32" && process.getuid?.() !== 0; + +/** Poll until `predicate` holds, or fail instead of hanging the suite. */ +async function waitFor(predicate: () => boolean, timeoutMs = 2_000): Promise { + const deadline = Date.now() + timeoutMs; + while (Date.now() < deadline) { + if (predicate()) return; + await new Promise((resolve) => setTimeout(resolve, 10)); + } + throw new Error("timed out waiting for the media fixture server"); +} + function config(overrides: Partial = {}): Config { resetConfigCache(); return loadConfig({ @@ -108,6 +136,55 @@ describe("resolveAttachment", () => { ).rejects.toMatchObject({ code: "invalid_attachment" }); }); + it("shares a request budget across sequential resolveAttachment calls", async () => { + const budget = createMediaBudget({ maxCount: 1, maxBytes: 1024 }); + + const attachment = await resolveAttachment( + { dataUri: `data:image/png;base64,${PNG_BASE64}` }, + config(), + { budget }, + ); + + expect(attachment.size).toBe(PNG_BUFFER.byteLength); + // Only the bytes actually retained are booked against the request budget. + expect(budget.usedCount).toBe(1); + expect(budget.usedBytes).toBe(PNG_BUFFER.byteLength); + + await expect( + resolveAttachment({ dataUri: `data:image/png;base64,${PNG_BASE64}` }, config(), { budget }), + ).rejects.toMatchObject({ code: "attachment_omitted", status: 400 }); + }); + + it("caps a budgeted attachment at the budget's byte ceiling and releases the slot on failure", async () => { + const budget = createMediaBudget({ maxCount: 4, maxBytes: PNG_BUFFER.byteLength - 1 }); + + await expect( + resolveAttachment({ dataUri: `data:image/png;base64,${PNG_BASE64}` }, config(), { budget }), + ).rejects.toMatchObject({ code: "attachment_too_large" }); + + // A failed resolution must not leak the count slot: the next source may + // still be tried. + expect(budget.usedCount).toBe(0); + expect(budget.usedBytes).toBe(0); + }); + + it("formats the omission note the prompt builder appends", () => { + expect(formatOmissionNote([], { maxCount: 16, maxBytes: 1024 })).toBe(""); + + const note = formatOmissionNote( + [ + { index: 0, name: "a.png", reason: "count" }, + { index: 1, reason: "bytes" }, + ], + { maxCount: 16, maxBytes: 1024 }, + ); + + expect(note).toBe( + "[attachments omitted: a.png (over the 16-file limit), attachment #2" + + " - the request exceeded the 1024-byte combined attachment budget]", + ); + }); + it("builds a data URI", () => { expect(buildDataUri({ data: "AAAA", mime: "image/png" })).toBe("data:image/png;base64,AAAA"); }); @@ -118,27 +195,72 @@ describe("resolveAttachment", () => { let port = 0; /** Requests that actually reached the fixture server. */ let hits = 0; + /** Fixture requests currently being answered. */ + let inFlight = 0; + /** Highest value `inFlight` reached since the last reset. */ + let maxInFlight = 0; + /** True once the never-ending `/slow` response lost its socket. */ + let slowClosed = false; + /** Bytes served by `/small`. */ + const SMALL_BUFFER = Buffer.alloc(1_000, 3); beforeAll(async () => { server = http.createServer((request, response) => { hits += 1; - if (request.url === "/image.png") { + inFlight += 1; + maxInFlight = Math.max(maxInFlight, inFlight); + response.on("close", () => { + inFlight -= 1; + }); + // The budget tests append a cache-busting `?i=` so every source has a + // distinct origin; route on the path only. + const route = request.url?.split("?")[0] ?? ""; + + if (route === "/image.png") { response.writeHead(200, { "content-type": "image/png" }); response.end(PNG_BUFFER); return; } - if (request.url === "/no-type") { + if (route === "/no-type") { response.writeHead(200); response.end(PNG_BUFFER); return; } - if (request.url === "/big") { + if (route === "/big") { response.writeHead(200, { "content-type": "image/png" }); response.end(Buffer.alloc(4096, 1)); return; } - if (request.url === "/slow") { + if (route === "/small") { + response.writeHead(200, { + "content-type": "application/octet-stream", + "content-length": String(SMALL_BUFFER.byteLength), + }); + response.end(SMALL_BUFFER); + return; + } + if (route === "/tick") { + // Answers after a delay, so overlapping workers are observable. + setTimeout(() => { + if (response.destroyed) return; + response.writeHead(200, { + "content-type": "image/png", + "content-length": String(PNG_BUFFER.byteLength), + }); + response.end(PNG_BUFFER); + }, 30); + return; + } + if (route === "/boom") { + response.writeHead(500); + response.end(); + return; + } + if (route === "/slow") { // Never ends: only an abort (or the fetch timeout) can settle this. + response.on("close", () => { + slowClosed = true; + }); response.writeHead(200, { "content-type": "image/png" }); return; } @@ -275,6 +397,161 @@ describe("resolveAttachment", () => { requestSpy.mockRestore(); lookup.mockRestore(); }); + + describe("request budget", () => { + /** Distinct URLs that all hit the same fixture route. */ + const many = (count: number, route: string): MediaSource[] => + Array.from({ length: count }, (_, index) => ({ url: `${baseUrl}${route}?i=${index}` })); + + it("fetches at most maxCount sources and reports the rest as omitted, in declaration order", async () => { + const before = hits; + + const result = await resolveAttachments(many(40, "/image.png"), config({ allowPrivateMediaUrls: true }), { + budget: createMediaBudget({ maxCount: 3, maxBytes: 1024 * 1024 }), + }); + + expect(result.attachments).toHaveLength(3); + expect(result.attachments.map((attachment) => attachment.origin)).toEqual([ + `${baseUrl}/image.png?i=0`, + `${baseUrl}/image.png?i=1`, + `${baseUrl}/image.png?i=2`, + ]); + expect(result.omitted).toHaveLength(37); + expect(result.omitted[0]).toEqual({ index: 3, reason: "count" }); + expect(result.omitted.every((entry) => entry.reason === "count")).toBe(true); + // Nothing beyond the cap was ever dialled. + expect(hits - before).toBe(3); + }); + + it("derives the default budget from the config caps", async () => { + const before = hits; + + const result = await resolveAttachments( + many(5, "/image.png"), + config({ allowPrivateMediaUrls: true, maxAttachments: 2 }), + ); + + expect(result.attachments).toHaveLength(2); + expect(result.omitted).toEqual([ + { index: 2, reason: "count" }, + { index: 3, reason: "count" }, + { index: 4, reason: "count" }, + ]); + expect(hits - before).toBe(2); + }); + + it("stops fetching once the combined byte budget is reserved", async () => { + const before = hits; + // 1 KiB each, a 2 KiB budget and one worker: the first two fit and the + // rest are refused before a socket is opened. + const result = await resolveAttachments(many(4, "/small"), config({ allowPrivateMediaUrls: true }), { + budget: createMediaBudget({ maxCount: 10, maxBytes: 2_000 }), + concurrency: 1, + }); + + expect(result.attachments.map((attachment) => attachment.size)).toEqual([1_000, 1_000]); + expect(result.omitted).toEqual([ + { index: 2, reason: "bytes" }, + { index: 3, reason: "bytes" }, + ]); + expect(hits - before).toBe(2); + }); + + it("bounds in-flight downloads with the configured worker pool", async () => { + maxInFlight = 0; + + await resolveAttachments(many(12, "/tick"), config({ allowPrivateMediaUrls: true }), { concurrency: 3 }); + + expect(maxInFlight).toBeGreaterThan(1); + expect(maxInFlight).toBeLessThanOrEqual(3); + }); + + it("bounds in-flight downloads with the default worker pool", async () => { + maxInFlight = 0; + + await resolveAttachments(many(10, "/tick"), config({ allowPrivateMediaUrls: true })); + + expect(maxInFlight).toBeGreaterThan(1); + expect(maxInFlight).toBeLessThanOrEqual(4); + }); + + it("aborts the in-flight siblings as soon as one part fails", async () => { + slowClosed = false; + maxInFlight = 0; + const started = Date.now(); + + await expect( + resolveAttachments( + [ + { url: `${baseUrl}/slow` }, + { url: `${baseUrl}/boom` }, + { url: `${baseUrl}/slow` }, + { url: `${baseUrl}/slow` }, + ], + config({ allowPrivateMediaUrls: true, mediaFetchTimeoutMs: 15_000 }), + { concurrency: 4 }, + ), + ).rejects.toMatchObject({ code: "attachment_download_failed" }); + + expect(Date.now() - started).toBeLessThan(2_000); + // The never-ending siblings must have been in flight, otherwise this + // test would pass without exercising the abort at all. + expect(maxInFlight).toBeGreaterThan(1); + // Without the request-level controller they stay open until the 15 s + // fetch timeout. + await waitFor(() => slowClosed); + expect(slowClosed).toBe(true); + }); + + it("chains an already-aborted caller signal to every download", async () => { + const started = Date.now(); + + await expect( + resolveAttachments(many(8, "/slow"), config({ allowPrivateMediaUrls: true }), { + signal: AbortSignal.abort(), + }), + ).rejects.toMatchObject({ code: "attachment_download_failed" }); + + expect(Date.now() - started).toBeLessThan(2_000); + }); + + it("leaves a within-budget request byte-identical", async () => { + const options = config({ allowPrivateMediaUrls: true }); + + const result = await resolveAttachments( + [{ url: `${baseUrl}/image.png` }, { url: `${baseUrl}/no-type` }], + options, + ); + const expected = [ + await resolveAttachment({ url: `${baseUrl}/image.png` }, options), + await resolveAttachment({ url: `${baseUrl}/no-type` }, options), + ]; + + expect(result.attachments).toEqual(expected); + expect(result.omitted).toEqual([]); + }); + + it("reports every omission through the onOmit hook", async () => { + const seen: Array<{ index: number; reason: string }> = []; + + await resolveAttachments(many(3, "/image.png"), config({ allowPrivateMediaUrls: true }), { + budget: createMediaBudget({ maxCount: 1, maxBytes: 1024 }), + onOmit: (omission) => seen.push({ index: omission.index, reason: omission.reason }), + }); + + expect(seen).toEqual([ + { index: 1, reason: "count" }, + { index: 2, reason: "count" }, + ]); + }); + + it("rejects a sparse source list instead of silently dropping entries", async () => { + const sparse: MediaSource[] = []; + sparse[1] = { dataUri: `data:image/png;base64,${PNG_BASE64}` }; + + await expect(resolveAttachments(sparse, config())).rejects.toMatchObject({ code: "invalid_attachment" }); + }); + }); }); describe("local files", () => { @@ -309,17 +586,28 @@ describe("resolveAttachment", () => { expect(attachment.name).toBe("image.png"); }); - it("re-checks the size after reading, not only from stat", async () => { + it("re-checks the size after reading, through the open handle", async () => { + // The post-read check must be asserted against the handle the code really + // reads from: spying on `fsp.readFile` no longer intercepts anything once + // the read goes through `fsp.open()`. const cap = PNG_BUFFER.byteLength + 16; - const readSpy = vi.spyOn(fsp, "readFile").mockResolvedValue(Buffer.alloc(cap * 2, 7) as never); + const handle = { + stat: vi.fn().mockResolvedValue({ isFile: () => true, size: PNG_BUFFER.byteLength }), + readFile: vi.fn().mockResolvedValue(Buffer.alloc(cap * 2, 7)), + close: vi.fn().mockResolvedValue(undefined), + }; + const openSpy = vi.spyOn(fsp, "open").mockResolvedValue(handle as unknown as FileHandle); + await expect( resolveAttachment( { path: path.join(workspace, "image.png") }, config({ allowLocalFiles: true, allowedFileRoots: [workspace], maxAttachmentBytes: cap }), ), ).rejects.toMatchObject({ code: "attachment_too_large" }); - expect(readSpy).toHaveBeenCalledTimes(1); - readSpy.mockRestore(); + + expect(handle.readFile).toHaveBeenCalledTimes(1); + expect(handle.close).toHaveBeenCalledTimes(1); + openSpy.mockRestore(); }); it("refuses files outside the allowed roots", async () => { @@ -339,6 +627,121 @@ describe("resolveAttachment", () => { ), ).rejects.toMatchObject({ code: "attachment_not_found" }); }); + + it("maps a file that vanishes before the open to 400 attachment_not_found", async () => { + const missing = Object.assign(new Error("ENOENT: no such file or directory"), { code: "ENOENT" }); + const openSpy = vi.spyOn(fsp, "open").mockRejectedValue(missing); + + await expect( + resolveAttachment( + { path: path.join(workspace, "image.png") }, + config({ allowLocalFiles: true, allowedFileRoots: [workspace] }), + ), + ).rejects.toMatchObject({ code: "attachment_not_found", status: 400 }); + + expect(openSpy).toHaveBeenCalledTimes(1); + openSpy.mockRestore(); + }); + + it("maps an unreadable file to 400 invalid_attachment instead of a 500", async () => { + const denied = Object.assign(new Error("EACCES: permission denied"), { code: "EACCES" }); + const openSpy = vi.spyOn(fsp, "open").mockRejectedValue(denied); + + await expect( + resolveAttachment( + { path: path.join(workspace, "image.png") }, + config({ allowLocalFiles: true, allowedFileRoots: [workspace] }), + ), + ).rejects.toMatchObject({ + code: "invalid_attachment", + status: 400, + message: expect.stringContaining("not readable"), + }); + + openSpy.mockRestore(); + }); + + it.skipIf(!canEnforceFileModes)( + "returns 400 invalid_attachment (not 500) for a mode-000 file inside the root", + async () => { + const locked = path.join(workspace, "locked.png"); + await fsp.writeFile(locked, PNG_BUFFER); + await fsp.chmod(locked, 0o000); + try { + await expect( + resolveAttachment( + { path: locked }, + config({ allowLocalFiles: true, allowedFileRoots: [workspace] }), + ), + ).rejects.toMatchObject({ code: "invalid_attachment", status: 400 }); + } finally { + await fsp.chmod(locked, 0o600); + await fsp.rm(locked, { force: true }); + } + }, + ); + + it.skipIf(process.platform === "win32")( + "reads through exactly one handle opened with O_NOFOLLOW", + async () => { + const openSpy = vi.spyOn(fsp, "open"); + const target = path.join(workspace, "image.png"); + + const attachment = await resolveAttachment( + { path: target }, + config({ allowLocalFiles: true, allowedFileRoots: [workspace] }), + ); + + expect(attachment.mime).toBe("image/png"); + expect(openSpy).toHaveBeenCalledTimes(1); + const [openedPath, flags] = openSpy.mock.calls[0] ?? []; + // The read must target the path that passed the roots check, and the + // final component must not be followed if it was swapped for a symlink. + expect(openedPath).toBe(await fsp.realpath(target)); + expect(typeof flags).toBe("number"); + expect((flags as number) & fsConstants.O_NOFOLLOW).toBe(fsConstants.O_NOFOLLOW); + openSpy.mockRestore(); + }, + ); + + it.skipIf(process.platform === "win32")( + "refuses a symlink that resolves outside the allowed roots", + async () => { + const link = path.join(workspace, "escape.txt"); + await fsp.symlink(path.join(outside, "secret.txt"), link); + try { + await expect( + resolveAttachment( + { path: link }, + config({ allowLocalFiles: true, allowedFileRoots: [workspace] }), + ), + ).rejects.toMatchObject({ code: "attachment_path_forbidden" }); + } finally { + await fsp.rm(link, { force: true }); + } + }, + ); + + it.skipIf(process.platform === "win32")( + "pins the residual hard-link risk: a link inside the root exposes outside content", + async () => { + // `realpath` and `O_NOFOLLOW` cannot see hard links: the same inode is + // reachable from both directories, so containment is a path property. + // This test pins the documented residual risk (see the module comment in + // src/media/resolve.ts) so a future mitigation is a deliberate change. + const link = path.join(workspace, "hardlink.txt"); + await fsp.link(path.join(outside, "secret.txt"), link); + try { + const attachment = await resolveAttachment( + { path: link }, + config({ allowLocalFiles: true, allowedFileRoots: [workspace] }), + ); + expect(Buffer.from(attachment.data, "base64").toString("utf8")).toBe("nope"); + } finally { + await fsp.rm(link, { force: true }); + } + }, + ); }); }); diff --git a/test/openai-chat.test.ts b/test/openai-chat.test.ts index 2666b6a..a6d26b2 100644 --- a/test/openai-chat.test.ts +++ b/test/openai-chat.test.ts @@ -598,6 +598,53 @@ describe("POST /v1/chat/completions (non-streaming)", () => { } }); + it("fetches no more media than the request budget allows", async () => { + const cap = testConfig().maxAttachments; + const body = Buffer.from(PNG_BASE64, "base64"); + let fetched = 0; + const server = http.createServer((_request, response) => { + fetched += 1; + response.writeHead(200, { "content-type": "image/png", "content-length": String(body.byteLength) }); + response.end(body); + }); + await new Promise((resolve) => server.listen(0, "127.0.0.1", resolve)); + const { port } = server.address() as AddressInfo; + + try { + const captured: InternalRequest[] = []; + const ctx = createTestContext({ onRun: (request) => captured.push(request) }); + const app = await buildServer(ctx); + + const image = { type: "image_url", image_url: { url: `http://127.0.0.1:${port}/image.png` } }; + const response = await app.inject({ + method: "POST", + url: "/v1/chat/completions", + headers: AUTH, + payload: { + model: MODEL, + messages: [ + { role: "user", content: Array.from({ length: cap }, () => image) }, + { role: "user", content: Array.from({ length: 5 }, () => image) }, + ], + }, + }); + + expect(response.statusCode).toBe(200); + // The budget is per request, not per message: the extra parts are reported + // in the prompt instead of being fetched, so the upstream sees exactly one + // GET per admitted attachment. + expect(fetched).toBe(cap); + const attachments = captured[0]?.messages.flatMap((message) => message.attachments ?? []) ?? []; + expect(attachments).toHaveLength(cap); + const promptText = (captured[0]?.messages ?? []).map((message) => message.text).join("\n"); + expect(promptText).toContain("attachments omitted"); + + await app.close(); + } finally { + await new Promise((resolve) => server.close(() => resolve())); + } + }); + it("rejects a file part that only carries a file_id", async () => { const app = await buildServer(createTestContext()); const response = await app.inject({ @@ -675,6 +722,43 @@ describe("POST /v1/chat/completions (non-streaming)", () => { await app.close(); }); + + it("reports an errored turn as 502 upstream_error instead of a completed 200", async () => { + const ctx = createTestContext({ + script: (request: InternalRequest): CompletionEvent[] => [ + { + kind: "start", + sessionId: "ses_error_turn", + messageId: "msg_error_turn", + model: request.model, + agent: "build", + reusedSession: false, + reasoningEnabled: false, + }, + { kind: "text_delta", text: "partial", ordinal: 0 }, + { kind: "end", finishReason: "error", usage: USAGE, messageId: "msg_error_turn" }, + ], + }); + const app = await buildServer(ctx); + + const response = await app.inject({ + method: "POST", + url: "/v1/chat/completions", + headers: AUTH, + payload: { model: MODEL, messages: [{ role: "user", content: "Go." }] }, + }); + + // Same cause, same code as /v1/responses (`status: "failed"` + + // `code: "upstream_error"`): an upstream failure must never look like a + // completed turn with `finish_reason: "stop"`. + expect(response.statusCode).toBe(502); + const body = response.json() as { error: { message: string; type: string; code: string } }; + expect(body.error.code).toBe("upstream_error"); + expect(body.error.type).toBe("api_error"); + expect(body.error.message).toBe("The upstream completion ended with an error."); + + await app.close(); + }); }); describe("usage accounting", () => { @@ -949,6 +1033,70 @@ describe("POST /v1/chat/completions (streaming)", () => { expect(frames.at(-1)?.json.error?.type).toBe("api_error"); await app.close(); }); + + it("ends an errored turn with an error frame and no finish chunk or [DONE]", async () => { + const ctx = createTestContext({ + script: (request: InternalRequest): CompletionEvent[] => [ + { + kind: "start", + sessionId: "ses_error_stream", + messageId: "msg_error_stream", + model: request.model, + agent: "build", + reusedSession: false, + reasoningEnabled: false, + }, + { kind: "text_delta", text: "partial", ordinal: 0 }, + { kind: "end", finishReason: "error", usage: USAGE, messageId: "msg_error_stream" }, + ], + }); + const app = await buildServer(ctx); + + const response = await app.inject({ + method: "POST", + url: "/v1/chat/completions", + headers: AUTH, + payload: { model: MODEL, messages: [{ role: "user", content: "Go." }], stream: true }, + }); + + expect(response.statusCode).toBe(200); + const frames = parseSseJson<{ error?: { code: string }; choices?: Chunk["choices"] }>(response.body); + // Role chunk, one text delta, then the terminal error frame. + expect(frames).toHaveLength(3); + expect(frames.at(-1)?.json.error?.code).toBe("upstream_error"); + expect(frames.some((frame) => frame.json.choices?.[0]?.finish_reason === "stop")).toBe(false); + expect(parseSse(response.body).some((frame) => frame.data === "[DONE]")).toBe(false); + + await app.close(); + }); + + it("reports a first-event error with a real HTTP status", async () => { + const ctx = createTestContext({ + script: (): CompletionEvent[] => [ + { + kind: "error", + error: ApiError.unavailable("OpenCode event stream is not connected.", { + code: "event_stream_unavailable", + }), + }, + ], + }); + const app = await buildServer(ctx); + + const response = await app.inject({ + method: "POST", + url: "/v1/chat/completions", + headers: AUTH, + payload: { model: MODEL, messages: [{ role: "user", content: "Hi" }], stream: true }, + }); + + // A failure known before the first event must not commit the SSE head. + expect(response.statusCode).toBe(503); + expect(response.headers["content-type"]).toContain("application/json"); + expect((response.json() as { error: { code: string } }).error.code).toBe("event_stream_unavailable"); + + await app.close(); + }); }); describe("POST /v1/embeddings", () => { diff --git a/test/openai-completions.test.ts b/test/openai-completions.test.ts index 103bc20..592278b 100644 --- a/test/openai-completions.test.ts +++ b/test/openai-completions.test.ts @@ -231,6 +231,39 @@ describe("POST /v1/completions (non-streaming)", () => { expect(missingModel.statusCode).toBe(400); await app.close(); }); + + it("reports an errored turn as 502 upstream_error instead of a completed 200", async () => { + const ctx = createTestContext({ + script: (request: InternalRequest): CompletionEvent[] => [ + ...textScript(request).slice(0, -1), + { + kind: "end", + finishReason: "error", + usage: { ...EMPTY_USAGE, inputTokens: 12, outputTokens: 4, totalTokens: 16 }, + messageId: "msg_cmpl", + }, + ], + }); + const app = await buildCompletionServer(ctx); + + const response = await app.inject({ + method: "POST", + url: "/v1/completions", + headers: AUTH, + payload: { model: MODEL, prompt: "Say hello" }, + }); + + // Same cause, same code as /v1/responses (`status: "failed"` + + // `code: "upstream_error"`): an upstream failure must never look like a + // completed turn with `finish_reason: "stop"`. + expect(response.statusCode).toBe(502); + const body = response.json() as { error: { message: string; type: string; code: string } }; + expect(body.error.code).toBe("upstream_error"); + expect(body.error.type).toBe("api_error"); + expect(body.error.message).toBe("The upstream completion ended with an error."); + + await app.close(); + }); }); describe("POST /v1/completions (streaming)", () => { @@ -336,4 +369,36 @@ describe("POST /v1/completions (streaming)", () => { expect(frames.at(-1)?.json.error?.message).toBe("late failure"); await app.close(); }); + + it("ends an errored turn with an error frame and no finish chunk or [DONE]", async () => { + const ctx = createTestContext({ + script: (request: InternalRequest): CompletionEvent[] => [ + ...textScript(request).slice(0, -1), + { + kind: "end", + finishReason: "error", + usage: { ...EMPTY_USAGE, inputTokens: 12, outputTokens: 4, totalTokens: 16 }, + messageId: "msg_cmpl", + }, + ], + }); + const app = await buildCompletionServer(ctx); + + const response = await app.inject({ + method: "POST", + url: "/v1/completions", + headers: AUTH, + payload: { model: MODEL, prompt: "Say hello", stream: true }, + }); + + expect(response.statusCode).toBe(200); + const frames = parseSseJson<{ error?: { code: string }; choices?: CompletionChoice[] }>(response.body); + // Two text chunks, then the terminal error frame. + expect(frames).toHaveLength(3); + expect(frames.at(-1)?.json.error?.code).toBe("upstream_error"); + expect(frames.some((frame) => frame.json.choices?.[0]?.finish_reason === "stop")).toBe(false); + expect(parseSse(response.body).some((frame) => frame.data === "[DONE]")).toBe(false); + + await app.close(); + }); }); diff --git a/test/openai-responses.test.ts b/test/openai-responses.test.ts index af3ac68..b905f2f 100644 --- a/test/openai-responses.test.ts +++ b/test/openai-responses.test.ts @@ -587,6 +587,106 @@ describe("POST /v1/responses (non-streaming)", () => { expect(body.incomplete_details).toBeNull(); expect(body.output_text).toBe("partial"); }); + + it("accepts an echoed reasoning input item and ignores it", async () => { + let captured: InternalRequest | undefined; + const app = await makeApp({ onRun: (request) => (captured = request) }); + + const response = await app.inject({ + method: "POST", + url: "/v1/responses", + headers: AUTH, + payload: { + model: "opencode/deepseek-v4.1-flash-free", + input: [ + { + type: "reasoning", + id: "rs_0123456789abcdef", + summary: [{ type: "summary_text", text: "thought" }], + content: [{ type: "reasoning_text", text: "thought" }], + encrypted_content: null, + }, + { role: "user", content: "Next." }, + ], + }, + }); + + expect(response.statusCode).toBe(200); + // The gateway has nowhere to store provider-side thinking state, so the + // item is validated and dropped instead of being rejected (same policy as + // the Anthropic surface's `thinking`/`redacted_thinking` blocks). + expect(captured?.messages).toHaveLength(1); + expect(captured?.messages[0]).toMatchObject({ role: "user", text: "Next." }); + }); + + it("accepts its own reasoning output fed back as input", async () => { + const app = await makeApp({ + script: (request): CompletionEvent[] => { + const usage = { ...EMPTY_USAGE, inputTokens: 4, outputTokens: 2, reasoningTokens: 3, totalTokens: 9 }; + return [ + { + kind: "start", + sessionId: "ses_round_trip", + messageId: "msg_round_trip", + model: request.model, + agent: "build", + reusedSession: false, + reasoningEnabled: true, + }, + { kind: "reasoning_delta", text: "thought", ordinal: 0 }, + { kind: "reasoning_end", text: "thought", ordinal: 0, messageId: "msg_round_trip" }, + { kind: "text_delta", text: "Answer", ordinal: 0 }, + { kind: "end", finishReason: "stop", usage, messageId: "msg_round_trip" }, + ]; + }, + }); + + const first = await app.inject({ + method: "POST", + url: "/v1/responses", + headers: AUTH, + payload: { + model: "opencode/deepseek-v4.1-flash-free", + input: "Think.", + reasoning: { effort: "high" }, + }, + }); + expect(first.statusCode).toBe(200); + const firstBody = first.json() as ResponsePayload; + expect(firstBody.output.map((item) => item.type)).toEqual(["reasoning", "message"]); + + // The documented stateless pattern: the previous `output` becomes `input`. + const second = await app.inject({ + method: "POST", + url: "/v1/responses", + headers: AUTH, + payload: { model: "opencode/deepseek-v4.1-flash-free", input: firstBody.output }, + }); + + expect(second.statusCode).toBe(200); + expect((second.json() as ResponsePayload).status).toBe("completed"); + }); + + it("still rejects a genuinely unknown input item type with 400", async () => { + const app = await makeApp(); + + const response = await app.inject({ + method: "POST", + url: "/v1/responses", + headers: AUTH, + payload: { + model: "opencode/deepseek-v4.1-flash-free", + input: [{ type: "bogus", id: "x" }, { role: "user", content: "Hi" }], + }, + }); + + expect(response.statusCode).toBe(400); + const body = response.json() as { error: { code: string; param: string } }; + expect(body.error.code).toBe("invalid_request"); + // The outer `string | array` union reports the failure at `input`, not at the + // offending item index: zod collapses the per-item issue into the union. + expect(body.error.param).toBe("input"); + }); }); describe("POST /v1/responses (streaming)", () => { @@ -613,6 +713,36 @@ describe("POST /v1/responses (streaming)", () => { expect(response.headers["content-type"]).toContain("application/json"); }); + it("reports a yielded first-event error with a real HTTP status", async () => { + const app = await makeApp({ + script: (): CompletionEvent[] => [ + // The orchestrator turns a pre-flight throw into a yielded `error` + // event, so the adapter must inspect the first event itself. + { + kind: "error", + error: ApiError.unavailable("OpenCode event stream is not connected.", { + code: "event_stream_unavailable", + }), + }, + ], + }); + + const response = await app.inject({ + method: "POST", + url: "/v1/responses", + headers: AUTH, + payload: { model: "opencode/deepseek-v4.1-flash-free", input: "hi", stream: true }, + }); + + expect(response.statusCode).toBe(503); + expect(response.headers["content-type"]).toContain("application/json"); + expect((response.json() as { error: { code: string } }).error.code).toBe("event_stream_unavailable"); + // No part of the SSE sequence may have been written. + expect(response.body).not.toContain("response.created"); + expect(response.body).not.toContain("response.in_progress"); + expect(response.body).not.toContain("response.failed"); + }); + it("emits the typed event sequence with monotonic sequence numbers", async () => { const app = await makeApp({ script: (): CompletionEvent[] => { diff --git a/test/process.test.ts b/test/process.test.ts index da2036f..eaf224b 100644 --- a/test/process.test.ts +++ b/test/process.test.ts @@ -9,6 +9,7 @@ import { EventEmitter } from "node:events"; import os from "node:os"; import { PassThrough } from "node:stream"; import { describe, expect, it } from "vitest"; +import { ApiError } from "../src/errors.js"; import { createLogger } from "../src/logger.js"; import { createMetrics } from "../src/metrics/registry.js"; import { UpstreamProcess, type SpawnedChild } from "../src/upstream/process.js"; @@ -49,7 +50,16 @@ interface Harness { children: FakeChild[]; } -function harness(): Harness { +interface HarnessOptions { + /** + * How long the scripted child waits before reporting readiness. + * `"never"` simulates a start that hangs until the readiness timeout. + */ + readyMs?: number | "never"; +} + +function harness(options: HarnessOptions = {}): Harness { + const readyMs = options.readyMs ?? 0; const children: FakeChild[] = []; const config = testConfig({ dataDir: os.tmpdir(), @@ -66,10 +76,14 @@ function harness(): Harness { const child = new FakeChild(4_000 + children.length); children.push(child); const port = args[args.indexOf("--port") + 1] ?? "0"; - setImmediate(() => { - child.stdout.write(`server listening on http://127.0.0.1:${port}\n`); - child.stdout.write("server password fake-password\n"); - }); + if (readyMs !== "never") { + const announce = (): void => { + child.stdout.write(`server listening on http://127.0.0.1:${port}\n`); + child.stdout.write("server password fake-password\n"); + }; + if (readyMs === 0) setImmediate(announce); + else setTimeout(announce, readyMs); + } return child as unknown as SpawnedChild; }, }); @@ -156,4 +170,64 @@ describe("UpstreamProcess", () => { await process.stop(); expect(children[1]?.signals).toContain("SIGTERM"); }); + + it("refuses to resolve after a terminal shutdown", async () => { + const { process, children } = harness(); + + await process.resolve(); + await process.shutdown(); + + // The adopted server is stopped exactly as `stop()` does. + expect(children[0]?.signals).toContain("SIGTERM"); + expect(process.status().ready).toBe(false); + + // Once terminal, a racing `resolve()` must not start a second server. + const error = await process.resolve().catch((reason: unknown) => reason); + expect(error).toBeInstanceOf(ApiError); + expect((error as ApiError).code).toBe("upstream_unavailable"); + expect((error as Error).message).toBe("upstream is shutting down"); + expect(children).toHaveLength(1); + }); + + it("kills a start that is still in flight when shutdown begins", async () => { + const { process, children } = harness({ readyMs: 200 }); + + const pending = process.resolve(); + // The child exists as soon as `#spawnChild` is called, before readiness. + expect(children).toHaveLength(1); + await process.shutdown(); + + await expect(pending).rejects.toThrow("upstream is shutting down"); + expect(children[0]?.signals).toContain("SIGKILL"); + expect(process.status().ready).toBe(false); + expect(children).toHaveLength(1); + }); + + it("kills a child that never reported readiness", async () => { + const { process, children } = harness({ readyMs: "never" }); + + const pending = process.resolve(); + const startedAt = Date.now(); + await process.shutdown(); + + // Without the terminal shutdown the pending resolve would only fail at the + // readiness timeout (2 s here) and the child would keep holding its port. + expect(Date.now() - startedAt).toBeLessThan(1_500); + await expect(pending).rejects.toThrow("upstream is shutting down"); + expect(children[0]?.signals).toContain("SIGKILL"); + expect(process.status().ready).toBe(false); + }); + + it("keeps stop() non-terminal so the admin restart path can respawn", async () => { + const { process, children } = harness(); + + await process.resolve(); + await process.invalidate("manual restart requested"); + await process.stop(); + const replacement = await process.resolve(); + + expect(children).toHaveLength(2); + expect(replacement.pid).not.toBe(children[0]?.pid); + expect(process.status().ready).toBe(true); + }); }); \ No newline at end of file diff --git a/test/regressions.test.ts b/test/regressions.test.ts index 0b3635d..55692cf 100644 --- a/test/regressions.test.ts +++ b/test/regressions.test.ts @@ -535,7 +535,11 @@ describe("responses media cancellation", () => { }); describe("stream accounting", () => { - it("leaves no active stream behind after a streamed responses request", async () => { + /** The gauge must be back to zero after every streaming surface settles. */ + async function activeStreamsAfter( + url: string, + payload: Record, + ): Promise> { const ctx = createTestContext({ script: () => [ { kind: "start", sessionId: "s", messageId: "m", model: MODEL, reusedSession: false, reasoningEnabled: false }, @@ -544,17 +548,41 @@ describe("stream accounting", () => { }); const app = await buildServer(ctx); - const response = await app.inject({ - method: "POST", - url: "/v1/responses", - headers: AUTH, - payload: { model: MODEL, input: "go", stream: true }, - }); + const response = await app.inject({ method: "POST", url, headers: AUTH, payload }); expect(response.statusCode).toBe(200); const values = (await ctx.metrics.activeStreams.get()).values; - expect(values.every((entry) => entry.value === 0)).toBe(true); await app.close(); + return values; + } + + it("leaves no active stream behind after a streamed responses request", async () => { + const values = await activeStreamsAfter("/v1/responses", { model: MODEL, input: "go", stream: true }); + expect(values.every((entry) => entry.value === 0)).toBe(true); + }); + + it("leaves no active stream behind after a streamed chat request", async () => { + const values = await activeStreamsAfter("/v1/chat/completions", { + model: MODEL, + messages: [{ role: "user", content: "go" }], + stream: true, + }); + expect(values.every((entry) => entry.value === 0)).toBe(true); + }); + + it("leaves no active stream behind after a streamed legacy completions request", async () => { + const values = await activeStreamsAfter("/v1/completions", { model: MODEL, prompt: "go", stream: true }); + expect(values.every((entry) => entry.value === 0)).toBe(true); + }); + + it("leaves no active stream behind after a streamed anthropic request", async () => { + const values = await activeStreamsAfter("/v1/messages", { + model: MODEL, + max_tokens: 64, + messages: [{ role: "user", content: "go" }], + stream: true, + }); + expect(values.every((entry) => entry.value === 0)).toBe(true); }); }); diff --git a/test/sessions.test.ts b/test/sessions.test.ts index 4df4390..cd14468 100644 --- a/test/sessions.test.ts +++ b/test/sessions.test.ts @@ -27,16 +27,29 @@ afterEach(() => { } }); -/** Construct a persistent store whose `sessions.json` contains `records`. */ -function persistedStore(records: Record): SessionStore { +/** + * Construct a persistent store whose `sessions.json` contains `records`. + * + * The file is written in the persisted envelope and, unless `fingerprint` says + * otherwise, claims to have been written by the store's own instance (the + * matching case). Pass a different fingerprint to simulate a file left behind by + * an earlier gateway run. + */ +function persistedStore(records: Record, fingerprint?: string): SessionStore { const dataDir = fs.mkdtempSync(path.join(os.tmpdir(), "opencode-sessions-")); tempDirs.push(dataDir); - fs.writeFileSync(path.join(dataDir, "sessions.json"), JSON.stringify(records), "utf8"); const config = testConfig({ sessionPersist: true, dataDir }); + const payload = { version: 1, fingerprint: fingerprint ?? config.instanceId, records }; + fs.writeFileSync(path.join(dataDir, "sessions.json"), JSON.stringify(payload), "utf8"); return new SessionStore(config, createLogger(config), createMetrics({ enabled: false })); } -const BASE_INPUT = { model: "opencode/big-pickle", agent: "build", toolsHash: "none" } as const; +const BASE_INPUT = { + model: "opencode/big-pickle", + agent: "build", + toolsHash: "none", + permissionProfile: "default", +} as const; describe("SessionStore", () => { it("starts a fresh session when nothing is cached", () => { @@ -116,6 +129,168 @@ describe("SessionStore", () => { expect(otherAgent.reason).toBe("no-record"); }); + it("does not reuse a session created under another permission profile", () => { + const sessions = store(); + // An explicit key keeps both turns in the same candidate list, so the profile + // comparison is what has to reject the reuse. Without a key the profile is + // part of `deriveKey` and the two turns land under different roots. + const first = sessions.acquire({ ...BASE_INPUT, key: "conversation-1", messages: [USER_1] }); + sessions.commit(first.key, "ses_1", { ...BASE_INPUT, key: "conversation-1", messages: [USER_1] }); + + const bridged = sessions.acquire({ + ...BASE_INPUT, + key: "conversation-1", + permissionProfile: "deny-native-tools", + messages: [USER_1, ASSISTANT_1, USER_2], + }); + expect(bridged.reused).toBe(false); + expect(bridged.reason).toBe("permission-profile-changed"); + }); + + it("does not reuse a session created for another tool set on an explicit key", () => { + // `x-conversation-id` bypasses `deriveKey`, so the tool fingerprint has to be + // compared here as well. + const sessions = store(); + const first = sessions.acquire({ ...BASE_INPUT, key: "conversation-1", messages: [USER_1] }); + sessions.commit(first.key, "ses_1", { ...BASE_INPUT, key: "conversation-1", messages: [USER_1] }); + + const otherTools = sessions.acquire({ + ...BASE_INPUT, + key: "conversation-1", + toolsHash: "abc123", + messages: [USER_1, ASSISTANT_1, USER_2], + }); + expect(otherTools.reused).toBe(false); + expect(otherTools.reason).toBe("tool-set-changed"); + }); + + it("treats a persisted record without a permission profile as never reusable", () => { + const now = Date.now(); + const sessions = persistedStore({ + "k:ses_legacy": { + key: "k", + sessionId: "ses_legacy", + model: "opencode/big-pickle", + agent: "build", + prefixHash: hashMessages([USER_1]), + deliveredCount: 1, + createdAt: now, + lastUsedAt: now, + busy: false, + reusedCount: 0, + }, + }); + + try { + const restored = sessions.list()[0]; + // The record was written before the field existed: it must not be assumed + // to match any live profile. + expect(restored?.permissionProfile).not.toBe(BASE_INPUT.permissionProfile); + + const result = sessions.acquire({ + ...BASE_INPUT, + key: "k", + messages: [USER_1, ASSISTANT_1, USER_2], + }); + expect(result.reused).toBe(false); + expect(result.reason).toBe("permission-profile-changed"); + } finally { + sessions.stop(); + } + }); + + it("does not restore a session cache written by another gateway instance", () => { + const now = Date.now(); + const sessions = persistedStore( + { + "k:ses_stale": { + key: "k", + sessionId: "ses_stale", + model: "opencode/big-pickle", + agent: "build", + permissionProfile: "default", + prefixHash: hashMessages([USER_1]), + deliveredCount: 1, + createdAt: now, + lastUsedAt: now, + busy: false, + reusedCount: 0, + }, + }, + "opencode-api-previous-run", + ); + + try { + // A `ses_*` id is only valid inside the upstream server that created it, so + // a file left behind by a dead process must not hand one back. + expect(sessions.list()).toEqual([]); + const result = sessions.acquire({ ...BASE_INPUT, key: "k", messages: [USER_1, ASSISTANT_1, USER_2] }); + expect(result.reused).toBe(false); + } finally { + sessions.stop(); + } + }); + + it("does not restore an unversioned sessions.json left by an earlier version", () => { + const dataDir = fs.mkdtempSync(path.join(os.tmpdir(), "opencode-sessions-")); + tempDirs.push(dataDir); + const now = Date.now(); + // The pre-P14 format: a bare map with no fingerprint, which the old loader + // restored unconditionally. + fs.writeFileSync( + path.join(dataDir, "sessions.json"), + JSON.stringify({ + "k:ses_legacy": { + key: "k", + sessionId: "ses_legacy", + model: "opencode/big-pickle", + agent: "build", + prefixHash: hashMessages([USER_1]), + deliveredCount: 1, + createdAt: now, + lastUsedAt: now, + busy: false, + reusedCount: 0, + }, + }), + "utf8", + ); + const config = testConfig({ sessionPersist: true, dataDir }); + const sessions = new SessionStore(config, createLogger(config), createMetrics({ enabled: false })); + + try { + expect(sessions.list()).toEqual([]); + } finally { + sessions.stop(); + } + }); + + it("restores its own records and drops them after a restart", () => { + const dataDir = fs.mkdtempSync(path.join(os.tmpdir(), "opencode-sessions-")); + tempDirs.push(dataDir); + + const persist = (instanceId: string): SessionStore => { + const config = testConfig({ sessionPersist: true, dataDir, instanceId }); + return new SessionStore(config, createLogger(config), createMetrics({ enabled: false })); + }; + + const first = persist("gateway-run-1"); + const acquired = first.acquire({ ...BASE_INPUT, messages: [USER_1] }); + first.commit(acquired.key, "ses_1", { ...BASE_INPUT, messages: [USER_1] }); + first.stop(); // flushes sessions.json + + // Same instance: the envelope round trip still restores the cache. + expect(persist("gateway-run-1").list().map((record) => record.sessionId)).toEqual(["ses_1"]); + + // The default instance id embeds the gateway pid, so a restart reads a + // different fingerprint and must not reuse the previous upstream's id. + const restarted = persist("gateway-run-2"); + expect(restarted.list()).toEqual([]); + const result = restarted.acquire({ ...BASE_INPUT, messages: [USER_1, ASSISTANT_1, USER_2] }); + expect(result.reused).toBe(false); + expect(result.reason).toBe("no-record"); + }); + it("refuses to interleave a busy session", () => { const sessions = store(); const first = sessions.acquire({ ...BASE_INPUT, messages: [USER_1] }); @@ -239,17 +414,19 @@ describe("SessionStore", () => { }); describe("key derivation", () => { + const base = { model: "m", agent: "build", toolsHash: "none", permissionProfile: "default", messages: [USER_1] }; + it("is stable for the same conversation root", () => { - const a = deriveKey({ model: "m", agent: "build", toolsHash: "none", messages: [USER_1, ASSISTANT_1, USER_2] }); - const b = deriveKey({ model: "m", agent: "build", toolsHash: "none", messages: [USER_1, ASSISTANT_1] }); + const a = deriveKey({ ...base, messages: [USER_1, ASSISTANT_1, USER_2] }); + const b = deriveKey({ ...base, messages: [USER_1, ASSISTANT_1] }); expect(a).toBe(b); }); - it("changes with the model, agent, tools or conversation root", () => { - const base = { model: "m", agent: "build", toolsHash: "none", messages: [USER_1] }; + it("changes with the model, agent, tools, permission profile or conversation root", () => { expect(deriveKey(base)).not.toBe(deriveKey({ ...base, model: "n" })); expect(deriveKey(base)).not.toBe(deriveKey({ ...base, agent: "plan" })); expect(deriveKey(base)).not.toBe(deriveKey({ ...base, toolsHash: "abc" })); + expect(deriveKey(base)).not.toBe(deriveKey({ ...base, permissionProfile: "deny-native-tools" })); expect(deriveKey(base)).not.toBe(deriveKey({ ...base, messages: [{ role: "user", text: "different" }] })); }); }); diff --git a/test/shutdown.test.ts b/test/shutdown.test.ts index 0dcfde5..6f7b5d0 100644 --- a/test/shutdown.test.ts +++ b/test/shutdown.test.ts @@ -12,14 +12,16 @@ interface Stub { deps: ShutdownDeps; events: ReturnType; sessions: ReturnType; - upstream: ReturnType; + upstreamStop: ReturnType; + upstreamShutdown: ReturnType; warnings: string[]; } function stub(): Stub { const events = vi.fn(async () => undefined); const sessions = vi.fn(() => undefined); - const upstream = vi.fn(async () => undefined); + const upstreamStop = vi.fn(async () => undefined); + const upstreamShutdown = vi.fn(async () => undefined); const warnings: string[] = []; const log = { info: () => undefined, @@ -28,15 +30,34 @@ function stub(): Stub { }, error: () => undefined, } as unknown as ShutdownDeps["log"]; + const upstream: ShutdownDeps["upstream"] = { + stop: upstreamStop, + shutdown: upstreamShutdown, + }; return { - deps: { log, events: { stop: events }, sessions: { stop: sessions }, upstream: { stop: upstream } }, + deps: { + log, + events: { stop: events }, + sessions: { stop: sessions }, + upstream, + }, events, sessions, - upstream, + upstreamStop, + upstreamShutdown, warnings, }; } +/** + * The process-exit path must use the terminal `shutdown()`, not the + * non-terminal `stop()` that `POST /admin/upstream/restart` relies on. + */ +function expectUpstreamHookCalledOnce(s: Stub): void { + expect(s.upstreamShutdown).toHaveBeenCalledTimes(1); + expect(s.upstreamStop).not.toHaveBeenCalled(); +} + function appWith(close: () => Promise, forceClose?: () => void): ShutdownApp { const app: { close: () => Promise; server?: { closeAllConnections?: () => void } } = { close }; if (forceClose) app.server = { closeAllConnections: forceClose }; @@ -56,7 +77,7 @@ describe("shutdown", () => { expect(forceClose).toHaveBeenCalledTimes(1); expect(s.events).toHaveBeenCalledTimes(1); expect(s.sessions).toHaveBeenCalledTimes(1); - expect(s.upstream).toHaveBeenCalledTimes(1); + expectUpstreamHookCalledOnce(s); }); it("does not run the stop hooks twice on a double invocation", async () => { @@ -68,7 +89,7 @@ describe("shutdown", () => { expect(s.events).toHaveBeenCalledTimes(1); expect(s.sessions).toHaveBeenCalledTimes(1); - expect(s.upstream).toHaveBeenCalledTimes(1); + expectUpstreamHookCalledOnce(s); }); it("stops the upstream even when closing the server fails", async () => { @@ -81,7 +102,7 @@ describe("shutdown", () => { expect(s.events).toHaveBeenCalledTimes(1); expect(s.sessions).toHaveBeenCalledTimes(1); - expect(s.upstream).toHaveBeenCalledTimes(1); + expectUpstreamHookCalledOnce(s); expect(s.warnings.some((line) => line.includes("closing the HTTP server failed"))).toBe(true); }); diff --git a/test/tools.test.ts b/test/tools.test.ts index 693e6e5..457d21f 100644 --- a/test/tools.test.ts +++ b/test/tools.test.ts @@ -58,6 +58,32 @@ describe("tool bridge instructions", () => { "at most one tool call block", ); }); + + it("rejects a tool_choice that requires a tool when none are declared", () => { + // Silently running without a bridge would leave the agent's own tools in + // place while the caller asked for a tool call: that request is invalid. + for (const choice of ["required", { name: "get_weather" }] as const) { + let caught: unknown; + try { + createToolBridge([], choice); + } catch (error) { + caught = error; + } + expect(caught).toMatchObject({ status: 400, code: "invalid_request", param: "tool_choice" }); + } + }); + + it("keeps accepting an optional or disabled tool_choice without tools", () => { + expect(createToolBridge([], "auto").active).toBe(false); + expect(createToolBridge([], "none").active).toBe(false); + expect(createToolBridge([]).active).toBe(false); + expect(createToolBridge([], undefined).instructions).toBe(""); + }); + + it("keeps accepting a tool-requiring choice when tools are declared", () => { + expect(createToolBridge([WEATHER], "required").active).toBe(true); + expect(createToolBridge([WEATHER], { name: "get_weather" }).active).toBe(true); + }); }); describe("parseToolCallBody", () => { @@ -94,6 +120,35 @@ describe("parseToolCallBody", () => { expect(calls[0]?.arguments).toBe('{"x":1}'); }); + it("repairs a trailing comma without rewriting one inside a string value", () => { + // The payload only fails to parse because of the comma before the final `}`. + // Repairing it must delete that comma, not the `,}` the model put in the text. + const calls = parseToolCallBody('{"name":"echo","arguments":{"text":"a,}",}}'); + expect(calls).toHaveLength(1); + expect(calls[0]?.name).toBe("echo"); + expect(JSON.parse(calls[0]?.arguments ?? "null")).toEqual({ text: "a,}" }); + }); + + it("keeps comma-bracket sequences and their spacing inside string values", () => { + const bracket = parseToolCallBody('{"name":"a","arguments":{"x":"[,]"},}'); + expect(JSON.parse(bracket[0]?.arguments ?? "null")).toEqual({ x: "[,]" }); + + const spaced = parseToolCallBody('{"name":"a","arguments":{"x":"a , } b"},}'); + expect(JSON.parse(spaced[0]?.arguments ?? "null")).toEqual({ x: "a , } b" }); + }); + + it("still repairs a genuine trailing comma inside an object", () => { + const calls = parseToolCallBody('{"name":"a","arguments":{"x":1,}}'); + expect(calls[0]?.arguments).toBe('{"x":1}'); + }); + + it("keeps a repaired string value inside a multi-value envelope", () => { + const calls = parseToolCallBody('{"name":"a","arguments":{"x":"[,]"},}\n{"name":"b","arguments":{}}'); + expect(calls.map((call) => call.name)).toEqual(["a", "b"]); + expect(JSON.parse(calls[0]?.arguments ?? "null")).toEqual({ x: "[,]" }); + expect(calls[1]?.arguments).toBe("{}"); + }); + it("returns nothing for unparsable payloads", () => { expect(parseToolCallBody("not json at all")).toEqual([]); expect(parseToolCallBody("")).toEqual([]); @@ -234,6 +289,19 @@ describe("ToolCallFilter", () => { expect(emitted + tail.text).toContain("definitely not json"); expect(tail.calls).toEqual([]); }); + + it("preserves comma-bracket text in a streamed envelope", () => { + const filter = new ToolCallFilter(); + const payload = `${TOOL_CALL_OPEN}{"name":"echo","arguments":{"text":"a,}",}}${TOOL_CALL_CLOSE}`; + let text = ""; + // One character at a time, so the delta boundary lands inside the envelope. + for (const char of payload) text += filter.push(char); + const tail = filter.finish(); + + expect(text + tail.text).toBe(""); + expect(tail.calls).toHaveLength(1); + expect(JSON.parse(tail.calls[0]?.arguments ?? "null")).toEqual({ text: "a,}" }); + }); }); describe("transcript rendering", () => { diff --git a/test/upstream-reconnect.test.ts b/test/upstream-reconnect.test.ts new file mode 100644 index 0000000..4bda138 --- /dev/null +++ b/test/upstream-reconnect.test.ts @@ -0,0 +1,288 @@ +/** + * P1 regression: a mid-turn event-stream reconnect must fail the turn loudly + * after a short grace window instead of silently truncating the answer. + * + * The fake hub below is reconnect-aware, unlike the one in + * `test/completion.test.ts` (whose `onReconnect` is a no-op), so it can drive + * `runCompletion` through a gap between two upstream connections. No network or + * live OpenCode server is involved. + */ +import { describe, expect, it } from "vitest"; +import { createLogger } from "../src/logger.js"; +import { createMetrics } from "../src/metrics/registry.js"; +import type { CompletionEvent, InternalRequest } from "../src/types/internal.js"; +import type { OpencodeEvent } from "../src/types/opencode.js"; +import type { OpencodeClient } from "../src/upstream/client.js"; +import { collectCompletion, runCompletion, type CompletionDeps } from "../src/upstream/completion.js"; +import type { EventHub, EventListener } from "../src/upstream/events.js"; +import { ModelRegistry } from "../src/upstream/models.js"; +import { SessionStore } from "../src/upstream/sessions.js"; +import { defaultModels, testConfig } from "./helpers/context.js"; + +interface Harness { + deps: CompletionDeps; + sessions: SessionStore; + /** Deliver an upstream event to the orchestrator as if it had been streamed. */ + emit: (event: OpencodeEvent) => void; + /** Simulate the hub noticing that the upstream stream reconnected. */ + fireReconnect: () => void; + interruptCalls: string[]; +} + +const SESSION_ID = "ses_test"; + +function harness( + script: (sessionId: string, call: number) => OpencodeEvent[], + configOverrides: Parameters[0] = {}, + options: { suppressReconnect?: boolean } = {}, +): Harness { + const config = testConfig({ modelCacheTtlMs: 60_000, ...configOverrides }); + const log = createLogger(config); + const metrics = createMetrics({ enabled: false }); + + const listeners = new Map>(); + const reconnectListeners = new Set<() => void>(); + const interruptCalls: string[] = []; + let callCount = 0; + + const events = { + subscribe(sessionId: string, listener: EventListener) { + const set = listeners.get(sessionId) ?? new Set(); + set.add(listener); + listeners.set(sessionId, set); + return () => { + set.delete(listener); + }; + }, + ensureConnected: async () => true, + start: () => undefined, + stop: async () => undefined, + onReconnect(listener: () => void) { + reconnectListeners.add(listener); + return () => { + reconnectListeners.delete(listener); + }; + }, + } as unknown as EventHub; + + const client = { + async listModels() { + return defaultModels(); + }, + async listProviders() { + return []; + }, + async listAgents() { + return [{ id: "build", name: "Build", mode: "primary", hidden: false, request: {} }]; + }, + async createSession() { + return { id: SESSION_ID }; + }, + async prompt(sessionId: string) { + const call = callCount; + callCount += 1; + queueMicrotask(() => { + for (const event of script(sessionId, call)) emitTo(sessionId, event); + }); + return { id: "msg_user" }; + }, + async interrupt(sessionId: string) { + interruptCalls.push(sessionId); + return undefined; + }, + async deleteSession() { + return undefined; + }, + } as unknown as OpencodeClient; + + function emitTo(sessionId: string, event: OpencodeEvent): void { + for (const listener of listeners.get(sessionId) ?? []) listener(event); + } + + const models = new ModelRegistry(client, config, log); + const sessions = new SessionStore(config, log, metrics); + const deps: CompletionDeps = { client, events, models, sessions, config, log, metrics }; + + return { + deps, + sessions, + interruptCalls, + emit: (event: OpencodeEvent) => emitTo(SESSION_ID, event), + fireReconnect: () => { + // `suppressReconnect` reproduces the pre-fix orchestrator, which never + // registered an `onReconnect` listener at all: the flag stays false. + if (options.suppressReconnect === true) return; + for (const listener of [...reconnectListeners]) listener(); + }, + }; +} + +function event(type: string, data: Record): OpencodeEvent { + return { id: `evt_${type}`, type, data: { sessionID: SESSION_ID, ...data } }; +} + +function request(): InternalRequest { + return { + surface: "openai.chat", + model: "opencode/seaglass-alpha-free", + messages: [{ role: "user", text: "Hello" }], + stream: false, + tools: [], + }; +} + +/** Consume the generator into an array, exposed as a promise. */ +function consume(harnessed: Harness): { events: CompletionEvent[]; done: Promise } { + const events: CompletionEvent[] = []; + const done = (async () => { + for await (const event of runCompletion(request(), harnessed.deps)) events.push(event); + })(); + return { events, done }; +} + +describe("runCompletion after an event-stream reconnect", () => { + it("fails the turn with event_stream_lost when no terminal event follows the gap", async () => { + const harnessed = harness( + () => [ + event("session.text.started", { assistantMessageID: "msg_a1", ordinal: 0 }), + event("session.text.delta", { assistantMessageID: "msg_a1", ordinal: 0, delta: "partial" }), + ], + // The gap grace window is capped by the request budget, so the failure is + // reported as the specific gap error rather than a generic timeout. + { upstreamRequestTimeoutMs: 300 }, + ); + + const { events, done } = consume(harnessed); + await waitFor(() => events.some((entry) => entry.kind === "text_delta")); + harnessed.fireReconnect(); + await done; + + expect(events.map((entry) => entry.kind)).toEqual(["start", "text_delta", "error"]); + const failure = events.at(-1); + expect(failure?.kind).toBe("error"); + if (failure?.kind !== "error") throw new Error("expected an error event"); + expect(failure.error.code).toBe("event_stream_lost"); + expect(failure.error.status).toBe(503); + expect(harnessed.interruptCalls).toEqual([SESSION_ID]); + }); + + it("reports the same gap as a generic timeout when the reconnect is not observed", async () => { + // Pre-fix behaviour, pinned as a contrast: before `execute()` subscribed to + // `onReconnect`, the gap was invisible, so the turn waited out the request + // budget and ended as `timeout_error` after up to `upstreamRequestTimeoutMs` + // (or truncated silently when a lost terminal event never arrived). + const harnessed = harness( + () => [ + event("session.text.started", { assistantMessageID: "msg_a1", ordinal: 0 }), + event("session.text.delta", { assistantMessageID: "msg_a1", ordinal: 0, delta: "partial" }), + ], + { upstreamRequestTimeoutMs: 300 }, + { suppressReconnect: true }, + ); + + const { events, done } = consume(harnessed); + await waitFor(() => events.some((entry) => entry.kind === "text_delta")); + harnessed.fireReconnect(); + await done; + + expect(events.map((entry) => entry.kind)).toEqual(["start", "text_delta", "error"]); + const failure = events.at(-1); + if (failure?.kind !== "error") throw new Error("expected an error event"); + expect(failure.error.code).toBe("timeout_error"); + expect(harnessed.interruptCalls).toEqual([SESSION_ID]); + }); + + it("completes normally when the terminal event arrives inside the grace window", async () => { + const harnessed = harness( + () => [event("session.text.delta", { assistantMessageID: "msg_a1", ordinal: 0, delta: "partial" })], + { upstreamRequestTimeoutMs: 30_000 }, + ); + + const { events, done } = consume(harnessed); + await waitFor(() => events.some((entry) => entry.kind === "text_delta")); + harnessed.fireReconnect(); + // Let the wait loop observe the gap and enter the grace window first. + await delay(50); + harnessed.emit(event("session.idle", { assistantMessageID: "msg_a1", outcome: "succeeded" })); + await done; + + expect(events.some((entry) => entry.kind === "error")).toBe(false); + const terminal = events.at(-1); + expect(terminal?.kind).toBe("end"); + if (terminal?.kind !== "end") throw new Error("expected an end event"); + expect(terminal.finishReason).toBe("stop"); + expect(harnessed.interruptCalls).toEqual([]); + }); + + it("does not fail a turn that never sees a reconnect", async () => { + const harnessed = harness( + () => [ + event("session.text.delta", { assistantMessageID: "msg_a1", ordinal: 0, delta: "partial" }), + event("session.step.ended", { + assistantMessageID: "msg_a1", + finish: "stop", + tokens: { input: 3, output: 1, reasoning: 0, cache: { read: 0, write: 0 } }, + }), + event("session.execution.succeeded", { assistantMessageID: "msg_a1" }), + ], + { upstreamRequestTimeoutMs: 300 }, + ); + + const { events, done } = consume(harnessed); + await done; + + expect(events.some((entry) => entry.kind === "error")).toBe(false); + const terminal = events.at(-1); + expect(terminal?.kind).toBe("end"); + }); + + it("releases the reserved session slot when the grace window expires", async () => { + const harnessed = harness( + (_sessionId, call) => + call === 0 + ? [ + event("session.text.delta", { assistantMessageID: "msg_a1", ordinal: 0, delta: "first" }), + event("session.step.ended", { + assistantMessageID: "msg_a1", + finish: "stop", + tokens: { input: 3, output: 1, reasoning: 0, cache: { read: 0, write: 0 } }, + }), + event("session.execution.succeeded", { assistantMessageID: "msg_a1" }), + ] + : [event("session.text.delta", { assistantMessageID: "msg_a2", ordinal: 0, delta: "partial" })], + { upstreamRequestTimeoutMs: 300 }, + ); + + // Turn 1 completes and caches the sticky session. + await collectCompletion(request(), harnessed.deps); + expect(harnessed.sessions.list()).toHaveLength(1); + + // Turn 2 reuses that session (so its record is reserved `busy`) and then the + // stream drops without a terminal event. + const { events, done } = consume(harnessed); + await waitFor(() => events.some((entry) => entry.kind === "text_delta")); + harnessed.fireReconnect(); + await done; + + const failure = events.at(-1); + if (failure?.kind !== "error") throw new Error("expected an error event"); + expect(failure.error.code).toBe("event_stream_lost"); + // The `finally` in `execute()` must release the reserved record, otherwise a + // later turn for this conversation would be forced onto a fresh session (or + // blocked) forever. + expect(harnessed.sessions.list().every((record) => !record.busy)).toBe(true); + }); +}); + +async function waitFor(predicate: () => boolean, timeoutMs = 2_000): Promise { + const deadline = Date.now() + timeoutMs; + while (Date.now() < deadline) { + if (predicate()) return; + await delay(5); + } + throw new Error("timed out waiting for condition"); +} + +function delay(ms: number): Promise { + return new Promise((resolve) => setTimeout(resolve, ms)); +}