diff --git a/README.md b/README.md index cc21286..c28fc17 100644 --- a/README.md +++ b/README.md @@ -414,6 +414,23 @@ Limitations, stated plainly: Bridged tools and native tools can appear in the same turn: the model may call your tool while the OpenCode agent independently uses its own. +## JSON output mode + +JSON output is bridged through the prompt for the same reason function calling is +— OpenCode accepts no per-request output schema: + +| Surface | Field | Values | +| --- | --- | --- | +| `/v1/chat/completions` | `response_format` | `{"type":"json_object"}`, `{"type":"json_schema","json_schema":{name,schema}}` | +| `/v1/responses` | `text.format` | `{"type":"json_object"}`, `{"type":"json_schema",name,schema}` | + +`{"type":"text"}` and an absent field leave the prompt unchanged. The gateway +adds a `# Response format` prompt section asking for a single valid JSON value +and, for a schema, for a value that validates against it. This is a model +contract, not a server-enforced one: nothing validates the reply, so a model that +ignores the instruction can still answer in prose. Validate the result on the +client when it matters. + ## Model naming | Form | Example | Resolves to | @@ -470,12 +487,16 @@ Every variable, with types, defaults and security notes: `opencode_api_`: `http_requests_total`, `http_request_duration_seconds`, `upstream_requests_total`, `upstream_request_duration_seconds`, `tokens_total`, `completions_total`, `active_streams`, `upstream_restarts_total`, - `session_cache_entries`, plus process defaults. Requires a key unless + `session_cache_entries`, `event_stream_connected`, plus process defaults. Requires a key unless `OPENCODE_METRICS_PUBLIC=true`. * **`/admin/*`** — `/admin/status` (config, upstream binary and URL, catalog counts, session count), `/admin/models/refresh`, `/admin/sessions` (list and delete-all), `/admin/upstream/restart`. Authenticated; restrict them at the proxy if you expose the gateway. +* **Request correlation.** Send `x-request-id` (up to 128 characters from + `A-Za-z0-9._:-`) and the gateway echoes it on the response and uses it as the + request id in its logs; anything else is replaced by a generated id. Streaming + responses carry it too. * **Sticky sessions.** OpenAI and Anthropic clients resend the whole conversation on every call. The gateway recognises the prefix it has already delivered upstream and continues the same OpenCode session instead of @@ -488,7 +509,9 @@ Every variable, with types, defaults and security notes: `OPENCODE_SESSION_CACHE=false` for fully stateless routing. * **Free-tier rate limits.** The bundled free models are limited per model and per window upstream. The gateway answers `429` with a `retry-after` header in - seconds and repeats the upstream message; back off for that long. Transient + seconds and repeats the upstream message; back off for that long. A stream + that already sent its first frame cannot add a header, so the same hint is + repeated as `retry_after_ms` inside the error frame. Transient `503 ServiceUnavailableError` ("Model is unavailable") is mapped to `overloaded_error`. Neither is a gateway bug — switch model or wait. @@ -558,7 +581,7 @@ The compose file maps `20123:20123`, reads `.env`, mounts | --- | --- | | `pnpm setup` | Write `.env` (keeps `sk-dummy-123`; `-- --random` generates a strong key instead). | | `pnpm dev` | Start with `tsx watch` and reload on change. | -| `pnpm build` | Type-check-free emit with `tsc -p tsconfig.build.json` into `dist/`. | +| `pnpm build` | Type-check and emit `src/` into `dist/` with `tsc -p tsconfig.build.json`. | | `pnpm typecheck` | `tsc -p tsconfig.json --noEmit`. | | `pnpm test` | Unit tests (excludes `test/integration/**`). | | `pnpm test:integration` | Integration tests against a live gateway/upstream. | @@ -584,7 +607,7 @@ opencode-api/ # package name; the project is "OpenCode API" │ │ ├── anthropic/ # /v1/messages, /v1/messages/count_tokens │ │ ├── common/ # reasoning mapping, tool bridge, usage maths │ │ └── openai/ # /v1/chat/completions, /v1/responses, /v1/models, /v1/embeddings -│ ├── http/ # SSE writer +│ ├── http/ # SSE writer, client-disconnect signal │ ├── media/ # data URI, remote fetch, local path resolution │ ├── metrics/ # Prometheus registry │ ├── routes/ # health, metrics, admin diff --git a/docs/API.md b/docs/API.md index c9b0ff2..89420e4 100644 --- a/docs/API.md +++ b/docs/API.md @@ -23,6 +23,7 @@ operational and documented in the README. | `x_opencode` | response field | Non-standard object attached to every completion payload: `session_id`, `agent`, `variant`, `reused_session`, and `native_tool_calls` (an array on the OpenAI surfaces, a count on the Anthropic surface) plus `reasoning: {enabled, note}` on `/v1/chat/completions`. | | `x-conversation-id` | request header | Explicit sticky-session key. Requests carrying the same value reuse the same upstream OpenCode session while their message prefix still matches. | | `x-opencode-agent` | request header | Run this request with a specific OpenCode agent instead of `OPENCODE_AGENT`. | +| `x-request-id` | request/response header | Caller-supplied correlation id, echoed on every response (JSON and SSE). Accepted when it matches `[A-Za-z0-9._:-]{1,128}`; anything else is replaced by a generated id. The same value is used as the request id in the gateway logs. | | `reasoning_effort` | request field | Non-standard on `/v1/messages`: an OpenAI-style alias for `thinking`. Ignored when `thinking` is present. | | `opencode.tool_call` | SSE event name | Native OpenCode tool activity (OpenAI chat surface only), emitted when `OPENCODE_EXPOSE_NATIVE_TOOLS=true`. Note that a request which declares `tools` runs with OpenCode's built-in actions denied (`OPENCODE_TOOL_BRIDGE_DENY_NATIVE_TOOLS=true`, the default), so native activity is normally empty for bridged turns. | @@ -64,11 +65,12 @@ when `OPENCODE_METRICS_PUBLIC=true`). | `reasoning_effort` | string | *(unset)* | `none`, `minimal`, `low`, `medium`, `high`, `xhigh`, `max` plus aliases (`off`, `min`, `maximum`, ...). | | `reasoning.effort` | string | *(unset)* | Used when `reasoning_effort` is absent. | | `max_tokens` / `max_completion_tokens` | number | *(unset)* | `max_completion_tokens` wins. Recorded, not enforced upstream: OpenCode's agent owns the generation budget. | -| `temperature`, `top_p` | number | *(unset)* | Accepted; sent upstream only for models whose capabilities advertise temperature support. | +| `temperature`, `top_p` | number | *(unset)* | Accepted and recorded, but not forwarded: OpenCode's agent loop owns the sampling parameters (same as `max_tokens`). | | `stop` | string \| string[] | *(unset)* | Accepted. Empty strings are dropped. | | `n` | number | `1` | **Only `1` is supported**; anything else returns `400 invalid_request`. | | `user`, `metadata`, `service_tier`, `parallel_tool_calls` | — | — | Accepted; not forwarded. `metadata` is carried on the internal request for logging. | -| `seed`, `logprobs`, `logit_bias`, `presence_penalty`, `frequency_penalty`, `response_format` | — | — | Accepted and deliberately ignored. | +| `response_format` | object | *(unset)* | `{"type":"text"}`, `{"type":"json_object"}` or `{"type":"json_schema","json_schema":{name,schema}}`. OpenCode cannot receive an output schema, so the requirement is rendered into the prompt (see "JSON output mode" below); it is a model contract, not a server-enforced one. | +| `seed`, `logprobs`, `logit_bias`, `presence_penalty`, `frequency_penalty` | — | — | Accepted and deliberately ignored. | ### Response (`stream: false`) @@ -112,7 +114,8 @@ when `OPENCODE_METRICS_PUBLIC=true`). semantics; `tool_calls` is then present. * `reasoning_content` is present only when reasoning was requested and surfaced. With `OPENCODE_REASONING_FIELD=both` an identical `reasoning` field is emitted - alongside it (the chat adapter reads that variable directly). + alongside it (read from `Config.reasoningField`, so two gateways in one process + cannot share the setting). * `finish_reason` is `stop`, `length`, `tool_calls` or `content_filter`; the internal `error`/`cancelled` reasons are reported as `stop`. * `x_opencode.native_tool_calls` lists native OpenCode tool activity as @@ -124,7 +127,8 @@ when `OPENCODE_METRICS_PUBLIC=true`). Headers: `content-type: text/event-stream; charset=utf-8`, `cache-control: no-cache, no-transform`, `x-accel-buffering: no`. A `: keep-alive` comment is written every 15 s. Frames carry the SSE `data:` field -only — the discriminator is inside the JSON, exactly like OpenAI. +only — the discriminator is inside the JSON, exactly like OpenAI. Headers set by +the gateway itself (CORS, `x-request-id`) are part of the SSE head too. ``` data: {"id":"chatcmpl-...","object":"chat.completion.chunk","created":1764662000,"model":"opencode/deepseek-v4.1-flash-free","choices":[{"index":0,"delta":{"role":"assistant","content":""},"finish_reason":null}]} @@ -192,7 +196,7 @@ data: {"error":{"message":"OpenCode did not finish the request in time.","type": | `401` | `invalid_request_error` | `authentication_error` | | `403` | `invalid_request_error` | `permission_error` | | `404` | `invalid_request_error` | `model_not_found` | -| `429` | `rate_limit_error` | `provider.free-limit`, `rate_limit_error` (with `retry-after` header, in seconds) | +| `429` | `rate_limit_error` | `provider.free-limit`, `rate_limit_error` (with `retry-after` header, in seconds; mid-stream the hint travels as `retry_after_ms` in the error frame instead) | | `499` | — | client disconnected before the response started | | `501` | `invalid_request_error` | `not_implemented_error` | | `502` | `api_error` | `upstream_error` | @@ -238,11 +242,14 @@ reasoning mapping and tool bridging with the chat endpoint. | `max_output_tokens`, `temperature`, `top_p`, `metadata`, `parallel_tool_calls`, `truncation` | — | — | Accepted and echoed back. `parallel_tool_calls` defaults to `true`; `truncation` defaults to `"disabled"`. | | `previous_response_id` | string | *(unset)* | Accepted and ignored — the gateway keeps no response store, so callers must resend the full `input`. Echoed as `null`. | | `store` | boolean | `false` | Accepted and ignored; nothing is persisted. Echoed as given. | -| `text.format`, `include`, `service_tier`, `top_logprobs`, `user` | — | — | Accepted for compatibility; no effect. | +| `text.format` | object | *(unset)* | `{"type":"text"}`, `{"type":"json_object"}` or `{"type":"json_schema",name,schema}`. Rendered into the prompt like the chat `response_format`; see "JSON output mode". | +| `include`, `service_tier`, `top_logprobs`, `user` | — | — | Accepted for compatibility; no effect. | `item_reference` items are skipped (they point at stored responses the gateway does not keep). `function_call` items become assistant tool calls; -`function_call_output` items become `role: "tool"` turns. +`function_call_output` items become `role: "tool"` turns. An `input_file` part +accepts `file_data`/`file_url`; a reference carrying only `file_id` is rejected +with `400 unsupported_file_reference` instead of being silently dropped. ### Response (`stream: false`) @@ -355,9 +362,9 @@ data: {"type":"response.completed","sequence_number":8,"response":{"id":"resp_.. * `response.created` and `response.in_progress` are always the first two frames, even before the upstream turn has been assigned a session. * Reasoning deltas use `response.reasoning_summary_part.added`, - `response.reasoning_summary_text.delta` and `response.reasoning_summary_text.done`; - the closing item appears as `response.output_item.done` with - `output_index: 0`. + `response.reasoning_summary_text.delta`, `response.reasoning_summary_text.done` + and `response.reasoning_summary_part.done`; the closing item then appears as + `response.output_item.done` with `output_index: 0`. * The message item occupies `output_index: 1` when a reasoning item precedes it. * Tool calls are emitted at the end of the stream as `response.output_item.added` (status `in_progress`), one @@ -533,7 +540,7 @@ Anthropic shape, selected by the request path (`/v1/messages*`): | `401` | `authentication_error` | | `403` | `permission_error` | | `404` | `not_found_error` | -| `429` | `rate_limit_error` (with `retry-after` header) | +| `429` | `rate_limit_error` (with `retry-after` header; mid-stream the hint travels as `retry_after_ms` in the error frame) | | `502` | `api_error` | | `503` | `overloaded_error` | | `504` | `timeout_error` | @@ -628,7 +635,7 @@ non-OpenAI fields are gateway extensions placed next to the standard keys. { "id": "opencode/deepseek-v4.1-flash-free", "object": "model", - "created": 1792195200000, + "created": 1792195200, "owned_by": "opencode", "name": "DeepSeek V4.1 Flash Free", "context_length": 200000, @@ -723,6 +730,24 @@ Unknown ids return `404`: } ``` +## JSON output mode + +OpenCode offers no per-request output-schema control: the client's tools cannot +be passed to it either, and function calling is bridged through the prompt for +the same reason. JSON output follows the same pattern. + +* `/v1/chat/completions`: `response_format` with `{"type":"json_object"}` or + `{"type":"json_schema","json_schema":{name,schema}}`. +* `/v1/responses`: `text.format` with `{"type":"json_object"}` or + `{"type":"json_schema",name,schema}`. +* `{"type":"text"}` and an absent field leave the prompt unchanged. + +The gateway appends a `# Response format` section to the prompt asking for a +single valid JSON value (plus the schema, when one was supplied) and no prose or +code fence. This is a **model contract, not a server-enforced one**: nothing +validates the reply, so a model that ignores the instruction can still return +prose. Validate the reply on the client when it matters. + ## Streaming mechanics * SSE payloads are UTF-8 JSON; a payload containing newlines is split across @@ -733,11 +758,15 @@ Unknown ids return `404`: return a proper JSON error with an HTTP status. `/v1/responses` opens the stream immediately and therefore reports pre-flight failures as an `error` frame. +* The SSE head carries every header the gateway set on the reply (CORS, + `x-request-id`), because the response is written outside Fastify's serialiser. * The gateway already sends `x-accel-buffering: no`; use `curl -N` and disable any proxy buffering when testing. * A client disconnect aborts the upstream turn: the gateway interrupts the - OpenCode session and releases the sticky session slot. In non-streaming mode a - cancelled request surfaces as `499`. + OpenCode session, cancels any in-flight attachment download and releases the + sticky session slot. Disconnects are detected from the response connection + (`request.raw` `close` fires when the body has been read, not when the caller + leaves). In non-streaming mode a cancelled request surfaces as `499`. * Sessions are reused only when the client resends a conversation whose prefix matches what the upstream session already holds. Pass `x-conversation-id` to make the key explicit, or set `OPENCODE_SESSION_CACHE=false` to disable reuse. diff --git a/docs/ARCHITECTURE.md b/docs/ARCHITECTURE.md index 2324038..369c0fa 100644 --- a/docs/ARCHITECTURE.md +++ b/docs/ARCHITECTURE.md @@ -171,8 +171,9 @@ completion work. ### 4.1 `src/types/internal.ts` (frozen) `Surface`, `Attachment`, `AttachmentKind`, `ToolDefinition`, `ToolCall`, -`InternalMessage`, `ReasoningRequest`, `InternalRequest`, `Usage`, -`FinishReason`, `NativeToolActivity`, `CompletionEvent`. +`InternalMessage`, `ReasoningRequest`, `ResponseFormat`, +`InternalRequest`, `Usage`, `FinishReason`, `NativeToolActivity`, +`CompletionEvent`. ### 4.2 `src/errors.ts` (frozen) @@ -279,7 +280,10 @@ Shared helpers each adapter may use: * `ctx.completion.run(request, completionDeps(ctx), { signal })` → `AsyncGenerator` * `ctx.completion.collect(request, completionDeps(ctx), { signal })` → `Promise` * `completionDeps(ctx)` from `src/context.ts` -* `SseWriter` from `src/http/sse.ts` +* `SseWriter` from `src/http/sse.ts` (its head merges `reply.getHeaders()`, + because `reply.hijack()` bypasses Fastify's serialiser) +* `createDisconnectSignal(request, reply)` from `src/http/disconnect.ts` — the + only supported way to turn a client disconnect into an `AbortSignal` * `ApiError` from `src/errors.ts` (throw it; the global error handler renders the right shape — Anthropic shape for `/v1/messages*`, OpenAI shape otherwise) * `resolveAttachment` from `src/media/resolve.ts` @@ -298,7 +302,9 @@ tests can substitute a scripted runner (`test/helpers/context.ts`). * Never call the model provider directly; use `runCompletion`/`collectCompletion`. * Streaming handlers must: * create the `SseWriter` only after validation succeeds, - * pass `{ signal }` from `request.raw` `close` events into `runCompletion`, + * pass the `createDisconnectSignal()` signal into `runCompletion` (`request.raw` + `close` fires when the body has been read on Node >= 16, so it is not a + disconnect signal), * always `close()` the writer, * increment `ctx.metrics.activeStreams` and decrement it in `finally`. * Tests live in `test/**/*.test.ts` and run with `vitest`. Unit tests must not @@ -336,3 +342,13 @@ tests can substitute a scripted runner (`test/helpers/context.ts`). embedding model is exposed by OpenCode. * Model names accept both `provider/model` and the bare `model` id, plus an optional `#variant` suffix and `OPENCODE_MODEL_ALIASES` indirection. +* Every response carries `x-request-id`: a caller-supplied value that matches + `[A-Za-z0-9._:-]{1,128}`, otherwise a generated id. It is the Fastify request + id, so it also correlates the log lines of one request. +* JSON output is bridged through the prompt, exactly like tool calling: + `response_format` (chat) and `text.format` (responses) become a + `# Response format` prompt section (`InternalRequest.responseFormat`). Nothing + validates the reply server-side. +* Client disconnects are detected from the response connection + (`src/http/disconnect.ts`); an in-flight turn is interrupted, the sticky slot + is released and a pending media download is aborted. diff --git a/docs/CONFIGURATION.md b/docs/CONFIGURATION.md index ef7ab33..6d81df5 100644 --- a/docs/CONFIGURATION.md +++ b/docs/CONFIGURATION.md @@ -100,6 +100,7 @@ uploads are always inlined for OpenCode as a `data:` URI. See the README section | `OPENCODE_TOOL_BRIDGE_DENY_NATIVE_TOOLS` | boolean | `true` | When a request declares client tools, add `deny` permission rules for OpenCode's built-in actions (`bash`, `webfetch`, `websearch`, `edit`, `write`, `patch`, `task`, `skill`) so the model emits a bridged tool call instead of running its own tools. | **Keep `true`.** Setting it to `false` lets a request that declares any tool also drive the agent's shell, web and file tools. The deny rules are merged on top of `OPENCODE_AGENT_PERMISSIONS` for that session only. | | `OPENCODE_EXPOSE_NATIVE_TOOLS` | boolean | `false` | Stream native OpenCode tool activity as SSE events (see `OPENCODE_NATIVE_TOOL_EVENT`). | Native tool payloads can reveal file paths and command input/output from the agent's workspace. | | `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_METRICS_ENABLED` | boolean | `true` | Enable Prometheus collection; when false, `GET /metrics` answers `404`. | — | @@ -108,15 +109,6 @@ uploads are always inlined for OpenCode as a `data:` URI. See the README section Boolean values accept `1/true/yes/on/enabled` and `0/false/no/off/disabled` (case-insensitive). Any other value falls back to the default. -## Adapter-level settings - -These are read directly by an adapter rather than by `src/config.ts`, so they are -not part of the `Config` object. - -| Variable | Type | Default | Description | Security implication | -| --- | --- | --- | --- | --- | -| `OPENCODE_REASONING_FIELD` | `reasoning_content` \| `both` | `reasoning_content` | `POST /v1/chat/completions` only: when `both`, the chat adapter emits an extra `reasoning` alias next to `reasoning_content` on messages and deltas. | — | - ## Environment variables read by other libraries `dotenv` loads `.env` in the working directory. The upstream launcher inherits the @@ -130,9 +122,13 @@ descriptor. The gateway exits with code 1 (before it listens) when: -1. no key is configured and `OPENCODE_ALLOW_NO_AUTH` is not `true`; -2. `OPENCODE_AGENT_PERMISSIONS` is set but is not a JSON array; -3. `OPENCODE_MODEL_ALIASES` is set but is not a JSON object. +1. `OPENCODE_AGENT_PERMISSIONS` is set but is not a JSON array; +2. `OPENCODE_MODEL_ALIASES` is set but is not a JSON object. + +A missing key is **not** fatal: with neither `OPENCODE_API_KEYS` nor +`OPENCODE_API_KEY` set, the gateway starts with the built-in development key +`sk-dummy-123` and logs a warning. Every variable is otherwise clamped to its +documented bounds, and an unrecognised boolean/value falls back to the default. ## Recommended hardening for a reachable deployment diff --git a/src/adapter/anthropic/messages.ts b/src/adapter/anthropic/messages.ts index 0cfe670..4e88f85 100644 --- a/src/adapter/anthropic/messages.ts +++ b/src/adapter/anthropic/messages.ts @@ -18,6 +18,7 @@ import { z } from "zod"; 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 type { CollectedCompletion } from "../../upstream/completion.js"; @@ -635,19 +636,6 @@ function headerValue(request: FastifyRequest, name: string): string | undefined return undefined; } -/** Abort the upstream call when the client goes away. */ -function abortOnClose(request: FastifyRequest): { signal: AbortSignal; dispose: () => void } { - const controller = new AbortController(); - const onClose = (): void => controller.abort(); - request.raw.on("close", onClose); - return { - signal: controller.signal, - dispose: () => { - request.raw.off("close", onClose); - }, - }; -} - /** * Stream one completion as Anthropic SSE. * @@ -850,7 +838,7 @@ async function streamAnthropicMessage( export function registerAnthropicMessageRoutes(app: FastifyInstance, ctx: AppContext): void { app.post("/v1/messages", async (request, reply) => { - const abort = abortOnClose(request); + const abort = createDisconnectSignal(request, reply); try { const body = parseAnthropicMessagesBody(request.body); const resolved = await ctx.models.resolve(body.model); diff --git a/src/adapter/openai/chat.ts b/src/adapter/openai/chat.ts index c95c2c7..6171aec 100644 --- a/src/adapter/openai/chat.ts +++ b/src/adapter/openai/chat.ts @@ -13,6 +13,7 @@ import { reasoningFromEffort } from "../common/reasoning.js"; import type { Config } from "../../config.js"; 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 { @@ -21,6 +22,7 @@ import { type FinishReason, type InternalMessage, type InternalRequest, + type ResponseFormat, type ToolCall, type ToolDefinition, type Usage, @@ -106,6 +108,25 @@ const toolChoiceSchema = z.union([ }), ]); +const responseFormatSchema = z.union([ + z.object({ type: z.literal("text") }).passthrough(), + z.object({ type: z.literal("json_object") }).passthrough(), + z + .object({ + type: z.literal("json_schema"), + json_schema: z + .object({ + name: z.string().optional(), + description: z.string().optional(), + schema: z.record(z.string(), z.unknown()).optional(), + strict: z.boolean().optional(), + }) + .passthrough() + .optional(), + }) + .passthrough(), +]); + const chatRequestSchema = z.object({ model: z.string().min(1), messages: z.array(messageSchema).min(1), @@ -131,7 +152,7 @@ const chatRequestSchema = z.object({ logit_bias: z.unknown().optional(), presence_penalty: z.unknown().optional(), frequency_penalty: z.unknown().optional(), - response_format: z.unknown().optional(), + response_format: responseFormatSchema.optional(), }); type ChatRequest = z.infer; @@ -141,7 +162,6 @@ type ChatFile = z.infer["file"]; // ----------------------------------------------------------------- routes --- export function registerOpenAiChatRoutes(app: FastifyInstance, ctx: AppContext): void { - reasoningField = ctx.config.reasoningField; app.post("/v1/chat/completions", async (request, reply) => { const parsed = chatRequestSchema.safeParse(request.body); if (!parsed.success) throw invalidRequestFromZod(parsed.error); @@ -158,26 +178,24 @@ export function registerOpenAiChatRoutes(app: FastifyInstance, ctx: AppContext): // even when the completion runner would only report them mid-stream. const resolved = await ctx.models.resolve(body.model); - const controller = new AbortController(); - const onClose = (): void => controller.abort(); - request.raw.on("close", onClose); + const abort = createDisconnectSignal(request, reply); try { - const internal = await buildRequest(body, request, resolved, ctx.config, controller.signal); + const internal = await buildRequest(body, request, resolved, ctx.config, abort.signal); if (body.stream !== true) { const collected = await ctx.completion.collect(internal, completionDeps(ctx), { - signal: controller.signal, + signal: abort.signal, }); - return reply.send(chatCompletionBody(collected)); + return reply.send(chatCompletionBody(collected, ctx.config.reasoningField)); } await streamChat(ctx, internal, reply, { includeUsage: body.stream_options?.include_usage === true, - signal: controller.signal, + signal: abort.signal, }); return reply; } finally { - request.raw.off("close", onClose); + abort.dispose(); } }); } @@ -212,6 +230,9 @@ async function buildRequest( const reasoning = reasoningFromEffort(body.reasoning_effort) ?? reasoningFromEffort(body.reasoning?.effort); if (reasoning !== undefined) internal.reasoning = reasoning; + const responseFormat = toResponseFormat(body.response_format); + if (responseFormat !== undefined) internal.responseFormat = responseFormat; + if (typeof body.temperature === "number") internal.temperature = body.temperature; if (typeof body.top_p === "number") internal.topP = body.top_p; @@ -300,6 +321,18 @@ function toToolCalls(calls: ChatMessage["tool_calls"]): ToolCall[] { })); } +/** Map OpenAI `response_format` onto the internal JSON output request. */ +function toResponseFormat(format: ChatRequest["response_format"]): ResponseFormat | undefined { + if (format === undefined || format.type === "text") return undefined; + if (format.type === "json_object") return { type: "json_object" }; + const spec = format.json_schema; + return { + type: "json_schema", + ...(spec?.name !== undefined ? { name: spec.name } : {}), + ...(spec?.schema !== undefined ? { schema: spec.schema } : {}), + }; +} + function toToolDefinition(tool: z.infer): ToolDefinition { const parameters = isRecord(tool.function.parameters) ? tool.function.parameters : { type: "object", properties: {} }; const definition: ToolDefinition = { name: tool.function.name, parameters }; @@ -399,7 +432,7 @@ function audioMime(format: string | undefined): string { // --------------------------------------------------------- non-streaming out --- -function chatCompletionBody(collected: CollectedCompletion): Record { +function chatCompletionBody(collected: CollectedCompletion, field: ReasoningField): Record { return { id: `chatcmpl-${randomUUID().replace(/-/g, "")}`, object: "chat.completion", @@ -408,7 +441,7 @@ function chatCompletionBody(collected: CollectedCompletion): Record { +function messagePayload(collected: CollectedCompletion, field: ReasoningField): Record { const calls = collected.calls.map((call) => ({ id: call.id, type: "function", @@ -431,7 +464,7 @@ function messagePayload(collected: CollectedCompletion): Record if (collected.reasoningEnabled && collected.reasoning.length > 0) { message["reasoning_content"] = collected.reasoning; - if (reasoningFieldMode() === "both") message["reasoning"] = collected.reasoning; + if (field === "both") message["reasoning"] = collected.reasoning; } return message; } @@ -515,7 +548,7 @@ async function streamChat( case "reasoning_delta": { const delta: Record = { reasoning_content: event.text }; - if (reasoningFieldMode() === "both") delta["reasoning"] = event.text; + if (ctx.config.reasoningField === "both") delta["reasoning"] = event.text; ensure().send({ ...base, choices: [{ index: 0, delta, finish_reason: null }] }); break; } @@ -607,14 +640,12 @@ function mapFinishReason(reason: FinishReason): string { } /** - * Where thinking output is reported. Set from `OPENCODE_REASONING_FIELD` - * (`reasoning_content`, the DeepSeek-compatible default, or `both`). + * Where thinking output is reported, taken from `Config.reasoningField` + * (`OPENCODE_REASONING_FIELD`): `reasoning_content` (the DeepSeek-compatible + * default) or `both` (adds a `reasoning` alias). Read from the server config on + * every request so two gateways in one process cannot share the setting. */ -let reasoningField: "reasoning_content" | "both" = "reasoning_content"; - -function reasoningFieldMode(): "reasoning_content" | "both" { - return reasoningField; -} +type ReasoningField = Config["reasoningField"]; /** * Build an in-stream OpenAI error frame. diff --git a/src/adapter/openai/responses.ts b/src/adapter/openai/responses.ts index 6de7266..a2e1488 100644 --- a/src/adapter/openai/responses.ts +++ b/src/adapter/openai/responses.ts @@ -27,6 +27,7 @@ import { normaliseArguments } from "../common/tools.js"; import { EMPTY_USAGE } from "../common/usage.js"; 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 type { @@ -36,6 +37,7 @@ import type { InternalMessage, InternalRequest, NativeToolActivity, + ResponseFormat, ToolCall, ToolDefinition, Usage, @@ -61,6 +63,7 @@ const inputFilePart = z filename: z.string().optional(), file_data: z.string().optional(), file_url: z.string().optional(), + file_id: z.string().optional(), }) .passthrough(); const inputAudioPart = z @@ -303,19 +306,21 @@ export function registerOpenAiResponsesRoutes(app: FastifyInstance, ctx: AppCont } const body = parsed.data; - // Resolve the model before opening a stream so an unknown model is reported - // as an HTTP 404 rather than as an in-stream error event. - await ctx.models.resolve(body.model); - const prepared = await prepare(body, request, ctx); - const abort = createAbortSignal(request); - - if (body.stream === true) { - await streamResponse(prepared, reply, ctx, abort.signal); - abort.dispose(); - return reply; - } + // The signal exists before normalisation so media downloads started while + // mapping the input can be cancelled when the caller disconnects. + const abort = createDisconnectSignal(request, reply); try { + // Resolve the model before opening a stream so an unknown model is + // reported as an HTTP 404 rather than as an in-stream error event. + await ctx.models.resolve(body.model); + const prepared = await prepare(body, request, ctx, abort.signal); + + if (body.stream === true) { + await streamResponse(prepared, reply, ctx, abort.signal); + return reply; + } + const collected = await ctx.completion.collect(prepared.request, completionDeps(ctx), { signal: abort.signal, }); @@ -349,7 +354,12 @@ export function registerOpenAiResponsesRoutes(app: FastifyInstance, ctx: AppCont * `instructions` becomes a leading `system` message; media parts are resolved * through the shared media pipeline and attached to their user message. */ -async function prepare(body: ResponsesRequest, request: FastifyRequest, ctx: AppContext): Promise { +async function prepare( + body: ResponsesRequest, + request: FastifyRequest, + ctx: AppContext, + signal: AbortSignal, +): Promise { const messages: InternalMessage[] = []; if (body.instructions !== undefined && body.instructions.length > 0) { messages.push({ role: "system", text: body.instructions }); @@ -358,7 +368,7 @@ async function prepare(body: ResponsesRequest, request: FastifyRequest, ctx: App if (typeof body.input === "string") { messages.push({ role: "user", text: body.input }); } else { - messages.push(...(await mapInputItems(body.input, ctx))); + messages.push(...(await mapInputItems(body.input, ctx, signal))); } const tools: ToolDefinition[] = (body.tools ?? []).map((tool) => ({ @@ -369,6 +379,7 @@ async function prepare(body: ResponsesRequest, request: FastifyRequest, ctx: App const choice = mapToolChoice(body.tool_choice); const reasoning = reasoningFromEffort(body.reasoning?.effort); + const responseFormat = mapResponseFormat(body.text?.format); const conversationKey = headerValue(request, "x-conversation-id"); const agent = headerValue(request, "x-opencode-agent"); @@ -380,6 +391,7 @@ async function prepare(body: ResponsesRequest, request: FastifyRequest, ctx: App tools, ...(choice !== undefined ? { toolChoice: choice } : {}), ...(reasoning !== undefined ? { reasoning } : {}), + ...(responseFormat !== undefined ? { responseFormat } : {}), ...(body.temperature !== undefined ? { temperature: body.temperature } : {}), ...(body.top_p !== undefined ? { topP: body.top_p } : {}), ...(body.max_output_tokens !== undefined ? { maxTokens: body.max_output_tokens } : {}), @@ -412,7 +424,7 @@ async function prepare(body: ResponsesRequest, request: FastifyRequest, ctx: App } /** Map the `input` array onto internal messages, preserving order. */ -async function mapInputItems(items: InputItem[], ctx: AppContext): Promise { +async function mapInputItems(items: InputItem[], ctx: AppContext, signal: AbortSignal): Promise { const messages: InternalMessage[] = []; for (const item of items) { @@ -435,7 +447,7 @@ async function mapInputItems(items: InputItem[], ctx: AppContext): Promise { if (typeof content === "string") return { role, text: content }; @@ -465,6 +478,12 @@ async function mapMessageItem( media.push(urlSource(urlOf(part.image_url))); break; case "input_file": { + if (part.file_id !== undefined && part.file_data === undefined && part.file_url === undefined) { + throw ApiError.badRequest( + "`file_id` references are not supported: send `file_data` as base64/a data URI or a `file_url`.", + { code: "unsupported_file_reference", param: "input" }, + ); + } const source: MediaSource = {}; if (part.file_data !== undefined) { if (isDataUri(part.file_data)) source.dataUri = part.file_data; @@ -495,7 +514,7 @@ async function mapMessageItem( if (media.length > 0) { const attachments: Attachment[] = []; for (const source of media) { - attachments.push(await resolveAttachment(source, ctx.config)); + attachments.push(await resolveAttachment(source, ctx.config, { signal })); } message.attachments = attachments; } @@ -541,6 +560,17 @@ function contentToText(value: string | ContentPart[] | undefined): string { .join("\n"); } +/** Map the Responses `text.format` object onto the internal JSON output request. */ +function mapResponseFormat(format: z.infer | undefined): ResponseFormat | undefined { + if (format === undefined || format.type === "text") return undefined; + if (format.type === "json_object") return { type: "json_object" }; + return { + type: "json_schema", + ...(format.name !== undefined ? { name: format.name } : {}), + ...(format.schema !== undefined ? { schema: format.schema } : {}), + }; +} + function mapToolChoice(value: unknown): InternalRequest["toolChoice"] | undefined { if (typeof value === "string") { if (value === "auto" || value === "none" || value === "required") return value; @@ -568,30 +598,6 @@ function headerValue(request: FastifyRequest, name: string): string | undefined return first !== undefined && first.length > 0 ? first : undefined; } -/** - * Build the cancellation signal for one request. - * - * The abort controller is wired to `request.raw` `close`/`aborted`, which is how - * Fastify surfaces a client disconnect. The listener is attached lazily (only - * when streaming starts) and always removed by `dispose()`. - */ -function createAbortSignal(request: FastifyRequest): { signal: AbortSignal; dispose: () => void } { - const controller = new AbortController(); - const onClosed = (): void => controller.abort(); - const raw = request.raw; - if (raw.aborted) controller.abort(); - raw.on("aborted", onClosed); - raw.on("close", onClosed); - - return { - signal: controller.signal, - dispose: () => { - raw.off("aborted", onClosed); - raw.off("close", onClosed); - }, - }; -} - // ------------------------------------------------------------------ payload --- function newId(prefix: string): string { @@ -726,38 +732,44 @@ async function streamResponse( ): Promise { const writer = new SseWriter(reply); ctx.metrics.activeStreams.inc({ surface: SURFACE }); - writer.open(); - - const state: StreamState = { - id: newId("resp"), - sessionId: "", - agent: prepared.request.agent ?? "", - variant: null, - reusedSession: false, - nativeTools: [], - reasoningEnabled: false, - reasoningRequested: prepared.reasoningRequested, - reasoningId: newId("rs"), - reasoningStarted: false, - reasoningVisible: false, - reasoningText: "", - messageId: newId("msg"), - messageStarted: false, - text: "", - calls: [], - usage: null, - finishReason: "stop", - }; + let opened = false; try { + writer.open(); + opened = true; + + const state: StreamState = { + id: newId("resp"), + sessionId: "", + agent: prepared.request.agent ?? "", + variant: null, + reusedSession: false, + nativeTools: [], + reasoningEnabled: false, + reasoningRequested: prepared.reasoningRequested, + reasoningId: newId("rs"), + reasoningStarted: false, + reasoningVisible: false, + reasoningText: "", + messageId: newId("msg"), + messageStarted: false, + text: "", + calls: [], + usage: null, + finishReason: "stop", + }; + const events = ctx.completion.run(prepared.request, completionDeps(ctx), { signal }); await pipeEvents(events, writer, prepared, state); } catch (error) { + // A head that could not be written still has a status line to send, so the + // failure is rethrown for Fastify; only a started stream reports in-band. + if (!opened) throw error; const apiError = toApiError(error, "OpenCode completion failed."); writer.send(errorFrame(apiError, Number.MAX_SAFE_INTEGER), "error"); } finally { ctx.metrics.activeStreams.dec({ surface: SURFACE }); - writer.close(); + if (opened) writer.close(); } } @@ -876,6 +888,17 @@ async function pipeEvents( }, "response.reasoning_summary_text.done", ); + writer.send( + { + type: "response.reasoning_summary_part.done", + sequence_number: sequence++, + item_id: state.reasoningId, + output_index: reasoningOutputIndex(), + summary_index: 0, + part: { type: "summary_text", text: state.reasoningText }, + }, + "response.reasoning_summary_part.done", + ); break; } diff --git a/src/http/disconnect.ts b/src/http/disconnect.ts new file mode 100644 index 0000000..ba297bc --- /dev/null +++ b/src/http/disconnect.ts @@ -0,0 +1,48 @@ +/** + * Cancellation signal for one inbound request. + * + * Every surface aborts the upstream turn when the caller goes away, but + * `IncomingMessage` "close" is **not** a disconnect signal on Node >= 16: it + * fires as soon as the request body has been consumed, which Fastify does before + * the route handler runs. A listener attached there therefore either misses the + * disconnect completely or aborts a healthy request, depending on when the body + * happened to be parsed. + * + * The response is the reliable source. Its "close" fires on a premature client + * disconnect (`writableFinished` is still false) and on a completed response + * (ignored), and the underlying socket "close" is used as a second signal for + * the same condition. + */ +import type { FastifyReply, FastifyRequest } from "fastify"; + +export interface DisconnectSignal { + signal: AbortSignal; + /** Remove the listeners attached to the request/reply. */ + dispose: () => void; +} + +export function createDisconnectSignal(request: FastifyRequest, reply: FastifyReply): DisconnectSignal { + const controller = new AbortController(); + const socket = request.raw.socket; + + if (socket?.destroyed === true || reply.raw.destroyed) { + controller.abort(); + } + + const onClose = (): void => { + // A response that finished normally also closes its socket; only an + // unfinished response means the caller went away. + if (!reply.raw.writableFinished) controller.abort(); + }; + + socket?.on("close", onClose); + reply.raw.on("close", onClose); + + return { + signal: controller.signal, + dispose: () => { + socket?.off("close", onClose); + reply.raw.off("close", onClose); + }, + }; +} diff --git a/src/http/sse.ts b/src/http/sse.ts index dc999e1..8d2d398 100644 --- a/src/http/sse.ts +++ b/src/http/sse.ts @@ -34,6 +34,10 @@ export class SseWriter { open(): void { const raw = this.#reply.raw; raw.writeHead(200, { + // `reply.hijack()` below stops Fastify from serialising the reply itself, + // so anything a hook attached (CORS, `x-request-id`, ...) has to be copied + // into the head explicitly; the SSE headers always win. + ...(this.#reply.getHeaders() as Record), "content-type": "text/event-stream; charset=utf-8", "cache-control": "no-cache, no-transform", connection: "keep-alive", @@ -100,8 +104,3 @@ export class SseWriter { this.#options.onClose?.(); } } - -/** Standard SSE headers documented in the OpenAI and Anthropic references. */ -export const SSE_HEADERS: Record = { - "cache-control": "no-cache, no-transform", -}; diff --git a/src/logger.ts b/src/logger.ts index 6e4fb06..7bbe55a 100644 --- a/src/logger.ts +++ b/src/logger.ts @@ -44,9 +44,3 @@ export function createLogger(config: Config): Logger { } return pino(options); } - -/** Logger used before configuration is available (module import time). */ -export const bootstrapLogger: Logger = pino({ - level: process.env["OPENCODE_LOG_LEVEL"] ?? "info", - base: { service: "opencode-api" }, -}); diff --git a/src/media/resolve.ts b/src/media/resolve.ts index 0031360..2be2f99 100644 --- a/src/media/resolve.ts +++ b/src/media/resolve.ts @@ -444,45 +444,72 @@ const MIME_SAMPLE_EXTENSIONS: Record = { export function isPrivateHost(hostname: string): boolean { let host = hostname.replace(/^\[|\]$/g, "").toLowerCase(); - // IPv6-mapped IPv4, in either the dotted form (`::ffff:127.0.0.1`) or the + // IPv4-mapped IPv6, in either the dotted form (`::ffff:127.0.0.1`) or the // normalised hex form WHATWG URL produces (`::ffff:7f00:1`). - if (host.startsWith("::ffff:")) { - const tail = host.slice("::ffff:".length); - if (/^\d{1,3}(?:\.\d{1,3}){3}$/.test(tail)) { - host = tail; - } else { - const hex = /^([0-9a-f]{1,4}):([0-9a-f]{1,4})$/.exec(tail); - if (hex) { - const high = Number.parseInt(hex[1] as string, 16); - const low = Number.parseInt(hex[2] as string, 16); - host = `${(high >> 8) & 0xff}.${high & 0xff}.${(low >> 8) & 0xff}.${low & 0xff}`; - } - } - } + const mapped = embeddedIpv4(host); + if (mapped !== undefined) host = mapped; - if (host === "localhost" || host.endsWith(".localhost") || host === "::1" || host.endsWith(".local")) return true; - if (host === "0.0.0.0" || host === "::" || host === "[::]") return true; - if (host.endsWith(".internal") || host.endsWith(".home.arpa")) return true; - - const ipv4 = /^(\d{1,3})\.(\d{1,3})\.(\d{1,3})\.(\d{1,3})$/.exec(host); - if (ipv4) { - const [a, b] = ipv4.slice(1, 5).map((part) => Number(part)) as [number, number, number, number]; - if (a === 10) return true; - if (a === 127) return true; - if (a === 0) return true; - if (a === 169 && b === 254) return true; - if (a === 172 && b >= 16 && b <= 31) return true; - if (a === 192 && b === 168) return true; - if (a === 192 && b === 0) return true; - if (a === 198 && (b === 18 || b === 19)) return true; - if (a === 100 && b >= 64 && b <= 127) return true; - if (a >= 224) return true; - return false; - } + // DNS names get the name-based checks only: a hostname that merely starts + // with `fc`, `fd` or `fe` (fcbank.com, fdic.gov, ...) is not an IPv6 range. + if (!host.includes(":")) return isPrivateHostname(host); + return isPrivateIpv6(host); +} + +/** Convert `::ffff:a.b.c.d` / `::ffff:xxxx:yyyy` / `::xxxx:yyyy` to dotted IPv4. */ +function embeddedIpv4(host: string): string | undefined { + const mapped = /^::ffff:(.+)$/.exec(host); + const tail = mapped?.[1] ?? /^::([0-9a-f]{1,4}:[0-9a-f]{1,4})$/.exec(host)?.[1]; + if (tail === undefined) return undefined; + if (/^\d{1,3}(?:\.\d{1,3}){3}$/.test(tail)) return tail; + const hex = /^([0-9a-f]{1,4}):([0-9a-f]{1,4})$/.exec(tail); + if (!hex) return undefined; + const high = Number.parseInt(hex[1] as string, 16); + const low = Number.parseInt(hex[2] as string, 16); + return `${(high >> 8) & 0xff}.${high & 0xff}.${(low >> 8) & 0xff}.${low & 0xff}`; +} + +function isPrivateHostname(host: string): boolean { + if (host === "") return false; + if (host === "localhost" || host.endsWith(".localhost")) return true; + if (host.endsWith(".local") || host.endsWith(".internal") || host.endsWith(".home.arpa")) return true; + const octets = parseIpv4(host); + return octets !== undefined && isPrivateIpv4(octets); +} + +function parseIpv4(host: string): [number, number, number, number] | undefined { + const match = /^(\d{1,3})\.(\d{1,3})\.(\d{1,3})\.(\d{1,3})$/.exec(host); + if (!match) return undefined; + const octets = match.slice(1, 5).map((part) => Number(part)); + if (octets.some((part) => !Number.isInteger(part) || part < 0 || part > 255)) return undefined; + return octets as [number, number, number, number]; +} + +function isPrivateIpv4(octets: readonly [number, number, number, number]): boolean { + const [a, b] = octets; + if (a === 0 || a === 10 || a === 127) return true; + if (a === 169 && b === 254) return true; + if (a === 172 && b >= 16 && b <= 31) return true; + if (a === 192 && b === 168) return true; + if (a === 192 && b === 0) return true; + if (a === 198 && (b === 18 || b === 19)) return true; + if (a === 100 && b >= 64 && b <= 127) return true; + // Multicast (224/4), reserved (240/4) and the limited broadcast address. + if (a >= 224) return true; + return false; +} - // IPv6 unique-local (fc00::/7), link-local (fe80::/10) and unspecified. +function isPrivateIpv6(host: string): boolean { + if (net.isIP(host) !== 6) return false; + if (host === "::" || host === "::1") return true; + // Unique-local fc00::/7 and link-local fe80::/10. if (host.startsWith("fc") || host.startsWith("fd")) return true; - if (host.startsWith("fe8") || host.startsWith("fe9") || host.startsWith("fea") || host.startsWith("feb")) return true; + if (/^fe[89ab]/.test(host)) return true; + // Deprecated site-local fec0::/10 and multicast ff00::/8. + if (/^fe[c-f]/.test(host)) return true; + if (host.startsWith("ff")) return true; + // Transition mechanisms that can carry another address family: NAT64 + // (64:ff9b::/96) and 6to4 (2002::/16). + if (host.startsWith("64:ff9b:") || host.startsWith("2002:")) return true; return false; } diff --git a/src/metrics/registry.ts b/src/metrics/registry.ts index 91f59a7..0fee1e4 100644 --- a/src/metrics/registry.ts +++ b/src/metrics/registry.ts @@ -15,6 +15,8 @@ export interface Metrics { readonly activeStreams: Gauge<"surface">; readonly upstreamRestarts: Counter<"reason">; readonly sessionCache: Gauge<"state">; + /** 1 while the global upstream event stream is connected, 0 otherwise. */ + readonly eventStream: Gauge; } export function createMetrics(options: { enabled: boolean; prefix?: string } = { enabled: true }): Metrics { @@ -90,6 +92,12 @@ export function createMetrics(options: { enabled: boolean; prefix?: string } = { registers: [registry], }); + const eventStream = new Gauge({ + name: `${prefix}event_stream_connected`, + help: "1 while the upstream event stream is connected, 0 otherwise.", + registers: [registry], + }); + return { registry, httpRequests, @@ -101,5 +109,6 @@ export function createMetrics(options: { enabled: boolean; prefix?: string } = { activeStreams, upstreamRestarts, sessionCache, + eventStream, }; } diff --git a/src/server.ts b/src/server.ts index 7718591..7c9dc57 100644 --- a/src/server.ts +++ b/src/server.ts @@ -1,6 +1,8 @@ /** * Fastify application assembly. */ +import { randomUUID } from "node:crypto"; +import type { IncomingHttpHeaders } from "node:http"; import Fastify, { type FastifyInstance, type FastifyRequest } from "fastify"; import { registerOpenAiChatRoutes } from "./adapter/openai/chat.js"; import { registerOpenAiEmbeddingRoutes } from "./adapter/openai/embeddings.js"; @@ -20,6 +22,22 @@ function isAnthropicSurface(request: FastifyRequest): boolean { return (request.url.split("?")[0] ?? "").startsWith("/v1/messages"); } +/** + * Characters a caller-supplied request id may contain. + * + * The value ends up in response headers and in every log line for the request, + * so anything outside this set (or longer than 128 characters) is replaced by a + * generated id instead of being echoed. + */ +const REQUEST_ID_PATTERN = /^[A-Za-z0-9._:-]{1,128}$/; + +/** Use the caller's `x-request-id` when it is safe, otherwise generate one. */ +function resolveRequestId(headers: IncomingHttpHeaders): string { + const header = headers["x-request-id"]; + const value = Array.isArray(header) ? header[0] : header; + return typeof value === "string" && REQUEST_ID_PATTERN.test(value) ? value : randomUUID(); +} + export async function buildServer(ctx: AppContext): Promise { // Fastify parameterises `FastifyInstance` by the logger type; casting keeps // every route module on the default `FastifyInstance` type without leaking @@ -28,11 +46,18 @@ export async function buildServer(ctx: AppContext): Promise { loggerInstance: ctx.log, bodyLimit: ctx.config.bodyLimitBytes, trustProxy: ctx.config.trustProxy, + // Correlate gateway logs with the caller's own trace id when it sends one. + genReqId: (raw) => resolveRequestId(raw.headers), // Upstream calls are long; never let Fastify cut a streaming response short. requestTimeout: 0, connectionTimeout: 0, }) as unknown as FastifyInstance; + // Every response — JSON, error and SSE alike — carries the request id. + app.addHook("onRequest", async (request, reply) => { + reply.header("x-request-id", request.id); + }); + // ---------------------------------------------------------------- CORS --- const allowedOrigins = new Set(ctx.config.corsOrigins); const allowAnyOrigin = allowedOrigins.has("*"); diff --git a/src/types/internal.ts b/src/types/internal.ts index d90604e..1098a8b 100644 --- a/src/types/internal.ts +++ b/src/types/internal.ts @@ -74,6 +74,22 @@ export interface ReasoningRequest { disabled?: boolean; } +/** + * JSON output shape requested by the caller. + * + * OpenAI chat sends `response_format`, the Responses surface sends + * `text.format`. OpenCode cannot receive an output schema, so the gateway + * renders it into the prompt (see `buildPrompt`); it is a best-effort contract + * with the model, not a server-enforced one. + */ +export interface ResponseFormat { + type: "json_object" | "json_schema"; + /** Schema name, when the caller supplied one. */ + name?: string; + /** JSON Schema the reply should validate against. */ + schema?: Record; +} + /** A fully normalised completion request. */ export interface InternalRequest { surface: Surface; @@ -87,6 +103,8 @@ export interface InternalRequest { tools: ToolDefinition[]; toolChoice?: "auto" | "none" | "required" | { name: string }; reasoning?: ReasoningRequest; + /** Requested JSON output shape; rendered into the prompt. */ + responseFormat?: ResponseFormat; temperature?: number; topP?: number; maxTokens?: number; diff --git a/src/upstream/client.ts b/src/upstream/client.ts index 826d853..774281f 100644 --- a/src/upstream/client.ts +++ b/src/upstream/client.ts @@ -79,7 +79,11 @@ export class OpencodeClient { const timeoutMs = options.timeoutMs ?? this.#config.upstreamRequestTimeoutMs; const controller = new AbortController(); - const timer = setTimeout(() => controller.abort(new Error("upstream timeout")), timeoutMs); + let timedOut = false; + const timer = setTimeout(() => { + timedOut = true; + controller.abort(new Error("upstream timeout")); + }, timeoutMs); const onAbort = (): void => controller.abort(options.signal?.reason); options.signal?.addEventListener("abort", onAbort, { once: true }); @@ -141,11 +145,20 @@ export class OpencodeClient { } const reason = error instanceof Error ? error.message : String(error); const aborted = options.signal?.aborted === true; - outcome = aborted ? "aborted" : "network_error"; + outcome = aborted ? "aborted" : timedOut ? "timeout" : "network_error"; this.#metrics.upstreamRequests.inc({ operation: options.operation, outcome }); if (aborted) { throw new ApiError(499, "timeout_error", "Client closed the request.", { cause: error }); } + if (timedOut) { + // The abort came from this client's own timer, not from the caller, so + // this is a gateway timeout (504), not an unreachable upstream (503). + this.#process.markStale(`Upstream request timed out: ${reason}`); + throw ApiError.timeout(`OpenCode did not answer within ${timeoutMs} ms.`, { + code: "upstream_timeout", + cause: error, + }); + } this.#process.markStale(`Upstream request failed: ${reason}`); throw ApiError.unavailable(`Could not reach the OpenCode server: ${reason}`, { code: "upstream_unreachable", diff --git a/src/upstream/completion.ts b/src/upstream/completion.ts index 838e2aa..dfbe814 100644 --- a/src/upstream/completion.ts +++ b/src/upstream/completion.ts @@ -13,6 +13,7 @@ import { createToolBridge, renderTranscript, type ToolBridge } from "../adapter/ import { EMPTY_USAGE, addUsage, toUsage } from "../adapter/common/usage.js"; import type { Config } from "../config.js"; import { ApiError, toApiError } from "../errors.js"; +import { buildDataUri } from "../media/resolve.js"; import type { Logger } from "../logger.js"; import type { Metrics } from "../metrics/registry.js"; import type { @@ -22,6 +23,7 @@ import type { InternalMessage, InternalRequest, NativeToolActivity, + ResponseFormat, ToolCall, Usage, } from "../types/internal.js"; @@ -232,7 +234,7 @@ async function prepare( reused = false; } - const { text, files } = buildPrompt(acquire.pending, bridge, config); + const { text, files } = buildPrompt(acquire.pending, bridge, request.responseFormat, config); return { request, @@ -559,10 +561,13 @@ async function* execute( function buildPrompt( pending: InternalMessage[], bridge: ToolBridge, + responseFormat: ResponseFormat | undefined, config: Config, ): { text: string; files: OpencodePromptFileAttachment[] } { const sections: string[] = []; if (bridge.active) sections.push(bridge.instructions); + const formatSection = renderResponseFormat(responseFormat); + if (formatSection) sections.push(formatSection); const messages = [...pending]; const current = messages.pop(); @@ -594,6 +599,30 @@ function buildPrompt( return { text: text.length > 0 ? text : "Continue.", files }; } +/** + * Render the caller's JSON output request into a prompt section. + * + * OpenCode has no per-request output-schema control, so — exactly like the tool + * bridge — the contract is carried by the prompt and depends on the model + * following it. + */ +function renderResponseFormat(format: ResponseFormat | undefined): string { + if (!format) return ""; + const lines = [ + "# Response format", + "", + "Reply with a single valid JSON value and nothing else: no prose before or after it,", + "no Markdown code fence and no commentary. The calling application parses the whole", + "reply as JSON.", + ]; + if (format.type === "json_schema") { + lines.push("", "The value must validate against this JSON Schema:"); + lines.push("", format.name ? `Schema name: ${format.name}` : "Schema name: (unnamed)"); + lines.push("", JSON.stringify(format.schema ?? { type: "object" }, null, 2)); + } + return lines.join("\n"); +} + /** * Collect the attachments to send upstream. * @@ -633,19 +662,14 @@ function collectAttachments( /** Convert a resolved attachment into the OpenCode prompt attachment shape. */ export function toPromptAttachment(attachment: Attachment): OpencodePromptFileAttachment { return { - uri: toDataUri(attachment.data, attachment.mime), + uri: buildDataUri(attachment), source: { type: "inline" }, ...(attachment.name ? { name: attachment.name } : {}), }; } -function toDataUri(data: string, mime: string): string { - return `data:${mime};base64,${data}`; -} - function validateAttachments(request: InternalRequest, info: OpencodeModelInfo | undefined, models: ModelRegistry): void { if (!info) return; - const supported = new Set(info.capabilities.input.map((entry) => entry.toLowerCase())); for (const message of request.messages) { for (const attachment of message.attachments ?? []) { const modality = modalityFor(attachment.kind); @@ -656,7 +680,6 @@ function validateAttachments(request: InternalRequest, info: OpencodeModelInfo | { code: "unsupported_modality", param: "messages" }, ); } - void supported; } } } diff --git a/src/upstream/events.ts b/src/upstream/events.ts index 049a00f..a514aa1 100644 --- a/src/upstream/events.ts +++ b/src/upstream/events.ts @@ -25,10 +25,11 @@ export class EventHub { #controller?: AbortController; #running = false; #connected = false; - #connectPromise?: Promise; - #resolveConnected?: () => void; #reconnectDelayMs = 250; + /** Callers waiting for the next connection, released together. */ + readonly #waiters = new Set<() => void>(); + readonly #listeners = new Map>(); readonly #reconnectListeners = new Set(); @@ -55,6 +56,9 @@ export class EventHub { this.#controller?.abort(); this.#controller = undefined; this.#connected = false; + // Nobody is going to be connected any more: release every waiter instead of + // leaving them to time out. + this.#notifyWaiters(); } /** Resolve once the stream is established, or after `timeoutMs`. */ @@ -62,15 +66,15 @@ export class EventHub { this.start(); if (this.#connected) return true; await new Promise((resolve) => { - const timer = setTimeout(() => { - this.#resolveConnected = undefined; - resolve(); - }, timeoutMs); - this.#resolveConnected = () => { + // Several completions can wait for the same connection; every waiter must + // be released, not just the most recent one. + const wait = (): void => { clearTimeout(timer); - this.#resolveConnected = undefined; + this.#waiters.delete(wait); resolve(); }; + const timer = setTimeout(wait, timeoutMs); + this.#waiters.add(wait); }); return this.#connected; } @@ -110,7 +114,7 @@ export class EventHub { const wasConnected = this.#connected; this.#connected = false; if (wasConnected) { - this.#metrics.sessionCache.set({ state: "event_stream" }, 0); + this.#metrics.eventStream.set(0); for (const listener of this.#reconnectListeners) { try { listener(); @@ -162,6 +166,13 @@ export class EventHub { } } + /** Release every caller waiting for a connection. */ + #notifyWaiters(): void { + const waiters = [...this.#waiters]; + this.#waiters.clear(); + for (const wake of waiters) wake(); + } + #handleFrame(frame: string): void { if (frame.length === 0) return; const dataLines: string[] = []; @@ -192,8 +203,8 @@ export class EventHub { if (parsed.type === "server.connected") { this.#connected = true; - this.#metrics.sessionCache.set({ state: "event_stream" }, 1); - this.#resolveConnected?.(); + this.#metrics.eventStream.set(1); + this.#notifyWaiters(); return; } diff --git a/src/upstream/process.ts b/src/upstream/process.ts index 25ce578..9c45513 100644 --- a/src/upstream/process.ts +++ b/src/upstream/process.ts @@ -7,7 +7,6 @@ * 3. a background OpenCode service discovered through `service.json`. */ import { type ChildProcessByStdio, spawn } from "node:child_process"; -import { randomUUID } from "node:crypto"; import fs from "node:fs"; import path from "node:path"; import type { Readable } from "node:stream"; @@ -18,7 +17,16 @@ import type { Metrics } from "../metrics/registry.js"; import { findOpencodeBinary, isProcessAlive, readServiceDescriptor } from "./discovery.js"; /** The child process shape produced by spawning with `stdio: ["ignore","pipe","pipe"]`. */ -type SpawnedChild = ChildProcessByStdio; +export type SpawnedChild = ChildProcessByStdio; + +/** Starts the OpenCode server; injectable so tests can script the lifecycle. */ +export type SpawnChildFn = (command: string, args: string[]) => SpawnedChild; + +/** Test seams for `UpstreamProcess`. Production code leaves both unset. */ +export interface UpstreamProcessOptions { + spawn?: SpawnChildFn; + findBinary?: (explicit?: string) => string | undefined; +} export type EndpointSource = "env" | "spawned" | "discovered"; @@ -53,6 +61,8 @@ export class UpstreamProcess { readonly #config: Config; readonly #log: Logger; readonly #metrics: Metrics; + readonly #spawnChild: SpawnChildFn; + readonly #findBinary: (explicit?: string) => string | undefined; #endpoint?: UpstreamEndpoint; #child?: SpawnedChild; @@ -63,11 +73,30 @@ export class UpstreamProcess { #binary?: string; #exitHookInstalled = false; - constructor(config: Config, log: Logger, metrics: Metrics) { + constructor( + config: Config, + log: Logger, + metrics: Metrics, + options: UpstreamProcessOptions = {}, + ) { this.#config = config; this.#log = log; this.#metrics = metrics; - this.#binary = findOpencodeBinary(config.upstreamBin); + this.#findBinary = options.findBinary ?? findOpencodeBinary; + this.#spawnChild = + options.spawn ?? + ((command, args) => + spawn(command, args, { + cwd: config.workdir, + env: { + ...process.env, + OPENCODE_DISABLE_AUTOUPDATE: "1", + NO_COLOR: "1", + }, + stdio: ["ignore", "pipe", "pipe"], + windowsHide: true, + }) as SpawnedChild); + this.#binary = this.#findBinary(config.upstreamBin); } get binary(): string | undefined { @@ -132,6 +161,27 @@ export class UpstreamProcess { }); } + /** + * Take ownership of a freshly spawned server. + * + * Exactly one child is supervised at a time. If the previous child is still + * alive when a replacement arrives (a restart after `markStale()`, or an admin + * restart that already dropped the endpoint), it is killed first: otherwise + * the gateway would lose the only handle to a process that keeps listening on + * the internal port. + */ + #adopt(child: SpawnedChild): void { + const previous = this.#child; + this.#child = child; + if (!previous || previous === child || previous.exitCode !== null) return; + this.#log.warn({ pid: previous.pid }, "terminating the previous OpenCode server before starting a new one"); + try { + previous.kill("SIGKILL"); + } catch { + /* already gone */ + } + } + async #resolveInternal(): Promise { this.#lastError = undefined; @@ -216,8 +266,11 @@ export class UpstreamProcess { } async #spawn(): Promise { + // 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; if (!this.#binary) { - this.#binary = findOpencodeBinary(this.#config.upstreamBin); + this.#binary = this.#findBinary(this.#config.upstreamBin); } if (!this.#binary) { throw new Error( @@ -238,7 +291,7 @@ export class UpstreamProcess { const spawned = await this.#spawnOnPort(port, logDir); // Track the child so `stop()` and shutdown can terminate it; without // this every restart would leak a server process and its port. - this.#child = spawned.child; + this.#adopt(spawned.child); this.#installExitHook(); return spawned; } catch (error) { @@ -262,16 +315,7 @@ export class UpstreamProcess { this.#log.debug({ binary: this.#binary, args }, "spawning OpenCode server"); - const child = spawn(this.#binary as string, args, { - cwd: this.#config.workdir, - env: { - ...process.env, - OPENCODE_DISABLE_AUTOUPDATE: "1", - NO_COLOR: "1", - }, - stdio: ["ignore", "pipe", "pipe"], - windowsHide: true, - }) as SpawnedChild; + const child = this.#spawnChild(this.#binary as string, args); const logStream = fs.createWriteStream(path.join(logDir, `opencode-${port}.log`), { flags: "a" }); @@ -348,7 +392,7 @@ export class UpstreamProcess { ); return; } - this.#onChildExit(code, signal); + this.#onChildExit(child, code, signal); }); }); } @@ -372,8 +416,16 @@ export class UpstreamProcess { }); } - #onChildExit(code: number | null, signal: NodeJS.Signals | null): void { + /** + * React to the death of a supervised server. + * + * Only the child that is currently tracked may reset the gateway state: an old + * child that was replaced and exits late must not clear the endpoint or the + * handle of its successor. + */ + #onChildExit(child: SpawnedChild, code: number | null, signal: NodeJS.Signals | null): void { if (this.#stopping) return; + if (this.#child !== child) return; this.#log.error({ code, signal }, "OpenCode server process exited"); this.#lastError = `OpenCode server exited (code=${code ?? "null"}, signal=${signal ?? "null"})`; this.#endpoint = undefined; @@ -393,9 +445,4 @@ export function authHeaders(password: string | undefined): Record Promise; +} + +const open: FakeUpstream[] = []; + +/** Start a server that accepts the request and never answers. */ +async function hangingUpstream(upstreamRequestTimeoutMs: number): Promise { + const server = http.createServer(() => { + /* deliberately never respond */ + }); + await new Promise((resolve) => server.listen(0, "127.0.0.1", resolve)); + const { port } = server.address() as AddressInfo; + + const config = testConfig({ upstreamRequestTimeoutMs }); + const log = createLogger(config); + const metrics = createMetrics({ enabled: false }); + const upstream = { + resolve: async () => ({ url: `http://127.0.0.1:${port}`, password: undefined, source: "env" as const }), + markStale: () => undefined, + } as unknown as UpstreamProcess; + + const client = new OpencodeClient(upstream, config, log, metrics); + const item: FakeUpstream = { + url: `http://127.0.0.1:${port}`, + client, + close: async () => { + server.closeAllConnections(); + await new Promise((resolve) => server.close(() => resolve())); + }, + }; + open.push(item); + return item; +} + +afterEach(async () => { + while (open.length > 0) { + const item = open.pop(); + if (item) await item.close(); + } +}); + +describe("OpencodeClient", () => { + it("reports its own request timeout as a 504", async () => { + const upstream = await hangingUpstream(150); + + await expect(upstream.client.listModels()).rejects.toMatchObject({ + status: 504, + kind: "timeout_error", + code: "upstream_timeout", + }); + }); + + it("still reports a caller abort as 499", async () => { + const upstream = await hangingUpstream(10_000); + const controller = new AbortController(); + const pending = upstream.client.request("/api/model", { + operation: "test", + signal: controller.signal, + }); + setTimeout(() => controller.abort(), 50); + + await expect(pending).rejects.toMatchObject({ status: 499 }); + }); +}); \ No newline at end of file diff --git a/test/completion.test.ts b/test/completion.test.ts index 7b21344..1b2e68b 100644 --- a/test/completion.test.ts +++ b/test/completion.test.ts @@ -200,6 +200,32 @@ describe("collectCompletion", () => { expect(promptCalls[0]?.text).toContain("Hello"); }); + it("renders the requested JSON output format into the prompt", async () => { + const { deps, promptCalls } = harness(() => simpleTurn('{"ok":true}')); + await collectCompletion( + request({ + responseFormat: { + type: "json_schema", + name: "answer", + schema: { type: "object", properties: { ok: { type: "boolean" } } }, + }, + }), + deps, + ); + + const text = promptCalls[0]?.text ?? ""; + expect(text).toContain("# Response format"); + expect(text).toContain("single valid JSON value"); + expect(text).toContain("Schema name: answer"); + expect(text).toContain('"ok"'); + }); + + it("adds no JSON instruction when the caller did not ask for one", async () => { + const { deps, promptCalls } = harness(() => simpleTurn("ok")); + await collectCompletion(request(), deps); + expect(promptCalls[0]?.text).not.toContain("# Response format"); + }); + it("replays earlier turns as a transcript on the first request", async () => { const { deps, promptCalls } = harness(() => simpleTurn("4")); await collectCompletion( diff --git a/test/disconnect.test.ts b/test/disconnect.test.ts new file mode 100644 index 0000000..98d5913 --- /dev/null +++ b/test/disconnect.test.ts @@ -0,0 +1,93 @@ +/** + * Client-disconnect detection. + * + * `IncomingMessage` "close" fires when the request body has been consumed, not + * when the caller goes away, so the surfaces must listen on the response. These + * tests pin that contract down without opening a socket. + */ +import { EventEmitter } from "node:events"; +import { describe, expect, it } from "vitest"; +import type { FastifyReply, FastifyRequest } from "fastify"; +import { createDisconnectSignal } from "../src/http/disconnect.js"; + +interface Fixture { + request: FastifyRequest; + reply: FastifyReply; + requestEvents: EventEmitter; + replyEvents: EventEmitter; + socketEvents: EventEmitter; + setFinished: (value: boolean) => void; +} + +function fixture(): Fixture { + const requestEvents = new EventEmitter() as EventEmitter & { socket: EventEmitter }; + const socketEvents = new EventEmitter(); + requestEvents.socket = socketEvents; + const replyEvents = new EventEmitter() as EventEmitter & { writableFinished: boolean; destroyed: boolean }; + replyEvents.writableFinished = false; + replyEvents.destroyed = false; + + return { + request: { raw: requestEvents } as unknown as FastifyRequest, + reply: { raw: replyEvents } as unknown as FastifyReply, + requestEvents, + replyEvents, + socketEvents, + setFinished: (value) => { + replyEvents.writableFinished = value; + }, + }; +} + +describe("createDisconnectSignal", () => { + it("ignores the request-stream close that Node emits once the body is consumed", () => { + const f = fixture(); + const { signal, dispose } = createDisconnectSignal(f.request, f.reply); + + // Node >= 16 emits this as soon as Fastify has parsed the body, which is + // before the route handler runs: treating it as a disconnect would abort + // every healthy request (or, worse, silently never fire at all). + f.requestEvents.emit("close"); + expect(signal.aborted).toBe(false); + dispose(); + }); + + it("aborts when the response closes before it finished", () => { + const f = fixture(); + const { signal, dispose } = createDisconnectSignal(f.request, f.reply); + + f.replyEvents.emit("close"); + expect(signal.aborted).toBe(true); + dispose(); + }); + + it("does not abort when the response finished normally", () => { + const f = fixture(); + const { signal, dispose } = createDisconnectSignal(f.request, f.reply); + + f.setFinished(true); + f.replyEvents.emit("close"); + f.socketEvents.emit("close"); + expect(signal.aborted).toBe(false); + dispose(); + }); + + it("aborts when the socket closes during an unfinished response", () => { + const f = fixture(); + const { signal, dispose } = createDisconnectSignal(f.request, f.reply); + + f.socketEvents.emit("close"); + expect(signal.aborted).toBe(true); + dispose(); + }); + + it("stops listening after dispose", () => { + const f = fixture(); + const { signal, dispose } = createDisconnectSignal(f.request, f.reply); + dispose(); + + f.replyEvents.emit("close"); + f.socketEvents.emit("close"); + expect(signal.aborted).toBe(false); + }); +}); \ No newline at end of file diff --git a/test/events.test.ts b/test/events.test.ts index 8b1ced5..3d48829 100644 --- a/test/events.test.ts +++ b/test/events.test.ts @@ -145,6 +145,38 @@ describe("EventHub", () => { expect(received[0]?.type).toBe("session.text.delta"); }); + it("releases every concurrent ensureConnected waiter", async () => { + const item = await fixture((response) => { + const timer = setTimeout(() => response.write(frame({ id: "e0", type: "server.connected", data: {} })), 120); + return () => clearTimeout(timer); + }); + active.push(item); + + const started = Date.now(); + const results = await Promise.all([ + item.hub.ensureConnected(3_000), + item.hub.ensureConnected(3_000), + item.hub.ensureConnected(3_000), + ]); + + expect(results).toEqual([true, true, true]); + // Every waiter must be released when the stream connects, not just the last + // one registered (which used to leave the others blocked for the timeout). + expect(Date.now() - started).toBeLessThan(1_500); + }); + + it("resolves pending ensureConnected waiters when the hub stops", async () => { + const item = await fixture(() => () => undefined); + active.push(item); + + const pending = item.hub.ensureConnected(5_000); + await delay(30); + const started = Date.now(); + await item.hub.stop(); + expect(await pending).toBe(false); + expect(Date.now() - started).toBeLessThan(1_000); + }); + it("reconnects after the stream drops and notifies subscribers", async () => { const item = await fixture((response, connection) => { response.write(frame({ id: "e0", type: "server.connected", data: {} })); diff --git a/test/openai-chat.test.ts b/test/openai-chat.test.ts index c174462..91f2f70 100644 --- a/test/openai-chat.test.ts +++ b/test/openai-chat.test.ts @@ -52,6 +52,37 @@ afterEach(() => { delete process.env["OPENCODE_REASONING_FIELD"]; }); +describe("response_format", () => { + it("maps the JSON output formats onto the internal request", async () => { + const captured: Array = []; + const app = await buildServer(createTestContext({ onRun: (request) => captured.push(request) })); + const send = async (response_format: unknown): Promise => { + const response = await app.inject({ + method: "POST", + url: "/v1/chat/completions", + headers: AUTH, + payload: { model: MODEL, messages: [{ role: "user", content: "Hi" }], response_format }, + }); + expect(response.statusCode).toBe(200); + }; + + await send({ type: "json_object" }); + await send({ + type: "json_schema", + json_schema: { name: "answer", schema: { type: "object", properties: { ok: { type: "boolean" } } } }, + }); + await send({ type: "text" }); + + expect(captured[0]?.responseFormat).toEqual({ type: "json_object" }); + expect(captured[1]?.responseFormat).toEqual({ + type: "json_schema", + name: "answer", + schema: { type: "object", properties: { ok: { type: "boolean" } } }, + }); + expect(captured[2]?.responseFormat).toBeUndefined(); + }); +}); + describe("POST /v1/chat/completions (non-streaming)", () => { it("returns an OpenAI chat completion object", async () => { const app = await buildServer(createTestContext({ script: (request) => defaultScript(request) })); diff --git a/test/openai-responses.test.ts b/test/openai-responses.test.ts index 0d72e48..439d314 100644 --- a/test/openai-responses.test.ts +++ b/test/openai-responses.test.ts @@ -196,6 +196,53 @@ describe("POST /v1/responses (non-streaming)", () => { expect(attachment?.data).toBe(PNG_BASE64); }); + it("maps text.format onto the internal JSON output request", async () => { + const captured: InternalRequest[] = []; + const app = await makeApp({ onRun: (request) => captured.push(request) }); + + await app.inject({ + method: "POST", + url: "/v1/responses", + headers: AUTH, + payload: { model: "opencode/deepseek-v4.1-flash-free", input: "hi", text: { format: { type: "json_object" } } }, + }); + await app.inject({ + method: "POST", + url: "/v1/responses", + headers: AUTH, + payload: { + model: "opencode/deepseek-v4.1-flash-free", + input: "hi", + text: { format: { type: "json_schema", name: "answer", schema: { type: "object" } } }, + }, + }); + + expect(captured[0]?.responseFormat).toEqual({ type: "json_object" }); + expect(captured[1]?.responseFormat).toEqual({ type: "json_schema", name: "answer", schema: { type: "object" } }); + }); + + it("rejects an input_file that only carries a file_id", 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: [ + { + role: "user", + content: [{ type: "input_text", text: "read this" }, { type: "input_file", file_id: "file-abc" }], + }, + ], + }, + }); + + expect(response.statusCode).toBe(400); + expect((response.json() as { error: { code: string } }).error.code).toBe("unsupported_file_reference"); + }); + it("turns instructions into a leading system message", async () => { let captured: InternalRequest | undefined; const app = await makeApp({ onRun: (request) => (captured = request) }); @@ -444,6 +491,7 @@ describe("POST /v1/responses (streaming)", () => { "response.reasoning_summary_part.added", "response.reasoning_summary_text.delta", "response.reasoning_summary_text.done", + "response.reasoning_summary_part.done", "response.output_item.added", "response.content_part.added", "response.output_text.delta", @@ -558,6 +606,12 @@ describe("POST /v1/responses (streaming)", () => { const types = eventTypes(response.payload); expect(types).toContain("response.reasoning_summary_part.added"); expect(types).toContain("response.reasoning_summary_text.done"); + expect(types).toContain("response.reasoning_summary_part.done"); + // The part must be closed after its text, before the closing response. + expect(types.indexOf("response.reasoning_summary_part.done")).toBeGreaterThan( + types.indexOf("response.reasoning_summary_text.done"), + ); + expect(types.indexOf("response.reasoning_summary_part.done")).toBeLessThan(types.indexOf("response.completed")); const final = frames(response.payload).at(-1)?.json["response"] as ResponsePayload; expect(final.output).toHaveLength(1); expect(final.output[0]?.type).toBe("reasoning"); diff --git a/test/process.test.ts b/test/process.test.ts new file mode 100644 index 0000000..d1cd142 --- /dev/null +++ b/test/process.test.ts @@ -0,0 +1,124 @@ +/** + * Upstream process supervision. + * + * The child process is scripted: `FakeChild` reports readiness on stdout exactly + * like `opencode serve` does, so the real spawn/readiness/exit code paths run + * without launching the CLI. + */ +import { EventEmitter } from "node:events"; +import os from "node:os"; +import { PassThrough } from "node:stream"; +import { describe, expect, it } from "vitest"; +import { createLogger } from "../src/logger.js"; +import { createMetrics } from "../src/metrics/registry.js"; +import { UpstreamProcess, type SpawnedChild } from "../src/upstream/process.js"; +import { testConfig } from "./helpers/context.js"; + +/** Stand-in for a spawned `opencode serve` child. */ +class FakeChild extends EventEmitter { + readonly pid: number; + readonly stdout = new PassThrough(); + readonly stderr = new PassThrough(); + readonly signals: NodeJS.Signals[] = []; + exitCode: number | null = null; + + constructor(pid: number) { + super(); + this.pid = pid; + } + + kill(signal: NodeJS.Signals = "SIGTERM"): boolean { + this.signals.push(signal); + if (this.exitCode !== null) return false; + this.exitCode = signal === "SIGTERM" ? 0 : null; + // A real child reports its exit asynchronously. + setImmediate(() => this.emit("exit", this.exitCode, signal)); + return true; + } + + /** Simulate an unexpected death (no signal from the gateway). */ + crash(): void { + if (this.exitCode !== null) return; + this.exitCode = 1; + this.emit("exit", 1, null); + } +} + +interface Harness { + process: UpstreamProcess; + children: FakeChild[]; +} + +function harness(): Harness { + const children: FakeChild[] = []; + const config = testConfig({ + dataDir: os.tmpdir(), + workdir: os.tmpdir(), + upstreamAutostart: true, + upstreamStartTimeoutMs: 2_000, + }); + const log = createLogger(config); + const metrics = createMetrics({ enabled: false }); + + const process = new UpstreamProcess(config, log, metrics, { + findBinary: () => "/fake/opencode", + spawn: (_command, args) => { + 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"); + }); + return child as unknown as SpawnedChild; + }, + }); + + return { process, children }; +} + +const tick = (): Promise => new Promise((resolve) => setTimeout(resolve, 10)); + +describe("UpstreamProcess", () => { + it("terminates the previous server when a respawn replaces it", async () => { + const { process, children } = harness(); + + const first = await process.resolve(); + await process.invalidate("test restart"); + const second = await process.resolve(); + + expect(children).toHaveLength(2); + expect(second.pid).not.toBe(first.pid); + // The replaced server must not stay alive listening on its port. + expect(children[0]?.signals).toContain("SIGKILL"); + }); + + it("ignores the late exit of a server it no longer tracks", async () => { + const { process, children } = harness(); + + await process.resolve(); + await process.invalidate("test restart"); + await process.resolve(); + await tick(); // the replaced child reports its exit here + + // The stale exit must not clear the tracking of the live replacement. + expect(process.status().ready).toBe(true); + await process.stop(); + expect(children[1]?.signals).toContain("SIGTERM"); + }); + + it("notices that a server restarted after stop() has died", async () => { + const { process, children } = harness(); + + await process.resolve(); + await process.stop(); + await process.resolve(); + expect(process.status().ready).toBe(true); + + // A restart must re-arm supervision: before the fix `#stopping` stayed set, + // so this unexpected exit was ignored and the status kept reporting ready. + children[1]?.crash(); + expect(process.status().ready).toBe(false); + expect(process.status().lastError).toContain("exited"); + }); +}); \ No newline at end of file diff --git a/test/regressions.test.ts b/test/regressions.test.ts index 9a15645..0bb35f9 100644 --- a/test/regressions.test.ts +++ b/test/regressions.test.ts @@ -3,6 +3,8 @@ * OpenCode CLI (see docs/ARCHITECTURE.md sections 2 and 6). */ import { describe, expect, it } from "vitest"; +import http from "node:http"; +import type { AddressInfo } from "node:net"; import { ApiError } from "../src/errors.js"; import { isPrivateHost } from "../src/media/resolve.js"; import { buildServer } from "../src/server.js"; @@ -159,6 +161,44 @@ describe("reasoning field configuration", () => { await app.close(); }); + it("keeps the reasoning field of each built server independent", async () => { + const script = (): CompletionEvent[] => [ + { kind: "start", sessionId: "s", messageId: "m", model: "opencode/deepseek-v4.1-flash-free", reusedSession: false, reasoningEnabled: true }, + { kind: "reasoning_delta", text: "thinking", ordinal: 0 }, + { kind: "text_delta", text: "answer", ordinal: 0 }, + { kind: "end", finishReason: "stop", usage: { inputTokens: 1, outputTokens: 1, reasoningTokens: 1, cacheReadTokens: 0, cacheWriteTokens: 0, totalTokens: 3 }, messageId: "m" }, + ]; + const payload = { + model: "opencode/deepseek-v4.1-flash-free", + messages: [{ role: "user", content: "hi" }], + reasoning_effort: "high", + }; + + // The second registration used to overwrite a module-level flag, changing + // the output of the first server. + const plain = await buildServer(createTestContext({ script })); + const both = await buildServer(createTestContext({ config: { reasoningField: "both" }, script })); + + const plainMessage = ( + (await plain.inject({ method: "POST", url: "/v1/chat/completions", headers: AUTH, payload })).json() as { + choices: Array<{ message: Record }>; + } + ).choices[0]?.message; + const bothMessage = ( + (await both.inject({ method: "POST", url: "/v1/chat/completions", headers: AUTH, payload })).json() as { + choices: Array<{ message: Record }>; + } + ).choices[0]?.message; + + expect(plainMessage?.["reasoning_content"]).toBe("thinking"); + expect(plainMessage?.["reasoning"]).toBeUndefined(); + expect(bothMessage?.["reasoning_content"]).toBe("thinking"); + expect(bothMessage?.["reasoning"]).toBe("thinking"); + + await plain.close(); + await both.close(); + }); + it("streams tool calls as complete argument chunks with finish_reason tool_calls", async () => { const ctx = createTestContext({ script: () => [ @@ -362,6 +402,160 @@ describe("Anthropic messages surface (scripted)", () => { }); }); +describe("request correlation id", () => { + it("echoes a caller-supplied x-request-id on a JSON response", async () => { + const ctx = createTestContext(); + const app = await buildServer(ctx); + const response = await app.inject({ + method: "GET", + url: "/v1/models", + headers: { ...AUTH, "x-request-id": "trace-42" }, + }); + expect(response.statusCode).toBe(200); + expect(response.headers["x-request-id"]).toBe("trace-42"); + await app.close(); + }); + + it("echoes the request id on a streamed response", async () => { + const ctx = createTestContext(); + const app = await buildServer(ctx); + const response = await app.inject({ + method: "POST", + url: "/v1/chat/completions", + headers: { ...AUTH, "x-request-id": "trace-stream" }, + payload: { model: MODEL, stream: true, messages: [{ role: "user", content: "hi" }] }, + }); + expect(response.statusCode).toBe(200); + expect(response.headers["x-request-id"]).toBe("trace-stream"); + await app.close(); + }); + + it("replaces an unsafe request id instead of echoing it", async () => { + const ctx = createTestContext(); + const app = await buildServer(ctx); + const response = await app.inject({ + method: "GET", + url: "/v1/models", + headers: { ...AUTH, "x-request-id": "bad value with spaces" }, + }); + expect(response.headers["x-request-id"]).not.toBe("bad value with spaces"); + expect(response.headers["x-request-id"]).toMatch(/^[A-Za-z0-9._:-]{1,128}$/); + await app.close(); + }); +}); + +describe("streaming response headers", () => { + it("keeps the CORS headers a hook set on a streamed response", async () => { + const ctx = createTestContext({ config: { corsOrigins: ["*"] } }); + const app = await buildServer(ctx); + const response = await app.inject({ + method: "POST", + url: "/v1/chat/completions", + headers: { ...AUTH, origin: "https://app.example" }, + payload: { model: MODEL, stream: true, messages: [{ role: "user", content: "hi" }] }, + }); + + expect(response.statusCode).toBe(200); + expect(response.headers["content-type"]).toContain("text/event-stream"); + // The SSE writer hijacks the reply; headers set by the CORS hook must still + // be part of the response head the browser sees. + expect(response.headers["access-control-allow-origin"]).toBe("*"); + expect(response.headers["vary"]).toBe("origin"); + await app.close(); + }); +}); + +describe("responses media cancellation", () => { + it("cancels a media download when the client disconnects", async () => { + // A media server that streams a body and never finishes it: the only way the + // connection closes is the gateway aborting the fetch. + let markRequested: () => void = () => undefined; + const requested = new Promise((resolve) => { + markRequested = resolve; + }); + let markClosed: () => void = () => undefined; + const closed = new Promise((resolve) => { + markClosed = resolve; + }); + let closedSeen = false; + + const media = http.createServer((_mediaRequest, mediaResponse) => { + mediaResponse.writeHead(200, { "content-type": "image/png" }); + mediaResponse.write(Buffer.from([0x89, 0x50, 0x4e, 0x47])); + mediaResponse.on("close", () => { + closedSeen = true; + markClosed(); + }); + markRequested(); + }); + await new Promise((resolve) => media.listen(0, "127.0.0.1", resolve)); + const mediaUrl = `http://127.0.0.1:${(media.address() as AddressInfo).port}/stream.png`; + + const ctx = createTestContext({ + config: { allowRemoteMediaUrls: true, allowPrivateMediaUrls: true, mediaFetchTimeoutMs: 30_000 }, + }); + const app = await buildServer(ctx); + await app.listen({ host: "127.0.0.1", port: 0 }); + const gatewayPort = (app.server.address() as AddressInfo).port; + + const request = http.request({ + host: "127.0.0.1", + port: gatewayPort, + path: "/v1/responses", + method: "POST", + headers: { ...AUTH, "content-type": "application/json" }, + }); + request.on("error", () => undefined); + request.end( + JSON.stringify({ + model: MODEL, + input: [ + { + role: "user", + content: [ + { type: "input_text", text: "look" }, + { type: "input_file", file_url: mediaUrl }, + ], + }, + ], + }), + ); + + await requested; + request.destroy(); + await Promise.race([closed, new Promise((resolve) => setTimeout(resolve, 5_000))]); + expect(closedSeen).toBe(true); + + await app.close(); + media.closeAllConnections(); + await new Promise((resolve) => media.close(() => resolve())); + }); +}); + +describe("stream accounting", () => { + it("leaves no active stream behind after a streamed responses request", async () => { + const ctx = createTestContext({ + script: () => [ + { kind: "start", sessionId: "s", messageId: "m", model: MODEL, reusedSession: false, reasoningEnabled: false }, + { kind: "error", error: new ApiError(502, "upstream_error", "boom") }, + ], + }); + const app = await buildServer(ctx); + + const response = await app.inject({ + method: "POST", + url: "/v1/responses", + headers: AUTH, + payload: { model: MODEL, input: "go", stream: true }, + }); + 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(); + }); +}); + describe("framework error handling", () => { it("reports a Fastify 4xx with its own status instead of 500", async () => { const ctx = createTestContext(); @@ -390,6 +584,16 @@ describe("adversarial input handling", () => { expect(isPrivateHost("metadata.google.internal")).toBe(true); expect(isPrivateHost("example.com")).toBe(false); expect(isPrivateHost(new URL("http://93.184.216.34/x").hostname)).toBe(false); + // Public DNS names that merely start with an IPv6 prefix are not addresses. + expect(isPrivateHost("fdic.gov")).toBe(false); + expect(isPrivateHost("fcbank.com")).toBe(false); + expect(isPrivateHost("feb.example.com")).toBe(false); + // Site-local, multicast, NAT64, 6to4 and IPv4-compatible literals are private. + expect(isPrivateHost(new URL("http://[fec0::1]/x").hostname)).toBe(true); + expect(isPrivateHost(new URL("http://[ff02::1]/x").hostname)).toBe(true); + expect(isPrivateHost(new URL("http://[64:ff9b::7f00:1]/x").hostname)).toBe(true); + expect(isPrivateHost(new URL("http://[2002:7f00:1::]/x").hostname)).toBe(true); + expect(isPrivateHost(new URL("http://[::127.0.0.1]/x").hostname)).toBe(true); }); it("refuses to fetch a loopback attachment when private URLs are blocked", async () => {