From 072e02eaf1fc2a11b72c1afeee46d6020986729d Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Ph=E1=BA=A1m=20V=C4=83n=20=C4=90=E1=BB=8Bnh?= Date: Thu, 3 Dec 2026 12:08:48 +0700 Subject: [PATCH 01/12] fix(upstream): harden the turn lifecycle, sessions and the event stream A vanished sticky session could not be replayed: fromUpstreamError() collapsed every upstream 4xx, including 404, into a caller-fault 400, so isStaleSession() was dead code and a dead ses_* id failed the whole conversation until its TTL expired. Preserve 404 as not_found_error, classify the replay on either field, and mirror the rate-limit and 404 handling in the event-path classifier. Four operational gaps found while auditing the module are closed too: the /api/event connect phase had no timeout, so an upstream that accepted the socket and never wrote a response head parked the hub for undici's header timeout and failed every concurrent turn with 503; a failed start was not remembered, so every incoming request re-spawned the CLI (a bounded exponential backoff now fails fast); the child's stdout and stderr were accumulated and rescanned for the whole process lifetime, which was unbounded memory and quadratic CPU; and stop() left the event_stream_connected gauge at 1 while a response head reset the reconnect delay, so a flapping stream was polled four times a second. The caller's abort signal now reaches createSession() and prompt(), the request gauges no longer flatten and sort the whole session cache, a consolidated text_end is adopted when it is longer than the deltas, and completions_total records an outcome for every failure through a bounded error_code label. The process exit hook is installed once per process instead of once per instance. --- src/errors.ts | 7 + src/metrics/registry.ts | 36 ++- src/upstream/client.ts | 15 +- src/upstream/completion.ts | 144 +++++++--- src/upstream/events.ts | 81 +++++- src/upstream/process.ts | 225 ++++++++++++++-- src/upstream/sessions.ts | 11 +- test/client.test.ts | 23 ++ test/completion.test.ts | 455 +++++++++++++++++++++++++++++++- test/events.test.ts | 151 ++++++++++- test/helpers/context.ts | 9 + test/process.test.ts | 130 ++++++++- test/sessions.test.ts | 32 ++- test/upstream-reconnect.test.ts | 48 +++- 14 files changed, 1262 insertions(+), 105 deletions(-) diff --git a/src/errors.ts b/src/errors.ts index 6e7f134..a343753 100644 --- a/src/errors.ts +++ b/src/errors.ts @@ -199,6 +199,13 @@ export function fromUpstreamError(input: { if (upstreamStatus === 503 || upstreamStatus === 502 || upstreamStatus === 504) { return new ApiError(503, "overloaded_error", message, options); } + // A vanished session is a not-found condition, not a bad request: the + // orchestrator classifies on it to replay the conversation on a fresh session. + // Collapsing it into the generic caller-fault branch would make that recovery + // unreachable. + if (upstreamStatus === 404) { + return ApiError.notFound(message, options); + } if (isCallerFault(upstreamStatus)) { return new ApiError(400, "invalid_request_error", message, options); } diff --git a/src/metrics/registry.ts b/src/metrics/registry.ts index 6a1daf6..b1ebfc9 100644 --- a/src/metrics/registry.ts +++ b/src/metrics/registry.ts @@ -11,12 +11,18 @@ export interface Metrics { readonly upstreamRequests: Counter<"operation" | "outcome">; readonly upstreamDuration: Histogram<"operation">; readonly tokens: Counter<"model" | "direction">; - readonly completions: Counter<"surface" | "model" | "stream" | "finish_reason">; + readonly completions: Counter<"surface" | "model" | "stream" | "finish_reason" | "error_code">; 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; + /** Reconnect attempts of the upstream event stream, by trigger. */ + readonly eventStreamReconnects: Counter<"reason">; + /** Upstream event frames the hub could not deliver, by reason. */ + readonly eventFramesDropped: Counter<"reason">; + /** Requests rejected by the in-process rate limiter, by bucket scope. */ + readonly rateLimitRejections: Counter<"scope">; } export function createMetrics(options: { enabled: boolean; prefix?: string } = { enabled: true }): Metrics { @@ -67,7 +73,7 @@ export function createMetrics(options: { enabled: boolean; prefix?: string } = { const completions = new Counter({ name: `${prefix}completions_total`, help: "Completed chat/completion requests per public surface.", - labelNames: ["surface", "model", "stream", "finish_reason"] as const, + labelNames: ["surface", "model", "stream", "finish_reason", "error_code"] as const, registers: [registry], }); @@ -80,7 +86,7 @@ export function createMetrics(options: { enabled: boolean; prefix?: string } = { const upstreamRestarts = new Counter({ name: `${prefix}upstream_restarts_total`, - help: "Number of times the managed OpenCode server was (re)started.", + help: "Upstream server (re)starts by reason: initial, stale, invalidated or restart.", labelNames: ["reason"] as const, registers: [registry], }); @@ -98,6 +104,27 @@ export function createMetrics(options: { enabled: boolean; prefix?: string } = { registers: [registry], }); + const eventStreamReconnects = new Counter({ + name: `${prefix}event_stream_reconnects_total`, + help: "Upstream event-stream reconnects by trigger: idle, ended or rejected.", + labelNames: ["reason"] as const, + registers: [registry], + }); + + const eventFramesDropped = new Counter({ + name: `${prefix}event_frames_dropped_total`, + help: "Upstream event frames the hub could not deliver, by reason: no_session, no_subscriber or malformed.", + labelNames: ["reason"] as const, + registers: [registry], + }); + + const rateLimitRejections = new Counter({ + name: `${prefix}rate_limit_rejections_total`, + help: "Requests rejected by the in-process rate limiter, by bucket scope.", + labelNames: ["scope"] as const, + registers: [registry], + }); + return { registry, httpRequests, @@ -110,5 +137,8 @@ export function createMetrics(options: { enabled: boolean; prefix?: string } = { upstreamRestarts, sessionCache, eventStream, + eventStreamReconnects, + eventFramesDropped, + rateLimitRejections, }; } diff --git a/src/upstream/client.ts b/src/upstream/client.ts index 7f8d3ab..b347e4f 100644 --- a/src/upstream/client.ts +++ b/src/upstream/client.ts @@ -165,6 +165,7 @@ export class OpencodeClient { const aborted = options.signal?.aborted === true; outcome = aborted ? "aborted" : timedOut ? "timeout" : "network_error"; this.#metrics.upstreamRequests.inc({ operation: options.operation, outcome }); + this.#log.debug({ err: reason, operation: options.operation, outcome }, "upstream request failed"); if (aborted) { throw new ApiError(499, "timeout_error", "Client closed the request.", { cause: error }); } @@ -218,11 +219,15 @@ export class OpencodeClient { return response.data ?? []; } - async createSession(payload: OpencodeSessionCreateRequest): Promise { + async createSession( + payload: OpencodeSessionCreateRequest, + options: { signal?: AbortSignal } = {}, + ): Promise { const response = await this.request>("/api/session", { method: "POST", body: payload, operation: "session.create", + ...(options.signal === undefined ? {} : { signal: options.signal }), }); return response.data; } @@ -247,12 +252,18 @@ export class OpencodeClient { sessionId: string, text: string, files: OpencodePromptFileAttachment[] = [], + options: { signal?: AbortSignal } = {}, ): Promise<{ id: string }> { const payload: OpencodePromptRequest = { text }; if (files.length > 0) payload.files = files; const response = await this.request>( `/api/session/${encodeURIComponent(sessionId)}/prompt`, - { method: "POST", body: payload, operation: "session.prompt" }, + { + method: "POST", + body: payload, + operation: "session.prompt", + ...(options.signal === undefined ? {} : { signal: options.signal }), + }, ); return response.data; } diff --git a/src/upstream/completion.ts b/src/upstream/completion.ts index e86198e..16f774c 100644 --- a/src/upstream/completion.ts +++ b/src/upstream/completion.ts @@ -115,20 +115,33 @@ export async function* runCompletion( // it as an `error` event and make sure the fresh slot is not left busy. let fresh: Prepared | undefined; try { - fresh = await prepare(request, deps, agent, { forceFresh: true }); + fresh = await prepare(request, deps, agent, { forceFresh: true, ...(options.signal ? { signal: options.signal } : {}) }); yield* execute(fresh, deps, options); } catch (replayError) { const replayApiError = toApiError(replayError, "OpenCode completion replay failed."); if (fresh) deps.sessions.release(fresh.key, fresh.sessionId, false); + recordCompletionFailure(deps, prepared, replayApiError); yield { kind: "error", error: replayApiError }; } return; } deps.sessions.release(prepared.key, prepared.sessionId, false); + recordCompletionFailure(deps, prepared, apiError); yield { kind: "error", error: apiError }; } } +/** Count a turn that failed before `execute()` could report its own outcome. */ +function recordCompletionFailure(deps: CompletionDeps, prepared: Prepared, error: ApiError): void { + deps.metrics.completions.inc({ + surface: prepared.request.surface, + model: prepared.resolved.canonical, + stream: String(prepared.request.stream), + finish_reason: "error", + error_code: error.code, + }); +} + /** Run a completion and aggregate the events into a single response. */ export async function collectCompletion( request: InternalRequest, @@ -165,9 +178,20 @@ export async function collectCompletion( case "text_delta": result.text += event.text; break; + case "text_end": + // A provider may deliver the consolidated text instead of (or in + // addition to) deltas. Adopt it only when it is longer than what the + // deltas accumulated — the same rule the Responses stream applies — so a + // step-level snapshot never truncates the buffered answer and the + // `finalise()` echo of the deltas is a no-op. + if (event.text.length > result.text.length) result.text = event.text; + break; case "reasoning_delta": result.reasoning += event.text; break; + case "reasoning_end": + if (event.text.length > result.reasoning.length) result.reasoning = event.text; + break; case "tool_calls": result.calls.push(...event.calls); break; @@ -196,7 +220,7 @@ async function prepare( request: InternalRequest, deps: CompletionDeps, agent: string, - options: { forceFresh: boolean }, + options: { forceFresh: boolean; signal?: AbortSignal }, ): Promise { const { client, config, models, sessions } = deps; @@ -240,18 +264,21 @@ async function prepare( let reused = acquire.reused && !options.forceFresh; try { if (!reused || !sessionId) { - const created = await client.createSession({ - model: { - providerID: resolved.providerID, - id: resolved.modelID, - ...(decision.variant ? { variant: decision.variant } : {}), + const created = await client.createSession( + { + model: { + providerID: resolved.providerID, + id: resolved.modelID, + ...(decision.variant ? { variant: decision.variant } : {}), + }, + agent, + title: deriveTitle(request.messages), + location: { directory: config.workdir }, + metadata: { gateway: "opencode-api", surface: request.surface }, + ...(permissions ? { permissions: permissions as never } : {}), }, - agent, - title: deriveTitle(request.messages), - location: { directory: config.workdir }, - metadata: { gateway: "opencode-api", surface: request.surface }, - ...(permissions ? { permissions: permissions as never } : {}), - }); + { ...(options.signal ? { signal: options.signal } : {}) }, + ); sessionId = created.id; reused = false; } @@ -309,6 +336,26 @@ async function* execute( }); let sessionSettled = false; + /** + * Count one terminal outcome. + * + * `finish_reason` alone cannot describe a failure (the `FinishReason` set has a + * single `"error"` member), so the bounded error code travels in its own + * dimension; error messages never become a label value. + */ + const recordOutcome = (finishReason: FinishReason, errorCode = ""): void => { + metrics.completions.inc({ + surface: prepared.request.surface, + model: prepared.resolved.canonical, + stream: String(prepared.request.stream), + finish_reason: finishReason, + error_code: errorCode, + }); + }; + const recordError = (error: ApiError): void => { + recordOutcome("error", error.code); + }; + try { if (!(await events.ensureConnected(5_000))) { // Without the event stream there is nowhere for the turn's events to @@ -319,6 +366,14 @@ async function* execute( }); } + // The caller may have gone away while the hub was connecting. Aborting here + // keeps an already-cancelled request from starting (and billing) a turn; the + // prompt below carries the same signal, so a disconnect during the request + // is not waited out for the full upstream timeout either. + if (options.signal?.aborted === true) { + throw new ApiError(499, "timeout_error", "Client disconnected."); + } + yield { kind: "start", sessionId, @@ -331,7 +386,9 @@ async function* execute( ...(prepared.decision.note ? { note: prepared.decision.note } : {}), }; - await client.prompt(sessionId, prepared.promptText, prepared.promptFiles); + await client.prompt(sessionId, prepared.promptText, prepared.promptFiles, { + ...(options.signal ? { signal: options.signal } : {}), + }); const filter = bridge.active ? bridge.createFilter() : undefined; const singleStep = bridge.active; @@ -361,29 +418,26 @@ async function* execute( 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", + const error = ApiError.unavailable("OpenCode event stream reconnected mid-turn; the response may be incomplete.", { + code: "event_stream_lost", }); - yield { - kind: "error", - error: ApiError.unavailable("OpenCode event stream reconnected mid-turn; the response may be incomplete.", { - code: "event_stream_lost", - }), - }; + recordError(error); + yield { kind: "error", error }; return; } } if (remaining <= 0) { await safeInterrupt(client, sessionId, log); - yield { kind: "error", error: ApiError.timeout("OpenCode did not finish the request in time.") }; + const error = ApiError.timeout("OpenCode did not finish the request in time."); + recordError(error); + yield { kind: "error", error }; return; } if (!sawText && Date.now() > firstTokenDeadline) { await safeInterrupt(client, sessionId, log); - yield { kind: "error", error: ApiError.timeout("OpenCode produced no output before the first-token timeout.") }; + const error = ApiError.timeout("OpenCode produced no output before the first-token timeout."); + recordError(error); + yield { kind: "error", error }; return; } @@ -391,7 +445,9 @@ async function* execute( 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.") }; + const error = new ApiError(499, "timeout_error", "Client disconnected."); + recordError(error); + yield { kind: "error", error }; return; } if (next === "timeout") continue; @@ -538,12 +594,14 @@ async function* execute( case "session.step.failed": { const error = structuredError(data["error"]); + recordError(error); yield { kind: "error", error }; return; } case "session.execution.failed": { const error = structuredError(data["error"]); + recordError(error); yield { kind: "error", error }; return; } @@ -558,6 +616,7 @@ async function* execute( case "session.idle": { if (event.type === "session.idle" && typeof data["outcome"] === "string" && data["outcome"] === "failed") { const error = structuredError(data["error"]); + recordError(error); yield { kind: "error", error }; return; } @@ -571,7 +630,6 @@ async function* execute( async function* finalise(): AsyncGenerator { if (sessionSettled) return; - sessionSettled = true; if (filter) { const tail = filter.finish(); @@ -602,12 +660,7 @@ async function* execute( yield { kind: "reasoning_end", text: reasoning, ordinal: 0 }; } - metrics.completions.inc({ - surface: prepared.request.surface, - model: prepared.resolved.canonical, - stream: String(prepared.request.stream), - finish_reason: finishReason, - }); + recordOutcome(finishReason); metrics.tokens.inc({ model: prepared.resolved.canonical, direction: "input" }, usage.inputTokens); metrics.tokens.inc({ model: prepared.resolved.canonical, direction: "output" }, usage.outputTokens); if (usage.reasoningTokens > 0) { @@ -623,6 +676,13 @@ async function* execute( permissionProfile: prepared.permissionProfile, }); + // Set only after the record is committed: the flag is what tells the + // `finally` below that the session slot is already settled. Setting it + // before the commit meant that abandoning the generator inside one of the + // yields above skipped the commit *and* the release, leaving the record + // `busy` until the sweeper reclaimed it. + sessionSettled = true; + yield { kind: "end", finishReason, @@ -859,7 +919,10 @@ function structuredError(value: unknown): ApiError { const record = (typeof value === "object" && value !== null ? value : {}) as OpencodeStructuredError; const message = typeof record.message === "string" ? record.message : "OpenCode reported a failure."; const status = typeof record.status === "number" ? record.status : undefined; - if (status === 429 || record.type === "provider.free-limit") { + // Mirrors `fromUpstreamError()`: `provider.rate-limit` is the same quota class + // as `provider.free-limit`, and a 404 must stay a not-found condition so the + // stale-session replay can see it instead of a generic 400. + if (status === 429 || record.type === "provider.free-limit" || record.type === "provider.rate-limit") { return new ApiError(429, "rate_limit_error", message, { code: record.type ?? "rate_limit_error", upstreamStatus: status, @@ -869,6 +932,9 @@ function structuredError(value: unknown): ApiError { if (status !== undefined && status >= 500) { return new ApiError(503, "overloaded_error", message, { code: record.type ?? "upstream_error", upstreamStatus: status }); } + if (status === 404) { + return ApiError.notFound(message, { code: record.type ?? "not_found_error", upstreamStatus: status }); + } if (status !== undefined && status >= 400 && status < 500) { return new ApiError(400, "invalid_request_error", message, { code: record.type ?? "invalid_request_error", upstreamStatus: status }); } @@ -880,8 +946,10 @@ function structuredErrorMessage(value: unknown): string { } function isStaleSession(error: ApiError): boolean { - if (error.status !== 404) return false; - return /session/i.test(error.message) || error.upstreamStatus === 404; + // `fromUpstreamError()` preserves `upstreamStatus` next to the caller-facing + // status, so either field can carry the 404 of a session that no longer + // exists; classifying on only one of them made this guard unreachable. + return error.status === 404 || error.upstreamStatus === 404; } async function safeInterrupt(client: OpencodeClient, sessionId: string, log: Logger): Promise { diff --git a/src/upstream/events.ts b/src/upstream/events.ts index 418a45e..dcb7ae4 100644 --- a/src/upstream/events.ts +++ b/src/upstream/events.ts @@ -20,6 +20,22 @@ export type ReconnectListener = () => void; const HEARTBEAT_INTERVAL_MS = 15_000; const IDLE_READ_TIMEOUT_MS = HEARTBEAT_INTERVAL_MS * 3; +/** Initial reconnect delay; doubles up to `MAX_RECONNECT_DELAY_MS`. */ +const INITIAL_RECONNECT_DELAY_MS = 250; +const MAX_RECONNECT_DELAY_MS = 5_000; + +/** + * A connection must stay up this long before the backoff is reset. + * + * An upstream that accepts `/api/event` and immediately ends the body (the + * documented slow-consumer overflow) used to reset the delay as soon as the + * response head arrived, pinning it at 250 ms and reconnecting four times per + * second for the life of the process. + */ +const HEALTHY_CONNECTION_MS = 5_000; + +type ReconnectReason = "idle" | "ended" | "rejected"; + export interface EventHubOptions { /** Override the idle-read watchdog; tests use a small value instead of waiting 45 s. */ idleTimeoutMs?: number; @@ -27,7 +43,6 @@ export interface EventHubOptions { export class EventHub { readonly #upstream: UpstreamProcess; - readonly #config: Config; readonly #log: Logger; readonly #metrics: Metrics; readonly #idleTimeoutMs: number; @@ -35,7 +50,11 @@ export class EventHub { #controller?: AbortController; #running = false; #connected = false; - #reconnectDelayMs = 250; + #reconnectDelayMs = INITIAL_RECONNECT_DELAY_MS; + /** When `server.connected` was parsed on the current connection. */ + #connectedAt?: number; + /** Why the current attempt is about to be abandoned; classified in `#loop`. */ + #dropReason?: ReconnectReason; /** Callers waiting for the next connection, released together. */ readonly #waiters = new Set<() => void>(); @@ -45,13 +64,14 @@ export class EventHub { constructor( upstream: UpstreamProcess, - config: Config, + // Retained for constructor stability (`new EventHub(upstream, config, log, + // metrics)`); the hub takes every timing knob from `EventHubOptions` today. + _config: Config, log: Logger, metrics: Metrics, options: EventHubOptions = {}, ) { this.#upstream = upstream; - this.#config = config; this.#log = log; this.#metrics = metrics; this.#idleTimeoutMs = options.idleTimeoutMs ?? IDLE_READ_TIMEOUT_MS; @@ -61,6 +81,11 @@ export class EventHub { return this.#connected; } + /** Current reconnect backoff; exposed so tests can pin the churn floor. */ + get reconnectDelayMs(): number { + return this.#reconnectDelayMs; + } + /** Start the background subscription. Idempotent. */ start(): void { if (this.#running) return; @@ -73,6 +98,10 @@ export class EventHub { this.#controller?.abort(); this.#controller = undefined; this.#connected = false; + // The gauge is zeroed here as well: `#loop`'s `finally` only observes the + // transition while `#connected` is still true, and `stop()` clears it first, + // so after a shutdown the exposition used to keep reporting 1. + this.#metrics.eventStream.set(0); // Nobody is going to be connected any more: release every waiter instead of // leaving them to time out. this.#notifyWaiters(); @@ -122,6 +151,7 @@ export class EventHub { async #loop(): Promise { while (this.#running) { + this.#dropReason = undefined; try { await this.#connectOnce(); } catch (error) { @@ -129,9 +159,13 @@ export class EventHub { this.#log.debug({ err: error instanceof Error ? error.message : String(error) }, "event stream ended"); } finally { const wasConnected = this.#connected; + const connectedAt = this.#connectedAt; + const reason = this.#dropReason ?? "ended"; this.#connected = false; + this.#connectedAt = undefined; if (wasConnected) { this.#metrics.eventStream.set(0); + this.#metrics.eventStreamReconnects.inc({ reason }); for (const listener of this.#reconnectListeners) { try { listener(); @@ -139,31 +173,42 @@ export class EventHub { /* listener errors must not kill the hub */ } } + // A connection that survived long enough to prove it works resets the + // backoff; a flapping one keeps doubling it. + const lifetime = connectedAt === undefined ? 0 : Date.now() - connectedAt; + if (lifetime >= HEALTHY_CONNECTION_MS) this.#reconnectDelayMs = INITIAL_RECONNECT_DELAY_MS; } } if (!this.#running) return; await delay(this.#reconnectDelayMs); - this.#reconnectDelayMs = Math.min(this.#reconnectDelayMs * 2, 5_000); + if (this.#reconnectDelayMs < MAX_RECONNECT_DELAY_MS) this.#reconnectDelayMs *= 2; } } async #connectOnce(): Promise { const endpoint = await this.#upstream.resolve(); + if (!this.#running) return; const controller = new AbortController(); this.#controller = controller; + // The idle watchdog only wraps `reader.read()`, i.e. it is reached after the + // response head. A server that accepts the connection and never writes the + // head would park this `await` for undici's ~300 s header timeout, during + // which the hub is not connected and every turn fails with + // `503 event_stream_unavailable`. Bound the connect phase only. + const connect = AbortSignal.timeout(this.#idleTimeoutMs); try { const response = await fetch(`${endpoint.url}/api/event`, { headers: { ...authHeaders(endpoint.password), accept: "text/event-stream", "cache-control": "no-cache" }, - signal: controller.signal, + signal: AbortSignal.any([controller.signal, connect]), }); if (!response.ok || !response.body) { + this.#dropReason = "rejected"; throw new Error(`event stream rejected with status ${response.status}`); } this.#log.debug({ url: endpoint.url }, "event stream connected"); - this.#reconnectDelayMs = 250; const reader = response.body.getReader(); // `decoder` and `buffer` are locals of this method ON PURPOSE: they hold @@ -179,7 +224,10 @@ export class EventHub { // `read()`, so each read is bounded by the idle watchdog: on expiry the // stream fails and `#loop` reconnects instead of hanging forever. const chunk = await withIdleDeadline(reader.read(), this.#idleTimeoutMs); - if (chunk.done) break; + if (chunk.done) { + this.#dropReason = "ended"; + break; + } buffer += decoder.decode(chunk.value, { stream: true }); let boundary = findBoundary(buffer); @@ -190,6 +238,11 @@ export class EventHub { boundary = findBoundary(buffer); } } + } catch (error) { + // Only the idle watchdog rejects here; a `stop()`-aborted read settles + // through `reader.cancel()` below. + this.#dropReason = "idle"; + throw error; } finally { // Release the response body on every exit path; without this a stop() or a // reconnect leaks one upstream SSE consumer. @@ -228,6 +281,7 @@ export class EventHub { try { parsed = JSON.parse(dataLines.join("\n")) as OpencodeEvent; } catch { + this.#metrics.eventFramesDropped.inc({ reason: "malformed" }); this.#log.debug({ frame: frame.slice(0, 200) }, "ignoring malformed event frame"); return; } @@ -237,15 +291,22 @@ export class EventHub { if (parsed.type === "server.connected") { this.#connected = true; + this.#connectedAt = Date.now(); this.#metrics.eventStream.set(1); this.#notifyWaiters(); return; } const sessionId = sessionIdOf(parsed); - if (!sessionId) return; + if (!sessionId) { + this.#metrics.eventFramesDropped.inc({ reason: "no_session" }); + return; + } const listeners = this.#listeners.get(sessionId); - if (!listeners || listeners.size === 0) return; + if (!listeners || listeners.size === 0) { + this.#metrics.eventFramesDropped.inc({ reason: "no_subscriber" }); + return; + } for (const listener of listeners) { try { listener(parsed); diff --git a/src/upstream/process.ts b/src/upstream/process.ts index 39ffb55..d7d4d3a 100644 --- a/src/upstream/process.ts +++ b/src/upstream/process.ts @@ -26,6 +26,11 @@ export type SpawnChildFn = (command: string, args: string[]) => SpawnedChild; export interface UpstreamProcessOptions { spawn?: SpawnChildFn; findBinary?: (explicit?: string) => string | undefined; + /** + * Override background-service discovery. Tests use it to stay independent of + * whatever `opencode serve` may be running on the machine. + */ + discover?: () => Promise; } export type EndpointSource = "env" | "spawned" | "discovered"; @@ -54,6 +59,8 @@ export interface UpstreamStatus { binary?: string; lastError?: string; lastStartedAt?: number; + /** Last lines the child wrote to stderr, oldest first (bounded ring buffer). */ + stderrTail?: string[]; } interface SpawnResult { @@ -65,12 +72,113 @@ const LISTEN_PATTERN = /server listening on\s+(https?:\/\/\S+)/i; const PASSWORD_PATTERN = /server password\s+(\S+)/i; const VERSION_PATTERN = /opencode\s+v?(\d+\.\d+\.\d+\S*)/i; +/** How much of the child's output is retained for readiness diagnostics. */ +const OUTPUT_TAIL_CHARS = 4_096; +/** How many recent stderr lines `status()` exposes. */ +const STDERR_TAIL_LINES = 50; +/** First failure window; doubles per consecutive failure up to the cap. */ +const START_BACKOFF_BASE_MS = 1_000; +const START_BACKOFF_MAX_MS = 30_000; + +/** + * Number of readiness scans performed, exposed for tests. + * + * After readiness is published the listener must not keep re-scanning the whole + * output; the counter proves no scan happens after the spawn settled. + */ +export const readinessScans = { + total: 0, +}; + +/** + * Bounded tail of a child stream. + * + * The previous implementation kept every chunk in an array and re-joined it on + * each arrival: unbounded memory plus quadratic CPU for the lifetime of the + * gateway. Only the tail matters, both for the `server listening on` / + * `server password` lines and for the readiness-error message. + */ +export class OutputTail { + #text = ""; + + constructor(private readonly limit: number) {} + + push(chunk: string): string { + this.#text += chunk; + if (this.#text.length > this.limit) this.#text = this.#text.slice(-this.limit); + return this.#text; + } + + get text(): string { + return this.#text; + } + + get length(): number { + return this.#text.length; + } +} + +/** + * Ring buffer of the child's most recent stderr lines. + * + * A readiness timeout or an exit right after spawn is the most common failure of + * this module; the last lines explain why, and the log file is not reachable + * from an operator without shell access. + */ +export class StderrTail { + readonly #lines: string[] = []; + readonly #limit: number; + #partial = ""; + + constructor(limit = STDERR_TAIL_LINES) { + this.#limit = limit; + } + + push(chunk: string): void { + this.#partial += chunk; + const parts = this.#partial.split("\n"); + this.#partial = parts.pop() ?? ""; + for (const part of parts) this.#append(part.replace(/\r$/, "")); + } + + get lines(): string[] { + return [...this.#lines]; + } + + get length(): number { + return this.#lines.length; + } + + clear(): void { + this.#lines.length = 0; + this.#partial = ""; + } + + #append(line: string): void { + if (line.length === 0) return; + this.#lines.push(line); + if (this.#lines.length > this.#limit) this.#lines.shift(); + } +} + export class UpstreamProcess { + /** + * Instances that have spawned at least one child, and the single `process` + * `exit` hook that kills their children. + * + * The registry exists so a process that builds many `UpstreamProcess` + * instances (the test suite does) installs exactly one exit listener instead + * of one per instance, which would trip Node's listener-leak warning. + */ + static readonly #liveInstances = new Set(); + static #exitHookInstalled = false; + readonly #config: Config; readonly #log: Logger; readonly #metrics: Metrics; readonly #spawnChild: SpawnChildFn; readonly #findBinary: (explicit?: string) => string | undefined; + readonly #discoverService: () => Promise; #endpoint?: UpstreamEndpoint; #child?: SpawnedChild; @@ -93,7 +201,19 @@ export class UpstreamProcess { #lastError?: string; #lastStartedAt?: number; #binary?: string; - #exitHookInstalled = false; + /** Recent stderr of the currently supervised (or last spawned) server. */ + readonly #stderrTail = new StderrTail(); + /** Consecutive spawn failures; drives the backoff window. */ + #startFailures = 0; + /** No spawn may be attempted before this instant after a failed start. */ + #startBackoffUntil = 0; + /** Set by the first successful resolve; later spawns are "restart", not "initial". */ + #startedOnce = false; + /** `stop()` was called, so the next successful spawn is a restart. */ + #stopped = false; + /** A `markStale()`/`invalidate()` happened since the last resolve. */ + #stalePending = false; + #invalidatedPending = false; constructor( config: Config, @@ -119,6 +239,7 @@ export class UpstreamProcess { windowsHide: true, }) as SpawnedChild); this.#binary = this.#findBinary(config.upstreamBin); + this.#discoverService = options.discover ?? (() => this.#discover()); } get binary(): string | undefined { @@ -134,6 +255,7 @@ export class UpstreamProcess { binary: this.#binary, lastError: this.#lastError, lastStartedAt: this.#lastStartedAt, + stderrTail: this.#stderrTail.lines, }; } @@ -153,11 +275,16 @@ export class UpstreamProcess { /** Drop the cached endpoint so the next call re-resolves it. */ async invalidate(reason: string): Promise { this.#log.warn({ reason, url: this.#endpoint?.url }, "invalidating upstream endpoint"); + // Recorded only when an endpoint was actually published: the orchestrator + // also invalidates a *session* (reason `stale-session`), which is not an + // upstream restart and must not be counted as one. + if (this.#endpoint) this.#invalidatedPending = true; this.#endpoint = undefined; } async stop(): Promise { this.#stopping = true; + this.#stopped = true; const child = this.#child; this.#child = undefined; this.#endpoint = undefined; @@ -245,6 +372,19 @@ export class UpstreamProcess { this.#lastError = undefined; this.#assertNotTerminated(); + // After a failed start, refuse to spawn again inside the backoff window: a + // crash-looping `opencode serve` would otherwise turn ordinary traffic into a + // fork storm (one child, two `mkdirSync` calls and a log file handle per + // request). `#starting` only dedupes attempts that overlap in time. + const backoffLeft = this.#startBackoffUntil - Date.now(); + if (backoffLeft > 0) { + throw ApiError.unavailable( + `The OpenCode server failed to start ${this.#startFailures} time(s) in a row; ` + + `retrying in ${backoffLeft} ms.`, + { code: "upstream_unavailable" }, + ); + } + if (this.#config.upstreamUrl) { const endpoint: UpstreamEndpoint = { url: this.#config.upstreamUrl.replace(/\/+$/, ""), @@ -267,16 +407,26 @@ export class UpstreamProcess { const spawned = await this.#spawn(); this.#endpoint = spawned.endpoint; this.#lastStartedAt = Date.now(); - this.#metrics.upstreamRestarts.inc({ reason: "spawn" }); + this.#startFailures = 0; + this.#startBackoffUntil = 0; + const reason = this.#nextStartReason(); + this.#startedOnce = true; + this.#metrics.upstreamRestarts.inc({ reason }); this.#log.info( - { url: spawned.endpoint.url, pid: spawned.endpoint.pid, binary: this.#binary }, + { url: spawned.endpoint.url, pid: spawned.endpoint.pid, binary: this.#binary, reason }, "started private OpenCode server", ); return spawned.endpoint; } catch (error) { const message = error instanceof Error ? error.message : String(error); failures.push(`spawn failed: ${message}`); - this.#log.warn({ err: message }, "could not start private OpenCode server; trying discovery"); + this.#startFailures += 1; + const delayMs = Math.min(2 ** this.#startFailures * START_BACKOFF_BASE_MS, START_BACKOFF_MAX_MS); + this.#startBackoffUntil = Date.now() + delayMs; + this.#log.warn( + { err: message, failures: this.#startFailures, retryInMs: delayMs }, + "could not start private OpenCode server; trying discovery", + ); } } @@ -284,10 +434,14 @@ export class UpstreamProcess { // probe budget on discovery, and must not publish an endpoint afterwards. this.#assertNotTerminated(); - const discovered = await this.#discover(); + const discovered = await this.#discoverService(); if (discovered) { this.#assertNotTerminated(); this.#endpoint = discovered; + // Discovery succeeded, so the failure chain is broken: a later resolve + // after this endpoint dies must not be blocked by the spawn backoff. + this.#startFailures = 0; + this.#startBackoffUntil = 0; this.#log.info({ url: discovered.url, pid: discovered.pid }, "using discovered OpenCode service"); return discovered; } @@ -400,6 +554,8 @@ export class UpstreamProcess { this.#log.debug({ binary: this.#binary, args }, "spawning OpenCode server"); + // A new server's output must not be mixed with the previous one's. + this.#stderrTail.clear(); const child = this.#spawnChild(this.#binary as string, args); // Registered synchronously: from here on the child is a process that exists, @@ -413,8 +569,8 @@ export class UpstreamProcess { return await new Promise((resolve, reject) => { let settled = false; - const stdout: string[] = []; - const stderr: string[] = []; + const stdout = new OutputTail(OUTPUT_TAIL_CHARS); + const stderr = new OutputTail(OUTPUT_TAIL_CHARS); const finish = (error?: Error, value?: SpawnResult): void => { if (settled) return; @@ -436,14 +592,15 @@ export class UpstreamProcess { finish( new Error( `OpenCode server did not report readiness within ${this.#config.upstreamStartTimeoutMs} ms. ` + - `stderr: ${stderr.join("").trim().slice(-500)}`, + `stderr: ${stderr.text.trim().slice(-500)}`, ), ); }, this.#config.upstreamStartTimeoutMs); - const inspect = (chunk: string, sink: string[]): void => { - sink.push(chunk); - const combined = sink.join(""); + /** Scan the accumulated output for the readiness lines. */ + const inspect = (chunk: string, sink: OutputTail): void => { + const combined = sink.push(chunk); + readinessScans.total += 1; const listen = LISTEN_PATTERN.exec(combined); const password = PASSWORD_PATTERN.exec(combined); if (listen?.[1] && password?.[1]) { @@ -465,11 +622,15 @@ export class UpstreamProcess { child.stderr.setEncoding("utf8"); child.stdout.on("data", (chunk: string) => { logStream.write(chunk); - inspect(chunk, stdout); + if (!settled) inspect(chunk, stdout); }); child.stderr.on("data", (chunk: string) => { logStream.write(chunk); - inspect(chunk, stderr); + // The stderr ring buffer is fed for the whole lifetime of the child, not + // only while waiting for readiness: an operator needs the reason a + // long-running server died, not just the reason a start failed. + this.#stderrTail.push(chunk); + if (!settled) inspect(chunk, stderr); }); child.once("error", (error) => finish(error)); @@ -479,7 +640,7 @@ export class UpstreamProcess { finish( new Error( `OpenCode server exited before becoming ready (code=${code ?? "null"}, signal=${signal ?? "null"}). ` + - `stderr: ${stderr.join("").trim().slice(-500)}`, + `stderr: ${stderr.text.trim().slice(-500)}`, ), ); return; @@ -499,10 +660,11 @@ export class UpstreamProcess { * yet, and killing it at exit time is the last chance to release its port. */ #installExitHook(): void { - if (this.#exitHookInstalled) return; - this.#exitHookInstalled = true; + UpstreamProcess.#liveInstances.add(this); + if (UpstreamProcess.#exitHookInstalled) return; + UpstreamProcess.#exitHookInstalled = true; process.once("exit", () => { - this.#killLiveChildren(); + for (const instance of UpstreamProcess.#liveInstances) instance.#killLiveChildren(); }); } @@ -552,6 +714,7 @@ export class UpstreamProcess { const stale = this.#endpoint; this.#endpoint = undefined; this.#lastError = reason; + if (stale) this.#stalePending = true; if (stale?.source !== "spawned") return; const child = this.#child; @@ -567,6 +730,34 @@ export class UpstreamProcess { /* already gone */ } } + + /** + * Classify the next published server for `upstream_restarts_total{reason}`. + * + * The first start of the instance is `initial`; a server started after a + * `stop()` is a `restart`; one started while an endpoint had been declared + * stale (a timeout, a network error or a rejected credential) is `stale`; and + * an explicit `invalidate()` is `invalidated`. Every value is consumed once, so + * a failed resolve does not leak its reason onto the next one. + */ + #nextStartReason(): "initial" | "stale" | "invalidated" | "restart" { + if (this.#stopped) { + this.#stopped = false; + this.#stalePending = false; + this.#invalidatedPending = false; + return "restart"; + } + if (this.#stalePending) { + this.#stalePending = false; + this.#invalidatedPending = false; + return "stale"; + } + if (this.#invalidatedPending) { + this.#invalidatedPending = false; + return "invalidated"; + } + return this.#startedOnce ? "restart" : "initial"; + } } /** The error every entry point throws once `shutdown()` made the instance terminal. */ diff --git a/src/upstream/sessions.ts b/src/upstream/sessions.ts index 6dc127a..982b58e 100644 --- a/src/upstream/sessions.ts +++ b/src/upstream/sessions.ts @@ -398,9 +398,16 @@ export class SessionStore { } #publishGauges(): void { + // Iterated in place: going through `list()` flattened and sorted up to + // `sessionMaxEntries` records to compute two integers that the order does not + // affect, on every commit, release, invalidate, clear and sweep. + let entries = 0; let busy = 0; - for (const record of this.list()) if (record.busy) busy += 1; - this.#metrics.sessionCache.set({ state: "entries" }, this.size()); + for (const candidates of this.#records.values()) { + entries += candidates.length; + for (const record of candidates) if (record.busy) busy += 1; + } + this.#metrics.sessionCache.set({ state: "entries" }, entries); this.#metrics.sessionCache.set({ state: "busy" }, busy); } diff --git a/test/client.test.ts b/test/client.test.ts index e91e9fa..3238dd7 100644 --- a/test/client.test.ts +++ b/test/client.test.ts @@ -144,4 +144,27 @@ describe("OpencodeClient", () => { ); expect(count?.value).toBe(1); }); + + it("cancels createSession and prompt when the caller aborts", async () => { + const upstream = await hangingUpstream(60_000); + + const createAbort = new AbortController(); + const creating = upstream.client.createSession( + { model: { providerID: "opencode", id: "m" }, agent: "build" }, + { signal: createAbort.signal }, + ); + setTimeout(() => createAbort.abort(), 30); + // The caller's signal must reach the fetch, not just the queue wait: without + // it a client disconnect stayed invisible for the whole request budget. + await expect(creating).rejects.toMatchObject({ status: 499 }); + + const promptAbort = new AbortController(); + const prompting = upstream.client.prompt("ses_1", "hello", [], { signal: promptAbort.signal }); + setTimeout(() => promptAbort.abort(), 30); + await expect(prompting).rejects.toMatchObject({ status: 499 }); + + const requests = await metricValues(upstream, "opencode_api_upstream_requests_total"); + expect(requests.map((value) => value.labels?.["outcome"])).toEqual(["aborted", "aborted"]); + expect(requests.map((value) => value.labels?.["operation"])).toEqual(["session.create", "session.prompt"]); + }); }); \ No newline at end of file diff --git a/test/completion.test.ts b/test/completion.test.ts index fcfa83a..2d76297 100644 --- a/test/completion.test.ts +++ b/test/completion.test.ts @@ -1,22 +1,50 @@ import { describe, expect, it } from "vitest"; +import http from "node:http"; +import type { AddressInfo } from "node:net"; import { createLogger } from "../src/logger.js"; -import { createMetrics } from "../src/metrics/registry.js"; +import { createMetrics, type Metrics } from "../src/metrics/registry.js"; import { ApiError } from "../src/errors.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 { SessionStore, deriveKey } from "../src/upstream/sessions.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 { OpencodeClient } from "../src/upstream/client.js"; +import type { UpstreamProcess } from "../src/upstream/process.js"; import { defaultModels, testConfig } from "./helpers/context.js"; interface Harness { deps: CompletionDeps; sessions: SessionStore; + metrics: Metrics; createSessionCalls: Array>; promptCalls: Array<{ sessionId: string; text: string; files: unknown[] }>; + /** Options every `prompt()` call received. */ + promptOptions: Array<{ signal?: AbortSignal }>; + /** A promise that resolves once `prompt()` has been called at least once. */ + waitForPrompt: () => Promise; +} + +/** One metric series out of `registry.getMetricsAsJSON()`. */ +interface MetricSeries { + labels: Record; + value: number; +} + +/** Read every series of one counter/gauge. */ +async function metricSeries(metrics: Metrics, name: string): Promise { + const json = (await metrics.registry.getMetricsAsJSON()) as unknown as Array<{ + name: string; + values?: Array<{ labels?: Record; value: number }>; + }>; + const entry = json.find((item) => item.name === name); + return (entry?.values ?? []).map((value) => ({ labels: value.labels ?? {}, value: value.value })); +} + +function matches(labels: Record, expected: Record): boolean { + return Object.entries(expected).every(([key, value]) => labels[key] === value); } /** @@ -26,7 +54,7 @@ interface Harness { function harness( script: (sessionId: string, call: number) => OpencodeEvent[], configOverrides: Parameters[0] = {}, - options: { ensureConnected?: () => Promise } = {}, + options: { ensureConnected?: () => Promise; promptAbortsWithSignal?: boolean } = {}, ): Harness { const config = testConfig({ modelCacheTtlMs: 60_000, ...configOverrides }); const log = createLogger(config); @@ -35,6 +63,11 @@ function harness( const listeners = new Map>(); const createSessionCalls: Array> = []; const promptCalls: Array<{ sessionId: string; text: string; files: unknown[] }> = []; + const promptOptions: Array<{ signal?: AbortSignal }> = []; + let markPrompted: () => void = () => undefined; + const prompted = new Promise((resolve) => { + markPrompted = resolve; + }); let callCount = 0; const events = { @@ -66,8 +99,21 @@ function harness( createSessionCalls.push(payload); return { id: "ses_test", projectID: "p", cost: 0, tokens: { input: 0, output: 0, reasoning: 0, cache: { read: 0, write: 0 } }, time: { created: 0, updated: 0 }, location: { directory: "/tmp" } }; }, - async prompt(sessionId: string, text: string, files: unknown[] = []) { + async prompt(sessionId: string, text: string, files: unknown[] = [], requestOptions: { signal?: AbortSignal } = {}) { promptCalls.push({ sessionId, text, files }); + promptOptions.push(requestOptions); + markPrompted(); + if (options.promptAbortsWithSignal === true) { + // Never resolves on its own: only the caller's signal can settle it, + // exactly like a real request against a hung upstream. + return await new Promise<{ id: string }>((_resolve, reject) => { + requestOptions.signal?.addEventListener( + "abort", + () => reject(new ApiError(499, "timeout_error", "Client closed the request.")), + { once: true }, + ); + }); + } const scripted = script(sessionId, callCount++); queueMicrotask(() => { for (const event of scripted) { @@ -87,7 +133,17 @@ function harness( const models = new ModelRegistry(client, config, log); const sessions = new SessionStore(config, log, metrics); - return { deps: { client, events, models, sessions, config, log, metrics }, sessions, createSessionCalls, promptCalls }; + return { + deps: { client, events, models, sessions, config, log, metrics }, + sessions, + metrics, + createSessionCalls, + promptCalls, + promptOptions, + waitForPrompt: async () => { + await prompted; + }, + }; } function event(type: string, data: Record): OpencodeEvent { @@ -184,6 +240,34 @@ describe("collectCompletion", () => { expect(result.reasoning).toBe("step by step"); }); + it("uses a consolidated text_end when the provider sent no deltas", async () => { + const { deps } = harness(() => [ + event("session.step.started", { assistantMessageID: "msg_a1" }), + event("session.text.ended", { assistantMessageID: "msg_a1", ordinal: 0, text: "all at once" }), + event("session.step.ended", { assistantMessageID: "msg_a1", finish: "stop", tokens: { input: 1, output: 1, reasoning: 0, cache: { read: 0, write: 0 } } }), + event("session.execution.succeeded", { assistantMessageID: "msg_a1" }), + ]); + + const result = await collectCompletion(request(), deps); + // The buffered answer used to be empty when the provider skipped the deltas. + expect(result.text).toBe("all at once"); + }); + + it("keeps the deltas when a step-level text_end is shorter than them", async () => { + const { deps } = harness(() => [ + event("session.step.started", { assistantMessageID: "msg_a1" }), + event("session.text.delta", { assistantMessageID: "msg_a1", ordinal: 0, delta: "First" }), + event("session.text.ended", { assistantMessageID: "msg_a1", ordinal: 0, text: "First" }), + event("session.text.delta", { assistantMessageID: "msg_a1", ordinal: 0, delta: " second" }), + event("session.text.ended", { assistantMessageID: "msg_a1", ordinal: 0, text: " second" }), + event("session.step.ended", { assistantMessageID: "msg_a1", finish: "stop", tokens: { input: 1, output: 1, reasoning: 0, cache: { read: 0, write: 0 } } }), + event("session.execution.succeeded", { assistantMessageID: "msg_a1" }), + ]); + + const result = await collectCompletion(request(), deps); + expect(result.text).toBe("First second"); + }); + it("turns a prompt-level tool envelope into tool calls", async () => { const envelope = `${TOOL_CALL_OPEN}{"name":"get_weather","arguments":{"city":"Hanoi"}}${TOOL_CALL_CLOSE}`; const { deps } = harness(() => simpleTurn(`Let me check ${envelope}`)); @@ -381,6 +465,26 @@ describe("collectCompletion", () => { it("fails fast when the event stream is not connected", async () => { const { deps, promptCalls, sessions } = harness(() => simpleTurn("ok"), {}, { ensureConnected: async () => false }); + // Seed a record under the key and session id the request will use, so the + // assertion below cannot pass on an empty list. `acquire()` cannot reuse it + // (the pending slice would be empty), so `prepare()` creates the same id and + // the failure path targets exactly this record. + const key = deriveKey({ + model: "opencode/seaglass-alpha-free", + agent: "build", + messages: [{ role: "user", text: "Hello" }], + toolsHash: "none", + permissionProfile: "default", + }); + sessions.commit(key, "ses_test", { + model: "opencode/seaglass-alpha-free", + agent: "build", + messages: [{ role: "user", text: "Hello" }], + toolsHash: "none", + permissionProfile: "default", + }); + expect(sessions.list()).toHaveLength(1); + await expect(collectCompletion(request(), deps)).rejects.toMatchObject({ status: 503, code: "event_stream_unavailable", @@ -388,7 +492,19 @@ describe("collectCompletion", () => { // No upstream turn may be started without a stream to receive its events. expect(promptCalls).toHaveLength(0); - expect(sessions.list().every((record) => !record.busy)).toBe(true); + // The failed turn must drop the record, not merely unlock it: a session that + // produced no answer is not reusable. + expect(sessions.list()).toHaveLength(0); + expect( + sessions.acquire({ + key, + model: "opencode/seaglass-alpha-free", + agent: "build", + messages: [{ role: "user", text: "Hello" }], + toolsHash: "none", + permissionProfile: "default", + }).reason, + ).toBe("no-record"); }); it("yields an error event instead of throwing when the stale-session replay fails", async () => { @@ -402,6 +518,7 @@ describe("collectCompletion", () => { request({ conversationKey: "stale-replay", messages: [{ role: "user", text: "Hello" }] }), deps, ); + expect(sessions.list()).toHaveLength(1); const events: CompletionEvent[] = []; let thrown: unknown; @@ -425,7 +542,9 @@ describe("collectCompletion", () => { expect(thrown).toBeUndefined(); expect(events.at(-1)?.kind).toBe("error"); - expect(sessions.list().every((record) => !record.busy)).toBe(true); + // Both the vanished session and the failed replacement must be dropped, not + // merely unlocked: the next turn has to start a fresh upstream session. + expect(sessions.list()).toHaveLength(0); }); it("caches the replayed session under the conversation key so the next turn reuses it", async () => { @@ -463,6 +582,123 @@ describe("collectCompletion", () => { expect(createSessionCalls).toHaveLength(2); }); + it("replays a sticky session that vanished upstream instead of returning 400", async () => { + // A real `OpencodeClient` against a stub HTTP upstream: `fromUpstreamError()` + // is what rewrites the upstream 404, so the stale-session recovery only runs + // if the classifier preserves it. + const created: string[] = []; + const prompts: Array<{ sessionId: string; body: { text?: string } }> = []; + /** Sessions the stub answers with 404, i.e. that vanished upstream. */ + const vanished = new Set(); + let sessionSeq = 0; + + const server = http.createServer((incoming, response) => { + const chunks: Buffer[] = []; + incoming.on("data", (chunk: Buffer) => chunks.push(chunk)); + incoming.on("end", () => { + const path = incoming.url ?? ""; + const raw = Buffer.concat(chunks).toString("utf8"); + const send = (status: number, payload: unknown): void => { + response.writeHead(status, { "content-type": "application/json" }); + response.end(JSON.stringify(payload)); + }; + if (path === "/api/model") { + send(200, { data: defaultModels() }); + return; + } + if (path === "/api/agent") { + send(200, { data: [{ id: "build", name: "Build", mode: "primary", hidden: false, request: {} }] }); + return; + } + if (path === "/api/provider") { + send(200, { data: [] }); + return; + } + if (incoming.method === "POST" && path === "/api/session") { + sessionSeq += 1; + const id = `ses_${sessionSeq}`; + created.push(id); + send(200, { data: { id } }); + return; + } + const prompt = /^\/api\/session\/([^/]+)\/prompt$/.exec(path); + if (incoming.method === "POST" && prompt) { + const sessionId = prompt[1] ?? ""; + prompts.push({ sessionId, body: JSON.parse(raw) as { text?: string } }); + if (vanished.has(sessionId)) { + send(404, { message: "session not found", _tag: "NotFound" }); + return; + } + send(200, { data: { id: "msg_1" } }); + // Complete the turn on the event stream, exactly like the real server. + queueMicrotask(() => { + for (const listener of listeners.get(sessionId) ?? []) { + listener(event("session.execution.succeeded", { assistantMessageID: "msg_2" })); + } + }); + return; + } + send(404, { message: `no route for ${path}` }); + }); + }); + await new Promise((resolve) => server.listen(0, "127.0.0.1", resolve)); + const base = `http://127.0.0.1:${(server.address() as AddressInfo).port}`; + + const config = testConfig({ modelCacheTtlMs: 60_000, upstreamUrl: base, upstreamAutostart: false }); + const log = createLogger(config); + const metrics = createMetrics({ enabled: false }); + const listeners = new Map>(); + 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: () => () => undefined, + } as unknown as EventHub; + const upstream = { + resolve: async () => ({ url: base, password: undefined, source: "env" as const }), + markStale: () => undefined, + } as unknown as UpstreamProcess; + const client = new OpencodeClient(upstream, config, log, metrics); + const models = new ModelRegistry(client, config, log); + const sessions = new SessionStore(config, log, metrics); + const deps: CompletionDeps = { client, events, models, sessions, config, log, metrics }; + + try { + const first = request({ conversationKey: "stale-http", messages: [{ role: "user", text: "Hello" }] }); + const firstResult = await collectCompletion(first, deps); + expect(created).toEqual(["ses_1"]); + expect(firstResult.finishReason).toBe("stop"); + + // The upstream server restarted (`markStale()`), which invalidates every + // cached `ses_*` id at once. + vanished.add("ses_1"); + + const second = request({ + conversationKey: "stale-http", + messages: [{ role: "user", text: "Hello" }, { role: "assistant", text: "Hi" }, { role: "user", text: "again" }], + }); + const result = await collectCompletion(second, deps); + + // Pre-fix the upstream 404 became a 400, `isStaleSession()` returned early + // and the caller saw an error instead of a replayed turn. + expect(created).toEqual(["ses_1", "ses_2"]); + expect(result.finishReason).toBe("stop"); + expect(prompts.map((entry) => entry.sessionId)).toEqual(["ses_1", "ses_1", "ses_2"]); + expect(sessions.list()[0]?.sessionId).toBe("ses_2"); + } finally { + server.closeAllConnections(); + await new Promise((resolve) => server.close(() => resolve())); + } + }); + it("keeps consuming after a non-tool step end when no bridged call was parsed", async () => { const { deps } = harness(() => [ event("session.step.started", { assistantMessageID: "msg_a1" }), @@ -495,6 +731,178 @@ describe("collectCompletion", () => { }); }); +describe("completion outcome metrics", () => { + it("counts a request timeout as an error with its code", async () => { + const { deps, metrics } = harness( + () => [event("session.step.started", { assistantMessageID: "msg_a1" })], + { upstreamRequestTimeoutMs: 300, upstreamFirstTokenTimeoutMs: 300 }, + ); + + await expect(collectCompletion(request(), deps)).rejects.toMatchObject({ status: 504 }); + + const series = await metricSeries(metrics, "opencode_api_completions_total"); + const failure = series.find((entry) => matches(entry.labels, { finish_reason: "error" })); + // Before the fix nothing at all was recorded for a timed-out turn, so an + // operator could not build a failure-rate panel. + expect(failure?.value).toBe(1); + expect(failure?.labels["error_code"]).toBe("timeout_error"); + expect(series.every((entry) => entry.labels["error_code"] !== undefined)).toBe(true); + }); + + it("counts a first-token timeout as an error with its code", async () => { + const { deps, metrics } = harness( + () => [event("session.step.started", { assistantMessageID: "msg_a1" })], + { upstreamRequestTimeoutMs: 5_000, upstreamFirstTokenTimeoutMs: 250 }, + ); + + await expect(collectCompletion(request(), deps)).rejects.toMatchObject({ status: 504 }); + + const failure = (await metricSeries(metrics, "opencode_api_completions_total")).find((entry) => + matches(entry.labels, { finish_reason: "error" }), + ); + expect(failure?.value).toBe(1); + expect(failure?.labels["error_code"]).toBe("timeout_error"); + }); + + it("counts a scripted step failure once, with the upstream error code", async () => { + const { deps, metrics } = harness(() => [ + event("session.step.started", { assistantMessageID: "msg_a1" }), + event("session.step.failed", { + assistantMessageID: "msg_a1", + error: { type: "provider.free-limit", message: "Free usage limit reached.", status: 429, retryAfterMs: 1_000 }, + }), + ]); + + await expect(collectCompletion(request(), deps)).rejects.toMatchObject({ status: 429 }); + + const failure = (await metricSeries(metrics, "opencode_api_completions_total")).find((entry) => + matches(entry.labels, { finish_reason: "error" }), + ); + expect(failure?.value).toBe(1); + expect(failure?.labels["error_code"]).toBe("provider.free-limit"); + }); + + it("labels a successful turn with an empty error code", async () => { + const { deps, metrics } = harness(() => simpleTurn("ok")); + await collectCompletion(request(), deps); + + const series = await metricSeries(metrics, "opencode_api_completions_total"); + expect(series).toHaveLength(1); + expect(series[0]?.labels["finish_reason"]).toBe("stop"); + expect(series[0]?.labels["error_code"]).toBe(""); + }); +}); + +describe("caller abort propagation", () => { + it("threads the caller signal into createSession and prompt and releases the slot", async () => { + const harnessed = harness( + () => [event("session.step.started", { assistantMessageID: "msg_a1" })], + {}, + { promptAbortsWithSignal: true }, + ); + const controller = new AbortController(); + + // Seed the sticky record the turn reuses, so the slot being held busy is + // observable. `deliveredCount: 0` makes the whole request pending, which is + // what `acquire()` needs to hand the record to this turn. + harnessed.sessions.commit("abort-conv", "ses_test", { + model: "opencode/seaglass-alpha-free", + agent: "build", + messages: [], + toolsHash: "none", + permissionProfile: "default", + }); + + let thrown: unknown; + const seen: CompletionEvent[] = []; + const consume = (async () => { + try { + for await (const item of runCompletion( + request({ conversationKey: "abort-conv", messages: [{ role: "user", text: "Hello" }] }), + harnessed.deps, + { signal: controller.signal }, + )) { + seen.push(item); + } + } catch (error) { + thrown = error; + } + })(); + + await harnessed.waitForPrompt(); + // The caller's signal must reach the request that spends the upstream turn, + // not just the queue wait: without it a disconnect stayed invisible for the + // whole request budget and the sticky record stayed busy meanwhile. + expect(harnessed.promptOptions[0]?.signal).toBe(controller.signal); + expect(harnessed.sessions.list()[0]?.busy).toBe(true); + + controller.abort(); + await consume; + + // The failure surfaces as an `error` event so streaming callers can report it + // mid-stream; it must be the 499 that marks a caller disconnect. + expect(thrown).toBeUndefined(); + const failure = seen.at(-1); + expect(failure?.kind).toBe("error"); + if (failure?.kind !== "error") throw new Error("expected an error event"); + expect(failure.error.status).toBe(499); + // The failed turn drops the reservation, so the next request is not blocked. + expect(harnessed.sessions.list()).toHaveLength(0); + }); + + it("does not prompt at all when the request is already aborted", async () => { + const harnessed = harness(() => simpleTurn("ok")); + const controller = new AbortController(); + controller.abort(); + + await expect( + collectCompletion(request({ conversationKey: "pre-abort" }), harnessed.deps, { signal: controller.signal }), + ).rejects.toMatchObject({ status: 499 }); + expect(harnessed.promptCalls).toHaveLength(0); + }); +}); + +describe("abandoned turn", () => { + it("does not leave the session record busy when the consumer abandons the generator", async () => { + const harnessed = harness(() => simpleTurn("Hi there"), { + upstreamRequestTimeoutMs: 5_000, + upstreamFirstTokenTimeoutMs: 5_000, + }); + + // Seed the record the turn reuses, otherwise there is no slot to leak. + harnessed.sessions.commit("abandon-conv", "ses_test", { + model: "opencode/seaglass-alpha-free", + agent: "build", + messages: [], + toolsHash: "none", + permissionProfile: "default", + }); + + const iterator = runCompletion( + request({ conversationKey: "abandon-conv", messages: [{ role: "user", text: "Hello" }] }), + harnessed.deps, + ); + + // Consume until `finalise()` has yielded its first event (the aggregated + // `text_end`). That yield happens after `sessionSettled` used to be set but + // before `sessions.commit()` ran. + let reachedFinaliseYield = false; + while (!reachedFinaliseYield) { + const step = await iterator.next(); + if (step.done === true) throw new Error("the turn ended before finalise yielded"); + reachedFinaliseYield = step.value.kind === "text_end"; + } + expect(harnessed.sessions.list()[0]?.busy).toBe(true); + + // Abandon the generator mid-`finalise()`. The `finally` in `execute()` must + // release the record: with `sessionSettled` set too early the release was + // skipped and the record stayed busy until the sweeper reclaimed it. + await iterator.return(undefined); + + expect(harnessed.sessions.list()).toHaveLength(0); + }); +}); + describe("runCompletion streaming", () => { it("emits deltas in order followed by a single end event", async () => { const { deps } = harness(() => simpleTurn("one two three")); @@ -597,31 +1005,50 @@ describe("runCompletion streaming", () => { it("releases the session slot when a request times out", async () => { const { deps, sessions } = harness( - () => [event("session.step.started", { assistantMessageID: "msg_a1" })], + (_sessionId, call) => + call === 0 + ? simpleTurn("Hi there") + : [event("session.step.started", { assistantMessageID: "msg_a1" })], { upstreamRequestTimeoutMs: 400, upstreamFirstTokenTimeoutMs: 400 }, ); + // Turn 1 commits a sticky record; turn 2 reuses it and then hangs. + const first = await collectCompletion( + request({ conversationKey: "timeout-conv", messages: [{ role: "user", text: "Hello" }] }), + deps, + ); + expect(sessions.list()).toHaveLength(1); + const started = Date.now(); await expect( collectCompletion( - request({ conversationKey: "timeout-conv", messages: [{ role: "user", text: "hang" }] }), + request({ + conversationKey: "timeout-conv", + messages: [ + { role: "user", text: "Hello" }, + { role: "assistant", text: "Hi there" }, + { role: "user", text: "hang" }, + ], + }), deps, ), ).rejects.toMatchObject({ status: 504 }); expect(Date.now() - started).toBeLessThan(10_000); + expect(first.finishReason).toBe("stop"); - // After the failed turn the conversation key must not be stuck as busy; a - // fresh request has to be able to start a new upstream session. + // After the failed turn the record must be gone, not merely unlocked: the + // session answered nothing, so it must not be reused. (`[].every(...)` was + // true whether the record was unlocked or thrown away.) + expect(sessions.list()).toHaveLength(0); const next = sessions.acquire({ key: "timeout-conv", model: "opencode/seaglass-alpha-free", agent: "build", - messages: [{ role: "user", text: "hang" }], + messages: [{ role: "user", text: "Hello" }], toolsHash: "none", permissionProfile: "default", }); expect(next.reason).not.toBe("session-busy"); - expect(sessions.list().every((record) => !record.busy)).toBe(true); }); }); diff --git a/test/events.test.ts b/test/events.test.ts index 867d36f..b22299f 100644 --- a/test/events.test.ts +++ b/test/events.test.ts @@ -2,7 +2,7 @@ import http from "node:http"; import type { AddressInfo } from "node:net"; import { afterEach, describe, expect, it } from "vitest"; import { createLogger } from "../src/logger.js"; -import { createMetrics } from "../src/metrics/registry.js"; +import { createMetrics, type Metrics } from "../src/metrics/registry.js"; import { EventHub } from "../src/upstream/events.js"; import type { UpstreamProcess } from "../src/upstream/process.js"; import type { OpencodeEvent } from "../src/types/opencode.js"; @@ -10,6 +10,7 @@ import { testConfig } from "./helpers/context.js"; interface Fixture { hub: EventHub; + metrics: Metrics; url: string; close: () => Promise; connectionCount: () => number; @@ -17,10 +18,16 @@ interface Fixture { closedCount: () => number; } +interface FixtureOptions { + idleTimeoutMs?: number; + /** Delay the response head by this long, simulating a hung connect phase. */ + beforeHeadMs?: number; +} + /** Start a fake `/api/event` server and point an EventHub at it. */ async function fixture( writeFrames: (response: http.ServerResponse, connection: number) => () => void, - options: { idleTimeoutMs?: number } = {}, + options: FixtureOptions = {}, ): Promise { let connections = 0; let closed = 0; @@ -33,11 +40,16 @@ async function fixture( return; } connections += 1; + const connection = connections; response.on("close", () => { closed += 1; }); - response.writeHead(200, { "content-type": "text/event-stream" }); - cleanups.push(writeFrames(response, connections)); + const start = (): void => { + response.writeHead(200, { "content-type": "text/event-stream" }); + cleanups.push(writeFrames(response, connection)); + }; + if (options.beforeHeadMs === undefined) start(); + else setTimeout(start, options.beforeHeadMs); }); await new Promise((resolve) => server.listen(0, "127.0.0.1", resolve)); @@ -51,10 +63,13 @@ async function fixture( resolve: async () => ({ url, password: undefined, source: "env" as const }), } as unknown as UpstreamProcess; - const hub = new EventHub(upstream, config, log, metrics, options); + const hub = new EventHub(upstream, config, log, metrics, { + ...(options.idleTimeoutMs === undefined ? {} : { idleTimeoutMs: options.idleTimeoutMs }), + }); return { hub, + metrics, url, connectionCount: () => connections, closedCount: () => closed, @@ -68,6 +83,28 @@ async function fixture( }; } +/** Counter value for one label set out of `registry.getMetricsAsJSON()`. */ +async function counterValue(metrics: Metrics, name: string, labels: Record): Promise { + const json = (await metrics.registry.getMetricsAsJSON()) as unknown as Array<{ + name: string; + values?: Array<{ labels?: Record; value: number }>; + }>; + const entry = json.find((item) => item.name === name); + const match = entry?.values?.find((value) => + Object.entries(labels).every(([key, expected]) => value.labels?.[key] === expected), + ); + return match?.value ?? 0; +} + +/** Gauge value out of `registry.getMetricsAsJSON()`. */ +async function gaugeValue(metrics: Metrics, name: string): Promise { + const json = (await metrics.registry.getMetricsAsJSON()) as unknown as Array<{ + name: string; + values?: Array<{ value: number }>; + }>; + return json.find((item) => item.name === name)?.values?.[0]?.value; +} + function frame(event: OpencodeEvent): string { return `data: ${JSON.stringify(event)}\n\n`; } @@ -312,6 +349,101 @@ describe("EventHub", () => { await waitFor(() => deltas.length === 1); expect(deltas).toEqual(["héllo ✓"]); }); + + it("bounds the connect phase instead of waiting for the header timeout", async () => { + // The fixture accepts the connection and only then delays the response head, + // which is the half-open case the idle watchdog cannot see: the watchdog only + // wraps `reader.read()`. + const item = await fixture( + (response) => { + response.write(frame({ id: "e0", type: "server.connected", data: {} })); + return () => undefined; + }, + { idleTimeoutMs: 100, beforeHeadMs: 150 }, + ); + active.push(item); + + // The old code parked `#loop` in `await fetch()` for undici's header timeout, + // so the hub never re-attempted and every turn failed with + // `503 event_stream_unavailable`. + expect(await item.hub.ensureConnected(250)).toBe(false); + await waitFor(() => item.connectionCount() >= 2, 3_000); + }); + + it("grows the reconnect interval when the stream keeps flapping", async () => { + const item = await fixture((response) => { + response.write(frame({ id: "e0", type: "server.connected", data: {} })); + response.write(frame({ id: "e1", type: "session.text.delta", data: { sessionID: "ses_1", delta: "x" } })); + // End the body immediately: a slow-consumer overflow looks exactly like + // this. The response head must no longer reset the backoff. + setImmediate(() => response.end()); + return () => undefined; + }); + active.push(item); + + let reconnects = 0; + item.hub.onReconnect(() => { + reconnects += 1; + }); + item.hub.start(); + + expect(await item.hub.ensureConnected(2_000)).toBe(true); + await waitFor(() => reconnects >= 2, 5_000); + // Pre-fix the delay was reset to 250 ms by the response head on every + // attempt, i.e. four reconnects per second forever. + expect(item.hub.reconnectDelayMs).toBeGreaterThan(250); + }); + + it("zeroes event_stream_connected when the hub stops", async () => { + const item = await fixture((response) => { + response.write(frame({ id: "e0", type: "server.connected", data: {} })); + return () => undefined; + }); + active.push(item); + + expect(await item.hub.ensureConnected(2_000)).toBe(true); + expect(await gaugeValue(item.metrics, "opencode_api_event_stream_connected")).toBe(1); + + await item.hub.stop(); + // `stop()` cleared `#connected` before the loop unwound, so the `finally` + // never saw the transition and the exposition kept reporting 1 after shutdown. + expect(await gaugeValue(item.metrics, "opencode_api_event_stream_connected")).toBe(0); + }); + + it("counts reconnects and dropped frames by reason", async () => { + const item = await fixture((response) => { + response.write(frame({ id: "e0", type: "server.connected", data: {} })); + // Delivered to nobody: no subscriber for this session. + response.write(frame({ id: "e1", type: "session.text.delta", data: { sessionID: "ses_absent", delta: "a" } })); + // No `sessionID` at all: not routable to any turn. + response.write(frame({ id: "e2", type: "session.text.delta", data: { delta: "b" } })); + response.write("data: {not json}\n\n"); + response.write(frame({ id: "e3", type: "session.text.delta", data: { sessionID: "ses_1", delta: "c" } })); + // Then let the idle watchdog fire so the reconnect is counted too. + return () => undefined; + }, { idleTimeoutMs: 120 }); + active.push(item); + + const received: OpencodeEvent[] = []; + item.hub.subscribe("ses_1", (event) => received.push(event)); + item.hub.start(); + + await waitFor(() => received.length === 1, 3_000); + + const dropped = async (reason: string): Promise => + await counterValue(item.metrics, "opencode_api_event_frames_dropped_total", { reason }); + expect(await dropped("no_subscriber")).toBe(1); + expect(await dropped("no_session")).toBe(1); + expect(await dropped("malformed")).toBe(1); + + // The fixture then goes silent, so the idle watchdog fails the connection and + // the reconnect is counted with its trigger. + await waitForAsync( + async () => + (await counterValue(item.metrics, "opencode_api_event_stream_reconnects_total", { reason: "idle" })) >= 1, + 3_000, + ); + }); }); async function waitFor(predicate: () => boolean, timeoutMs = 3_000): Promise { @@ -323,6 +455,15 @@ async function waitFor(predicate: () => boolean, timeoutMs = 3_000): Promise Promise, timeoutMs = 3_000): Promise { + const deadline = Date.now() + timeoutMs; + while (Date.now() < deadline) { + if (await predicate()) return; + await delay(10); + } + throw new Error("timed out waiting for condition"); +} + function delay(ms: number): Promise { return new Promise((resolve) => setTimeout(resolve, ms)); } diff --git a/test/helpers/context.ts b/test/helpers/context.ts index 028c040..da485d0 100644 --- a/test/helpers/context.ts +++ b/test/helpers/context.ts @@ -163,9 +163,18 @@ export function aggregate(request: InternalRequest, events: CompletionEvent[]) { case "text_delta": result.text += event.text; break; + case "text_end": + // Mirrors `collectCompletion`: a consolidated `text_end` is adopted only + // when it is longer than what the deltas produced, so a text_end-only + // turn is scriptable without changing any delta-based expectation. + if (event.text.length > result.text.length) result.text = event.text; + break; case "reasoning_delta": result.reasoning += event.text; break; + case "reasoning_end": + if (event.text.length > result.reasoning.length) result.reasoning = event.text; + break; case "tool_calls": result.calls.push(...event.calls); break; diff --git a/test/process.test.ts b/test/process.test.ts index eaf224b..a4f5a45 100644 --- a/test/process.test.ts +++ b/test/process.test.ts @@ -11,8 +11,14 @@ 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"; +import { createMetrics, type Metrics } from "../src/metrics/registry.js"; +import { + OutputTail, + StderrTail, + UpstreamProcess, + readinessScans, + type SpawnedChild, +} from "../src/upstream/process.js"; import { testConfig } from "./helpers/context.js"; /** Stand-in for a spawned `opencode serve` child. */ @@ -48,6 +54,7 @@ class FakeChild extends EventEmitter { interface Harness { process: UpstreamProcess; children: FakeChild[]; + metrics: Metrics; } interface HarnessOptions { @@ -56,6 +63,30 @@ interface HarnessOptions { * `"never"` simulates a start that hangs until the readiness timeout. */ readyMs?: number | "never"; + /** Write the readiness lines at all (false simulates a failed start). */ + ready?: boolean; + /** Write this text to stderr right before (or instead of) readiness. */ + stderr?: string; + upstreamStartTimeoutMs?: number; + /** Keep discovery away from whatever `opencode serve` runs on this machine. */ + discover?: () => Promise<{ url: string; password?: string; source: "env" | "spawned" | "discovered" } | undefined>; +} + +/** Counter value for one label set out of `registry.getMetricsAsJSON()`. */ +async function counterValue( + metrics: Metrics, + name: string, + labels: Record, +): Promise { + const json = (await metrics.registry.getMetricsAsJSON()) as unknown as Array<{ + name: string; + values?: Array<{ labels?: Record; value: number }>; + }>; + const entry = json.find((item) => item.name === name); + const match = entry?.values?.find((value) => + Object.entries(labels).every(([key, expected]) => value.labels?.[key] === expected), + ); + return match?.value ?? 0; } function harness(options: HarnessOptions = {}): Harness { @@ -65,30 +96,37 @@ function harness(options: HarnessOptions = {}): Harness { dataDir: os.tmpdir(), workdir: os.tmpdir(), upstreamAutostart: true, - upstreamStartTimeoutMs: 2_000, + upstreamStartTimeoutMs: options.upstreamStartTimeoutMs ?? 2_000, }); const log = createLogger(config); const metrics = createMetrics({ enabled: false }); const process = new UpstreamProcess(config, log, metrics, { findBinary: () => "/fake/opencode", + discover: options.discover ?? (async () => undefined), spawn: (_command, args) => { const child = new FakeChild(4_000 + children.length); children.push(child); const port = args[args.indexOf("--port") + 1] ?? "0"; - if (readyMs !== "never") { + if (options.stderr !== undefined) child.stderr.write(options.stderr); + if (options.ready !== false) { 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 !== "never") { + 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); + else if (readyMs !== "never") setTimeout(announce, readyMs); + } else { + // Fail the start: the child exits before reporting readiness. + setImmediate(() => child.crash()); } return child as unknown as SpawnedChild; }, }); - return { process, children }; + return { process, children, metrics }; } const tick = (): Promise => new Promise((resolve) => setTimeout(resolve, 10)); @@ -230,4 +268,80 @@ describe("UpstreamProcess", () => { expect(replacement.pid).not.toBe(children[0]?.pid); expect(process.status().ready).toBe(true); }); + + it("backs off after a failed start instead of spawning on every request", async () => { + const { process, children } = harness({ ready: false, upstreamStartTimeoutMs: 150 }); + + await expect(process.resolve()).rejects.toMatchObject({ code: "upstream_unavailable" }); + expect(children).toHaveLength(1); + + // Inside the failure window the next request must fail fast without + // spawning: a crash-looping binary used to fork one child per request. + await expect(process.resolve()).rejects.toMatchObject({ code: "upstream_unavailable" }); + await expect(process.resolve()).rejects.toThrow(/failed to start/); + expect(children).toHaveLength(1); + + // Once the window expires a new attempt is allowed. + await new Promise((resolve) => setTimeout(resolve, 2_100)); + await expect(process.resolve()).rejects.toMatchObject({ code: "upstream_unavailable" }); + expect(children).toHaveLength(2); + }); + + it("counts an initial start and a stale restart under different reasons", async () => { + const { process, metrics } = harness(); + + await process.resolve(); + expect(await counterValue(metrics, "opencode_api_upstream_restarts_total", { reason: "initial" })).toBe(1); + expect(await counterValue(metrics, "opencode_api_upstream_restarts_total", { reason: "stale" })).toBe(0); + + process.markStale("hung upstream"); + await process.resolve(); + expect(await counterValue(metrics, "opencode_api_upstream_restarts_total", { reason: "stale" })).toBe(1); + expect(await counterValue(metrics, "opencode_api_upstream_restarts_total", { reason: "initial" })).toBe(1); + + await process.stop(); + await process.resolve(); + expect(await counterValue(metrics, "opencode_api_upstream_restarts_total", { reason: "restart" })).toBe(1); + }); + + it("stops scanning the child output once readiness is published", async () => { + const { process, children } = harness(); + await process.resolve(); + const scans = readinessScans.total; + expect(scans).toBeGreaterThan(0); + + const child = children[0] as FakeChild; + for (let index = 0; index < 10_000; index += 1) { + child.stdout.emit("data", `still logging line ${index}\n`); + } + + // The readiness pattern scan used to run over the whole accumulated output + // for every chunk, forever; after `settled` no scan may happen at all. + expect(readinessScans.total).toBe(scans); + }); + + it("keeps the retained stdout/stderr tail bounded", () => { + const tail = new OutputTail(64); + for (let index = 0; index < 10_000; index += 1) tail.push(`chunk ${index} `); + // Only the last 64 characters are retained, so the readiness scan stays O(1) + // instead of joining an ever-growing array. + expect(tail.length).toBe(64); + expect(tail.text.endsWith(" ")).toBe(true); + + const stderr = new StderrTail(4); + for (let index = 0; index < 10; index += 1) stderr.push(`line ${index}\n`); + expect(stderr.lines).toEqual(["line 6", "line 7", "line 8", "line 9"]); + }); + + it("exposes the child's recent stderr through status()", async () => { + const { process } = harness({ ready: false, stderr: "provider config invalid\ntoken missing\n" }); + + await expect(process.resolve()).rejects.toMatchObject({ code: "upstream_unavailable" }); + expect(process.status().stderrTail).toEqual(["provider config invalid", "token missing"]); + + // The tail is bounded: only the newest lines survive a chatty child. + const stderr = new StderrTail(3); + for (let index = 0; index < 10; index += 1) stderr.push(`line ${index}\n`); + expect(stderr.lines).toEqual(["line 7", "line 8", "line 9"]); + }); }); \ No newline at end of file diff --git a/test/sessions.test.ts b/test/sessions.test.ts index cd14468..92847de 100644 --- a/test/sessions.test.ts +++ b/test/sessions.test.ts @@ -1,7 +1,7 @@ import fs from "node:fs"; import os from "node:os"; import path from "node:path"; -import { afterEach, describe, expect, it } from "vitest"; +import { afterEach, describe, expect, it, vi } from "vitest"; import { createLogger } from "../src/logger.js"; import { createMetrics } from "../src/metrics/registry.js"; import { SessionStore, deriveKey, hashMessages, hashTools } from "../src/upstream/sessions.js"; @@ -411,6 +411,36 @@ describe("SessionStore", () => { expect(second.reused).toBe(false); expect(second.reason).toBe("cache-disabled"); }); + + it("publishes the gauges without flattening and sorting the whole cache", async () => { + const metrics = createMetrics({ enabled: false }); + const config = testConfig({ sessionPersist: false, sessionMaxEntries: 500 }); + const sessions = new SessionStore(config, createLogger(config), metrics); + + for (let index = 0; index < 500; index += 1) { + sessions.commit(`key-${index}`, `ses_${index}`, { + ...BASE_INPUT, + messages: [{ role: "user", text: `message ${index}` }], + }); + } + + // `list()` flattens every bucket and sorts by `lastUsedAt`; `#publishGauges()` + // ran it on every mutation to count one integer. + const listSpy = vi.spyOn(sessions, "list"); + sessions.release("key-0", "ses_0"); + expect(listSpy).not.toHaveBeenCalled(); + listSpy.mockRestore(); + + const json = (await metrics.registry.getMetricsAsJSON()) as unknown as Array<{ + name: string; + values?: Array<{ labels?: Record; value: number }>; + }>; + const cache = json.find((entry) => entry.name === "opencode_api_session_cache_entries"); + const valueOf = (state: string): number | undefined => + cache?.values?.find((value) => value.labels?.["state"] === state)?.value; + expect(valueOf("entries")).toBe(500); + expect(valueOf("busy")).toBe(0); + }); }); describe("key derivation", () => { diff --git a/test/upstream-reconnect.test.ts b/test/upstream-reconnect.test.ts index 4bda138..cc98b91 100644 --- a/test/upstream-reconnect.test.ts +++ b/test/upstream-reconnect.test.ts @@ -9,7 +9,7 @@ */ import { describe, expect, it } from "vitest"; import { createLogger } from "../src/logger.js"; -import { createMetrics } from "../src/metrics/registry.js"; +import { createMetrics, type Metrics } from "../src/metrics/registry.js"; import type { CompletionEvent, InternalRequest } from "../src/types/internal.js"; import type { OpencodeEvent } from "../src/types/opencode.js"; import type { OpencodeClient } from "../src/upstream/client.js"; @@ -117,6 +117,21 @@ function harness( }; } +/** Series of one counter out of `registry.getMetricsAsJSON()`. */ +async function metricSeries( + metrics: Metrics, + name: string, +): Promise; value: number }>> { + const json = (await metrics.registry.getMetricsAsJSON()) as unknown as Array<{ + name: string; + values?: Array<{ labels?: Record; value: number }>; + }>; + return (json.find((entry) => entry.name === name)?.values ?? []).map((value) => ({ + labels: value.labels ?? {}, + value: value.value, + })); +} + function event(type: string, data: Record): OpencodeEvent { return { id: `evt_${type}`, type, data: { sessionID: SESSION_ID, ...data } }; } @@ -267,10 +282,33 @@ describe("runCompletion after an event-stream reconnect", () => { 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); + // The record must not survive the loss: the upstream session's state is + // unknown after the gap, so the next turn starts a fresh one instead of + // reusing a session that may already hold a different turn. + expect(harnessed.sessions.list()).toHaveLength(0); + }); + + it("counts a lost event stream as an error with a bounded code", async () => { + 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 }, + ); + + const { events, done } = consume(harnessed); + await waitFor(() => events.some((entry) => entry.kind === "text_delta")); + harnessed.fireReconnect(); + await done; + + const series = await metricSeries(harnessed.deps.metrics, "opencode_api_completions_total"); + const failure = series.find((entry) => entry.labels["finish_reason"] === "error"); + expect(failure?.value).toBe(1); + // `event_stream_lost` is not a `FinishReason`; it belongs in the bounded + // `error_code` dimension, where it used to be reported as a finish reason. + expect(failure?.labels["error_code"]).toBe("event_stream_lost"); + expect(series.every((entry) => entry.labels["finish_reason"] !== "event_stream_lost")).toBe(true); }); }); From 96b28dc1e30c44bdcea5a66332704997d8a45702 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Ph=E1=BA=A1m=20V=C4=83n=20=C4=90=E1=BB=8Bnh?= Date: Thu, 3 Dec 2026 12:08:48 +0700 Subject: [PATCH 02/12] fix(responses): complete the output-item lifecycle and status reporting The reasoning item was never announced with response.output_item.added, yet the message item was opened at output_index 1, so a client building output[] from the stream saw a hole at index 0 and a late .done for it. Announce the reasoning item first, at index 0, in both the delta and the consolidated branch. A filtered turn was reported as completed, a length limit was the only incomplete reason, created_at was recomputed on every frame, instructions was always null even when the caller sent it, a failed stream fabricated all-zero usage, and text that arrived only in the consolidated text_end event was in output_text but missing from output. Report content_filter as incomplete with the documented incomplete_details.reason, capture created_at once per response, echo instructions, use null usage when no usage event arrived, and open the message item for text_end-only turns. Text accumulation is now a string list joined once at finalise. --- src/adapter/openai/responses.ts | 356 +++++++++++++++++----- test/openai-responses.test.ts | 520 +++++++++++++++++++++++++++++++- 2 files changed, 781 insertions(+), 95 deletions(-) diff --git a/src/adapter/openai/responses.ts b/src/adapter/openai/responses.ts index 70535e3..c9f306e 100644 --- a/src/adapter/openai/responses.ts +++ b/src/adapter/openai/responses.ts @@ -11,21 +11,31 @@ * by `ctx.completion`, exactly like every other surface; this module only * translates wire formats. * - * 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. The value - * is echoed back as the caller sent it, so the field does not claim the - * response was stored. + * Not implemented, by design — these are rejected with `400 + * unsupported_parameter` instead of being silently dropped, because a 200 that + * ignores what the caller asked for cannot be detected: + * - `previous_response_id` (no server-side response store; resend the `input`), + * - `include` (no encrypted reasoning state can be returned), + * - `store: true` (responses are never persisted; `store: false` is accepted + * and echoed, so the stateless pattern still works), + * - `logprobs` / `top_logprobs`, `modalities`, `audio`, `prediction`, + * `web_search_options` and the legacy `functions` / `function_call` pair, + * because the provider exposes none of those features. + * + * The generation knobs (`temperature`, `top_p`, `max_output_tokens`, the + * penalties, `seed`, `logit_bias`) are accepted and recorded instead: answering + * 400 for them would break most SDK clients, so they are reported through + * `x_opencode.unapplied` on every response object. + * + * Other accepted-but-not-applied fields: * - `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 - * `response_format` (see "JSON output mode"). + * - `service_tier` and `user` are accepted for API compatibility and have no + * effect on the completion. `text.format` is not in this list: it is rendered + * into the prompt like the chat `response_format` (see "JSON output mode"). */ import { randomUUID } from "node:crypto"; import type { FastifyInstance, FastifyReply, FastifyRequest } from "fastify"; @@ -33,14 +43,19 @@ import { z } from "zod"; import { reasoningFromEffort } from "../common/reasoning.js"; import { normaliseArguments } from "../common/tools.js"; import { EMPTY_USAGE } from "../common/usage.js"; +import { + assertHonouredParameters, + rejectUnsupported, + resolveMessageMedia, + unappliedParameters, + type MessageMediaDraft, +} from "./chat.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 { createMediaBudget, - formatOmissionNote, - resolveAttachments, type MediaBudget, type MediaSource, } from "../../media/resolve.js"; @@ -227,6 +242,21 @@ const responsesRequest = z include: z.array(z.string()).optional(), service_tier: z.string().optional(), top_logprobs: z.number().optional(), + // Accepted for schema compatibility only; every one of them is rejected with + // `unsupported_parameter` because the gateway cannot honour it. + logprobs: z.boolean().optional(), + modalities: z.array(z.string()).optional(), + audio: z.unknown().optional(), + prediction: z.unknown().optional(), + web_search_options: z.unknown().optional(), + functions: z.array(z.unknown()).optional(), + function_call: z.union([z.string(), z.object({ name: z.string().min(1) }).passthrough()]).optional(), + // Generation knobs: accepted and recorded, then reported through + // `x_opencode.unapplied` because the OpenCode agent loop owns them. + presence_penalty: z.number().optional(), + frequency_penalty: z.number().optional(), + seed: z.number().optional(), + logit_bias: z.record(z.string(), z.number()).optional(), }) .strip(); @@ -261,6 +291,17 @@ const NULL_MEANS_UNSET_FIELDS: ReadonlySet = new Set([ "include", "service_tier", "top_logprobs", + "logprobs", + "presence_penalty", + "frequency_penalty", + "seed", + "logit_bias", + "modalities", + "audio", + "prediction", + "web_search_options", + "functions", + "function_call", ]); /** Drop top-level `null` values for the optional request fields above. */ @@ -290,6 +331,7 @@ interface ReasoningTextPart { interface ReasoningItem { id: string; type: "reasoning"; + status: "in_progress" | "completed"; summary: SummaryTextPart[]; content: ReasoningTextPart[]; } @@ -303,7 +345,7 @@ interface OutputTextPart { interface MessageItem { id: string; type: "message"; - status: "in_progress" | "completed"; + status: "in_progress" | "completed" | "incomplete"; role: "assistant"; content: OutputTextPart[]; } @@ -345,7 +387,7 @@ interface ResponseBody { metadata: Record; incomplete_details: { reason: string } | null; error: { code: string; message: string } | null; - instructions: null; + instructions: string | null; max_output_tokens: number | null; previous_response_id: null; store: boolean; @@ -373,6 +415,13 @@ interface ResponseEcho { store: boolean; reasoningEffort: string | null; reasoningSummary: string | null; + /** `instructions` the caller sent, echoed back like the real API does. */ + instructions: string | null; + /** + * Generation knobs the caller supplied that the gateway recorded but could + * not apply, in a stable order; empty when there were none. + */ + unapplied: string[]; } interface Prepared { @@ -393,6 +442,37 @@ const FAILED_TURN: { code: string; message: string } = { message: "The upstream completion ended with an error.", }; +/** + * Reject every request field this surface cannot honour without changing the + * shape of the response. + * + * The generation knobs (`temperature`, `top_p`, `max_output_tokens`, the + * penalties, `seed`, `logit_bias`) stay accepted: they are recorded and echoed + * back through `x_opencode.unapplied`, matching the chat and legacy-completions + * surfaces. The rest gets a `400 unsupported_parameter` instead of a 200 that + * silently drops it. + */ +function assertSupportedRequest(body: ResponsesRequest): void { + assertHonouredParameters(body); + if (body.previous_response_id != null) { + throw ApiError.badRequest( + "`previous_response_id` is not supported: the gateway keeps no response store; resend the full `input`.", + { code: "unsupported_parameter", param: "previous_response_id" }, + ); + } + if (body.include !== undefined && body.include.length > 0) { + rejectUnsupported( + "include", + "the gateway keeps no response state and cannot return encrypted reasoning content", + ); + } +} + +/** Unix time in seconds, the unit OpenAI uses for `created_at` / `created`. */ +function unixSeconds(): number { + return Math.floor(Date.now() / 1000); +} + // ------------------------------------------------------------------ routing --- export function registerOpenAiResponsesRoutes(app: FastifyInstance, ctx: AppContext): void { @@ -408,6 +488,10 @@ export function registerOpenAiResponsesRoutes(app: FastifyInstance, ctx: AppCont } const body = parsed.data; + assertSupportedRequest(body); + // The response is created here: `created_at` is a property of the response, + // not of the frame or of the moment the turn happens to finish. + const createdAt = unixSeconds(); // 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); @@ -428,10 +512,11 @@ export function registerOpenAiResponsesRoutes(app: FastifyInstance, ctx: AppCont const collected = await ctx.completion.collect(prepared.request, completionDeps(ctx), { signal: abort.signal, }); - const output = buildOutput(collected.reasoning, collected.text, collected.calls); + const output = buildOutput(collected.reasoning, collected.text, collected.calls, collected.finishReason); return reply.status(200).send( baseResponse(prepared, { id: newId("resp"), + createdAt, status: responseStatus(collected.finishReason), output, outputText: collected.text, @@ -504,6 +589,9 @@ async function prepare( ...(choice !== undefined ? { toolChoice: choice } : {}), ...(reasoning !== undefined ? { reasoning } : {}), ...(responseFormat !== undefined ? { responseFormat } : {}), + // Accepted and recorded, but not forwarded: OpenCode's agent loop owns the + // sampling parameters and the generation budget. `x_opencode.unapplied` + // tells the caller which of them the turn could not apply. ...(body.temperature !== undefined ? { temperature: body.temperature } : {}), ...(body.top_p !== undefined ? { topP: body.top_p } : {}), ...(body.max_output_tokens !== undefined ? { maxTokens: body.max_output_tokens } : {}), @@ -531,6 +619,8 @@ async function prepare( store: body.store === true, reasoningEffort: reasoning?.effort ?? null, reasoningSummary: body.reasoning?.summary ?? null, + instructions: body.instructions ?? null, + unapplied: unappliedParameters(body), }; return { request: internal, echo, reasoningRequested: reasoning?.enabled === true }; @@ -544,6 +634,7 @@ async function mapInputItems( budget: MediaBudget, ): Promise { const messages: InternalMessage[] = []; + const drafts: MessageMediaDraft[] = []; for (const item of items) { if (item.type === "function_call") { @@ -573,21 +664,31 @@ async function mapInputItems( } // `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, budget)); + const draft = messageDraft(item.role, item.content); + drafts.push(draft); + // `resolveMessageMedia` fills the very same message object in place, so the + // interleaving with the non-message turns above is preserved. + messages.push(draft.message); } + // One `resolveAttachments` call for the whole request: the per-item pools used + // to run one after another, so N media messages cost the sum of their + // download times instead of the maximum. + await resolveMessageMedia(drafts, ctx.config, { signal, budget, field: "input" }); return messages; } -/** Map one message-typed input item, resolving any media parts to attachments. */ -async function mapMessageItem( +/** + * Map one message-typed input item to a draft, without downloading its media. + * + * Validation stays here (a `file_id` reference is rejected before any fetch + * starts); the actual resolution happens once for the whole request. + */ +function messageDraft( role: "user" | "assistant" | "system" | "developer", content: string | ContentPart[], - ctx: AppContext, - signal: AbortSignal, - budget: MediaBudget, -): Promise { - if (typeof content === "string") return { role, text: content }; +): MessageMediaDraft { + if (typeof content === "string") return { message: { role, text: content }, sources: [] }; const text: string[] = []; const media: MediaSource[] = []; @@ -602,6 +703,7 @@ async function mapMessageItem( text.push(part.refusal); break; case "input_image": + assertImageDetail(part.detail); media.push(urlSource(urlOf(part.image_url))); break; case "input_file": { @@ -637,23 +739,16 @@ async function mapMessageItem( } } - const message: InternalMessage = { role, text: text.join("\n") }; - if (media.length > 0) { - // 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; + return { message: { role, text: text.join("\n") }, sources: media }; +} + +/** `input_image.detail` values the gateway can honour: it always sends full media. */ +function assertImageDetail(detail: string | undefined): void { + if (detail === undefined || detail === "auto") return; + throw ApiError.badRequest('`input_image.detail` must be "auto": this gateway cannot downscale media.', { + code: "unsupported_parameter", + param: "input", + }); } function urlOf(value: string | { url: string }): string { @@ -754,10 +849,10 @@ function toResponseUsage(usage: Usage): ResponseUsage { }; } -function reasoningItem(id: string, text: string): ReasoningItem { +function reasoningItem(id: string, text: string, status: ReasoningItem["status"]): ReasoningItem { const summary: SummaryTextPart[] = text.length > 0 ? [{ type: "summary_text", text }] : []; const content: ReasoningTextPart[] = text.length > 0 ? [{ type: "reasoning_text", text }] : []; - return { id, type: "reasoning", summary, content }; + return { id, type: "reasoning", status, summary, content }; } function messageItem(id: string, text: string, status: MessageItem["status"]): MessageItem { @@ -766,7 +861,7 @@ function messageItem(id: string, text: string, status: MessageItem["status"]): M type: "message", status, role: "assistant", - content: status === "completed" ? [{ type: "output_text", text, annotations: [] }] : [], + content: status === "in_progress" ? [] : [{ type: "output_text", text, annotations: [] }], }; } @@ -782,16 +877,23 @@ function functionCallItem(call: ToolCall, status: FunctionCallItem["status"]): F } /** Assemble the final `output` array: reasoning, message, then function calls. */ -function buildOutput(reasoning: string, text: string, calls: ToolCall[]): ResponseOutputItem[] { +function buildOutput(reasoning: string, text: string, calls: ToolCall[], finishReason: FinishReason): ResponseOutputItem[] { const output: ResponseOutputItem[] = []; - if (reasoning.length > 0) output.push(reasoningItem(newId("rs"), reasoning)); - if (text.length > 0) output.push(messageItem(newId("msg"), text, "completed")); + if (reasoning.length > 0) output.push(reasoningItem(newId("rs"), reasoning, "completed")); + if (text.length > 0) { + // An incomplete response carries an incomplete message item, exactly like the + // streamed path, so the two forms agree. + const status: MessageItem["status"] = incompleteReason(finishReason) === null ? "completed" : "incomplete"; + output.push(messageItem(newId("msg"), text, status)); + } for (const call of calls) output.push(functionCallItem(call, "completed")); return output; } interface ResponseState { id: string; + /** Unix seconds; constant for the whole response, whichever frame reports it. */ + createdAt: number; status: ResponseBody["status"]; output: ResponseOutputItem[]; outputText: string; @@ -806,29 +908,42 @@ interface ResponseState { error?: { code: string; message: string } | null; } -/** Wire status for a finished turn; only `length`/`error` override `completed`. */ +/** Why a finished turn is `incomplete`, or `null` when it completed. */ +function incompleteReason(finishReason: FinishReason | undefined): string | null { + if (finishReason === "length") return "max_output_tokens"; + if (finishReason === "content_filter") return "content_filter"; + return null; +} + +/** + * Wire status for a finished turn. + * + * `length` and `content_filter` are both `incomplete` (the real API reports a + * filtered turn with `incomplete_details.reason: "content_filter"`); only + * `error` fails. + */ function responseStatus(finishReason: FinishReason): ResponseBody["status"] { if (finishReason === "error") return "failed"; - if (finishReason === "length") return "incomplete"; + if (incompleteReason(finishReason) !== null) return "incomplete"; return "completed"; } function baseResponse(prepared: Prepared, state: ResponseState): ResponseBody { const inProgress = state.status === "in_progress"; const failed = state.status === "failed"; - const incomplete = !inProgress && !failed && state.finishReason === "length"; + const incompleteReasonForTurn = inProgress || failed ? null : incompleteReason(state.finishReason); const status: ResponseBody["status"] = inProgress ? "in_progress" : failed ? "failed" - : incomplete + : incompleteReasonForTurn !== null ? "incomplete" : "completed"; return { id: state.id, object: "response", - created_at: Math.floor(Date.now() / 1000), + created_at: state.createdAt, status, model: prepared.echo.model, output: state.output, @@ -841,9 +956,9 @@ function baseResponse(prepared: Prepared, state: ResponseState): ResponseBody { top_p: prepared.echo.topP, reasoning: { effort: prepared.echo.reasoningEffort, summary: prepared.echo.reasoningSummary }, metadata: prepared.echo.metadata, - incomplete_details: incomplete ? { reason: "max_output_tokens" } : null, + incomplete_details: incompleteReasonForTurn !== null ? { reason: incompleteReasonForTurn } : null, error: state.error ?? null, - instructions: null, + instructions: prepared.echo.instructions, max_output_tokens: prepared.echo.maxOutputTokens, previous_response_id: null, store: prepared.echo.store, @@ -854,6 +969,9 @@ function baseResponse(prepared: Prepared, state: ResponseState): ResponseBody { variant: state.variant, reused_session: state.reusedSession, native_tool_calls: state.nativeTools, + // Omitted when the caller sent no unapplied generation knob, so payloads + // that do not use them keep exactly their previous shape. + ...(prepared.echo.unapplied.length > 0 ? { unapplied: [...prepared.echo.unapplied] } : {}), }, }; } @@ -862,6 +980,8 @@ function baseResponse(prepared: Prepared, state: ResponseState): ResponseBody { interface StreamState { id: string; + /** Unix seconds captured when the response started; never recomputed. */ + createdAt: number; sessionId: string; agent: string; variant: string | null; @@ -872,10 +992,17 @@ interface StreamState { reasoningId: string; reasoningStarted: boolean; reasoningVisible: boolean; - reasoningText: string; + /** + * Reasoning text accumulated as fragments and joined once when it is reported. + * Appending to one string on every delta made a long turn quadratic. + */ + reasoningParts: string[]; + reasoningLength: number; messageId: string; messageStarted: boolean; - text: string; + /** Visible text fragments; joined once in `finaliseStream` / failure paths. */ + textParts: string[]; + textLength: number; calls: ToolCall[]; usage: Usage | null; finishReason: FinishReason; @@ -910,6 +1037,7 @@ async function streamResponse( }; const state: StreamState = { id: newId("resp"), + createdAt: unixSeconds(), sessionId: "", agent: prepared.request.agent ?? "", variant: null, @@ -920,10 +1048,12 @@ async function streamResponse( reasoningId: newId("rs"), reasoningStarted: false, reasoningVisible: false, - reasoningText: "", + reasoningParts: [], + reasoningLength: 0, messageId: newId("msg"), messageStarted: false, - text: "", + textParts: [], + textLength: 0, calls: [], usage: null, finishReason: "stop", @@ -979,6 +1109,16 @@ function emitFrame( state.sequence = sequence + 1; } +/** Join the visible text fragments accumulated by the stream. */ +function streamText(state: StreamState): string { + return state.textParts.join(""); +} + +/** Join the reasoning fragments accumulated by the stream. */ +function streamReasoning(state: StreamState): string { + return state.reasoningParts.join(""); +} + /** Terminal response object for a stream that failed after its first frames. */ function failedStreamResponse( prepared: Prepared, @@ -986,20 +1126,24 @@ function failedStreamResponse( error: { code: string; message: string }, ): ResponseBody { const output: ResponseOutputItem[] = []; - if (state.reasoningVisible && state.reasoningText.length > 0) { - output.push(reasoningItem(state.reasoningId, state.reasoningText)); + if (state.reasoningVisible && state.reasoningLength > 0) { + output.push(reasoningItem(state.reasoningId, streamReasoning(state), "completed")); } - if (state.messageStarted || state.text.length > 0) { - output.push(messageItem(state.messageId, state.text, "completed")); + if (state.messageStarted || state.textLength > 0) { + output.push(messageItem(state.messageId, streamText(state), "completed")); } for (const call of state.calls) output.push(functionCallItem(call, "completed")); return baseResponse(prepared, { id: state.id, + createdAt: state.createdAt, status: "failed", output, - outputText: state.text, - usage: toResponseUsage(state.usage ?? EMPTY_USAGE), + outputText: streamText(state), + // A turn that failed before the first usage event consumed upstream tokens + // the gateway cannot see; reporting zeros asserted a cost that never + // happened, so the honest value is `null` (the field is nullable). + usage: state.usage === null ? null : toResponseUsage(state.usage), finishReason: state.finishReason, sessionId: state.sessionId, agent: state.agent, @@ -1032,6 +1176,7 @@ async function pipeEvents( const inProgress = (): ResponseBody => baseResponse(prepared, { id: state.id, + createdAt: state.createdAt, status: "in_progress", output: [], outputText: "", @@ -1081,6 +1226,15 @@ async function pipeEvents( state.reasoningVisible = true; if (!state.reasoningStarted) { state.reasoningStarted = true; + // Every output item is announced before its content, index 0 is the + // reasoning item: without this frame a client building `output[]` + // from the stream sees a `.done` for an index it never saw opened. + emitFrame(writer, state, "response.output_item.added", (sequence) => ({ + type: "response.output_item.added", + sequence_number: sequence, + output_index: reasoningOutputIndex(), + item: reasoningItem(state.reasoningId, "", "in_progress"), + })); emitFrame(writer, state, "response.reasoning_summary_part.added", (sequence) => ({ type: "response.reasoning_summary_part.added", sequence_number: sequence, @@ -1090,7 +1244,8 @@ async function pipeEvents( part: { type: "summary_text", text: "" }, })); } - state.reasoningText += event.text; + state.reasoningParts.push(event.text); + state.reasoningLength += event.text.length; emitFrame(writer, state, "response.reasoning_summary_text.delta", (sequence) => ({ type: "response.reasoning_summary_text.delta", sequence_number: sequence, @@ -1103,13 +1258,22 @@ async function pipeEvents( } case "reasoning_end": { - if (event.text.length > 0) state.reasoningText = event.text; + if (event.text.length > 0) { + state.reasoningParts = [event.text]; + state.reasoningLength = event.text.length; + } if (!state.reasoningStarted) { // The provider sent the consolidated summary without deltas. if (!state.reasoningEnabled && !state.reasoningRequested) break; - if (state.reasoningText.length === 0) break; + if (state.reasoningLength === 0) break; state.reasoningStarted = true; state.reasoningVisible = true; + emitFrame(writer, state, "response.output_item.added", (sequence) => ({ + type: "response.output_item.added", + sequence_number: sequence, + output_index: reasoningOutputIndex(), + item: reasoningItem(state.reasoningId, "", "in_progress"), + })); emitFrame(writer, state, "response.reasoning_summary_part.added", (sequence) => ({ type: "response.reasoning_summary_part.added", sequence_number: sequence, @@ -1120,13 +1284,14 @@ async function pipeEvents( })); } if (!state.reasoningVisible) break; + const reasoningText = streamReasoning(state); emitFrame(writer, state, "response.reasoning_summary_text.done", (sequence) => ({ type: "response.reasoning_summary_text.done", sequence_number: sequence, item_id: state.reasoningId, output_index: reasoningOutputIndex(), summary_index: 0, - text: state.reasoningText, + text: reasoningText, })); emitFrame(writer, state, "response.reasoning_summary_part.done", (sequence) => ({ type: "response.reasoning_summary_part.done", @@ -1134,7 +1299,7 @@ async function pipeEvents( item_id: state.reasoningId, output_index: reasoningOutputIndex(), summary_index: 0, - part: { type: "summary_text", text: state.reasoningText }, + part: { type: "summary_text", text: reasoningText }, })); break; } @@ -1157,7 +1322,8 @@ async function pipeEvents( part: { type: "output_text", text: "", annotations: [] }, })); } - state.text += event.text; + state.textParts.push(event.text); + state.textLength += event.text.length; emitFrame(writer, state, "response.output_text.delta", (sequence) => ({ type: "response.output_text.delta", sequence_number: sequence, @@ -1169,9 +1335,32 @@ async function pipeEvents( break; } - case "text_end": - if (event.text.length > state.text.length) state.text = event.text; + case "text_end": { + if (event.text.length <= state.textLength) break; + // The provider delivered the consolidated text instead of deltas: the + // message item and its content part still have to be announced, or the + // final payload would carry `output_text` with an empty `output`. + if (!state.messageStarted) { + state.messageStarted = true; + emitFrame(writer, state, "response.output_item.added", (sequence) => ({ + type: "response.output_item.added", + sequence_number: sequence, + output_index: messageOutputIndex(state), + item: messageItem(state.messageId, "", "in_progress"), + })); + emitFrame(writer, state, "response.content_part.added", (sequence) => ({ + type: "response.content_part.added", + sequence_number: sequence, + item_id: state.messageId, + output_index: messageOutputIndex(state), + content_index: 0, + part: { type: "output_text", text: "", annotations: [] }, + })); + } + state.textParts = [event.text]; + state.textLength = event.text.length; break; + } case "tool_calls": state.calls.push(...event.calls); @@ -1197,6 +1386,10 @@ async function pipeEvents( default: break; } + // Throttle the producer when the client is not reading: `send()` never + // blocks, so without this wait a slow reader would grow the write queue + // without bound (bounded by the writer's drain timeout). + await writer.drain(); } } catch (error) { sendFailure(writer, prepared, state, toApiError(error, "OpenCode completion failed.")); @@ -1214,8 +1407,14 @@ function finaliseStream(writer: SseWriter, prepared: Prepared, state: StreamStat // regenerate them, or clients cannot correlate the stream with the result. const doneItems: ResponseOutputItem[] = []; + const incompleteReasonForTurn = incompleteReason(state.finishReason); + const failed = state.finishReason === "error"; + const incomplete = !failed && incompleteReasonForTurn !== null; + // An incomplete response has an incomplete message item, matching the real API. + const messageStatus: MessageItem["status"] = incomplete ? "incomplete" : "completed"; + if (state.reasoningVisible) { - const item = reasoningItem(state.reasoningId, state.reasoningText); + const item = reasoningItem(state.reasoningId, streamReasoning(state), "completed"); emitFrame(writer, state, "response.output_item.done", (sequence) => ({ type: "response.output_item.done", sequence_number: sequence, @@ -1227,13 +1426,14 @@ function finaliseStream(writer: SseWriter, prepared: Prepared, state: StreamStat } if (state.messageStarted) { + const text = streamText(state); emitFrame(writer, state, "response.output_text.done", (sequence) => ({ type: "response.output_text.done", sequence_number: sequence, item_id: state.messageId, output_index: outputIndex, content_index: 0, - text: state.text, + text, })); emitFrame(writer, state, "response.content_part.done", (sequence) => ({ type: "response.content_part.done", @@ -1241,9 +1441,9 @@ function finaliseStream(writer: SseWriter, prepared: Prepared, state: StreamStat item_id: state.messageId, output_index: outputIndex, content_index: 0, - part: { type: "output_text", text: state.text, annotations: [] }, + part: { type: "output_text", text, annotations: [] }, })); - const item = messageItem(state.messageId, state.text, "completed"); + const item = messageItem(state.messageId, text, messageStatus); emitFrame(writer, state, "response.output_item.done", (sequence) => ({ type: "response.output_item.done", sequence_number: sequence, @@ -1287,15 +1487,13 @@ function finaliseStream(writer: SseWriter, prepared: Prepared, state: StreamStat outputIndex += 1; } - const incomplete = state.finishReason === "length"; - const failed = state.finishReason === "error"; const output: ResponseOutputItem[] = doneItems; - const final = baseResponse(prepared, { id: state.id, + createdAt: state.createdAt, status: failed ? "failed" : incomplete ? "incomplete" : "completed", output, - outputText: state.text, + outputText: streamText(state), usage: toResponseUsage(state.usage ?? EMPTY_USAGE), finishReason: state.finishReason, sessionId: state.sessionId, diff --git a/test/openai-responses.test.ts b/test/openai-responses.test.ts index b905f2f..eff3e67 100644 --- a/test/openai-responses.test.ts +++ b/test/openai-responses.test.ts @@ -6,7 +6,7 @@ */ import http from "node:http"; import type { AddressInfo } from "node:net"; -import { afterAll, afterEach, beforeAll, describe, expect, it } from "vitest"; +import { afterAll, afterEach, beforeAll, describe, expect, it, vi } from "vitest"; import Fastify, { type FastifyInstance, type FastifyReply, type FastifyRequest } from "fastify"; import { registerOpenAiResponsesRoutes } from "../src/adapter/openai/responses.js"; import { requireApiKey } from "../src/auth.js"; @@ -42,11 +42,13 @@ afterEach(async () => { * the real server uses, keeping the unit test independent of the other files. * * `run` optionally replaces the scripted runner, which lets a test throw from - * inside the completion stream itself. + * inside the completion stream itself. `configure` runs before `ready()` so a + * test can attach hooks (for example to simulate socket backpressure). */ async function makeApp( options: TestContextOptions = {}, run?: CompletionRunner["run"], + configure?: (app: FastifyInstance) => void, ): Promise { const base = createTestContext(options); const ctx: AppContext = run === undefined ? base : { ...base, completion: { ...base.completion, run } }; @@ -57,6 +59,7 @@ async function makeApp( const apiError = error instanceof ApiError ? error : toApiError(error, "Internal server error."); return reply.status(apiError.status).send(toOpenAiError(apiError)); }); + configure?.(app); registerOpenAiResponsesRoutes(app, ctx); await app.ready(); @@ -92,7 +95,7 @@ interface ResponsePayload { total_tokens: number; input_tokens_details: { cached_tokens: number }; output_tokens_details: { reasoning_tokens: number }; - }; + } | null; parallel_tool_calls: boolean; tool_choice: string; tools: Array>; @@ -102,7 +105,7 @@ interface ResponsePayload { reasoning: { effort: string | null; summary: string | null }; incomplete_details: { reason: string } | null; error: { code: string; message: string } | null; - instructions: null; + instructions: string | null; previous_response_id: null; store: boolean; truncation: string; @@ -112,6 +115,7 @@ interface ResponsePayload { variant: string | null; reused_session: boolean; native_tool_calls: unknown[]; + unapplied?: string[]; }; } @@ -190,7 +194,7 @@ describe("POST /v1/responses (non-streaming)", () => { role: "user", content: [ { type: "input_text", text: "What is in this picture?" }, - { type: "input_image", image_url: PNG_DATA_URI, detail: "high" }, + { type: "input_image", image_url: PNG_DATA_URI, detail: "auto" }, ], }, ], @@ -274,14 +278,37 @@ describe("POST /v1/responses (non-streaming)", () => { expect(response.statusCode).toBe(200); const body = response.json() as ResponsePayload; - expect(body.instructions).toBeNull(); + // The real API echoes the instructions that were used; the gateway always + // reported `null` even when the caller sent them. + expect(body.instructions).toBe("You are terse."); expect(captured?.messages).toEqual([ { role: "system", text: "You are terse." }, { role: "user", text: "Say hello." }, ]); }); - it("forwards headers, tools, reasoning effort and max_output_tokens", async () => { + it("echoes the request instructions on the streamed response object too", 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", + instructions: "You are terse.", + input: "Say hello.", + stream: true, + }, + }); + + expect(response.statusCode).toBe(200); + const created = frames(response.payload)[0]?.json["response"] as ResponsePayload; + const completed = frames(response.payload).at(-1)?.json["response"] as ResponsePayload; + expect(created.instructions).toBe("You are terse."); + expect(completed.instructions).toBe("You are terse."); + }); + + it("forwards headers, tools, reasoning effort and echoes the request options", async () => { let captured: InternalRequest | undefined; const app = await makeApp({ onRun: (request) => (captured = request) }); @@ -308,6 +335,7 @@ describe("POST /v1/responses (non-streaming)", () => { expect(captured?.conversationKey).toBe("conv_42"); expect(captured?.agent).toBe("plan"); + // Accepted and recorded; `x_opencode.unapplied` says they were not applied. expect(captured?.maxTokens).toBe(512); expect(captured?.temperature).toBe(0.3); expect(captured?.topP).toBe(0.9); @@ -327,6 +355,131 @@ describe("POST /v1/responses (non-streaming)", () => { expect(body.tools).toHaveLength(1); expect(body.store).toBe(false); expect(body.truncation).toBe("disabled"); + expect(body.x_opencode.unapplied).toEqual(["temperature", "top_p", "max_output_tokens"]); + }); + + it("reports x_opencode.unapplied on the streamed response object and omits it when empty", async () => { + const app = await makeApp(); + + const withKnobs = await app.inject({ + method: "POST", + url: "/v1/responses", + headers: AUTH, + payload: { + model: "opencode/deepseek-v4.1-flash-free", + input: "hi", + temperature: 0.3, + max_output_tokens: 64, + seed: 7, + stream: true, + }, + }); + expect(withKnobs.statusCode).toBe(200); + const streamed = frames(withKnobs.payload); + const created = streamed[0]?.json["response"] as ResponsePayload; + const completed = streamed.at(-1)?.json["response"] as ResponsePayload; + expect(created.x_opencode.unapplied).toEqual(["temperature", "seed", "max_output_tokens"]); + expect(completed.x_opencode.unapplied).toEqual(["temperature", "seed", "max_output_tokens"]); + + const plain = await app.inject({ + method: "POST", + url: "/v1/responses", + headers: AUTH, + payload: { model: "opencode/deepseek-v4.1-flash-free", input: "hi", stream: true }, + }); + expect(plain.statusCode).toBe(200); + const plainCreated = frames(plain.payload)[0]?.json["response"] as ResponsePayload; + expect(plainCreated.x_opencode.unapplied).toBeUndefined(); + }); + + it("rejects every field that changes the response shape with 400 unsupported_parameter", async () => { + const app = await makeApp(); + const rejections: Array<{ field: string; payload: Record; param: string }> = [ + { field: "logprobs", payload: { logprobs: true }, param: "logprobs" }, + { field: "top_logprobs", payload: { top_logprobs: 3 }, param: "top_logprobs" }, + { field: "modalities", payload: { modalities: ["text", "audio"] }, param: "modalities" }, + { field: "audio", payload: { audio: { voice: "alloy" } }, param: "audio" }, + { field: "prediction", payload: { prediction: { type: "content", content: "x" } }, param: "prediction" }, + { field: "store", payload: { store: true }, param: "store" }, + { field: "web_search_options", payload: { web_search_options: {} }, param: "web_search_options" }, + { field: "functions", payload: { functions: [{ name: "lookup" }] }, param: "functions" }, + { field: "function_call", payload: { function_call: "auto" }, param: "function_call" }, + { + field: "previous_response_id", + payload: { previous_response_id: "resp_x" }, + param: "previous_response_id", + }, + { + field: "include", + payload: { include: ["reasoning.encrypted_content"] }, + param: "include", + }, + { + field: "input_image.detail", + payload: { + input: [ + { + role: "user", + content: [ + { type: "input_text", text: "what is this?" }, + { type: "input_image", image_url: PNG_DATA_URI, detail: "low" }, + ], + }, + ], + }, + param: "input", + }, + ]; + + for (const { field, payload, param } of rejections) { + const response = await app.inject({ + method: "POST", + url: "/v1/responses", + headers: AUTH, + payload: { model: "opencode/deepseek-v4.1-flash-free", input: "hi", ...payload }, + }); + expect(response.statusCode, `${field} must be rejected`).toBe(400); + const body = response.json() as { error: { code: string; param: string | null } }; + expect(body.error.code, `${field} must be unsupported_parameter`).toBe("unsupported_parameter"); + expect(body.error.param, `${field} must name itself`).toBe(param); + } + + // The stateless pattern's harmless values stay accepted. + const accepted = await app.inject({ + method: "POST", + url: "/v1/responses", + headers: AUTH, + payload: { + model: "opencode/deepseek-v4.1-flash-free", + input: "hi", + store: false, + include: [], + modalities: ["text"], + function_call: "none", + functions: [], + logprobs: false, + }, + }); + expect(accepted.statusCode).toBe(200); + }); + + it("rejects previous_response_id with a diagnostic message", 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: "hi", + previous_response_id: "resp_x", + }, + }); + + expect(response.statusCode).toBe(400); + const body = response.json() as { error: { code: string; message: string } }; + expect(body.error.code).toBe("unsupported_parameter"); + expect(body.error.message).toContain("resend the full `input`"); }); it("emits one function_call item per tool call", async () => { @@ -378,7 +531,7 @@ describe("POST /v1/responses (non-streaming)", () => { method: "POST", url: "/v1/responses", headers: AUTH, - payload: { model: "opencode/deepseek-v4.1-flash-free", input: "Count forever.", max_output_tokens: 8 }, + payload: { model: "opencode/deepseek-v4.1-flash-free", input: "Count forever." }, }); expect(response.statusCode).toBe(200); @@ -386,9 +539,41 @@ describe("POST /v1/responses (non-streaming)", () => { expect(body.status).toBe("incomplete"); expect(body.incomplete_details).toEqual({ reason: "max_output_tokens" }); expect(body.output_text).toBe("truncated"); - expect(body.max_output_tokens).toBe(8); + expect(body.max_output_tokens).toBeNull(); expect(body.output).toHaveLength(1); - expect(body.output[0]?.status).toBe("completed"); + // The message item is incomplete on the buffered path too, matching the + // streamed `response.output_item.done` shape. + expect(body.output[0]?.status).toBe("incomplete"); + }); + + it("reports a content-filtered turn as an incomplete response", async () => { + const app = await makeApp({ + script: (request): CompletionEvent[] => { + const usage = { ...EMPTY_USAGE, inputTokens: 3, outputTokens: 2, totalTokens: 5 }; + return [ + { kind: "start", sessionId: "ses_filter", messageId: "msg_filter", model: request.model, agent: "build", reusedSession: false, reasoningEnabled: false }, + { kind: "text_delta", text: "blocked", ordinal: 0 }, + { kind: "end", finishReason: "content_filter", usage, messageId: "msg_filter" }, + ]; + }, + }); + + const response = await app.inject({ + method: "POST", + url: "/v1/responses", + headers: AUTH, + payload: { model: "opencode/deepseek-v4.1-flash-free", input: "Go." }, + }); + + expect(response.statusCode).toBe(200); + const body = response.json() as ResponsePayload; + // A filtered turn is incomplete, not completed: the caller must be able to + // tell it apart from a full answer. + expect(body.status).toBe("incomplete"); + expect(body.incomplete_details).toEqual({ reason: "content_filter" }); + expect(body.error).toBeNull(); + expect(body.output_text).toBe("blocked"); + expect(body.output[0]?.status).toBe("incomplete"); }); it("surfaces reasoning as a reasoning item when requested", async () => { @@ -423,8 +608,9 @@ describe("POST /v1/responses (non-streaming)", () => { expect(reasoning?.type).toBe("reasoning"); expect(reasoning?.id).toMatch(/^rs_[0-9a-f]{32}$/); expect(reasoning?.summary).toEqual([{ type: "summary_text", text: "thinking hard" }]); + expect(reasoning?.status).toBe("completed"); expect(body.output[1]?.type).toBe("message"); - expect(body.usage.output_tokens_details.reasoning_tokens).toBe(6); + expect(body.usage?.output_tokens_details.reasoning_tokens).toBe(6); }); it("rejects a body without input with 400", async () => { @@ -543,7 +729,9 @@ describe("POST /v1/responses (non-streaming)", () => { total_tokens: 18, output_tokens_details: { reasoning_tokens: 3 }, }); - expect(bufferedBody.usage.input_tokens + bufferedBody.usage.output_tokens).toBe(bufferedBody.usage.total_tokens); + expect((bufferedBody.usage?.input_tokens ?? 0) + (bufferedBody.usage?.output_tokens ?? 0)).toBe( + bufferedBody.usage?.total_tokens, + ); const streamed = await app.inject({ method: "POST", @@ -554,8 +742,10 @@ describe("POST /v1/responses (non-streaming)", () => { expect(streamed.statusCode).toBe(200); const streamedBody = frames(streamed.payload).at(-1)?.json["response"] as ResponsePayload; expect(streamedBody.usage).toMatchObject({ input_tokens: 10, output_tokens: 8, total_tokens: 18 }); - expect(streamedBody.usage.output_tokens_details.reasoning_tokens).toBe(3); - expect(streamedBody.usage.input_tokens + streamedBody.usage.output_tokens).toBe(streamedBody.usage.total_tokens); + expect(streamedBody.usage?.output_tokens_details.reasoning_tokens).toBe(3); + expect((streamedBody.usage?.input_tokens ?? 0) + (streamedBody.usage?.output_tokens ?? 0)).toBe( + streamedBody.usage?.total_tokens, + ); }); it("reports a failed turn as status failed with an error object", async () => { @@ -785,6 +975,9 @@ describe("POST /v1/responses (streaming)", () => { expect(eventTypes(response.payload)).toEqual([ "response.created", "response.in_progress", + // The reasoning item must be announced before its summary part: the old + // stream opened index 1 and closed index 0, leaving a hole. + "response.output_item.added", "response.reasoning_summary_part.added", "response.reasoning_summary_text.delta", "response.reasoning_summary_text.done", @@ -804,6 +997,27 @@ describe("POST /v1/responses (streaming)", () => { "response.completed", ]); + // Every index that receives content was announced by an `.added` frame + // first, and the reasoning item is the first one at index 0. + const addedIndexes: number[] = []; + const announced = new Set(); + for (const frame of parsed) { + const type = frame.json["type"]; + const index = frame.json["output_index"]; + if (type === "response.output_item.added") { + addedIndexes.push(index as number); + announced.add(index as number); + continue; + } + if (typeof index === "number") { + expect(announced.has(index), `output_index ${index} was used before it was added`).toBe(true); + } + } + expect(addedIndexes[0]).toBe(0); + const firstAdded = parsed.find((frame) => frame.json["type"] === "response.output_item.added"); + expect((firstAdded?.json["item"] as ResponseItem | undefined)?.type).toBe("reasoning"); + expect((firstAdded?.json["item"] as ResponseItem | undefined)?.status).toBe("in_progress"); + const created = parsed[0]?.json["response"] as ResponsePayload; expect((parsed[0]?.json["response"] as Record)["status"]).toBe("in_progress"); expect(created.output).toEqual([]); @@ -816,7 +1030,7 @@ describe("POST /v1/responses (streaming)", () => { expect(completed.x_opencode.session_id).toBe("ses_stream"); expect(completed.x_opencode.variant).toBe("high"); expect(completed.x_opencode.reused_session).toBe(true); - expect(completed.usage.output_tokens_details.reasoning_tokens).toBe(2); + expect(completed.usage?.output_tokens_details.reasoning_tokens).toBe(2); const deltas = parsed.filter((frame) => frame.json["type"] === "response.output_text.delta"); expect(deltas.map((frame) => frame.json["delta"])).toEqual(["He", "llo"]); @@ -839,7 +1053,7 @@ describe("POST /v1/responses (streaming)", () => { method: "POST", url: "/v1/responses", headers: AUTH, - payload: { model: "opencode/deepseek-v4.1-flash-free", input: "Go.", stream: true, max_output_tokens: 4 }, + payload: { model: "opencode/deepseek-v4.1-flash-free", input: "Go.", stream: true }, }); expect(response.statusCode).toBe(200); @@ -852,6 +1066,40 @@ describe("POST /v1/responses (streaming)", () => { expect(final.status).toBe("incomplete"); expect(final.incomplete_details).toEqual({ reason: "max_output_tokens" }); expect(final.output_text).toBe("partial"); + expect(final.output[0]?.status).toBe("incomplete"); + }); + + it("emits response.incomplete with reason content_filter for a filtered streamed turn", async () => { + const app = await makeApp({ + script: (request): CompletionEvent[] => { + const usage = { ...EMPTY_USAGE, inputTokens: 2, outputTokens: 3, totalTokens: 5 }; + return [ + { kind: "start", sessionId: "ses_filter_stream", messageId: "msg_filter_stream", model: request.model, agent: "build", reusedSession: false, reasoningEnabled: false }, + { kind: "text_delta", text: "blocked", ordinal: 0 }, + { kind: "end", finishReason: "content_filter", usage, messageId: "msg_filter_stream" }, + ]; + }, + }); + + const response = await app.inject({ + method: "POST", + url: "/v1/responses", + headers: AUTH, + payload: { model: "opencode/deepseek-v4.1-flash-free", input: "Go.", stream: true }, + }); + + expect(response.statusCode).toBe(200); + const parsed = frames(response.payload); + const types = parsed.map((frame) => frame.json["type"]); + expect(types).toContain("response.incomplete"); + expect(types).not.toContain("response.completed"); + expect(types).not.toContain("response.failed"); + + const final = parsed.at(-1)?.json["response"] as ResponsePayload; + expect(final.status).toBe("incomplete"); + expect(final.incomplete_details).toEqual({ reason: "content_filter" }); + expect(final.output_text).toBe("blocked"); + expect(final.output[0]?.status).toBe("incomplete"); }); it("emits a typed error frame when the completion fails", async () => { @@ -1028,6 +1276,213 @@ describe("POST /v1/responses (streaming)", () => { expect(response.headers["content-type"]).toContain("application/json"); expect((response.json() as ResponsePayload).object).toBe("response"); }); + + it("keeps created_at constant across every frame and the buffered body", async () => { + const BASE_MS = 1_700_000_000_000; + const now = vi.spyOn(Date, "now").mockReturnValue(BASE_MS); + try { + const usage = { ...EMPTY_USAGE, inputTokens: 1, outputTokens: 1, totalTokens: 2 }; + const streamApp = await makeApp({}, async function* (request: InternalRequest): AsyncGenerator { + yield { + kind: "start", + sessionId: "ses_clock", + messageId: "msg_clock", + model: request.model, + agent: "build", + reusedSession: false, + reasoningEnabled: false, + }; + // Cross a second boundary in the middle of the turn. + now.mockReturnValue(BASE_MS + 5_000); + yield { kind: "text_delta", text: "Hello", ordinal: 0 }; + yield { kind: "end", finishReason: "stop", usage, messageId: "msg_clock" }; + }); + + const streamed = await streamApp.inject({ + method: "POST", + url: "/v1/responses", + headers: AUTH, + payload: { model: "opencode/deepseek-v4.1-flash-free", input: "Hi.", stream: true }, + }); + expect(streamed.statusCode).toBe(200); + const createdAts = frames(streamed.payload) + .filter((frame) => frame.json["response"] !== undefined) + .map((frame) => (frame.json["response"] as ResponsePayload).created_at); + expect(createdAts.length).toBeGreaterThan(2); + expect(new Set(createdAts).size).toBe(1); + expect(createdAts[0]).toBe(BASE_MS / 1000); + + // The buffered body is built from the response that was created at the + // start of the request, not at the moment the turn happened to finish. + now.mockReturnValue(BASE_MS); + const bufferedApp = await makeApp({ + script: async (request): Promise => { + now.mockReturnValue(BASE_MS + 9_000); + return [ + { kind: "start", sessionId: "ses_clock_b", messageId: "msg_clock_b", model: request.model, agent: "build", reusedSession: false, reasoningEnabled: false }, + { kind: "text_delta", text: "Hello", ordinal: 0 }, + { kind: "end", finishReason: "stop", usage, messageId: "msg_clock_b" }, + ]; + }, + }); + const buffered = await bufferedApp.inject({ + method: "POST", + url: "/v1/responses", + headers: AUTH, + payload: { model: "opencode/deepseek-v4.1-flash-free", input: "Hi." }, + }); + expect(buffered.statusCode).toBe(200); + expect((buffered.json() as ResponsePayload).created_at).toBe(BASE_MS / 1000); + } finally { + now.mockRestore(); + } + }); + + it("reports null usage when a streamed turn fails before any usage event", async () => { + const app = await makeApp({ + script: (request): CompletionEvent[] => [ + { kind: "start", sessionId: "ses_no_usage", messageId: "msg_no_usage", model: request.model, agent: "build", reusedSession: false, reasoningEnabled: false }, + { kind: "text_delta", text: "partial", ordinal: 0 }, + { kind: "error", error: new ApiError(502, "upstream_error", "boom") }, + ], + }); + + const response = await app.inject({ + method: "POST", + url: "/v1/responses", + headers: AUTH, + payload: { model: "opencode/deepseek-v4.1-flash-free", input: "Go.", stream: true }, + }); + + expect(response.statusCode).toBe(200); + const terminal = frames(response.payload).at(-1); + expect(terminal?.event).toBe("response.failed"); + const body = terminal?.json["response"] as ResponsePayload; + expect(body.status).toBe("failed"); + // A fabricated all-zero usage asserted a cost for a turn that failed before + // the gateway saw any token accounting. + expect(body.usage).toBeNull(); + }); + + it("announces the message item when the text only arrives in text_end", async () => { + const app = await makeApp({ + script: (request): CompletionEvent[] => { + const usage = { ...EMPTY_USAGE, inputTokens: 2, outputTokens: 3, totalTokens: 5 }; + return [ + { kind: "start", sessionId: "ses_text_end", messageId: "msg_text_end", model: request.model, agent: "build", reusedSession: false, reasoningEnabled: false }, + // No `text_delta` at all: the provider sent the consolidated text. + { kind: "text_end", text: "all at once", ordinal: 0 }, + { kind: "end", finishReason: "stop", usage, messageId: "msg_text_end" }, + ]; + }, + }); + + const response = await app.inject({ + method: "POST", + url: "/v1/responses", + headers: AUTH, + payload: { model: "opencode/deepseek-v4.1-flash-free", input: "Go.", stream: true }, + }); + + expect(response.statusCode).toBe(200); + const parsed = frames(response.payload); + const types = parsed.map((frame) => frame.json["type"]); + expect(types).toContain("response.output_item.added"); + expect(types).toContain("response.content_part.added"); + expect(types).toContain("response.output_text.done"); + expect(types).not.toContain("response.output_text.delta"); + + const final = parsed.at(-1)?.json["response"] as ResponsePayload; + expect(final.output_text).toBe("all at once"); + expect(final.output).toHaveLength(1); + expect(final.output[0]?.type).toBe("message"); + expect(final.output[0]?.content?.[0]?.text).toBe("all at once"); + }); + + it("streams 5000 deltas and joins the text once", async () => { + const pieces = Array.from({ length: 5_000 }, (_, index) => `chunk-${index};`); + const app = await makeApp({ + script: (request): CompletionEvent[] => { + const usage = { ...EMPTY_USAGE, inputTokens: 1, outputTokens: pieces.length, totalTokens: pieces.length + 1 }; + const events: CompletionEvent[] = [ + { kind: "start", sessionId: "ses_many", messageId: "msg_many", model: request.model, agent: "build", reusedSession: false, reasoningEnabled: false }, + ...pieces.map((text): CompletionEvent => ({ kind: "text_delta", text, ordinal: 0 })), + { kind: "end", finishReason: "stop", usage, messageId: "msg_many" }, + ]; + return events; + }, + }); + + const response = await app.inject({ + method: "POST", + url: "/v1/responses", + headers: AUTH, + payload: { model: "opencode/deepseek-v4.1-flash-free", input: "Go.", stream: true }, + }); + + expect(response.statusCode).toBe(200); + const expected = pieces.join(""); + const final = frames(response.payload).at(-1)?.json["response"] as ResponsePayload; + expect(final.output_text).toBe(expected); + expect(final.output[0]?.content?.[0]?.text).toBe(expected); + expect(frames(response.payload).filter((frame) => frame.json["type"] === "response.output_text.delta")).toHaveLength( + pieces.length, + ); + }); + + it("awaits writer drain under backpressure and still closes the stream", async () => { + // Force the first `raw.write()` to report a full socket buffer, then emit + // `drain` asynchronously. The loop only resumes producing after it has + // awaited `writer.drain()`, so frames written after the real drain event + // prove the backpressure wait is wired in; without it every frame would be + // written synchronously before the timer fires. + let drainedAt = 0; + let writesAfterDrain = 0; + let ended = false; + const app = await makeApp({}, undefined, (application) => { + application.addHook("preHandler", async (_request, reply) => { + const raw = reply.raw; + const originalWrite = raw.write.bind(raw); + let backpressured = false; + raw.write = ((chunk: string, ...rest: unknown[]) => { + const result = (originalWrite as (chunk: string, ...args: unknown[]) => boolean)(chunk, ...rest); + if (!backpressured) { + // The chunk is buffered (as a real backpressured write would be) but + // the buffer is reported full until the socket drains. + backpressured = true; + setTimeout(() => { + drainedAt = Date.now(); + raw.emit("drain"); + }, 10); + return false; + } + if (drainedAt > 0) writesAfterDrain += 1; + return result; + }) as typeof raw.write; + const originalEnd = raw.end.bind(raw); + raw.end = ((...args: unknown[]) => { + ended = true; + return (originalEnd as (...inner: unknown[]) => unknown)(...args); + }) as typeof raw.end; + }); + }); + + const response = await app.inject({ + method: "POST", + url: "/v1/responses", + headers: AUTH, + payload: { model: "opencode/deepseek-v4.1-flash-free", input: "Go.", stream: true }, + }); + + expect(response.statusCode).toBe(200); + const parsed = frames(response.payload); + expect(parsed.at(-1)?.event).toBe("response.completed"); + expect(parsed.map((frame) => frame.json.sequence_number)).toEqual(parsed.map((_, index) => index)); + expect(drainedAt).toBeGreaterThan(0); + expect(writesAfterDrain).toBeGreaterThan(0); + // `SseWriter.close()` ends the response; the stream must not stay open. + expect(ended).toBe(true); + }); }); describe("POST /v1/responses (media concurrency)", () => { @@ -1089,4 +1544,37 @@ describe("POST /v1/responses (media concurrency)", () => { // Serial resolution would need at least two full fixture delays. expect(elapsed).toBeLessThan(MEDIA_DELAY_MS * 2 - 10); }); + + it("downloads the media of different input items through one request pool", async () => { + let captured: InternalRequest | undefined; + const app = await makeApp({ + config: { allowPrivateMediaUrls: true }, + onRun: (request) => (captured = request), + }); + + const startedAt = Date.now(); + const response = await app.inject({ + method: "POST", + url: "/v1/responses", + headers: AUTH, + payload: { + model: "opencode/deepseek-v4.1-flash-free", + input: [ + { role: "user", content: [{ type: "input_image", image_url: `${baseUrl}/first.png` }] }, + { role: "assistant", content: "ok" }, + { role: "user", content: [{ type: "input_image", image_url: `${baseUrl}/second.png` }] }, + ], + }, + }); + const elapsed = Date.now() - startedAt; + + expect(response.statusCode).toBe(200); + const attachments = captured?.messages.flatMap((message) => message.attachments ?? []) ?? []; + expect(attachments.map((attachment) => attachment.origin)).toEqual([ + `${baseUrl}/first.png`, + `${baseUrl}/second.png`, + ]); + // Resolving item by item would serialise two pools and cost two delays. + expect(elapsed).toBeLessThan(MEDIA_DELAY_MS * 2 - 10); + }); }); From f58c41fbc455e0d5a5f3c5c72d833d6a3d0ecada Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Ph=E1=BA=A1m=20V=C4=83n=20=C4=90=E1=BB=8Bnh?= Date: Thu, 3 Dec 2026 12:08:58 +0700 Subject: [PATCH 03/12] fix(openai): honour stop and make unhonoured fields visible stop was accepted and then ignored, so the delimiter stayed in the answer and finish_reason stayed stop; it is now a text-truncation filter shared by both paths, exactly like the Anthropic surface, without interrupting the upstream turn. Requests from different messages no longer download their media one message at a time: the adapters build every media source first and resolve them through one request-wide pool. Fields that would change the shape of the response and cannot be emulated were accepted and silently dropped. logprobs and top_logprobs, non-text modalities, audio, prediction, store: true, web_search_options, the legacy functions and function_call pair, previous_response_id, non-empty include, best_of and suffix now answer 400 unsupported_parameter naming the field. image_url.detail accepts only auto. A tool_choice that names a function the request never declared is rejected instead of being answered with prose. The generation knobs OpenCode's agent loop owns stay accepted for client compatibility, but every response names them in x_opencode.unapplied so a caller can detect that they were not applied. The tool-call envelope filter no longer rescans the whole accumulated body per delta. --- src/adapter/common/tools.ts | 100 +++++--- src/adapter/openai/chat.ts | 389 +++++++++++++++++++++++++++--- src/adapter/openai/completions.ts | 67 ++++- test/openai-chat.test.ts | 246 ++++++++++++++++++- test/openai-completions.test.ts | 82 ++++++- test/tools.test.ts | 36 ++- 6 files changed, 838 insertions(+), 82 deletions(-) diff --git a/src/adapter/common/tools.ts b/src/adapter/common/tools.ts index 7a09c5f..62cac3e 100644 --- a/src/adapter/common/tools.ts +++ b/src/adapter/common/tools.ts @@ -54,7 +54,7 @@ function schemaToText(tool: ToolDefinition): string { ].join("\n"); } -function choiceInstruction(tools: ToolDefinition[], choice: ToolChoice | undefined): string { +function choiceInstruction(choice: ToolChoice | undefined): string { if (choice === "none") { return "The caller disabled tool use for this turn: answer in plain text and never emit a tool call block."; } @@ -62,27 +62,35 @@ function choiceInstruction(tools: ToolDefinition[], choice: ToolChoice | undefin return "The caller requires a tool call for this turn: emit at least one tool call block."; } if (choice && typeof choice === "object") { - const known = tools.some((tool) => tool.name === choice.name); - return known - ? `The caller requires the tool \`${choice.name}\` for this turn: emit exactly one tool call block for it.` - : `The caller requested the unknown tool \`${choice.name}\`. Explain that the tool is unavailable instead of inventing it.`; + return `The caller requires the tool \`${choice.name}\` for this turn: emit exactly one tool call block for it.`; } 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. + * Reject a `tool_choice` the request cannot satisfy. * * 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. + * and no bridged call, which is the opposite of what the caller asked for: a + * choice that requires a tool call with no declared tools, or one that names a + * function the request never declared, is a 400 like the OpenAI API returns. */ 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" }, - ); + if (choice === undefined) return; + if (tools.length === 0) { + if (choice === "required" || typeof choice === "object") { + throw ApiError.badRequest( + "`tool_choice` requires a tool call, but the request declared no `tools`.", + { code: "invalid_request", param: "tool_choice" }, + ); + } + return; + } + if (typeof choice === "object" && !tools.some((tool) => tool.name === choice.name)) { + throw ApiError.badRequest(`\`tool_choice\` names unknown tool '${choice.name}'.`, { + code: "invalid_request", + param: "tool_choice", + }); } } @@ -133,7 +141,7 @@ export function createToolBridge( "", "## Tool choice", "", - choiceInstruction(tools, choice), + choiceInstruction(choice), ].join("\n") : ""; @@ -147,48 +155,84 @@ export function createToolBridge( /** Streaming filter that separates assistant text from tool-call envelopes. */ export class ToolCallFilter { + /** Text held back between calls: the partial-marker lookahead. */ #pending = ""; + /** Committed envelope-body fragments; joined once when the close marker arrives. */ + #bodyParts: string[] = []; + /** Body tail short enough to still contain a split closing marker. */ + #bodyTail = ""; #inCall = false; + #scanned = 0; readonly #calls: ToolCall[] = []; + /** + * Characters examined while looking for an envelope marker. + * + * Every delta is searched once, plus the bounded carry from the previous one, + * so the value stays linear in the size of the payload. It is exposed so a + * test can pin that property (the previous implementation re-scanned the whole + * accumulated envelope on every delta, which was quadratic). + */ + get scannedCharacters(): number { + return this.#scanned; + } + /** Feed a text delta; returns the text that may be forwarded to the caller. */ push(delta: string): string { - this.#pending += delta; let output = ""; + let input = delta; for (;;) { if (this.#inCall) { - const end = this.#pending.indexOf(TOOL_CALL_CLOSE); - if (end === -1) break; - const body = this.#pending.slice(0, end); - this.#pending = this.#pending.slice(end + TOOL_CALL_CLOSE.length); + // Only the carry plus the new delta is searched: the body already + // committed to `#bodyParts` can no longer contain the close marker. + const combined = this.#bodyTail + input; + this.#scanned += combined.length; + const end = combined.indexOf(TOOL_CALL_CLOSE); + if (end === -1) { + const commit = Math.max(0, combined.length - (TOOL_CALL_CLOSE.length - 1)); + if (commit > 0) this.#bodyParts.push(combined.slice(0, commit)); + this.#bodyTail = combined.slice(commit); + break; + } + const body = this.#bodyParts.join("") + combined.slice(0, end); + this.#bodyParts = []; + this.#bodyTail = ""; this.#inCall = false; + input = combined.slice(end + TOOL_CALL_CLOSE.length); const calls = parseToolCallBody(body); if (calls.length > 0) { this.#calls.push(...calls); // Drop a trailing code fence the model may have added around the block. - this.#pending = this.#pending.replace(/^\s*```[a-zA-Z0-9]*[ \t]*\r?\n?/, ""); + input = input.replace(/^\s*```[a-zA-Z0-9]*[ \t]*\r?\n?/, ""); } else { output += body; } continue; } - const start = this.#pending.indexOf(TOOL_CALL_OPEN); + const combined = this.#pending + input; + const start = combined.indexOf(TOOL_CALL_OPEN); + this.#scanned += combined.length; if (start !== -1) { - let before = this.#pending.slice(0, start); + let before = combined.slice(0, start); // Drop a code fence that immediately precedes the envelope. before = before.replace(/```[a-zA-Z0-9]*[ \t]*\r?\n?$/, ""); output += before; - this.#pending = this.#pending.slice(start + TOOL_CALL_OPEN.length); + input = combined.slice(start + TOOL_CALL_OPEN.length); + this.#pending = ""; this.#inCall = true; + this.#bodyParts = []; + this.#bodyTail = ""; continue; } const lookahead = Math.max(0, TOOL_CALL_OPEN.length - 1); - if (this.#pending.length > lookahead) { - output += this.#pending.slice(0, this.#pending.length - lookahead); - this.#pending = this.#pending.slice(this.#pending.length - lookahead); + if (combined.length > lookahead) { + output += combined.slice(0, combined.length - lookahead); + this.#pending = combined.slice(combined.length - lookahead); + } else { + this.#pending = combined; } break; } @@ -201,11 +245,13 @@ export class ToolCallFilter { let text = ""; if (this.#inCall) { // Unterminated envelope: surface it verbatim rather than dropping content. - text += TOOL_CALL_OPEN + this.#pending; + text += TOOL_CALL_OPEN + this.#bodyParts.join("") + this.#bodyTail; } else { text += this.#pending; } this.#pending = ""; + this.#bodyParts = []; + this.#bodyTail = ""; this.#inCall = false; return { text, calls: [...this.#calls] }; } diff --git a/src/adapter/openai/chat.ts b/src/adapter/openai/chat.ts index 4ffe53c..45de22e 100644 --- a/src/adapter/openai/chat.ts +++ b/src/adapter/openai/chat.ts @@ -21,6 +21,7 @@ import { resolveAttachments, type MediaBudget, type MediaSource, + type OmittedAttachment, } from "../../media/resolve.js"; import { EMPTY_USAGE, @@ -138,6 +139,10 @@ const chatRequestSchema = z.object({ messages: z.array(messageSchema).min(1), stream: z.boolean().optional(), stream_options: z.object({ include_usage: z.boolean().optional() }).optional(), + // Generation knobs OpenAI clients send; the OpenCode agent loop owns the + // sampling parameters and the generation budget, so these are accepted and + // recorded but reported through `x_opencode.unapplied` (see + // `unappliedParameters`) instead of being applied or rejected. temperature: z.number().optional(), top_p: z.number().optional(), max_tokens: z.number().optional(), @@ -152,12 +157,23 @@ const chatRequestSchema = z.object({ metadata: z.unknown().optional(), service_tier: z.string().optional(), parallel_tool_calls: z.boolean().optional(), - // Accepted for compatibility and deliberately ignored. + // Generation knobs: accepted and recorded, reported through + // `x_opencode.unapplied` because the OpenCode agent loop owns them. seed: z.unknown().optional(), - logprobs: z.unknown().optional(), logit_bias: z.unknown().optional(), presence_penalty: z.unknown().optional(), frequency_penalty: z.unknown().optional(), + // Accepted for schema compatibility only; every one of them is rejected with + // `unsupported_parameter` because the gateway cannot honour it. + logprobs: z.boolean().optional(), + top_logprobs: z.number().optional(), + modalities: z.array(z.string()).optional(), + audio: z.unknown().optional(), + prediction: z.unknown().optional(), + store: z.boolean().optional(), + web_search_options: z.unknown().optional(), + functions: z.array(z.unknown()).optional(), + function_call: z.union([z.string(), z.object({ name: z.string().min(1) }).passthrough()]).optional(), response_format: responseFormatSchema.optional(), }); @@ -198,6 +214,16 @@ const NULLABLE_TOP_LEVEL_FIELDS: ReadonlySet = new Set([ "response_format", "tools", "tool_choice", + "top_logprobs", + "modalities", + "audio", + "prediction", + "store", + "web_search_options", + "functions", + "function_call", + "best_of", + "suffix", ]); /** @@ -228,6 +254,121 @@ function parseChatRequest(body: unknown): ChatRequest { return parsed.data; } +/** + * Reject a request field the gateway accepts for compatibility but cannot honour. + * + * A 200 that silently drops what the caller asked for cannot be detected by the + * client, so an unusable field is a `400 unsupported_parameter` — the same + * policy `echo` follows on `/v1/completions`. Shared by the OpenAI surfaces so + * chat, legacy completions and responses answer identically. + * + * Only fields that change the *shape* of the response are rejected here. The + * generation knobs (`temperature`, `top_p`, `max_tokens`, the penalties, `seed`, + * `logit_bias`) stay accepted and are reported through `x_opencode.unapplied` + * instead: most SDK clients send them unconditionally, and a gateway that + * answers 400 for `temperature` is not OpenAI-compatible in practice. + */ +export function rejectUnsupported(param: string, reason: string): never { + throw ApiError.badRequest(`\`${param}\` is not supported: ${reason}.`, { + code: "unsupported_parameter", + param, + }); +} + +/** True when `modalities` asks for text output only. */ +export function isTextOnlyModalities(modalities: readonly string[]): boolean { + return modalities.length === 1 && modalities[0] === "text"; +} + +/** + * Generation knobs the gateway records but cannot apply, in a stable order. + * + * OpenCode's agent loop owns the sampling parameters and the generation budget, + * so these values never reach the model; they are echoed back through + * `x_opencode.unapplied` instead of being silently dropped or rejected. + */ +const UNAPPLIED_ORDER = [ + "temperature", + "top_p", + "presence_penalty", + "frequency_penalty", + "seed", + "logit_bias", + "max_tokens", + "max_completion_tokens", + "max_output_tokens", +] as const; + +/** + * Request fields that were supplied but could not be applied, in + * `UNAPPLIED_ORDER`. Empty when the caller sent none of them. + */ +export function unappliedParameters(body: object): string[] { + const record = body as Record; + return UNAPPLIED_ORDER.filter((param) => record[param] !== undefined); +} + +/** + * Reject every request field that would change the shape of the response but + * cannot be honoured. + * + * - `logprobs` / `top_logprobs` cannot be produced at all. + * - `modalities`, `audio`, `prediction` and `web_search_options` require + * provider features OpenCode does not expose. + * - `store: true` would promise a response store the gateway does not have, and + * the legacy `functions` / `function_call` pair is superseded by `tools` / + * `tool_choice`. + * + * `stop` is deliberately absent: it is honoured by `truncateAtStopSequences`. + * The generation knobs are absent too: they are recorded and listed in + * `x_opencode.unapplied` (see `unappliedParameters`). + */ +export function assertHonouredParameters(body: { + logprobs?: unknown; + top_logprobs?: unknown; + modalities?: unknown; + audio?: unknown; + prediction?: unknown; + store?: unknown; + web_search_options?: unknown; + functions?: unknown; + function_call?: unknown; +}): void { + if (body.top_logprobs !== undefined) { + rejectUnsupported("top_logprobs", "the gateway cannot return token log probabilities"); + } + // `logprobs: false` (and the legacy completions `logprobs: 0`) request nothing. + if (body.logprobs !== undefined && body.logprobs !== false && body.logprobs !== 0) { + rejectUnsupported("logprobs", "the gateway cannot return token log probabilities"); + } + if (Array.isArray(body.modalities) && !isTextOnlyModalities(body.modalities as string[])) { + rejectUnsupported("modalities", "this gateway returns text only"); + } + if (body.audio !== undefined) rejectUnsupported("audio", "this gateway cannot return audio output"); + if (body.prediction !== undefined) { + rejectUnsupported("prediction", "predicted outputs cannot be passed to the OpenCode runtime"); + } + if (body.store === true) rejectUnsupported("store", "the gateway keeps no response store"); + if (body.web_search_options !== undefined) { + rejectUnsupported("web_search_options", "the gateway cannot run provider-side web search"); + } + if (Array.isArray(body.functions) && body.functions.length > 0) { + rejectUnsupported("functions", "legacy `functions` are not supported; declare `tools` instead"); + } + if (body.function_call !== undefined && body.function_call !== "none") { + rejectUnsupported("function_call", "legacy `function_call` is not supported; use `tool_choice` instead"); + } +} + +/** `image_url.detail` values the gateway can honour: it always sends full media. */ +function assertImageDetail(detail: string | undefined): void { + if (detail === undefined || detail === "auto") return; + throw ApiError.badRequest('`image_url.detail` must be "auto": this gateway cannot downscale media.', { + code: "unsupported_parameter", + param: "messages", + }); +} + /** `docs/API.md` requires a non-empty `tool_call_id` on every `role: "tool"` message. */ function assertToolCallIds(messages: ChatMessage[]): void { const invalid = messages.some((message) => message.role === "tool" && !hasText(message.tool_call_id)); @@ -250,6 +391,10 @@ export function registerOpenAiChatRoutes(app: FastifyInstance, ctx: AppContext): app.post("/v1/chat/completions", async (request, reply) => { const body = parseChatRequest(request.body); assertToolCallIds(body.messages); + assertHonouredParameters(body); + // Generation knobs stay accepted: they are recorded on the internal request + // and echoed back as `x_opencode.unapplied`. + const unapplied = unappliedParameters(body); if (body.n !== undefined && body.n !== 1) { throw ApiError.badRequest("Only `n: 1` is supported by this gateway.", { @@ -271,7 +416,11 @@ export function registerOpenAiChatRoutes(app: FastifyInstance, ctx: AppContext): signal: abort.signal, }); if (collected.finishReason === "error") throw failedTurnError(); - return reply.send(chatCompletionBody(collected, ctx.config.reasoningField)); + // `stop` is enforced here, exactly like the streamed path below: only the + // visible answer is cut, the upstream turn keeps running (same trade-off + // as the Anthropic surface's `stop_sequences`). + const text = truncateAtStopSequences(collected.text, internal.stop); + return reply.send(chatCompletionBody({ ...collected, text }, ctx.config.reasoningField, unapplied)); } await streamChat(ctx, internal, reply, { @@ -294,13 +443,15 @@ async function buildRequest( config: Config, 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, budget)); - } + // Two-phase mapping: every message is built (and validated) first, then one + // `resolveAttachments` call downloads all of their media through a single + // worker pool. Resolving message by message serialised the pools, so N + // messages cost the sum of their download times instead of the maximum. + const drafts = body.messages.map(toInternalMessageDraft); + const messages = await resolveMessageMedia(drafts, config, { signal, budget, field: "messages" }); const internal: InternalRequest = { surface: "openai.chat", @@ -321,6 +472,9 @@ async function buildRequest( const responseFormat = toResponseFormat(body.response_format); if (responseFormat !== undefined) internal.responseFormat = responseFormat; + // Accepted and recorded, but not forwarded: the OpenCode agent loop owns the + // sampling parameters and the generation budget. `x_opencode.unapplied` tells + // the caller which of them the turn could not apply. if (typeof body.temperature === "number") internal.temperature = body.temperature; if (typeof body.top_p === "number") internal.topP = body.top_p; @@ -343,12 +497,19 @@ async function buildRequest( return internal; } -async function toInternalMessage( - message: ChatMessage, - config: Config, - signal: AbortSignal, - budget: MediaBudget, -): Promise { +/** One message whose media has been separated from its text, before resolution. */ +export interface MessageMediaDraft { + message: InternalMessage; + sources: MediaSource[]; +} + +/** + * Build a message without resolving its media. + * + * Validation of the media parts happens here, so an invalid part is reported + * before any download starts. + */ +function toInternalMessageDraft(message: ChatMessage): MessageMediaDraft { const texts: string[] = []; const sources: MediaSource[] = []; @@ -360,31 +521,17 @@ async function toInternalMessage( texts.push(part.text); continue; } + if (part.type === "image_url") assertImageDetail(part.image_url.detail); const source = mediaSourceOf(part); if (source !== undefined) sources.push(source); } } - // 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"), - formatOmissionNote(omitted, { maxCount: config.maxAttachments, maxBytes: config.maxAttachmentBytes }), - ] - .filter((text) => text.length > 0) - .join("\n"), + text: texts.filter((text) => text.length > 0).join("\n"), }; - if (attachments.length > 0) internal.attachments = attachments; - if (message.role === "assistant") { const calls = toToolCalls(message.tool_calls); if (calls.length > 0) internal.toolCalls = calls; @@ -395,7 +542,72 @@ async function toInternalMessage( if (message.name !== undefined) internal.name = message.name; } - return internal; + return { message: internal, sources }; +} + +/** + * Resolve the media of every message in one `resolveAttachments` call. + * + * The flat result is mapped back onto the messages it came from: attachment + * order is the declaration order (the resolver preserves it), and an omission + * carries its declaration index, which is remapped to the message-local index so + * each message keeps the prompt note it had when it was resolved on its own. + */ +export async function resolveMessageMedia( + drafts: readonly MessageMediaDraft[], + config: Config, + options: { signal: AbortSignal; budget: MediaBudget; field: string }, +): Promise { + const limits = { maxCount: config.maxAttachments, maxBytes: config.maxAttachmentBytes }; + const owners: number[] = []; + const allSources: MediaSource[] = []; + const starts: number[] = []; + for (const [index, draft] of drafts.entries()) { + starts.push(allSources.length); + owners.push(...draft.sources.map(() => index)); + allSources.push(...draft.sources); + } + + const resolved = + allSources.length > 0 + ? await resolveAttachments(allSources, config, { + signal: options.signal, + budget: options.budget, + field: options.field, + }) + : { attachments: [] as Attachment[], omitted: [] as OmittedAttachment[] }; + + const omittedIndexes = new Set(resolved.omitted.map((entry) => entry.index)); + const attachmentsByMessage: Attachment[][] = drafts.map(() => []); + let attachmentIndex = 0; + for (let index = 0; index < allSources.length; index += 1) { + if (omittedIndexes.has(index)) continue; + const attachment = resolved.attachments[attachmentIndex]; + attachmentIndex += 1; + if (attachment === undefined) break; + const owner = owners[index]; + if (owner !== undefined) attachmentsByMessage[owner]?.push(attachment); + } + + const omittedByMessage = new Map(); + for (const omission of resolved.omitted) { + const owner = owners[omission.index]; + if (owner === undefined) continue; + const local = omission.index - (starts[owner] ?? 0); + const list = omittedByMessage.get(owner) ?? []; + list.push({ ...omission, index: local }); + omittedByMessage.set(owner, list); + } + + return drafts.map((draft, index) => { + const message = draft.message; + const note = formatOmissionNote(omittedByMessage.get(index) ?? [], limits); + const text = [message.text, note].filter((part) => part.length > 0).join("\n"); + if (text.length > 0) message.text = text; + const attachments = attachmentsByMessage[index] ?? []; + if (attachments.length > 0) message.attachments = attachments; + return message; + }); } /** The media source a non-text content part carries, if any. */ @@ -536,7 +748,11 @@ function audioMime(format: string | undefined): string { // --------------------------------------------------------- non-streaming out --- -function chatCompletionBody(collected: CollectedCompletion, field: ReasoningField): Record { +function chatCompletionBody( + collected: CollectedCompletion, + field: ReasoningField, + unapplied: readonly string[] = [], +): Record { return { id: `chatcmpl-${randomUUID().replace(/-/g, "")}`, object: "chat.completion", @@ -550,7 +766,7 @@ function chatCompletionBody(collected: CollectedCompletion, field: ReasoningFiel }, ], usage: openAiUsage(collected.usage), - x_opencode: openCodeExtension(collected), + x_opencode: openCodeExtension(collected, unapplied), }; } @@ -576,8 +792,15 @@ function messagePayload(collected: CollectedCompletion, field: ReasoningField): /** * Native OpenCode activity, exposed as a non-standard extension object. * Shared with the legacy completions surface (`completions.ts`). + * + * `unapplied` lists the generation knobs the caller supplied that the gateway + * could not apply, in a stable order; the key is omitted when there are none, so + * a request that sends no such field keeps exactly its previous payload shape. */ -export function openCodeExtension(collected: CollectedCompletion): Record { +export function openCodeExtension( + collected: CollectedCompletion, + unapplied: readonly string[] = [], +): Record { return { session_id: collected.sessionId, agent: collected.agent, @@ -585,6 +808,7 @@ export function openCodeExtension(collected: CollectedCompletion): Record 0 ? { unapplied: [...unapplied] } : {}), }; } @@ -617,6 +841,84 @@ interface StreamOptions { signal: AbortSignal; } +/** + * Streaming `stop` enforcement for the OpenAI surfaces. + * + * OpenAI's `stop` truncates the visible answer at the first delimiter. The + * gateway cannot pass the delimiter to the OpenCode agent, so the filter holds + * back the longest delimiter minus one character between deltas (a match may + * span a delta boundary) and stops forwarding text after a match. Only assistant + * text is filtered — never reasoning or tool arguments — and the upstream turn + * keeps running, exactly like the Anthropic surface's `stop_sequences`. + */ +export class StopSequenceFilter { + readonly #sequences: readonly string[]; + readonly #hold: number; + #pending = ""; + #matched = false; + + constructor(sequences: readonly string[]) { + this.#sequences = [...sequences]; + this.#hold = Math.max(0, sequences.reduce((longest, entry) => Math.max(longest, entry.length), 0) - 1); + } + + /** True once a delimiter has been seen; later text is dropped. */ + get matched(): boolean { + return this.#matched; + } + + /** Feed a text delta; returns the part of it that may still be forwarded. */ + push(delta: string): string { + if (this.#matched) return ""; + this.#pending += delta; + const at = this.#firstMatch(); + if (at !== -1) { + const emitted = this.#pending.slice(0, at); + this.#pending = ""; + this.#matched = true; + return emitted; + } + if (this.#pending.length <= this.#hold) return ""; + const emitted = this.#pending.slice(0, this.#pending.length - this.#hold); + this.#pending = this.#pending.slice(this.#pending.length - this.#hold); + return emitted; + } + + /** Flush the held-back tail once the turn ends without a match. */ + finish(): string { + if (this.#matched) return ""; + const text = this.#pending; + this.#pending = ""; + return text; + } + + #firstMatch(): number { + let first = -1; + for (const sequence of this.#sequences) { + const at = this.#pending.indexOf(sequence); + if (at !== -1 && (first === -1 || at < first)) first = at; + } + return first; + } +} + +/** + * Truncate a complete answer at the first `stop` delimiter. + * + * The buffered twin of `StopSequenceFilter`, so both paths return the same + * visible text. + */ +export function truncateAtStopSequences(text: string, sequences: readonly string[] | undefined): string { + if (sequences === undefined || sequences.length === 0) return text; + let first = -1; + for (const sequence of sequences) { + if (sequence.length === 0) continue; + const at = text.indexOf(sequence); + if (at !== -1 && (first === -1 || at < first)) first = at; + } + return first === -1 ? text : text.slice(0, first); +} + async function streamChat( ctx: AppContext, request: InternalRequest, @@ -626,6 +928,7 @@ async function streamChat( const id = `chatcmpl-${randomUUID().replace(/-/g, "")}`; const created = unixSeconds(); const base = { id, object: "chat.completion.chunk", created, model: request.model }; + const stopFilter = new StopSequenceFilter(request.stop ?? []); let writer: SseWriter | undefined; let started = false; @@ -657,12 +960,15 @@ async function streamChat( ensure(); break; - case "text_delta": + case "text_delta": { + const text = stopFilter.push(event.text); + if (text.length === 0) break; ensure().send({ ...base, - choices: [{ index: 0, delta: { content: event.text }, finish_reason: null }], + choices: [{ index: 0, delta: { content: text }, finish_reason: null }], }); break; + } case "reasoning_delta": { const delta: Record = { reasoning_content: event.text }; @@ -710,6 +1016,10 @@ async function streamChat( default: break; } + // Throttle the producer when the client is not reading: `send()` never + // blocks, so without this wait a slow reader would grow the write queue + // without bound (bounded by the writer's drain timeout). + if (writer !== undefined) await writer.drain(); } // A turn the upstream ended with `error` is a failure, not a completion: @@ -718,6 +1028,15 @@ async function streamChat( // the head is committed, and never a finish chunk or `[DONE]`. if (failure !== undefined) throw failure; + // Release the text the stop-delimiter lookahead held back, then finish. + const tail = stopFilter.finish(); + if (tail.length > 0) { + ensure().send({ + ...base, + choices: [{ index: 0, delta: { content: tail }, finish_reason: null }], + }); + } + const active = ensure(); active.send({ ...base, diff --git a/src/adapter/openai/completions.ts b/src/adapter/openai/completions.ts index ce81679..ef0c7d4 100644 --- a/src/adapter/openai/completions.ts +++ b/src/adapter/openai/completions.ts @@ -28,11 +28,16 @@ import { import type { CollectedCompletion } from "../../upstream/completion.js"; import type { ResolvedModel } from "../../upstream/models.js"; import { + assertHonouredParameters, headerValue, mapFinishReason, normaliseNullFields, openAiUsage, openCodeExtension, + rejectUnsupported, + StopSequenceFilter, + truncateAtStopSequences, + unappliedParameters, } from "./chat.js"; /** Metric label for this surface. */ @@ -47,12 +52,33 @@ const completionRequestSchema = z.object({ n: z.number().optional(), stream: z.boolean().optional(), stream_options: z.object({ include_usage: z.boolean().optional() }).optional(), + // Generation knobs the OpenCode agent loop owns: accepted and recorded, then + // reported through `x_opencode.unapplied` (see `chat.ts`). max_tokens: z.number().optional(), temperature: z.number().optional(), stop: z.union([z.string(), z.array(z.string())]).optional(), user: z.string().optional(), - // Accepted for API compatibility and deliberately unsupported. + // Generation knobs: accepted and recorded, reported through + // `x_opencode.unapplied` because the OpenCode agent loop owns them. + presence_penalty: z.unknown().optional(), + frequency_penalty: z.unknown().optional(), + seed: z.unknown().optional(), + logit_bias: z.unknown().optional(), + // Accepted for schema compatibility only; rejected with `unsupported_parameter`. echo: z.boolean().optional(), + logprobs: z.union([z.boolean(), z.number()]).optional(), + top_logprobs: z.number().optional(), + best_of: z.number().optional(), + suffix: z.string().optional(), + // The same fields the other OpenAI surfaces reject, so all three answer the + // same way for a field none of them can honour. + modalities: z.array(z.string()).optional(), + audio: z.unknown().optional(), + prediction: z.unknown().optional(), + store: z.boolean().optional(), + web_search_options: z.unknown().optional(), + functions: z.array(z.unknown()).optional(), + function_call: z.union([z.string(), z.object({ name: z.string().min(1) }).passthrough()]).optional(), }); type CompletionRequest = z.infer; @@ -69,6 +95,10 @@ function parseCompletionRequest(body: unknown): CompletionRequest { export function registerOpenAiCompletionRoutes(app: FastifyInstance, ctx: AppContext): void { app.post("/v1/completions", async (request, reply) => { const body = parseCompletionRequest(request.body); + assertHonouredParameters(body); + // Generation knobs stay accepted: they are recorded on the internal request + // and echoed back as `x_opencode.unapplied`. + const unapplied = unappliedParameters(body); if (body.echo === true) { throw ApiError.badRequest("`echo` is not supported by this gateway.", { @@ -77,6 +107,13 @@ export function registerOpenAiCompletionRoutes(app: FastifyInstance, ctx: AppCon }); } + if (body.best_of !== undefined) { + rejectUnsupported("best_of", "the gateway produces exactly one completion per request"); + } + if (body.suffix !== undefined) { + rejectUnsupported("suffix", "the OpenCode runtime cannot insert a suffix"); + } + if (body.n !== undefined && body.n !== 1) { throw ApiError.badRequest("Only `n: 1` is supported by this gateway.", { code: "invalid_request", @@ -109,7 +146,11 @@ export function registerOpenAiCompletionRoutes(app: FastifyInstance, ctx: AppCon signal: abort.signal, }); if (collected.finishReason === "error") throw failedTurnError(); - return reply.send(completionBody(collected)); + // `stop` is enforced on the visible text only, exactly like the streamed + // path; the upstream turn is not interrupted (same trade-off as the + // Anthropic surface's `stop_sequences`). + const text = truncateAtStopSequences(collected.text, internal.stop); + return reply.send(completionBody({ ...collected, text }, unapplied)); } await streamCompletion(ctx, internal, reply, { @@ -138,6 +179,9 @@ function buildRequest(body: CompletionRequest, resolved: ResolvedModel): Interna }; if (resolved.variant !== undefined) internal.variant = resolved.variant; + // Accepted and recorded, but not forwarded: the OpenCode agent loop owns the + // sampling parameters and the generation budget; `x_opencode.unapplied` names + // every such field the caller supplied. if (typeof body.temperature === "number") internal.temperature = body.temperature; if (typeof body.max_tokens === "number") internal.maxTokens = body.max_tokens; @@ -155,7 +199,7 @@ function normaliseStop(stop: string | string[] | undefined): string[] | undefine // --------------------------------------------------------- non-streaming out --- -function completionBody(collected: CollectedCompletion): Record { +function completionBody(collected: CollectedCompletion, unapplied: readonly string[] = []): Record { return { id: `cmpl-${randomUUID().replace(/-/g, "")}`, object: "text_completion", @@ -170,7 +214,7 @@ function completionBody(collected: CollectedCompletion): Record }, ], usage: openAiUsage(collected.usage), - x_opencode: openCodeExtension(collected), + x_opencode: openCodeExtension(collected, unapplied), }; } @@ -190,6 +234,7 @@ async function streamCompletion( const id = `cmpl-${randomUUID().replace(/-/g, "")}`; const created = unixSeconds(); const base = { id, object: "text_completion", created, model: request.model }; + const stopFilter = new StopSequenceFilter(request.stop ?? []); let writer: SseWriter | undefined; let startEmitted = false; @@ -221,9 +266,11 @@ async function streamCompletion( ensure(); break; - case "text_delta": - ensure().send(chunk(event.text, null)); + case "text_delta": { + const text = stopFilter.push(event.text); + if (text.length > 0) ensure().send(chunk(text, null)); break; + } case "usage": usage = event.usage; @@ -245,6 +292,10 @@ async function streamCompletion( // representation in the legacy completions wire format. break; } + // Throttle the producer when the client is not reading: `send()` never + // blocks, so without this wait a slow reader would grow the write queue + // without bound (bounded by the writer's drain timeout). + if (writer !== undefined) await writer.drain(); } // A turn the upstream ended with `error` is a failure, not a completion: @@ -253,6 +304,10 @@ async function streamCompletion( // the head is committed, and never a finish chunk or `[DONE]`. if (failure !== undefined) throw failure; + // Release the text the stop-delimiter lookahead held back, then finish. + const tail = stopFilter.finish(); + if (tail.length > 0) ensure().send(chunk(tail, null)); + const active = ensure(); active.send(chunk("", mapFinishReason(finishReason))); if (options.includeUsage) { diff --git a/test/openai-chat.test.ts b/test/openai-chat.test.ts index a6d26b2..abe1bd0 100644 --- a/test/openai-chat.test.ts +++ b/test/openai-chat.test.ts @@ -4,6 +4,8 @@ import { afterEach, describe, expect, it } from "vitest"; import http from "node:http"; import type { AddressInfo } from "node:net"; +import { createToolBridge } from "../src/adapter/common/tools.js"; +import type { AppContext } from "../src/context.js"; import { ApiError } from "../src/errors.js"; import { buildServer } from "../src/server.js"; import { EMPTY_USAGE, type CompletionEvent, type InternalRequest, type Usage } from "../src/types/internal.js"; @@ -144,7 +146,7 @@ describe("POST /v1/chat/completions (non-streaming)", () => { await app.close(); }); - it("accepts and ignores unsupported OpenAI fields", async () => { + it("still accepts the compatibility fields it can honour", async () => { const app = await buildServer(createTestContext()); const response = await app.inject({ method: "POST", @@ -153,12 +155,11 @@ describe("POST /v1/chat/completions (non-streaming)", () => { payload: { model: MODEL, messages: [{ role: "user", content: "Hi" }], - seed: 7, - logprobs: true, - top_logprobs: 3, - logit_bias: { "123": 1 }, - presence_penalty: 0.5, - frequency_penalty: 0.25, + logprobs: false, + store: false, + modalities: ["text"], + function_call: "none", + functions: [], response_format: { type: "json_object" }, service_tier: "auto", parallel_tool_calls: false, @@ -167,7 +168,136 @@ describe("POST /v1/chat/completions (non-streaming)", () => { }); expect(response.statusCode).toBe(200); - expect((response.json() as ChatBody).choices[0]?.message.content).toBe("Hello world"); + const body = response.json() as ChatBody; + expect(body.choices[0]?.message.content).toBe("Hello world"); + // Nothing unapplied was supplied, so the key stays absent. + expect(body.x_opencode["unapplied"]).toBeUndefined(); + await app.close(); + }); + + it("records the generation knobs and names them in x_opencode.unapplied", async () => { + const captured: InternalRequest[] = []; + const app = await buildServer(createTestContext({ onRun: (request) => captured.push(request) })); + const response = await app.inject({ + method: "POST", + url: "/v1/chat/completions", + headers: AUTH, + payload: { + model: MODEL, + messages: [{ role: "user", content: "Hi" }], + temperature: 0.5, + top_p: 0.9, + presence_penalty: 0.5, + seed: 7, + max_completion_tokens: 16, + }, + }); + + expect(response.statusCode).toBe(200); + const body = response.json() as ChatBody; + expect(captured[0]?.temperature).toBe(0.5); + expect(captured[0]?.topP).toBe(0.9); + expect(captured[0]?.maxTokens).toBe(16); + // Stable order, and exactly the fields that were supplied. + expect(body.x_opencode["unapplied"]).toEqual([ + "temperature", + "top_p", + "presence_penalty", + "seed", + "max_completion_tokens", + ]); + await app.close(); + }); + + it("rejects every field that changes the response shape with 400 unsupported_parameter", async () => { + const app = await buildServer(createTestContext()); + const rejections: Array<{ field: string; payload: Record; param: string }> = [ + { field: "logprobs", payload: { logprobs: true }, param: "logprobs" }, + { field: "top_logprobs", payload: { top_logprobs: 3 }, param: "top_logprobs" }, + { field: "modalities", payload: { modalities: ["text", "audio"] }, param: "modalities" }, + { field: "audio", payload: { audio: { voice: "alloy" } }, param: "audio" }, + { field: "prediction", payload: { prediction: { type: "content", content: "x" } }, param: "prediction" }, + { field: "store", payload: { store: true }, param: "store" }, + { field: "web_search_options", payload: { web_search_options: {} }, param: "web_search_options" }, + { field: "functions", payload: { functions: [{ name: "lookup" }] }, param: "functions" }, + { field: "function_call", payload: { function_call: "auto" }, param: "function_call" }, + ]; + + for (const { field, payload, param } of rejections) { + const response = await app.inject({ + method: "POST", + url: "/v1/chat/completions", + headers: AUTH, + payload: { model: MODEL, messages: [{ role: "user", content: "Hi" }], ...payload }, + }); + expect(response.statusCode, `${field} must be rejected`).toBe(400); + const body = response.json() as { error: { code: string; param: string | null } }; + expect(body.error.code, `${field} must be unsupported_parameter`).toBe("unsupported_parameter"); + expect(body.error.param, `${field} must name itself`).toBe(param); + } + + await app.close(); + }); + + it("rejects a non-auto image_url.detail instead of silently sending full media", async () => { + const app = await buildServer(createTestContext()); + const response = await app.inject({ + method: "POST", + url: "/v1/chat/completions", + headers: AUTH, + payload: { + model: MODEL, + messages: [ + { + role: "user", + content: [ + { type: "text", text: "what is this?" }, + { type: "image_url", image_url: { url: "data:image/png;base64,AAAA", detail: "low" } }, + ], + }, + ], + }, + }); + + expect(response.statusCode).toBe(400); + const body = response.json() as { error: { code: string; param: string | null; message: string } }; + expect(body.error.code).toBe("unsupported_parameter"); + expect(body.error.param).toBe("messages"); + expect(body.error.message).toContain("detail"); + await app.close(); + }); + + it("rejects a tool_choice naming an undeclared tool", async () => { + // The real `runCompletion` builds the shared tool bridge; the scripted test + // runner replaces it, so invoke the same assertion the orchestrator runs. + const base = createTestContext(); + const ctx: AppContext = { + ...base, + completion: { + ...base.completion, + collect: async (request, deps, options) => { + createToolBridge(request.tools, request.toolChoice); + return base.completion.collect(request, deps, options); + }, + }, + }; + const app = await buildServer(ctx); + const response = await app.inject({ + method: "POST", + url: "/v1/chat/completions", + headers: AUTH, + payload: { + model: MODEL, + messages: [{ role: "user", content: "Hi" }], + tools: [{ type: "function", function: { name: "declared" } }], + tool_choice: { type: "function", function: { name: "undeclared" } }, + }, + }); + + expect(response.statusCode).toBe(400); + const body = response.json() as { error: { code: string; param: string | null } }; + expect(body.error.code).toBe("invalid_request"); + expect(body.error.param).toBe("tool_choice"); await app.close(); }); @@ -558,7 +688,8 @@ describe("POST /v1/chat/completions (non-streaming)", () => { const fixture = await startPngFixture(DELAY_MS); try { const captured: InternalRequest[] = []; - const ctx = createTestContext({ onRun: (request) => captured.push(request) }); + // The fixture listens on loopback, which is blocked by default (SSRF guard). + const ctx = createTestContext({ config: { allowPrivateMediaUrls: true }, onRun: (request) => captured.push(request) }); const app = await buildServer(ctx); const startedAt = Date.now(); @@ -598,6 +729,45 @@ describe("POST /v1/chat/completions (non-streaming)", () => { } }); + it("downloads the attachments of different messages concurrently (one pool per request)", async () => { + const DELAY_MS = 80; + const fixture = await startPngFixture(DELAY_MS); + try { + const captured: InternalRequest[] = []; + const ctx = createTestContext({ config: { allowPrivateMediaUrls: true }, onRun: (request) => captured.push(request) }); + const app = await buildServer(ctx); + + const startedAt = Date.now(); + const response = await app.inject({ + method: "POST", + url: "/v1/chat/completions", + headers: AUTH, + payload: { + model: MODEL, + messages: [ + { role: "user", content: [{ type: "image_url", image_url: { url: `${fixture.origin}/first.png` } }] }, + { role: "assistant", content: "ok" }, + { role: "user", content: [{ type: "image_url", image_url: { url: `${fixture.origin}/second.png` } }] }, + ], + }, + }); + const elapsed = Date.now() - startedAt; + + expect(response.statusCode).toBe(200); + const attachments = captured[0]?.messages.flatMap((message) => message.attachments ?? []) ?? []; + expect(attachments.map((attachment) => attachment.origin)).toEqual([ + `${fixture.origin}/first.png`, + `${fixture.origin}/second.png`, + ]); + // Resolving message by message serialises the pools: two fixture delays. + expect(elapsed).toBeLessThan(DELAY_MS * 2 - 40); + + await app.close(); + } finally { + await fixture.close(); + } + }); + it("fetches no more media than the request budget allows", async () => { const cap = testConfig().maxAttachments; const body = Buffer.from(PNG_BASE64, "base64"); @@ -612,7 +782,10 @@ describe("POST /v1/chat/completions (non-streaming)", () => { try { const captured: InternalRequest[] = []; - const ctx = createTestContext({ onRun: (request) => captured.push(request) }); + const ctx = createTestContext({ + config: { allowPrivateMediaUrls: true }, + 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` } }; @@ -638,6 +811,10 @@ describe("POST /v1/chat/completions (non-streaming)", () => { expect(attachments).toHaveLength(cap); const promptText = (captured[0]?.messages ?? []).map((message) => message.text).join("\n"); expect(promptText).toContain("attachments omitted"); + // The omission is reported on the message that declared the extra parts, + // with a message-local index (the first one), not the flat request index. + expect(captured[0]?.messages[1]?.text).toContain("attachment #1"); + expect(captured[0]?.messages[0]?.text).not.toContain("attachments omitted"); await app.close(); } finally { @@ -662,7 +839,7 @@ describe("POST /v1/chat/completions (non-streaming)", () => { await app.close(); }); - it("normalises messages, headers and sampling fields into the internal request", async () => { + it("normalises messages, headers and the stop field into the internal request", async () => { const captured: InternalRequest[] = []; const ctx = createTestContext({ onRun: (request) => captured.push(request) }); const app = await buildServer(ctx); @@ -690,10 +867,10 @@ describe("POST /v1/chat/completions (non-streaming)", () => { { role: "tool", tool_call_id: "call_9", name: "lookup", content: "42" }, { role: "user", content: "go" }, ], + stop: "END", temperature: 0.3, top_p: 0.9, max_completion_tokens: 128, - stop: "END", tool_choice: { type: "function", function: { name: "lookup" } }, metadata: { trace: "t1" }, }, @@ -706,6 +883,8 @@ describe("POST /v1/chat/completions (non-streaming)", () => { expect(request?.stream).toBe(false); expect(request?.conversationKey).toBe("conv-1"); expect(request?.agent).toBe("plan"); + // The generation knobs are accepted and recorded; they are reported to the + // caller through `x_opencode.unapplied` (covered by their own test). expect(request?.temperature).toBe(0.3); expect(request?.topP).toBe(0.9); expect(request?.maxTokens).toBe(128); @@ -723,6 +902,49 @@ describe("POST /v1/chat/completions (non-streaming)", () => { await app.close(); }); + it("truncates the visible answer at the first stop delimiter (buffered)", async () => { + const app = await buildServer(createTestContext()); + const response = await app.inject({ + method: "POST", + url: "/v1/chat/completions", + headers: AUTH, + payload: { + model: MODEL, + messages: [{ role: "user", content: "Hi" }], + stop: [" world"], + }, + }); + + expect(response.statusCode).toBe(200); + const body = response.json() as ChatBody; + expect(body.choices[0]?.message.content).toBe("Hello"); + expect(body.choices[0]?.finish_reason).toBe("stop"); + await app.close(); + }); + + it("truncates the visible answer at the first stop delimiter (streamed)", async () => { + const app = await buildServer(createTestContext()); + const response = await app.inject({ + method: "POST", + url: "/v1/chat/completions", + headers: AUTH, + payload: { + model: MODEL, + messages: [{ role: "user", content: "Hi" }], + stop: ["lo w"], + stream: true, + }, + }); + + expect(response.statusCode).toBe(200); + const chunks = parseSseJson(response.body).map((frame) => frame.json); + const text = chunks.map((chunk) => chunk.choices[0]?.delta?.["content"] ?? "").join(""); + // The delimiter spans the "Hello" / " world" delta boundary. + expect(text).toBe("Hel"); + expect(chunks.at(-1)?.choices[0]?.finish_reason).toBe("stop"); + 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[] => [ diff --git a/test/openai-completions.test.ts b/test/openai-completions.test.ts index 592278b..9cc2971 100644 --- a/test/openai-completions.test.ts +++ b/test/openai-completions.test.ts @@ -60,7 +60,7 @@ describe("POST /v1/completions (non-streaming)", () => { method: "POST", url: "/v1/completions", headers: AUTH, - payload: { model: MODEL, prompt: "Say hello", max_tokens: 32, temperature: 0.2, stop: "END", user: "u-1" }, + payload: { model: MODEL, prompt: "Say hello", stop: "END", temperature: 0.2, max_tokens: 32, user: "u-1" }, }); expect(response.statusCode).toBe(200); @@ -86,10 +86,12 @@ describe("POST /v1/completions (non-streaming)", () => { reused_session: false, reasoning: { enabled: false, note: null }, native_tool_calls: [], + unapplied: ["temperature", "max_tokens"], }); expect(captured[0]?.surface).toBe("openai.completions"); expect(captured[0]?.messages).toEqual([{ role: "user", text: "Say hello" }]); + // Accepted and recorded; `x_opencode.unapplied` says they were not applied. expect(captured[0]?.maxTokens).toBe(32); expect(captured[0]?.temperature).toBe(0.2); expect(captured[0]?.stop).toEqual(["END"]); @@ -98,6 +100,84 @@ describe("POST /v1/completions (non-streaming)", () => { await app.close(); }); + it("omits x_opencode.unapplied when no generation knob was supplied", async () => { + const ctx = createTestContext({ script: textScript }); + const app = await buildCompletionServer(ctx); + const response = await app.inject({ + method: "POST", + url: "/v1/completions", + headers: AUTH, + payload: { model: MODEL, prompt: "Say hello" }, + }); + + expect(response.statusCode).toBe(200); + expect((response.json() as CompletionBody).x_opencode["unapplied"]).toBeUndefined(); + await app.close(); + }); + + it("rejects every field that changes the response shape with 400 unsupported_parameter", async () => { + const ctx = createTestContext({ script: textScript }); + const app = await buildCompletionServer(ctx); + const rejections: Array<{ field: string; payload: Record; param: string }> = [ + { field: "logprobs", payload: { logprobs: 2 }, param: "logprobs" }, + { field: "top_logprobs", payload: { top_logprobs: 2 }, param: "top_logprobs" }, + { field: "best_of", payload: { best_of: 2 }, param: "best_of" }, + { field: "suffix", payload: { suffix: "end" }, param: "suffix" }, + { field: "modalities", payload: { modalities: ["text", "audio"] }, param: "modalities" }, + { field: "store", payload: { store: true }, param: "store" }, + { field: "functions", payload: { functions: [{ name: "lookup" }] }, param: "functions" }, + ]; + + for (const { field, payload, param } of rejections) { + const response = await app.inject({ + method: "POST", + url: "/v1/completions", + headers: AUTH, + payload: { model: MODEL, prompt: "hi", ...payload }, + }); + expect(response.statusCode, `${field} must be rejected`).toBe(400); + const body = response.json() as { error: { code: string; param: string | null } }; + expect(body.error.code, `${field} must be unsupported_parameter`).toBe("unsupported_parameter"); + expect(body.error.param, `${field} must name itself`).toBe(param); + } + + // `logprobs: false` and `logprobs: 0` request nothing and are accepted. + for (const logprobs of [false, 0]) { + const accepted = await app.inject({ + method: "POST", + url: "/v1/completions", + headers: AUTH, + payload: { model: MODEL, prompt: "hi", logprobs }, + }); + expect(accepted.statusCode).toBe(200); + } + + await app.close(); + }); + + it("truncates the visible completion at the first stop delimiter on both paths", async () => { + const ctx = createTestContext({ script: textScript }); + const app = await buildCompletionServer(ctx); + const payload = { model: MODEL, prompt: "Say hello", stop: [" world"] }; + + const buffered = await app.inject({ method: "POST", url: "/v1/completions", headers: AUTH, payload }); + expect(buffered.statusCode).toBe(200); + expect((buffered.json() as CompletionBody).choices[0]?.text).toBe("Hello"); + + const streamed = await app.inject({ + method: "POST", + url: "/v1/completions", + headers: AUTH, + payload: { ...payload, stream: true }, + }); + expect(streamed.statusCode).toBe(200); + const chunks = parseSseJson<{ choices: CompletionChoice[] }>(streamed.body).map((frame) => frame.json); + const text = chunks.map((chunk) => chunk.choices[0]?.text ?? "").join(""); + expect(text).toBe("Hello"); + + await app.close(); + }); + it("forwards x-conversation-id and x-opencode-agent", async () => { const captured: InternalRequest[] = []; const ctx = createTestContext({ onRun: (request) => captured.push(request) }); diff --git a/test/tools.test.ts b/test/tools.test.ts index 457d21f..e3750b3 100644 --- a/test/tools.test.ts +++ b/test/tools.test.ts @@ -46,7 +46,19 @@ describe("tool bridge instructions", () => { it("reflects the requested tool choice", () => { expect(createToolBridge([WEATHER], "required").instructions).toContain("requires a tool call"); expect(createToolBridge([WEATHER], { name: "get_weather" }).instructions).toContain("exactly one tool call"); - expect(createToolBridge([WEATHER], { name: "unknown" }).instructions).toContain("unknown tool"); + }); + + it("rejects a tool_choice naming a tool the request did not declare", () => { + // Real OpenAI answers 400; rendering "explain that the tool is unavailable" + // instead ran the turn and returned prose with finish_reason "stop". + let caught: unknown; + try { + createToolBridge([WEATHER], { name: "unknown" }); + } catch (error) { + caught = error; + } + expect(caught).toMatchObject({ status: 400, code: "invalid_request", param: "tool_choice" }); + expect((caught as Error).message).toContain("unknown tool 'unknown'"); }); it("asks for at most one call when parallel tool calls are disabled", () => { @@ -302,6 +314,28 @@ describe("ToolCallFilter", () => { expect(tail.calls).toHaveLength(1); expect(JSON.parse(tail.calls[0]?.arguments ?? "null")).toEqual({ text: "a,}" }); }); + + it("scans each delta once instead of rescanning the whole envelope", () => { + // The old implementation re-concatenated the accumulated envelope and + // searched it from the start on every delta: a 64 KB payload delivered in + // 1 KB chunks scanned roughly 2 GB cumulatively. The counter is the only + // way to observe that on a primitive `string`; linear means the examined + // character count stays close to the payload size, not its square. + const blob = "x".repeat(64 * 1024); + const payload = envelope({ name: "big", arguments: { blob } }); + const chunkSize = 1024; + const filter = new ToolCallFilter(); + let text = ""; + for (let offset = 0; offset < payload.length; offset += chunkSize) { + text += filter.push(payload.slice(offset, offset + chunkSize)); + } + const tail = filter.finish(); + + expect(text + tail.text).toBe(""); + expect(tail.calls).toHaveLength(1); + expect(JSON.parse(tail.calls[0]?.arguments ?? "null")).toEqual({ blob }); + expect(filter.scannedCharacters).toBeLessThan(payload.length * 3); + }); }); describe("transcript rendering", () => { From 5ce755f90ffade82996b236cec9d428dffbf36d1 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Ph=E1=BA=A1m=20V=C4=83n=20=C4=90=E1=BB=8Bnh?= Date: Thu, 3 Dec 2026 12:08:58 +0700 Subject: [PATCH 04/12] fix(anthropic): validate the schema and report failed turns max_tokens is required by the Anthropic schema but accepted zero and negative values, a turn the upstream reported as failed was rendered as a successful end_turn with partial text, a streamed message_start advertised zero usage while the docs presented it as the usage carrier, thinking.effort was advertised as tolerated but stripped by the schema, and disable_parallel_tool_use was ignored even though the bridge supports capping the turn at one call. Require an integer of at least 1, answer a failed turn with 502 api_error when buffered and a terminal error event when streamed, mark a cancelled turn with x_opencode.interrupted, accept thinking.effort, and honour disable_parallel_tool_use. count_tokens now charges inline media with a documented bytes-per-token constant instead of a fixed placeholder, so a large image is no longer counted as five tokens. --- src/adapter/anthropic/countTokens.ts | 10 +- src/adapter/anthropic/messages.ts | 121 +++++++++++++- test/anthropic-count-tokens.test.ts | 32 ++++ test/anthropic.test.ts | 236 ++++++++++++++++++++++++++- 4 files changed, 389 insertions(+), 10 deletions(-) diff --git a/src/adapter/anthropic/countTokens.ts b/src/adapter/anthropic/countTokens.ts index 19b4d32..9dfb019 100644 --- a/src/adapter/anthropic/countTokens.ts +++ b/src/adapter/anthropic/countTokens.ts @@ -21,6 +21,7 @@ import type { InternalRequest } from "../../types/internal.js"; import { createToolBridge } from "../common/tools.js"; import { estimateConversationTokens, estimateTokens } from "../common/usage.js"; import { + estimateMediaTokens, parseAnthropicCountTokensBody, toInternalRequest, type AnthropicCountTokensBody, @@ -74,9 +75,14 @@ export function registerAnthropicCountTokenRoutes(app: FastifyInstance, ctx: App resolveMedia: false, }); + // Inline media still costs prompt tokens even though it is never downloaded + // here: charge the documented per-byte constant so a large image no longer + // looks like a five-token placeholder. + const mediaTokens = estimateMediaTokens(body); + return reply.status(200).send({ - input_tokens: estimateRequestTokens(internal), - x_opencode: { estimated: true, method: "mixed" }, + input_tokens: Math.max(1, estimateRequestTokens(internal) + mediaTokens), + x_opencode: { estimated: true, method: mediaTokens > 0 ? "mixed+media" : "mixed" }, }); }); } diff --git a/src/adapter/anthropic/messages.ts b/src/adapter/anthropic/messages.ts index e9c7ac2..44f0ee8 100644 --- a/src/adapter/anthropic/messages.ts +++ b/src/adapter/anthropic/messages.ts @@ -162,23 +162,33 @@ const toolSchema = z.object({ cache_control: cacheControlSchema, }); +/** + * Requested tool choice. + * + * `disable_parallel_tool_use` is part of the Anthropic contract on the `auto`, + * `any` and `tool` variants; it maps onto `InternalRequest.parallelToolCalls`. + */ const toolChoiceSchema = z.discriminatedUnion("type", [ - z.object({ type: z.literal("auto") }), - z.object({ type: z.literal("any") }), + z.object({ type: z.literal("auto"), disable_parallel_tool_use: z.boolean().optional() }), + z.object({ type: z.literal("any"), disable_parallel_tool_use: z.boolean().optional() }), z.object({ type: z.literal("none") }), - z.object({ type: z.literal("tool"), name: z.string() }), + z.object({ type: z.literal("tool"), name: z.string(), disable_parallel_tool_use: z.boolean().optional() }), ]); const thinkingSchema = z.object({ type: z.enum(["enabled", "disabled"]), budget_tokens: z.number().optional(), + /** Non-standard convenience alias mapped by `reasoningFromThinking()`. */ + effort: z.string().optional(), }); /** Request schema of `POST /v1/messages`. */ const anthropicMessageBaseSchema = z.object({ model: z.string().min(1), messages: z.array(messageSchema).min(1), - max_tokens: z.number(), + // Anthropic requires a positive integer; `0` and negative values used to be + // accepted and reached the orchestrator unchanged. + max_tokens: z.number().int().min(1), system: systemSchema.optional(), stream: z.boolean().optional(), temperature: z.number().optional(), @@ -208,7 +218,7 @@ export const anthropicMessagesSchema = anthropicMessageBaseSchema; /** Request schema of `POST /v1/messages/count_tokens` (`max_tokens` optional). */ export const anthropicCountTokensSchema = anthropicMessageBaseSchema.extend({ - max_tokens: z.number().optional(), + max_tokens: z.number().int().min(1).optional(), }); export type AnthropicMessagesBody = z.infer; @@ -260,6 +270,8 @@ export interface AnthropicOpenCodeExtension { variant: string | null; reused_session: boolean; native_tool_calls: number; + /** True when the turn was cancelled (the upstream reported `cancelled`). */ + interrupted: boolean; } export interface AnthropicMessageResponse { @@ -613,11 +625,64 @@ export async function toInternalRequest( if (stopSequences.length > 0) request.stop = stopSequences; const toolChoice = mapToolChoice(body.tool_choice); if (toolChoice !== undefined) request.toolChoice = toolChoice; + // Anthropic's `disable_parallel_tool_use` maps onto the bridge's existing + // parallel-call control. `none` has no such field (and no tool call at all). + if (body.tool_choice !== undefined && body.tool_choice.type !== "none") { + request.parallelToolCalls = body.tool_choice.disable_parallel_tool_use !== true; + } if (body.metadata !== undefined) request.metadata = { ...body.metadata }; return request; } +/** Bytes per token charged for inline media by the `count_tokens` estimate. */ +export const MEDIA_BYTES_PER_TOKEN = 750; + +/** + * Decoded length of a base64 payload without decoding it. + * + * `count_tokens` must stay cheap: a 20 MiB attachment is ~27 MiB of base64 in + * the request body, and decoding it only to count its size would double the + * memory cost of the endpoint. + */ +export function base64DecodedBytes(payload: string): number { + const cleaned = payload.replace(/\s+/g, ""); + const withoutPadding = cleaned.replace(/={1,2}$/, ""); + return Math.floor((withoutPadding.length * 3) / 4); +} + +/** + * Prompt-token cost of the media blocks a request declares. + * + * The gateway cannot read image dimensions without downloading the media, which + * `count_tokens` deliberately does not do. Instead every inline `base64` source + * is charged `ceil(decodedBytes / 750)` — a documented per-byte constant — so a + * large image no longer collapses to a ~5-token placeholder and the estimate + * stays usable for pre-flight context checks. `url` sources remain placeholders + * because their size is unknown. + */ +export function estimateMediaTokens(body: AnthropicRequestInput): number { + let bytes = 0; + const addSource = (source: MediaBlock["source"]): void => { + if (source.type === "base64") bytes += base64DecodedBytes(source.data); + }; + + for (const message of body.messages) { + if (typeof message.content === "string") continue; + for (const block of message.content) { + if (block.type === "image" || block.type === "document" || block.type === "audio" || block.type === "video") { + addSource(block.source); + } + if (block.type !== "tool_result" || typeof block.content === "string" || block.content === undefined) continue; + for (const nested of block.content) { + if (nested.type === "image" || nested.type === "document") addSource(nested.source); + } + } + } + + return bytes === 0 ? 0 : Math.ceil(bytes / MEDIA_BYTES_PER_TOKEN); +} + // ------------------------------------------------------ response shaping --- /** @@ -673,9 +738,12 @@ function mapStopReason(finishReason: FinishReason, calls: ToolCall[], toolsOffer return "tool_use"; case "content_filter": return "refusal"; - case "stop": case "error": + // A failed turn is never reported as a normally finished one; the route + // answers 502 (buffered) or an `error` event (streamed) before this runs. + return null; case "cancelled": + case "stop": default: return "end_turn"; } @@ -831,6 +899,14 @@ export function renderAnthropicMessage( request: InternalRequest, stopSequence: string | null = null, ): AnthropicMessageResponse { + // A turn the upstream reported as failed is not a normal `end_turn`: the + // caller must see a real error instead of a 200 carrying partial text. + if (collected.finishReason === "error") { + throw new ApiError(502, "upstream_error", "The OpenCode turn failed before it could complete.", { + code: "upstream_error", + }); + } + const id = newMessageId(); const content: AnthropicContentBlock[] = []; @@ -868,6 +944,9 @@ export function renderAnthropicMessage( variant: collected.variant ?? null, reused_session: collected.reusedSession, native_tool_calls: collected.nativeTools.length, + // `cancelled` is not a normal finish: the answer is incomplete, and the + // caller needs to be able to tell that from a complete `end_turn`. + interrupted: collected.finishReason === "cancelled", }, }; } @@ -896,6 +975,9 @@ async function streamAnthropicMessage( ): Promise { const writer = new SseWriter(reply); ctx.metrics.activeStreams.inc({ surface: ANTHROPIC_MESSAGES_SURFACE }); + // The writer observes its own socket: a dead reader aborts the upstream turn + // even though the disconnect signal is the primary cancellation source. + const runSignal = AbortSignal.any([signal, writer.closedSignal]); let opened = false; try { @@ -970,7 +1052,7 @@ async function streamAnthropicMessage( ); }; - const stream = ctx.completion.run(request, completionDeps(ctx), { signal }); + const stream = ctx.completion.run(request, completionDeps(ctx), { signal: runSignal }); try { for await (const event of stream) { @@ -990,6 +1072,9 @@ async function streamAnthropicMessage( content: [], stop_reason: null, stop_sequence: null, + // Kept at zero on purpose: usage is only known once the turn + // ends, and the authoritative numbers travel in `message_delta`. + // This is documented in docs/API.md §4. usage: { input_tokens: 0, output_tokens: 0 }, }, }, @@ -1061,6 +1146,10 @@ async function streamAnthropicMessage( default: break; } + // Throttle the producer when the client is not reading: `send()` never + // blocks, so without this wait a slow reader would grow the write queue + // without bound (bounded by the writer's drain timeout). + await writer.drain(); } } catch (error) { if (!opened) throw error; @@ -1068,6 +1157,21 @@ async function streamAnthropicMessage( return reply; } + // The upstream reported a failed turn (`finishReason: "error"`). The HTTP + // status is already committed, so the failure travels as an `error` event + // instead of a synthetic `end_turn` the caller would read as success. + if (finishReason === "error") { + send( + anthropicErrorFrame( + new ApiError(502, "upstream_error", "The OpenCode turn failed before it could complete.", { + code: "upstream_error", + }), + ), + "error", + ); + 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 @@ -1111,6 +1215,9 @@ async function streamAnthropicMessage( cache_read_input_tokens: usage.cacheReadTokens, cache_creation_input_tokens: usage.cacheWriteTokens, }, + // `cancelled` keeps `end_turn` but is flagged, so a client can tell an + // interrupted answer from a complete one. + ...(finishReason === "cancelled" ? { x_opencode: { interrupted: true } } : {}), }, "message_delta", ); diff --git a/test/anthropic-count-tokens.test.ts b/test/anthropic-count-tokens.test.ts index 94e4d51..0d3805e 100644 --- a/test/anthropic-count-tokens.test.ts +++ b/test/anthropic-count-tokens.test.ts @@ -118,4 +118,36 @@ describe("POST /v1/messages/count_tokens estimate", () => { // `count_tokens` never fetches or decodes media, so nothing is attached. expect(internal.messages.every((message) => (message.attachments ?? []).length === 0)).toBe(true); }); + + it("charges inline media by decoded size and reports mixed+media (A8)", async () => { + const app = await server(); + // 150_000 decoded bytes: 200 tokens at the documented 750 bytes/token. + const largeImage = Buffer.alloc(150_000, 7).toString("base64"); + + const response = await app.inject({ + method: "POST", + url: "/v1/messages/count_tokens", + headers: { ...AUTH, "content-type": "application/json" }, + payload: { + model: MODEL, + messages: [ + { + role: "user", + content: [ + { type: "text", text: "Describe this" }, + { type: "image", source: { type: "base64", media_type: "image/png", data: largeImage } }, + ], + }, + ], + }, + }); + + expect(response.statusCode).toBe(200); + const body = JSON.parse(response.body) as { input_tokens: number; x_opencode: { method: string } }; + expect(body.x_opencode.method).toBe("mixed+media"); + expect(body.input_tokens).toBeGreaterThanOrEqual(200); + + // A text-only request stays exactly what it was before the media charge. + expect(await estimateInputTokens(app, { model: MODEL, messages: [{ role: "user", content: "hi" }] })).toBe(5); + }); }); diff --git a/test/anthropic.test.ts b/test/anthropic.test.ts index 3b6d408..411e60f 100644 --- a/test/anthropic.test.ts +++ b/test/anthropic.test.ts @@ -59,7 +59,8 @@ interface StreamFrame { text?: string; }; usage?: Record; - message?: { id?: string; model?: string; role?: string }; + message?: { id?: string; model?: string; role?: string; usage?: Record }; + x_opencode?: { interrupted?: boolean }; } function usage(inputTokens: number, outputTokens: number, reasoningTokens = 0): Usage { @@ -132,6 +133,7 @@ describe("POST /v1/messages", () => { variant: null, reused_session: false, native_tool_calls: 0, + interrupted: false, }); // The Anthropic spec has no `object` field. expect((body as unknown as Record)["object"]).toBeUndefined(); @@ -326,6 +328,9 @@ describe("POST /v1/messages", () => { const capture: { request?: InternalRequest } = {}; const { app } = await serverWith({ + // The fixture only exists on loopback, which the default configuration + // now refuses (A1); this test is about concurrent media resolution. + config: { allowPrivateMediaUrls: true }, onRun: (request) => { capture.request = request; }, @@ -1188,3 +1193,232 @@ describe("POST /v1/messages/count_tokens", () => { expect(error.error.type).toBe("not_found_error"); }); }); + +// ------------------------------------------------------------------ A2-A13 --- + +const START: CompletionEvent = { + kind: "start", + sessionId: "ses_hardening", + messageId: "msg_hardening", + model: CANONICAL_MODEL, + agent: "build", + reusedSession: false, + reasoningEnabled: false, +}; + +describe("max_tokens validation (A5)", () => { + it("rejects 0 and negative values on both endpoints", async () => { + const { app } = await serverWith(); + for (const maxTokens of [0, -5]) { + const messages = await post(app, "/v1/messages", { + model: MODEL, + max_tokens: maxTokens, + messages: [{ role: "user", content: "hi" }], + }); + expect(messages.statusCode).toBe(400); + const error = JSON.parse(messages.body) as AnthropicErrorBody; + expect(error.type).toBe("error"); + expect(error.error.type).toBe("invalid_request_error"); + expect(error.error.message).toContain("max_tokens"); + + const count = await post(app, "/v1/messages/count_tokens", { + model: MODEL, + max_tokens: maxTokens, + messages: [{ role: "user", content: "hi" }], + }); + expect(count.statusCode).toBe(400); + expect((JSON.parse(count.body) as AnthropicErrorBody).error.message).toContain("max_tokens"); + } + }); +}); + +describe("failed and cancelled turns (A6)", () => { + const events: CompletionEvent[] = [ + START, + { kind: "text_delta", text: "partial answer", ordinal: 0 }, + { kind: "end", finishReason: "error", usage: usage(3, 1), messageId: "msg_hardening" }, + ]; + + it("reports a failed buffered turn as 502 api_error instead of end_turn", async () => { + const { app } = await serverWith({ script: () => events }); + + const response = await post(app, "/v1/messages", { + model: MODEL, + max_tokens: 8, + messages: [{ role: "user", content: "hi" }], + }); + + expect(response.statusCode).toBe(502); + const error = JSON.parse(response.body) as AnthropicErrorBody; + expect(error.type).toBe("error"); + expect(error.error.type).toBe("api_error"); + expect(error.error.message).toContain("failed"); + }); + + it("reports a failed streamed turn as a terminal error event", async () => { + const { app } = await serverWith({ script: () => events }); + + const response = await post(app, "/v1/messages", { + model: MODEL, + max_tokens: 8, + stream: true, + messages: [{ role: "user", content: "hi" }], + }); + + expect(response.statusCode).toBe(200); + const frames = parseSse(response.body); + expect(frames.at(-1)?.event).toBe("error"); + const payload = JSON.parse(frames.at(-1)?.data ?? "{}") as AnthropicErrorBody; + expect(payload.type).toBe("error"); + expect(payload.error.type).toBe("api_error"); + }); + + it("keeps `cancelled` as end_turn but flags it as interrupted on both paths", async () => { + const cancelled: CompletionEvent[] = [ + START, + { kind: "text_delta", text: "stopped early", ordinal: 0 }, + { kind: "end", finishReason: "cancelled", usage: usage(4, 2), messageId: "msg_hardening" }, + ]; + const { app } = await serverWith({ script: () => cancelled }); + + const buffered = await post(app, "/v1/messages", { + model: MODEL, + max_tokens: 8, + messages: [{ role: "user", content: "hi" }], + }); + expect(buffered.statusCode).toBe(200); + const body = JSON.parse(buffered.body) as AnthropicResponseBody; + expect(body.stop_reason).toBe("end_turn"); + expect(body.x_opencode["interrupted"]).toBe(true); + + const streamed = await post(app, "/v1/messages", { + model: MODEL, + max_tokens: 8, + stream: true, + messages: [{ role: "user", content: "hi" }], + }); + const payloads = parseSse(streamed.body).map((frame) => JSON.parse(frame.data) as StreamFrame); + const messageDelta = payloads.find((frame) => frame.type === "message_delta"); + expect(messageDelta?.delta?.stop_reason).toBe("end_turn"); + expect(messageDelta?.x_opencode?.interrupted).toBe(true); + }); +}); + +describe("disable_parallel_tool_use (A9)", () => { + const tools = [{ name: "lookup", input_schema: { type: "object" } }]; + + it("reaches the bridge as parallelToolCalls: false", 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: 8, + messages: [{ role: "user", content: "look it up" }], + tools, + tool_choice: { type: "auto", disable_parallel_tool_use: true }, + }); + + expect(response.statusCode).toBe(200); + expect(capture.request?.parallelToolCalls).toBe(false); + }); + + it("leaves parallel tool calls enabled when the flag is absent", async () => { + const capture: { request?: InternalRequest } = {}; + const { app } = await serverWith({ onRun: (request) => (capture.request = request) }); + + await post(app, "/v1/messages", { + model: MODEL, + max_tokens: 8, + messages: [{ role: "user", content: "look it up" }], + tools, + tool_choice: { type: "auto" }, + }); + + expect(capture.request?.parallelToolCalls).not.toBe(false); + }); +}); + +describe("thinking.effort (A12)", () => { + it("is no longer stripped from the thinking block", 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: 8, + messages: [{ role: "user", content: "think hard" }], + thinking: { type: "enabled", effort: "high" }, + }); + + expect(response.statusCode).toBe(200); + expect(capture.request?.reasoning?.enabled).toBe(true); + expect(capture.request?.reasoning?.effort).toBe("high"); + }); +}); + +describe("streamed usage (A13)", () => { + it("keeps message_start at zero and reports the totals in message_delta", async () => { + const turnUsage = usage(10, 3, 5); + const events: CompletionEvent[] = [ + { ...START, reasoningEnabled: true }, + { kind: "text_delta", text: "Answer.", ordinal: 0 }, + { kind: "usage", usage: turnUsage }, + { kind: "end", finishReason: "stop", usage: turnUsage, messageId: "msg_hardening" }, + ]; + const { app } = await serverWith({ script: () => events }); + const payload = (stream: boolean) => ({ + model: MODEL, + max_tokens: 64, + stream, + messages: [{ role: "user", content: "count" }], + }); + + const streamed = await post(app, "/v1/messages", payload(true)); + const buffered = await post(app, "/v1/messages", payload(false)); + expect(streamed.statusCode).toBe(200); + expect(buffered.statusCode).toBe(200); + + const frames = parseSse(streamed.body).map((frame) => JSON.parse(frame.data) as StreamFrame); + const messageStart = frames.find((frame) => frame.type === "message_start"); + expect(messageStart?.message?.usage).toEqual({ input_tokens: 0, output_tokens: 0 }); + + const messageDelta = frames.find((frame) => frame.type === "message_delta"); + const bufferedBody = JSON.parse(buffered.body) as AnthropicResponseBody; + expect(messageDelta?.usage).toEqual({ + input_tokens: bufferedBody.usage["input_tokens"], + output_tokens: bufferedBody.usage["output_tokens"], + cache_creation_input_tokens: bufferedBody.usage["cache_creation_input_tokens"], + cache_read_input_tokens: bufferedBody.usage["cache_read_input_tokens"], + }); + }); +}); + +describe("rate limiting (A2)", () => { + it("answers 429 with retry-after for the limited key and leaves another key unaffected", async () => { + const { app } = await serverWith({ + config: { apiKeys: ["test-key", "second-key"], rateLimitRpm: 2, rateLimitBurst: 2 }, + }); + const body = { model: MODEL, max_tokens: 8, messages: [{ role: "user", content: "hi" }] }; + const headers = { ...AUTH, "content-type": "application/json" }; + + const first = await app.inject({ method: "POST", url: "/v1/messages", headers, payload: body }); + const second = await app.inject({ method: "POST", url: "/v1/messages", headers, payload: body }); + expect(first.statusCode).toBe(200); + expect(second.statusCode).toBe(200); + + const limited = await app.inject({ method: "POST", url: "/v1/messages", headers, payload: body }); + expect(limited.statusCode).toBe(429); + expect(Number(limited.headers["retry-after"])).toBeGreaterThanOrEqual(1); + const error = JSON.parse(limited.body) as AnthropicErrorBody; + expect(error.error.type).toBe("rate_limit_error"); + + const other = await app.inject({ + method: "POST", + url: "/v1/messages", + headers: { authorization: "Bearer second-key", "content-type": "application/json" }, + payload: body, + }); + expect(other.statusCode).toBe(200); + }); +}); From 4960f85c7bddf8b5f0daa18cbb45022981671e92 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Ph=E1=BA=A1m=20V=C4=83n=20=C4=90=E1=BB=8Bnh?= Date: Thu, 3 Dec 2026 12:09:10 +0700 Subject: [PATCH 05/12] feat(server): rate limit requests and gate metrics with a token One authenticated caller could open unlimited concurrent sockets and drive unlimited paid upstream turns: nothing limited request rate, and the server disabled the request timeout globally. Add an in-process token bucket keyed by a hash of the authenticated key (never the raw key), with a separate bucket for /admin/*, wired as a preHandler beside requireApiKey; OPENCODE_RATE_LIMIT_RPM=0 keeps the previous behaviour and a rejection answers 429 with retry-after. Buffered routes get a bounded socket timeout again while streaming routes stay unbounded. OPENCODE_METRICS_TOKEN lets a scraper read /metrics with a dedicated credential, compared in constant time before the metricsPublic bypass, so the endpoint no longer has to be anonymous to be scraped. The logger redaction list now covers every secret field the code actually builds, including upstreamPassword and nested authorization headers. The SseWriter reports backpressure instead of discarding it: drain() resolves when the socket catches up or after a bounded wait, and closedSignal aborts when the connection dies, so a dead reader stops the producer on every surface. BREAKING CHANGE: OPENCODE_ALLOW_PRIVATE_MEDIA_URLS now defaults to false. Remote media on loopback, private, link-local and metadata addresses is rejected unless the variable is set to true explicitly; enabling it while HOST is not a loopback address logs a startup error. --- .env.example | 18 ++++- src/auth.ts | 58 +++++++++++++-- src/config.ts | 19 ++++- src/http/rateLimit.ts | 159 ++++++++++++++++++++++++++++++++++++++++ src/http/sse.ts | 78 +++++++++++++++++++- src/http/timeout.ts | 65 ++++++++++++++++ src/index.ts | 11 ++- src/logger.ts | 57 ++++++++++---- src/server.ts | 22 ++++++ src/startup.ts | 31 ++++++++ test/config.test.ts | 122 +++++++++++++++++++++++++++++- test/disconnect.test.ts | 112 ++++++++++++++++++++++++++++ test/health.test.ts | 16 ++++ 13 files changed, 737 insertions(+), 31 deletions(-) create mode 100644 src/http/rateLimit.ts create mode 100644 src/http/timeout.ts diff --git a/.env.example b/.env.example index f1c4c04..d4cb301 100644 --- a/.env.example +++ b/.env.example @@ -55,6 +55,18 @@ PORT=20123 # Serve GET /metrics without authentication. # OPENCODE_METRICS_PUBLIC=false +# Dedicated scrape credential for GET /metrics. When set, the endpoint requires +# it (timing-safe compare) even when OPENCODE_METRICS_PUBLIC=true, so a scraper +# never needs a general-purpose API key. +# OPENCODE_METRICS_TOKEN= + +# In-process rate limit per authenticated API key. RPM is requests per minute; +# BURST is the bucket capacity (0 derives max(1, ceil(rpm / 6))). RPM=0 disables +# the limiter. /admin/* uses a separate bucket. Rejections answer 429 with a +# retry-after header. +# OPENCODE_RATE_LIMIT_RPM=0 +# OPENCODE_RATE_LIMIT_BURST=0 + # --------------------------------------------------------------------------- # Upstream OpenCode server # --------------------------------------------------------------------------- @@ -140,8 +152,10 @@ PORT=20123 # OPENCODE_ALLOW_REMOTE_MEDIA_URLS=true # Allow remote media on private/loopback addresses. Disabling it prevents SSRF -# against the host network; keep it false unless you control the URL sources. -# OPENCODE_ALLOW_PRIVATE_MEDIA_URLS=true +# against the host network. Default: false. Set it to true only when every media +# URL source is trusted; when it is enabled while HOST is not loopback the +# gateway logs a startup error naming the SSRF exposure. +# OPENCODE_ALLOW_PRIVATE_MEDIA_URLS=false # Size and count limits. The same byte budget applies to one attachment and to # the combined total per request: an attachment that would push the request over diff --git a/src/auth.ts b/src/auth.ts index 4624d72..231ff9d 100644 --- a/src/auth.ts +++ b/src/auth.ts @@ -20,6 +20,16 @@ import { ApiError } from "./errors.js"; const PUBLIC_PATHS = new Set(["/", "/health", "/ready", "/healthz"]); +/** Path of a request URL, ignoring the query string. */ +export function requestPath(request: FastifyRequest): string { + return request.url.split("?")[0] ?? ""; +} + +/** True for the routes that never require a credential. */ +export function isPublicPath(path: string): boolean { + return PUBLIC_PATHS.has(path); +} + /** * API key extraction. * @@ -75,16 +85,48 @@ export function isAuthorized(config: Config, presented: string | undefined): boo return config.apiKeys.some((key) => safeEqual(key, presented)); } +/** + * True when the presented credential is the dedicated metrics scrape token. + * + * The comparison is timing-safe and happens **before** the `metricsPublic` + * bypass, so configuring the token makes `/metrics` authenticated again even if + * the endpoint was made public earlier. + */ +export function isMetricsToken(config: Config, presented: string | undefined): boolean { + if (config.metricsToken === undefined || presented === undefined) return false; + return safeEqual(config.metricsToken, presented); +} + +function unauthorized(): ApiError { + return ApiError.unauthorized( + "Missing or invalid API key. Send it as `Authorization: Bearer `, `x-api-key: `, " + + "or `Authorization: Basic `.", + ); +} + /** Fastify preHandler enforcing authentication. */ export function requireApiKey(config: Config) { return async function authenticate(request: FastifyRequest, _reply: FastifyReply): Promise { - if (PUBLIC_PATHS.has(request.url.split("?")[0] ?? "")) return; - if (config.metricsPublic && request.url.split("?")[0] === "/metrics") return; - if (!isAuthorized(config, extractApiKey(request))) { - throw ApiError.unauthorized( - "Missing or invalid API key. Send it as `Authorization: Bearer `, `x-api-key: `, " + - "or `Authorization: Basic `.", - ); + const path = requestPath(request); + if (isPublicPath(path)) return; + + const presented = extractApiKey(request); + + if (path === "/metrics") { + // A configured scrape token is checked first, so it works even when the + // endpoint is public and never requires handing a scraper a general key. + if (isMetricsToken(config, presented)) return; + if (config.metricsToken !== undefined) { + // With a token configured the endpoint is never anonymous; a general + // API key is still accepted. + if (!isAuthorized(config, presented)) throw unauthorized(); + return; + } + if (config.metricsPublic) return; + if (!isAuthorized(config, presented)) throw unauthorized(); + return; } + + if (!isAuthorized(config, presented)) throw unauthorized(); }; -} +} \ No newline at end of file diff --git a/src/config.ts b/src/config.ts index e1969c4..4c501df 100644 --- a/src/config.ts +++ b/src/config.ts @@ -24,6 +24,17 @@ export interface Config { readonly usingDefaultApiKey: boolean; readonly allowNoAuth: boolean; readonly metricsPublic: boolean; + /** + * Dedicated scrape credential for `GET /metrics`. + * + * When set, the endpoint requires it (timing-safe compare) even with + * `metricsPublic` enabled, so a scraper never needs a general-purpose API key. + */ + readonly metricsToken?: string; + /** Requests per minute allowed per API key; `0` disables the limiter. */ + readonly rateLimitRpm: number; + /** Burst capacity per API key; `0` derives `max(1, ceil(rpm / 6))`. */ + readonly rateLimitBurst: number; readonly corsOrigins: readonly string[]; /** Explicit upstream server. When unset the gateway spawns or discovers one. */ @@ -295,6 +306,9 @@ export function loadConfig(overrides: Partial = {}): Config { usingDefaultApiKey, allowNoAuth: envBool("OPENCODE_ALLOW_NO_AUTH", false), metricsPublic: envBool("OPENCODE_METRICS_PUBLIC", false), + metricsToken: envOptStr("OPENCODE_METRICS_TOKEN"), + rateLimitRpm: envInt("OPENCODE_RATE_LIMIT_RPM", 0, 0), + rateLimitBurst: envInt("OPENCODE_RATE_LIMIT_BURST", 0, 0), corsOrigins: Object.freeze(envList("OPENCODE_CORS_ORIGINS")), upstreamUrl: envOptStr("OPENCODE_SERVER_URL"), @@ -334,7 +348,10 @@ export function loadConfig(overrides: Partial = {}): Config { allowLocalFiles: envBool("OPENCODE_ALLOW_LOCAL_FILES", false), allowedFileRoots: Object.freeze(allowedRoots), allowRemoteMediaUrls: envBool("OPENCODE_ALLOW_REMOTE_MEDIA_URLS", true), - allowPrivateMediaUrls: envBool("OPENCODE_ALLOW_PRIVATE_MEDIA_URLS", true), + // Off by default: enabling it lets any authenticated caller make the gateway + // fetch loopback, private-range and cloud-metadata addresses (SSRF). Set + // OPENCODE_ALLOW_PRIVATE_MEDIA_URLS=true only when every URL source is trusted. + allowPrivateMediaUrls: envBool("OPENCODE_ALLOW_PRIVATE_MEDIA_URLS", false), maxAttachmentBytes: envInt("OPENCODE_MAX_ATTACHMENT_BYTES", 20 * 1024 * 1024, 1), maxAttachments: envInt("OPENCODE_MAX_ATTACHMENTS", 16, 1), mediaFetchTimeoutMs: envInt("OPENCODE_MEDIA_FETCH_TIMEOUT_MS", 15_000, 100), diff --git a/src/http/rateLimit.ts b/src/http/rateLimit.ts new file mode 100644 index 0000000..eb4c0fe --- /dev/null +++ b/src/http/rateLimit.ts @@ -0,0 +1,159 @@ +/** + * In-process token-bucket rate limiting. + * + * One bucket per authenticated API key (never the raw key: only a SHA-256 hash + * is retained) plus one shared bucket for anonymous callers. The limiter is a + * `preHandler` beside `requireApiKey`, so an unauthenticated caller is rejected + * before any bucket is touched, and `/admin/*` gets its own bucket so operator + * traffic cannot be starved by completion traffic. + * + * There is no distributed state: every gateway instance limits on its own. That + * is deliberate — no new runtime dependency and no shared store. + */ +import { createHash } from "node:crypto"; +import type { FastifyReply, FastifyRequest } from "fastify"; +import { extractApiKey, isPublicPath, requestPath } from "../auth.js"; +import type { Config } from "../config.js"; +import { ApiError } from "../errors.js"; + +interface BucketState { + /** Tokens currently available, never above the burst capacity. */ + tokens: number; + /** Timestamp the token count was last refilled. */ + refreshedAt: number; +} + +export interface TokenBucketLimiterOptions { + /** Sustained requests per minute; `0` disables the limiter. */ + rpm: number; + /** Bucket capacity; `0` derives `max(1, ceil(rpm / 6))`. */ + burst: number; + /** Injectable clock, for tests. */ + now?: () => number; +} + +/** Bucket capacity when `OPENCODE_RATE_LIMIT_BURST` is left at 0. */ +export function derivedBurst(rpm: number): number { + return Math.max(1, Math.ceil(rpm / 6)); +} + +export class TokenBucketLimiter { + readonly #rpm: number; + readonly #burst: number; + readonly #now: () => number; + readonly #buckets = new Map(); + + constructor(options: TokenBucketLimiterOptions) { + this.#rpm = Math.max(0, options.rpm); + this.#burst = options.burst > 0 ? options.burst : derivedBurst(this.#rpm); + this.#now = options.now ?? Date.now; + } + + /** False when the limiter is disabled (`rpm` is 0). */ + get enabled(): boolean { + return this.#rpm > 0; + } + + /** Configured burst capacity, after the derived default. */ + get burst(): number { + return this.#burst; + } + + /** Number of live buckets, for tests and diagnostics. */ + get size(): number { + return this.#buckets.size; + } + + /** + * Consume one token for `key`. + * + * Returns `undefined` when the call is allowed, otherwise the number of + * milliseconds the caller should wait before the next attempt. + */ + take(key: string): number | undefined { + if (!this.enabled) return undefined; + + const now = this.#now(); + const refillPerMs = this.#rpm / 60_000; + let bucket = this.#buckets.get(key); + if (bucket === undefined) { + bucket = { tokens: this.#burst, refreshedAt: now }; + this.#buckets.set(key, bucket); + } else { + const elapsed = Math.max(0, now - bucket.refreshedAt); + bucket.tokens = Math.min(this.#burst, bucket.tokens + elapsed * refillPerMs); + bucket.refreshedAt = now; + } + + if (bucket.tokens >= 1) { + bucket.tokens -= 1; + return undefined; + } + return Math.max(1, Math.ceil((1 - bucket.tokens) / refillPerMs)); + } + + /** Drop every bucket; used by tests. */ + reset(): void { + this.#buckets.clear(); + } +} + +/** Hash an identifying credential so a raw API key is never retained. */ +function bucketKey(scope: string, credential: string | undefined): string { + const material = credential === undefined ? "anonymous" : credential; + return createHash("sha256").update(`${scope}\u0000${material}`).digest("hex"); +} + +/** + * Credential used for bucketing. + * + * Only a key that is actually configured may create its own bucket; with + * `OPENCODE_ALLOW_NO_AUTH=true` an arbitrary caller-supplied header would + * otherwise grow the bucket map without bound. + */ +function credentialFor(config: Config, request: FastifyRequest): string | undefined { + const presented = extractApiKey(request); + if (presented === undefined) return undefined; + return config.apiKeys.includes(presented) ? presented : undefined; +} + +/** Limiter pair wired into the request lifecycle. */ +export interface RateLimiters { + readonly api: TokenBucketLimiter; + readonly admin: TokenBucketLimiter; +} + +export function createRateLimiters(config: Config, now?: () => number): RateLimiters { + const options = { rpm: config.rateLimitRpm, burst: config.rateLimitBurst, ...(now ? { now } : {}) }; + return { api: new TokenBucketLimiter(options), admin: new TokenBucketLimiter(options) }; +} + +/** + * Build the rate-limiting `preHandler`. + * + * Health/metrics probes and preflight requests are exempt; `/admin/*` uses the + * admin bucket. A rejected request answers `429 rate_limit_error` with the + * documented `retry-after` header (Fastify's error handler derives it from + * `retryAfterMs`). + */ +export function requireRateLimit(config: Config, limiters: RateLimiters, onReject?: (scope: "api" | "admin") => void) { + return async function rateLimit(request: FastifyRequest, _reply: FastifyReply): Promise { + if (!limiters.api.enabled) return; + const path = requestPath(request); + if (isPublicPath(path) || path === "/metrics" || request.method === "OPTIONS") return; + + const scope = path === "/admin" || path.startsWith("/admin/") ? "admin" : "api"; + const limiter = scope === "admin" ? limiters.admin : limiters.api; + const retryAfterMs = limiter.take(bucketKey(scope, credentialFor(config, request))); + if (retryAfterMs === undefined) return; + + onReject?.(scope); + throw new ApiError( + 429, + "rate_limit_error", + `Rate limit exceeded: at most ${config.rateLimitRpm} requests per minute per API key. ` + + `Retry in ${Math.ceil(retryAfterMs / 1000)}s.`, + { code: "rate_limit_exceeded", retryAfterMs }, + ); + }; +} \ No newline at end of file diff --git a/src/http/sse.ts b/src/http/sse.ts index 8d2d398..4c3781d 100644 --- a/src/http/sse.ts +++ b/src/http/sse.ts @@ -4,6 +4,13 @@ * Routed through `reply.hijack()` so the response is written directly to the * socket: every surface needs full control over framing, flushing and * keep-alives, which Fastify's serialisers would otherwise interfere with. + * + * Backpressure: `raw.write()` returns `false` once the socket's buffer is full. + * That result used to be discarded, so a slow reader could not throttle the + * producer and the queue behind it grew without bound. `drain()` now resolves + * when the socket has caught up (or after a bounded wait), and `closedSignal` + * is aborted as soon as the connection dies, so a producer can stop even if it + * never calls `createDisconnectSignal()`. */ import type { FastifyReply } from "fastify"; @@ -13,13 +20,24 @@ export interface SseWriterOptions { /** Extra response headers. */ headers?: Record; onClose?: () => void; + /** + * Longest a `drain()` call waits for a backed-up socket before releasing the + * producer. Default 5000; `0` makes `drain()` resolve immediately. + */ + drainTimeoutMs?: number; } +/** Default bound for one backpressure wait. */ +export const DEFAULT_DRAIN_TIMEOUT_MS = 5_000; + export class SseWriter { readonly #reply: FastifyReply; readonly #options: SseWriterOptions; + readonly #closedController = new AbortController(); #heartbeat?: NodeJS.Timeout; #closed = false; + #pendingDrain: Promise | undefined; + #resolveDrain: (() => void) | undefined; constructor(reply: FastifyReply, options: SseWriterOptions = {}) { this.#reply = reply; @@ -30,6 +48,11 @@ export class SseWriter { return this.#closed; } + /** Aborted when the connection closes, whether via `close()` or a dead socket. */ + get closedSignal(): AbortSignal { + return this.#closedController.signal; + } + /** Send the SSE response headers and start the stream. */ open(): void { const raw = this.#reply.raw; @@ -74,12 +97,24 @@ export class SseWriter { this.#write(`: ${text}\n\n`); } + /** + * Resolves once the socket has caught up after the last backed-up write. + * + * Calling it when nothing is backed up returns immediately, so a producer can + * await it after every frame without adding latency on a healthy connection. + */ + drain(): Promise { + return this.#pendingDrain ?? Promise.resolve(); + } + /** Terminate the stream. */ close(): void { if (this.#closed) return; this.#closed = true; if (this.#heartbeat) clearInterval(this.#heartbeat); this.#heartbeat = undefined; + this.#releaseDrain(); + if (!this.#closedController.signal.aborted) this.#closedController.abort(); try { this.#reply.raw.end(); } catch { @@ -90,17 +125,56 @@ export class SseWriter { #write(chunk: string): void { try { - this.#reply.raw.write(chunk); + if (this.#reply.raw.write(chunk) === false) this.#awaitDrain(); } catch { this.#handleClose(); } } + /** + * Bound the wait for a full socket buffer. + * + * The producer blocks on `drain()` instead of the writer queueing frames: a + * reader that never catches up releases the producer after + * `drainTimeoutMs`, so a stuck connection cannot grow the process heap. + */ + #awaitDrain(): void { + if (this.#pendingDrain !== undefined || this.#closed) return; + const raw = this.#reply.raw; + const timeoutMs = Math.max(0, this.#options.drainTimeoutMs ?? DEFAULT_DRAIN_TIMEOUT_MS); + if (timeoutMs === 0) return; + + this.#pendingDrain = new Promise((resolve) => { + let timer: NodeJS.Timeout | undefined; + const done = (): void => { + if (timer !== undefined) clearTimeout(timer); + raw.off("drain", done); + raw.off("close", done); + raw.off("error", done); + this.#pendingDrain = undefined; + this.#resolveDrain = undefined; + resolve(); + }; + this.#resolveDrain = done; + raw.once("drain", done); + raw.once("close", done); + raw.once("error", done); + timer = setTimeout(done, timeoutMs); + timer.unref?.(); + }); + } + + #releaseDrain(): void { + this.#resolveDrain?.(); + } + #handleClose(): void { if (this.#closed) return; this.#closed = true; if (this.#heartbeat) clearInterval(this.#heartbeat); this.#heartbeat = undefined; + this.#releaseDrain(); + if (!this.#closedController.signal.aborted) this.#closedController.abort(); this.#options.onClose?.(); } -} +} \ No newline at end of file diff --git a/src/http/timeout.ts b/src/http/timeout.ts new file mode 100644 index 0000000..f6365f1 --- /dev/null +++ b/src/http/timeout.ts @@ -0,0 +1,65 @@ +/** + * Per-request socket timeout. + * + * Fastify has no route-level `requestTimeout`, so the server-level option stays + * `0` and the bound is applied per request once the body is known: a buffered + * completion may not hold a connection (and an upstream turn) forever, while an + * SSE response must never be cut off by it. + */ +import type { FastifyReply, FastifyRequest } from "fastify"; +import type { Config } from "../config.js"; + +/** + * True when the parsed request body asks for a streamed response. + * + * Every completion surface uses the same field (`stream: true`); a body without + * it is buffered. + */ +export function isStreamingBody(body: unknown): boolean { + if (typeof body !== "object" || body === null || Array.isArray(body)) return false; + return (body as { stream?: unknown }).stream === true; +} + +/** + * Socket timeout for one request, in milliseconds; `0` means "no timeout". + * + * Streamed requests are unbounded (the upstream turn has its own + * `OPENCODE_REQUEST_TIMEOUT_MS` budget and the SSE stream must survive long + * answers). Buffered requests share that same upstream budget, so a caller + * cannot park a connection indefinitely. + */ +export function requestTimeoutFor(config: Pick, body: unknown): number { + return isStreamingBody(body) ? 0 : config.upstreamRequestTimeoutMs; +} + +/** + * Apply the per-request timeout to the underlying socket. + * + * The raw socket is the only place Node exposes this; `IncomingMessage#setTimeout` + * is absent on test doubles, so the call is guarded. + */ +export function applyRequestTimeout( + request: FastifyRequest, + reply: FastifyReply, + config: Pick, +): void { + const raw = request.raw; + if (typeof raw.setTimeout !== "function") return; + const timeoutMs = requestTimeoutFor(config, request.body); + if (timeoutMs <= 0) { + raw.setTimeout(0); + return; + } + + const socket = raw.socket; + const onTimeout = (): void => { + raw.destroy(); + }; + raw.setTimeout(timeoutMs, onTimeout); + // `IncomingMessage#setTimeout(ms, cb)` registers a one-shot `timeout` listener + // on the socket; drop it when the response ends so a keep-alive connection + // cannot accumulate one per request. + reply.raw.once("close", () => { + socket?.off("timeout", onTimeout); + }); +} \ No newline at end of file diff --git a/src/index.ts b/src/index.ts index 95d249e..9f174a0 100644 --- a/src/index.ts +++ b/src/index.ts @@ -21,7 +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"; +import { defaultApiKeyNote, privateMediaUrlWarning } from "./startup.js"; /** Directory holding this file: `/dist` when built, `/src` under tsx. */ const moduleDir = path.dirname(fileURLToPath(import.meta.url)); @@ -59,6 +59,15 @@ async function main(): Promise { } } + const privateMediaWarning = privateMediaUrlWarning(config); + if (privateMediaWarning !== undefined) { + // Security-relevant misconfiguration: logged at `error` so it stands out in + // production logs as well as on the terminal. Startup is not refused: the + // documented Docker flow binds HOST=0.0.0.0 deliberately. + log.error({ host: config.host, allowPrivateMediaUrls: true }, "remote media may target private addresses"); + process.stderr.write(`\n${privateMediaWarning}\n\n`); + } + const metrics = createMetrics({ enabled: config.metricsEnabled }); const upstream = new UpstreamProcess(config, log, metrics); const client = new OpencodeClient(upstream, config, log, metrics); diff --git a/src/logger.ts b/src/logger.ts index 7bbe55a..33386ad 100644 --- a/src/logger.ts +++ b/src/logger.ts @@ -4,30 +4,55 @@ import type { Config } from "./config.js"; export type { Logger }; /** - * Build the process logger. + * Paths whose values must never reach a log line. * - * Pretty transport is loaded lazily and only when requested, so production - * deployments never need the extra dependency chain at runtime. + * The list covers the secret vocabulary of the whole codebase: caller + * credentials (`authorization`, `x-api-key`), the upstream server password + * (`upstreamPassword`, `OPENCODE_SERVER_PASSWORD`) and generic `password` / + * `apiKey` fields. `*` matches one level, so `*.*.authorization` covers an + * `{ context: { headers: { authorization } } }` callback-style log argument. */ -export function createLogger(config: Config): Logger { - const options: LoggerOptions = { +export const REDACT_PATHS: readonly string[] = [ + "req.headers.authorization", + "req.headers['x-api-key']", + "headers.authorization", + "headers['x-api-key']", + "password", + "apiKey", + "*.password", + "*.apiKey", + "*.authorization", + "*.upstreamPassword", + "upstreamPassword", + "*.*.authorization", + "*.*['x-api-key']", + "*.*.password", + "*.*.apiKey", + "*.*.upstreamPassword", +]; + +/** Build the pino options shared by every destination. */ +export function loggerOptions(config: Config): LoggerOptions { + return { level: config.logLevel, base: { service: "opencode-api", instance: config.instanceId }, timestamp: pino.stdTimeFunctions.isoTime, redact: { - paths: [ - "req.headers.authorization", - "req.headers['x-api-key']", - "headers.authorization", - "headers['x-api-key']", - "password", - "apiKey", - "*.password", - "*.apiKey", - ], + paths: [...REDACT_PATHS], censor: "[redacted]", + remove: false, }, }; +} + +/** + * Build the process logger. + * + * Pretty transport is loaded lazily and only when requested, so production + * deployments never need the extra dependency chain at runtime. + */ +export function createLogger(config: Config): Logger { + const options = loggerOptions(config); if (config.logPretty) { try { @@ -43,4 +68,4 @@ export function createLogger(config: Config): Logger { } } return pino(options); -} +} \ No newline at end of file diff --git a/src/server.ts b/src/server.ts index 26407aa..4bbf2ac 100644 --- a/src/server.ts +++ b/src/server.ts @@ -14,6 +14,8 @@ import { registerAnthropicMessageRoutes } from "./adapter/anthropic/messages.js" import { requireApiKey } from "./auth.js"; import type { AppContext } from "./context.js"; import { ApiError, toAnthropicError, toApiError, toOpenAiError } from "./errors.js"; +import { createRateLimiters, requireRateLimit } from "./http/rateLimit.js"; +import { applyRequestTimeout } from "./http/timeout.js"; import { registerAdminRoutes } from "./routes/admin.js"; import { registerHealthRoutes } from "./routes/health.js"; import { registerMetricsRoutes } from "./routes/metrics.js"; @@ -50,6 +52,8 @@ export async function buildServer(ctx: AppContext): Promise { // 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. + // Fastify has no route-level timeout, so buffered routes get their bound per + // request in the `preHandler` below (`http/timeout.ts`), while SSE keeps 0. requestTimeout: 0, connectionTimeout: 0, // Shutdown must not wait for an in-flight SSE stream to finish, and an @@ -123,6 +127,24 @@ export async function buildServer(ctx: AppContext): Promise { // ---------------------------------------------------------------- auth --- app.addHook("preHandler", requireApiKey(ctx.config)); + // --------------------------------------------------------- rate limit --- + // Beside `requireApiKey`, so a rejected caller is counted against its own + // bucket only after authentication; `/admin/*` has a separate bucket. + const limiters = createRateLimiters(ctx.config); + app.addHook( + "preHandler", + requireRateLimit(ctx.config, limiters, (scope) => { + ctx.metrics.rateLimitRejections.inc({ scope }); + }), + ); + + // ------------------------------------------------------------- timeout --- + // Buffered routes get a bounded socket timeout; streaming routes stay + // unbounded so a long SSE answer is never cut off. + app.addHook("preHandler", async (request, reply) => { + applyRequestTimeout(request, reply, ctx.config); + }); + // ------------------------------------------------------------- metrics --- app.addHook("onResponse", async (request, reply) => { // Never use the raw request URL as a label: prom-client keeps one series per diff --git a/src/startup.ts b/src/startup.ts index ddf2ab0..b809de2 100644 --- a/src/startup.ts +++ b/src/startup.ts @@ -27,3 +27,34 @@ export function defaultApiKeyNote(projectRoot: string): string { "Set OPENCODE_ALLOW_NO_AUTH=true to disable authentication entirely on a trusted host." ); } + +/** Hosts that only accept connections from the same machine. */ +const LOOPBACK_HOSTS = new Set(["127.0.0.1", "::1", "localhost", "::ffff:127.0.0.1"]); + +/** True when `host` binds the loopback interface only. */ +export function isLoopbackHost(host: string): boolean { + const normalised = host.trim().toLowerCase().replace(/^\[|\]$/g, ""); + if (LOOPBACK_HOSTS.has(normalised)) return true; + // The whole 127.0.0.0/8 block is loopback, not just 127.0.0.1. + return /^127(?:\.\d{1,3}){3}$/.test(normalised); +} + +/** + * Warning printed when remote media may target private addresses on a host that + * is reachable from the network. + * + * `OPENCODE_ALLOW_PRIVATE_MEDIA_URLS` defaults to `false`; an operator who + * turned it back on for the loopback-only quickstart must be told that the + * gateway now performs SSRF-capable fetches for every caller. The gateway does + * not refuse to start: the documented Docker flow binds `0.0.0.0` and the + * operator owns that decision. + */ +export function privateMediaUrlWarning(config: { host: string; allowPrivateMediaUrls: boolean }): string | undefined { + if (!config.allowPrivateMediaUrls || isLoopbackHost(config.host)) return undefined; + return ( + `OPENCODE_ALLOW_PRIVATE_MEDIA_URLS is enabled while HOST=${config.host}, which is reachable from the network.\n` + + "Any authenticated caller can make the gateway fetch loopback, private-range and cloud-metadata URLs " + + "(SSRF against the host network).\n" + + "Set OPENCODE_ALLOW_PRIVATE_MEDIA_URLS=false unless every media URL source is trusted." + ); +} diff --git a/test/config.test.ts b/test/config.test.ts index bad6442..f22f705 100644 --- a/test/config.test.ts +++ b/test/config.test.ts @@ -1,11 +1,13 @@ import { readFileSync } from "node:fs"; import os from "node:os"; import path from "node:path"; +import pino, { type DestinationStream } from "pino"; 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 { loggerOptions } from "../src/logger.js"; import { buildServer } from "../src/server.js"; -import { defaultApiKeyNote } from "../src/startup.js"; +import { defaultApiKeyNote, isLoopbackHost, privateMediaUrlWarning } from "../src/startup.js"; import { createTestContext } from "./helpers/context.js"; const KEY_VARS = ["OPENCODE_API_KEYS", "OPENCODE_API_KEY"] as const; @@ -337,4 +339,122 @@ describe("HTTP server shutdown and CORS", () => { await app.close(); }); +}); + +describe("OPENCODE_ALLOW_PRIVATE_MEDIA_URLS (A1)", () => { + it("is disabled by default so the SSRF guard is on out of the box", () => { + setEnv("OPENCODE_ALLOW_PRIVATE_MEDIA_URLS", undefined); + expect(config().allowPrivateMediaUrls).toBe(false); + }); + + it("can be re-enabled explicitly for a trusted deployment", () => { + setEnv("OPENCODE_ALLOW_PRIVATE_MEDIA_URLS", "true"); + expect(config().allowPrivateMediaUrls).toBe(true); + }); + + it("warns only when the guard is off and HOST is reachable from the network", () => { + expect(privateMediaUrlWarning({ host: "127.0.0.1", allowPrivateMediaUrls: true })).toBeUndefined(); + expect(privateMediaUrlWarning({ host: "::1", allowPrivateMediaUrls: true })).toBeUndefined(); + expect(privateMediaUrlWarning({ host: "localhost", allowPrivateMediaUrls: true })).toBeUndefined(); + expect(privateMediaUrlWarning({ host: "0.0.0.0", allowPrivateMediaUrls: true })).toContain( + "OPENCODE_ALLOW_PRIVATE_MEDIA_URLS", + ); + expect(privateMediaUrlWarning({ host: "10.0.0.5", allowPrivateMediaUrls: true })).toContain("SSRF"); + // The guard being on is the default and is never noisy. + expect(privateMediaUrlWarning({ host: "0.0.0.0", allowPrivateMediaUrls: false })).toBeUndefined(); + }); + + it("recognises the loopback spellings, including the whole 127/8 block", () => { + expect(isLoopbackHost("127.0.0.1")).toBe(true); + expect(isLoopbackHost("127.1.2.3")).toBe(true); + expect(isLoopbackHost("[::1]")).toBe(true); + expect(isLoopbackHost("LOCALHOST")).toBe(true); + expect(isLoopbackHost("0.0.0.0")).toBe(false); + expect(isLoopbackHost("192.168.1.10")).toBe(false); + }); +}); + +describe("OPENCODE_METRICS_TOKEN and the rate-limit variables (A2, A10)", () => { + it("reads the scrape token and leaves it unset by default", () => { + setEnv("OPENCODE_METRICS_TOKEN", undefined); + expect(config().metricsToken).toBeUndefined(); + setEnv("OPENCODE_METRICS_TOKEN", "scrape-secret"); + expect(config().metricsToken).toBe("scrape-secret"); + }); + + it("disables the limiter by default so existing deployments are unchanged", () => { + setEnv("OPENCODE_RATE_LIMIT_RPM", undefined); + setEnv("OPENCODE_RATE_LIMIT_BURST", undefined); + const resolved = config(); + expect(resolved.rateLimitRpm).toBe(0); + expect(resolved.rateLimitBurst).toBe(0); + }); + + it("parses the rate-limit variables and clamps a negative value to 0", () => { + setEnv("OPENCODE_RATE_LIMIT_RPM", "60"); + setEnv("OPENCODE_RATE_LIMIT_BURST", "5"); + expect(config().rateLimitRpm).toBe(60); + expect(config().rateLimitBurst).toBe(5); + + setEnv("OPENCODE_RATE_LIMIT_RPM", "-10"); + expect(config().rateLimitRpm).toBe(0); + }); +}); + +describe("logger redaction (A4)", () => { + it("redacts every spelling of a secret field, at every nesting level", () => { + const lines: string[] = []; + const destination = { + write: (line: string) => { + lines.push(line); + }, + } as unknown as DestinationStream; + const log = pino(loggerOptions(config({ logLevel: "info" })), destination); + + log.info( + { + upstreamPassword: "secret-upstream-password", + password: "secret-top-level-password", + apiKey: "secret-top-level-api-key", + headers: { authorization: "Bearer secret-header-token", "x-api-key": "secret-header-api-key" }, + nested: { + authorization: "Bearer secret-nested-token", + password: "secret-nested-password", + apiKey: "secret-nested-api-key-field", + upstreamPassword: "secret-nested-upstream-password", + }, + envelope: { + inner: { + authorization: "Bearer secret-deep-token", + "x-api-key": "secret-deep-api-key", + password: "secret-deep-password", + apiKey: "secret-deep-api-key-field", + upstreamPassword: "secret-deep-upstream-password", + }, + }, + }, + "redaction check", + ); + + const output = lines.join(""); + expect(output).toContain("[redacted]"); + for (const secret of [ + "secret-upstream-password", + "secret-top-level-password", + "secret-top-level-api-key", + "secret-header-token", + "secret-header-api-key", + "secret-nested-token", + "secret-nested-password", + "secret-nested-api-key-field", + "secret-nested-upstream-password", + "secret-deep-token", + "secret-deep-api-key", + "secret-deep-password", + "secret-deep-api-key-field", + "secret-deep-upstream-password", + ]) { + expect(output).not.toContain(secret); + } + }); }); \ No newline at end of file diff --git a/test/disconnect.test.ts b/test/disconnect.test.ts index 98d5913..4501dfe 100644 --- a/test/disconnect.test.ts +++ b/test/disconnect.test.ts @@ -9,6 +9,7 @@ import { EventEmitter } from "node:events"; import { describe, expect, it } from "vitest"; import type { FastifyReply, FastifyRequest } from "fastify"; import { createDisconnectSignal } from "../src/http/disconnect.js"; +import { SseWriter } from "../src/http/sse.js"; interface Fixture { request: FastifyRequest; @@ -90,4 +91,115 @@ describe("createDisconnectSignal", () => { f.socketEvents.emit("close"); expect(signal.aborted).toBe(false); }); +}); + +/** Minimal `ServerResponse` double: backpressure is controlled by `full`. */ +class FakeRawResponse extends EventEmitter { + readonly written: string[] = []; + full = false; + headWritten = false; + ended = false; + + write(chunk: string): boolean { + this.written.push(chunk); + return !this.full; + } + + writeHead(..._args: unknown[]): void { + this.headWritten = true; + } + + flushHeaders(): void { + /* no-op */ + } + + end(): void { + this.ended = true; + } +} + +function writerWith(raw: FakeRawResponse, drainTimeoutMs = 5_000): SseWriter { + const reply = { + raw, + getHeaders: () => ({}), + hijack: () => undefined, + } as unknown as FastifyReply; + return new SseWriter(reply, { heartbeatMs: 0, drainTimeoutMs }); +} + +describe("SseWriter backpressure and liveness (A3)", () => { + it("resolves immediately when the socket accepted the frame", async () => { + const raw = new FakeRawResponse(); + const writer = writerWith(raw); + writer.open(); + writer.send({ ok: true }, "message"); + + let resolved = false; + void writer.drain().then(() => { + resolved = true; + }); + await Promise.resolve(); + expect(resolved).toBe(true); + expect(raw.written.join("")).toContain("event: message"); + }); + + it("waits for the socket to drain once write() reports backpressure", async () => { + const raw = new FakeRawResponse(); + raw.full = true; + const writer = writerWith(raw); + writer.open(); + writer.send("frame"); + + let resolved = false; + const drained = writer.drain().then(() => { + resolved = true; + }); + await Promise.resolve(); + await Promise.resolve(); + expect(resolved).toBe(false); + + raw.full = false; + raw.emit("drain"); + await drained; + expect(resolved).toBe(true); + }); + + it("releases the producer after the drain timeout instead of buffering forever", async () => { + const raw = new FakeRawResponse(); + raw.full = true; + const writer = writerWith(raw, 20); + writer.open(); + writer.send("frame"); + + const startedAt = Date.now(); + await writer.drain(); + expect(Date.now() - startedAt).toBeLessThan(1_000); + }); + + it("aborts closedSignal when the socket dies or the writer closes", () => { + const raw = new FakeRawResponse(); + const writer = writerWith(raw); + writer.open(); + expect(writer.closedSignal.aborted).toBe(false); + + raw.emit("close"); + expect(writer.closed).toBe(true); + expect(writer.closedSignal.aborted).toBe(true); + + const second = new FakeRawResponse(); + const other = writerWith(second); + other.open(); + other.close(); + expect(other.closedSignal.aborted).toBe(true); + }); + + it("drops frames written after the connection died", () => { + const raw = new FakeRawResponse(); + const writer = writerWith(raw); + writer.open(); + raw.emit("close"); + const before = raw.written.length; + writer.send("late frame"); + expect(raw.written.length).toBe(before); + }); }); \ No newline at end of file diff --git a/test/health.test.ts b/test/health.test.ts index 10415ad..61d40a7 100644 --- a/test/health.test.ts +++ b/test/health.test.ts @@ -7,6 +7,7 @@ */ import { describe, expect, it, vi } from "vitest"; import { createMetrics } from "../src/metrics/registry.js"; +import { isStreamingBody, requestTimeoutFor } from "../src/http/timeout.js"; import type { UpstreamStatus } from "../src/upstream/process.js"; import { buildServer } from "../src/server.js"; import { createTestContext, defaultModels } from "./helpers/context.js"; @@ -81,6 +82,21 @@ describe("health routes", () => { }); }); +describe("per-request timeout (A2)", () => { + it("keeps streamed responses unbounded and bounds buffered ones", () => { + const config = { upstreamRequestTimeoutMs: 600_000 }; + expect(isStreamingBody({ stream: true })).toBe(true); + expect(isStreamingBody({ stream: false })).toBe(false); + expect(isStreamingBody(undefined)).toBe(false); + expect(isStreamingBody("text")).toBe(false); + + // SSE must never be cut off; a buffered completion gets the upstream budget. + expect(requestTimeoutFor(config, { stream: true })).toBe(0); + expect(requestTimeoutFor(config, { stream: false })).toBe(600_000); + expect(requestTimeoutFor(config, undefined)).toBe(600_000); + }); +}); + describe("HTTP latency histogram", () => { it("can describe completions longer than two minutes", async () => { const metrics = createMetrics({ enabled: false }); From 622a393412e7f3a3d5c7fdc5eed9406114991ac0 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Ph=E1=BA=A1m=20V=C4=83n=20=C4=90=E1=BB=8Bnh?= Date: Thu, 3 Dec 2026 12:09:10 +0700 Subject: [PATCH 06/12] fix(media): reject encoded downloads and pin the Windows file read The remote download asked for accept-encoding: identity but never inspected the response, and the byte caps bound the bytes as received, so a compressed body under the cap was inlined and labelled as media of the declared type. Reject any non-identity content-encoding with attachment_download_failed instead. On Windows O_NOFOLLOW collapses to 0, so the realpath-then-open sequence had no final-component guarantee on the platform this project is developed on. The final component is now lstat-checked for a symlink or junction before the open, and the opened handle's dev and ino are compared with the pre-open lstat, refusing the read on any mismatch. isPrivateHost() also normalises the address itself now: any IPv6 spelling is expanded before classification, so it is correct for non-canonical input instead of relying on new URL() having canonicalised the hostname. --- src/media/resolve.ts | 121 +++++++++++++++++++++++++++++++++++++------ test/media.test.ts | 120 ++++++++++++++++++++++++++++++++++++++---- 2 files changed, 214 insertions(+), 27 deletions(-) diff --git a/src/media/resolve.ts b/src/media/resolve.ts index 2bc2fee..28ad4f9 100644 --- a/src/media/resolve.ts +++ b/src/media/resolve.ts @@ -16,12 +16,15 @@ * 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. + * component swapped for a symlink after the check cannot redirect the read. On + * Windows, where the flag is `0`, the final component is additionally rejected + * when `lstat()` reports a symlink/junction and the opened handle's `dev`/`ino` + * are compared with the pre-open `lstat()` so a swap between the two is caught. * 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. + * root still reaches the outside inode, and a parent directory can be swapped + * between `realpath` and `open`. 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"; @@ -542,6 +545,19 @@ async function resolveUrl( ); } + // `readBounded()` caps the bytes **as received**, so a compressed body + // would bypass the decoded-size budget and be inlined as media of the + // declared type. `node:http` does not decompress, and the request asks + // for `identity`, so any other encoding is a protocol mismatch. + const encoding = normalise(headerValue(response.headers["content-encoding"]) ?? ""); + if (encoding !== "" && encoding !== "identity") { + response.body.destroy(); + throw ApiError.badRequest( + `Attachment download used an unsupported content-encoding: ${encoding}.`, + { code: "attachment_download_failed", param: 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); @@ -662,7 +678,7 @@ function assertAddressesPublic(addresses: readonly LookupAddress[], hostname: st /** A `net` lookup callback that always returns the pinned address. */ function pinnedLookup(pinned: PinnedAddress): net.LookupFunction { - return (hostname, options, callback) => { + return (_hostname, options, callback) => { if (options.all === true) { callback(null, [{ address: pinned.address, family: pinned.family }]); return; @@ -781,8 +797,30 @@ async function resolveLocalFile( let handle: FileHandle | undefined; let buffer: Buffer; try { + // Windows has no `O_NOFOLLOW`, so the final component is checked by hand: + // reject a symlink/junction immediately before the open, then prove the + // handle still refers to the same file (dev/ino) after the open. The POSIX + // path keeps its single `O_NOFOLLOW` handle and is not changed. + let openedIdentity: { dev: number; ino: number } | undefined; + if (process.platform === "win32") { + const linkStats = await fsp.lstat(realPath); + if (linkStats.isSymbolicLink()) { + throw ApiError.badRequest(`Attachment path is a symbolic link: ${requested}`, { + code: "invalid_attachment", + param: field, + }); + } + openedIdentity = { dev: linkStats.dev, ino: linkStats.ino }; + } + handle = await fsp.open(realPath, fsConstants.O_RDONLY | OPEN_NOFOLLOW); const stats = await handle.stat(); + if (openedIdentity !== undefined && (stats.dev !== openedIdentity.dev || stats.ino !== openedIdentity.ino)) { + throw ApiError.badRequest(`Attachment path changed while it was being opened: ${requested}`, { + code: "invalid_attachment", + param: field, + }); + } if (!stats.isFile()) { throw ApiError.badRequest(`Attachment path is not a regular file: ${requested}`, { code: "invalid_attachment", @@ -972,17 +1010,68 @@ export function isPrivateHost(hostname: string): boolean { return isPrivateIpv6(host); } -/** Convert `::ffff:a.b.c.d` / `::ffff:xxxx:yyyy` / `::xxxx:yyyy` to dotted IPv4. */ +/** Convert an IPv4-mapped or IPv4-compatible IPv6 literal 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}`; + if (!host.includes(":")) return undefined; + const groups = expandIpv6(host); + if (groups === undefined) return undefined; + const [g0, g1, g2, g3, g4, g5, g6, g7] = groups as [ + number, + number, + number, + number, + number, + number, + number, + number, + ]; + const mapped = g0 === 0 && g1 === 0 && g2 === 0 && g3 === 0 && g4 === 0 && g5 === 0xffff; + const compatible = g0 === 0 && g1 === 0 && g2 === 0 && g3 === 0 && g4 === 0 && g5 === 0; + if (!mapped && !compatible) return undefined; + return `${(g6 >> 8) & 0xff}.${g6 & 0xff}.${(g7 >> 8) & 0xff}.${g7 & 0xff}`; +} + +/** + * Expand an IPv6 literal into its eight 16-bit groups. + * + * The caller may hand over any spelling `net.isIP()` accepts, including the + * fully written `0:0:0:0:0:ffff:7f00:1`, a compressed `::ffff:7f00:1` and a + * dotted tail (`::ffff:127.0.0.1`). Normalising here is what makes + * `isPrivateHost()` correct for input that has not been through `new URL()`. + */ +function expandIpv6(host: string): number[] | undefined { + let value = host; + const lastColon = value.lastIndexOf(":"); + const tail = lastColon === -1 ? value : value.slice(lastColon + 1); + if (tail.includes(".")) { + const octets = parseIpv4(tail); + if (octets === undefined) return undefined; + const high = (octets[0] << 8) | octets[1]; + const low = (octets[2] << 8) | octets[3]; + value = `${value.slice(0, lastColon + 1)}${high.toString(16)}:${low.toString(16)}`; + } + + const halves = value.split("::"); + if (halves.length > 2) return undefined; + + const parseGroups = (part: string): number[] | undefined => { + if (part === "") return []; + const parts = part.split(":"); + if (parts.some((group) => !/^[0-9a-f]{1,4}$/.test(group))) return undefined; + return parts.map((group) => Number.parseInt(group, 16)); + }; + + if (halves.length === 1) { + const groups = parseGroups(halves[0] ?? ""); + return groups !== undefined && groups.length === 8 ? groups : undefined; + } + + const head = parseGroups(halves[0] ?? ""); + const tailGroups = parseGroups(halves[1] ?? ""); + if (head === undefined || tailGroups === undefined) return undefined; + const zeros = 8 - head.length - tailGroups.length; + if (zeros < 1) return undefined; + return [...head, ...new Array(zeros).fill(0), ...tailGroups]; } function isPrivateHostname(host: string): boolean { diff --git a/test/media.test.ts b/test/media.test.ts index 0df73f3..94ddd37 100644 --- a/test/media.test.ts +++ b/test/media.test.ts @@ -7,6 +7,7 @@ import type { FileHandle } from "node:fs/promises"; import type { AddressInfo } from "node:net"; import os from "node:os"; import path from "node:path"; +import zlib from "node:zlib"; 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"; @@ -231,6 +232,18 @@ describe("resolveAttachment", () => { response.end(Buffer.alloc(4096, 1)); return; } + if (route === "/gzip") { + // 234 bytes on the wire for a PNG that decodes to more: the transfer + // cap alone would accept it (A7). + const compressed = zlib.gzipSync(PNG_BUFFER); + response.writeHead(200, { + "content-type": "image/png", + "content-encoding": "gzip", + "content-length": String(compressed.byteLength), + }); + response.end(compressed); + return; + } if (route === "/small") { response.writeHead(200, { "content-type": "application/octet-stream", @@ -311,6 +324,20 @@ describe("resolveAttachment", () => { ).rejects.toMatchObject({ code: "private_media_blocked" }); }); + it("refuses private addresses by default, with no configuration at all (A1)", async () => { + // The loopback fixture is exactly the address the SSRF guard exists for; + // flipping the default must reject it without any explicit override. + await expect(resolveAttachment({ url: `${baseUrl}/image.png` }, config())).rejects.toMatchObject({ + code: "private_media_blocked", + }); + }); + + it("refuses a compressed download instead of capping its transfer size (A7)", async () => { + await expect( + resolveAttachment({ url: `${baseUrl}/gzip` }, config({ allowPrivateMediaUrls: true })), + ).rejects.toMatchObject({ code: "attachment_download_failed" }); + }); + it("refuses remote media when disabled", async () => { await expect( resolveAttachment({ url: `${baseUrl}/image.png` }, config({ allowRemoteMediaUrls: false })), @@ -592,22 +619,32 @@ describe("resolveAttachment", () => { // the read goes through `fsp.open()`. const cap = PNG_BUFFER.byteLength + 16; const handle = { - stat: vi.fn().mockResolvedValue({ isFile: () => true, size: PNG_BUFFER.byteLength }), + stat: vi.fn().mockResolvedValue({ isFile: () => true, size: PNG_BUFFER.byteLength, dev: 7, ino: 8 }), 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); + // On Windows the pre-open `lstat()` identity must agree with the handle's. + const lstatSpy = vi.spyOn(fsp, "lstat").mockResolvedValue({ + isSymbolicLink: () => false, + dev: 7, + ino: 8, + } as unknown as Awaited>); + + try { + await expect( + resolveAttachment( + { path: path.join(workspace, "image.png") }, + config({ allowLocalFiles: true, allowedFileRoots: [workspace], maxAttachmentBytes: cap }), + ), + ).rejects.toMatchObject({ code: "attachment_too_large" }); - await expect( - resolveAttachment( - { path: path.join(workspace, "image.png") }, - config({ allowLocalFiles: true, allowedFileRoots: [workspace], maxAttachmentBytes: cap }), - ), - ).rejects.toMatchObject({ code: "attachment_too_large" }); - - expect(handle.readFile).toHaveBeenCalledTimes(1); - expect(handle.close).toHaveBeenCalledTimes(1); - openSpy.mockRestore(); + expect(handle.readFile).toHaveBeenCalledTimes(1); + expect(handle.close).toHaveBeenCalledTimes(1); + } finally { + openSpy.mockRestore(); + lstatSpy.mockRestore(); + } }); it("refuses files outside the allowed roots", async () => { @@ -722,6 +759,54 @@ describe("resolveAttachment", () => { }, ); + it.skipIf(process.platform !== "win32")( + "refuses a symlink or junction final component on Windows (A11)", + async () => { + // Windows has no `O_NOFOLLOW`; the adapter rejects a reparse point from + // `lstat()` immediately before opening the file. + const lstatSpy = vi.spyOn(fsp, "lstat").mockResolvedValue({ + isSymbolicLink: () => true, + dev: 1, + ino: 2, + } as unknown as Awaited>); + + try { + await expect( + resolveAttachment( + { path: path.join(workspace, "image.png") }, + config({ allowLocalFiles: true, allowedFileRoots: [workspace] }), + ), + ).rejects.toMatchObject({ code: "invalid_attachment", status: 400 }); + } finally { + lstatSpy.mockRestore(); + } + }, + ); + + it.skipIf(process.platform !== "win32")( + "refuses a file whose identity changed between the check and the open (A11)", + async () => { + // A different `dev`/`ino` than the handle reports means the path was + // re-pointed after the pre-open check; the read must be refused. + const lstatSpy = vi.spyOn(fsp, "lstat").mockResolvedValue({ + isSymbolicLink: () => false, + dev: -1, + ino: -1, + } as unknown as Awaited>); + + try { + await expect( + resolveAttachment( + { path: path.join(workspace, "image.png") }, + config({ allowLocalFiles: true, allowedFileRoots: [workspace] }), + ), + ).rejects.toMatchObject({ code: "invalid_attachment", status: 400 }); + } finally { + lstatSpy.mockRestore(); + } + }, + ); + it.skipIf(process.platform === "win32")( "pins the residual hard-link risk: a link inside the root exposes outside content", async () => { @@ -758,6 +843,19 @@ describe("host and path guards", () => { expect(isPrivateHost("8.8.8.8")).toBe(false); }); + it("normalises non-canonical IPv6 spellings before classifying (A14)", () => { + // `new URL()` happens to canonicalise these today, but the exported helper + // must not depend on its caller. + expect(isPrivateHost("0:0:0:0:0:ffff:7f00:1")).toBe(true); + expect(isPrivateHost("::FFFF:127.0.0.1")).toBe(true); + expect(isPrivateHost("0:0:0:0:0:ffff:7f00:1".toUpperCase())).toBe(true); + expect(isPrivateHost("0:0:0:0:0:0:0:1")).toBe(true); + expect(isPrivateHost("fe80:0:0:0:0:0:0:1")).toBe(true); + // Public addresses must stay public in any spelling. + expect(isPrivateHost("0:0:0:0:0:ffff:808:808")).toBe(false); + expect(isPrivateHost("2001:0db8:0:0:0:0:0:1")).toBe(false); + }); + it("checks path containment", () => { const roots = [path.join(os.tmpdir(), "root")]; expect(isWithinRoots(path.join(roots[0] as string, "a", "b.png"), roots)).toBe(true); From d16fe89898408b20f05025055c564a4ce76a0dae Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Ph=E1=BA=A1m=20V=C4=83n=20=C4=90=E1=BB=8Bnh?= Date: Thu, 3 Dec 2026 12:09:22 +0700 Subject: [PATCH 07/12] test: cover both paths, the operational routes and the env tables GET /metrics had no HTTP-level test at all, including the metricsPublic bypass and the new scrape token, and five /admin/* routes were untested at the HTTP layer. Add both, plus a table-driven suite that runs the same scripted turn through stream: false and stream: true on all four completion surfaces and compares text, ids, finish reason, usage and the Responses output items, so a change that only handles one path fails immediately. The docs-consistency test parses the environment variables out of src/config.ts and asserts that .env.example, docs/CONFIGURATION.md and the README configuration summary agree with the code in both directions, which is what keeps three hand-maintained tables honest. --- test/admin.test.ts | 299 ++++++++++++++++- test/docs-consistency.test.ts | 110 ++++++ test/metrics.test.ts | 112 +++++++ test/parity.test.ts | 610 ++++++++++++++++++++++++++++++++++ 4 files changed, 1129 insertions(+), 2 deletions(-) create mode 100644 test/docs-consistency.test.ts create mode 100644 test/metrics.test.ts create mode 100644 test/parity.test.ts diff --git a/test/admin.test.ts b/test/admin.test.ts index 43de1db..661e513 100644 --- a/test/admin.test.ts +++ b/test/admin.test.ts @@ -1,14 +1,50 @@ /** * Operational `/admin/*` endpoints. * - * The config view is the only new one; the point of these tests is that it is - * authenticated and never echoes a secret back to the caller. + * Every route is driven at the HTTP layer through `buildServer(ctx)` and + * `app.inject()`: each one requires an API key and each answers with the body + * shape documented in `docs/API.md` §Operational endpoints. The config view is + * also checked for redaction: it must never echo a secret back to the caller. */ import { describe, expect, it } from "vitest"; +import type { AppContext } from "../src/context.js"; import { buildServer } from "../src/server.js"; +import type { UpstreamEndpoint, UpstreamStatus } from "../src/upstream/process.js"; import { createTestContext } from "./helpers/context.js"; const AUTH = { authorization: "Bearer test-key" }; +const MODEL = "opencode/big-pickle"; + +/** Context whose scripted upstream reports exactly this status payload. */ +function contextWithUpstreamStatus(status: UpstreamStatus): AppContext { + const base = createTestContext(); + return { + ...base, + upstream: { + ...base.upstream, + status: () => status, + } as unknown as AppContext["upstream"], + }; +} + +/** Register one sticky session so `/admin/sessions` has a documented record. */ +function seedSession(ctx: AppContext, key: string, sessionId: string): void { + ctx.sessions.commit(key, sessionId, { + key, + model: MODEL, + agent: "build", + messages: [{ role: "user", text: "hi" }], + toolsHash: "none", + permissionProfile: "default", + }); +} + +/** Assert an RFC 3339 timestamp the wire format documents. */ +function expectIsoTimestamp(value: unknown): void { + expect(typeof value).toBe("string"); + const text = value as string; + expect(new Date(text).toISOString()).toBe(text); +} describe("GET /admin/config", () => { it("requires an API key", async () => { @@ -55,4 +91,263 @@ describe("GET /admin/config", () => { expect(serialised).not.toContain("Bearer"); await app.close(); }); +}); + +describe("GET /metrics authentication", () => { + it("requires the configured scrape token even when the endpoint is public", async () => { + const ctx = createTestContext({ + config: { metricsEnabled: true, metricsPublic: true, metricsToken: "scrape-secret" }, + }); + const app = await buildServer(ctx); + try { + const missing = await app.inject({ method: "GET", url: "/metrics" }); + expect(missing.statusCode).toBe(401); + + const wrong = await app.inject({ method: "GET", url: "/metrics", headers: { "x-api-key": "not-the-token" } }); + expect(wrong.statusCode).toBe(401); + + const right = await app.inject({ method: "GET", url: "/metrics", headers: { "x-api-key": "scrape-secret" } }); + expect(right.statusCode).toBe(200); + expect(right.headers["content-type"]).toContain("text/plain"); + + // A general-purpose key is still accepted, so an operator does not need + // to keep two credentials in the same script. + const general = await app.inject({ method: "GET", url: "/metrics", headers: AUTH }); + expect(general.statusCode).toBe(200); + } finally { + await app.close(); + } + }); + + it("keeps the endpoint authenticated when no token is configured and it is not public", async () => { + const ctx = createTestContext({ config: { metricsEnabled: true, metricsPublic: false } }); + const app = await buildServer(ctx); + try { + const denied = await app.inject({ method: "GET", url: "/metrics" }); + expect(denied.statusCode).toBe(401); + + const allowed = await app.inject({ method: "GET", url: "/metrics", headers: AUTH }); + expect(allowed.statusCode).toBe(200); + } finally { + await app.close(); + } + }); +}); + +describe("rate limiting", () => { + it("limits /admin/* with its own bucket, independently of the completion routes", async () => { + const ctx = createTestContext({ config: { rateLimitRpm: 1, rateLimitBurst: 1 } }); + const app = await buildServer(ctx); + try { + const first = await app.inject({ method: "GET", url: "/admin/status", headers: AUTH }); + expect(first.statusCode).toBe(200); + + // A separate bucket: completion traffic is not affected by admin traffic. + const completion = await app.inject({ + method: "POST", + url: "/v1/messages", + headers: { ...AUTH, "content-type": "application/json" }, + payload: { model: "deepseek-v4.1-flash-free", max_tokens: 8, messages: [{ role: "user", content: "hi" }] }, + }); + expect(completion.statusCode).toBe(200); + + const third = await app.inject({ method: "GET", url: "/admin/status", headers: AUTH }); + expect(third.statusCode).toBe(429); + expect(Number(third.headers["retry-after"])).toBeGreaterThanOrEqual(1); + expect((third.json() as { error?: { type?: string } }).error?.type).toBe("rate_limit_error"); + } finally { + await app.close(); + } + }); +}); + +// ------------------------------------------------------- remaining admin routes --- + +const ADMIN_ROUTES: Array<{ method: "GET" | "POST" | "DELETE"; url: string }> = [ + { method: "GET", url: "/admin/status" }, + { method: "POST", url: "/admin/models/refresh" }, + { method: "GET", url: "/admin/sessions" }, + { method: "DELETE", url: "/admin/sessions" }, + { method: "POST", url: "/admin/upstream/restart" }, +]; + +describe("admin route authentication", () => { + it.each(ADMIN_ROUTES)("$method $url rejects a request without a key", async ({ method, url }) => { + const ctx = createTestContext(); + const app = await buildServer(ctx); + try { + const response = await app.inject({ method, url }); + + expect(response.statusCode).toBe(401); + const body = response.json() as { error?: { message?: string } }; + expect(typeof body.error?.message).toBe("string"); + expect(body.error?.message ?? "").not.toBe(""); + } finally { + await app.close(); + } + }); +}); + +describe("GET /admin/status", () => { + it("returns the documented sections and the upstream stderr tail", async () => { + const ctx = contextWithUpstreamStatus({ + ready: true, + source: "env", + url: "http://127.0.0.1:20124", + pid: 4321, + stderrTail: ["server listening on http://127.0.0.1:20124", "warn: slow provider"], + }); + const app = await buildServer(ctx); + try { + const response = await app.inject({ method: "GET", url: "/admin/status", headers: AUTH }); + + expect(response.statusCode).toBe(200); + const body = response.json() as Record; + expect(typeof body["service"]).toBe("string"); + expect(typeof body["version"]).toBe("string"); + expect(typeof body["uptimeSeconds"]).toBe("number"); + + const config = body["config"] as Record; + expect(config["workdir"]).toBe(ctx.config.workdir); + expect(config["defaultAgent"]).toBe(ctx.config.agent); + expect(config["sessionCache"]).toBe(ctx.config.sessionCacheEnabled); + + const upstream = body["upstream"] as Record; + expect(upstream["ready"]).toBe(true); + expect(upstream["url"]).toBe("http://127.0.0.1:20124"); + expect(upstream["pid"]).toBe(4321); + // The last stderr lines of the supervised server are exposed verbatim, so + // an operator can diagnose a failed start without shell access. + expect(upstream["stderrTail"]).toEqual([ + "server listening on http://127.0.0.1:20124", + "warn: slow provider", + ]); + // A status without a resolved binary reports `null`, never `undefined`. + expect(upstream["binary"]).toBeNull(); + + const models = body["models"] as Record; + expect(models["cached"]).toBe(0); + expect(models["agents"]).toBe(0); + expect(models["fetchedAt"]).toBeNull(); + + const sessions = body["sessions"] as Record; + expect(sessions["entries"]).toBe(0); + } finally { + await app.close(); + } + }); +}); + +describe("POST /admin/models/refresh", () => { + it("reloads the catalogue and caches it for the next status call", async () => { + const ctx = createTestContext(); + const app = await buildServer(ctx); + try { + const before = await app.inject({ method: "GET", url: "/admin/status", headers: AUTH }); + expect((before.json() as { models: { cached: number } }).models.cached).toBe(0); + + const response = await app.inject({ method: "POST", url: "/admin/models/refresh", headers: AUTH }); + + expect(response.statusCode).toBe(200); + const body = response.json() as { refreshedAt: unknown; models: unknown; providers: unknown; agents: unknown }; + expectIsoTimestamp(body.refreshedAt); + expect(body.models).toBe(5); + expect(body.providers).toEqual(["opencode"]); + expect(body.agents).toEqual(["build", "plan"]); + + const after = await app.inject({ method: "GET", url: "/admin/status", headers: AUTH }); + const status = after.json() as { models: { cached: number; agents: number; fetchedAt: unknown } }; + expect(status.models.cached).toBe(5); + expect(status.models.agents).toBe(2); + expectIsoTimestamp(status.models.fetchedAt); + } finally { + await app.close(); + } + }); +}); + +describe("sticky session administration", () => { + it("lists every cached session with its documented fields", async () => { + const ctx = createTestContext(); + seedSession(ctx, "conv-a", "ses_a"); + const app = await buildServer(ctx); + try { + const response = await app.inject({ method: "GET", url: "/admin/sessions", headers: AUTH }); + + expect(response.statusCode).toBe(200); + const body = response.json() as { count: number; sessions: Array> }; + expect(body.count).toBe(1); + expect(body.sessions).toHaveLength(1); + + const session = body.sessions[0] ?? {}; + expect(session["key"]).toBe("conv-a"); + expect(session["sessionId"]).toBe("ses_a"); + expect(session["model"]).toBe(MODEL); + expect(session["agent"]).toBe("build"); + expect(session["variant"]).toBeNull(); + expect(session["deliveredCount"]).toBe(1); + expect(session["reusedCount"]).toBe(0); + expect(session["busy"]).toBe(false); + expectIsoTimestamp(session["createdAt"]); + expectIsoTimestamp(session["lastUsedAt"]); + } finally { + await app.close(); + } + }); + + it("drops every cached session and reports how many were cleared", async () => { + const ctx = createTestContext(); + seedSession(ctx, "conv-a", "ses_a"); + seedSession(ctx, "conv-b", "ses_b"); + const app = await buildServer(ctx); + try { + const cleared = await app.inject({ method: "DELETE", url: "/admin/sessions", headers: AUTH }); + expect(cleared.statusCode).toBe(200); + expect(cleared.json()).toEqual({ cleared: 2 }); + + const after = await app.inject({ method: "GET", url: "/admin/sessions", headers: AUTH }); + expect(after.json()).toEqual({ count: 0, sessions: [] }); + + const again = await app.inject({ method: "DELETE", url: "/admin/sessions", headers: AUTH }); + expect(again.json()).toEqual({ cleared: 0 }); + } finally { + await app.close(); + } + }); +}); + +describe("POST /admin/upstream/restart", () => { + it("invalidates, stops and re-resolves the upstream endpoint", async () => { + const calls: string[] = []; + const base = createTestContext(); + const ctx: AppContext = { + ...base, + upstream: { + ...base.upstream, + invalidate: async (reason: string): Promise => { + calls.push(`invalidate:${reason}`); + }, + stop: async (): Promise => { + calls.push("stop"); + }, + resolve: async (): Promise => { + calls.push("resolve"); + return { url: "http://127.0.0.1:20222", password: "rotated", source: "spawned", pid: 987 }; + }, + } as unknown as AppContext["upstream"], + }; + const app = await buildServer(ctx); + try { + const response = await app.inject({ method: "POST", url: "/admin/upstream/restart", headers: AUTH }); + + expect(response.statusCode).toBe(200); + expect(response.json()).toEqual({ url: "http://127.0.0.1:20222", source: "spawned", pid: 987 }); + // The endpoint password resolved with the new endpoint stays server-side. + expect(response.body).not.toContain("rotated"); + // Documented order: invalidate, stop the spawned server, resolve a new one. + expect(calls).toEqual(["invalidate:manual restart requested", "stop", "resolve"]); + } finally { + await app.close(); + } + }); }); \ No newline at end of file diff --git a/test/docs-consistency.test.ts b/test/docs-consistency.test.ts new file mode 100644 index 0000000..792f9ba --- /dev/null +++ b/test/docs-consistency.test.ts @@ -0,0 +1,110 @@ +/** + * D1 — the environment-variable documentation must not drift from `src/config.ts`. + * + * `docs/CONFIGURATION.md` states that its table "is derived from + * `src/config.ts`; `src/config.ts` reads no other variable", and `AGENTS.md` + * requires a new variable to land in `src/config.ts`, `.env.example` and + * `docs/CONFIGURATION.md` in the same change. Nothing enforced either rule: a + * variable could be added to the code, or deleted from a document, with CI + * still green. + * + * The sources are read as text on purpose. Importing `src/config.ts` would + * execute the module, and the guard must observe the call sites rather than a + * loaded configuration. + */ +import { readFileSync } from "node:fs"; +import path from "node:path"; +import { fileURLToPath } from "node:url"; +import { describe, expect, it } from "vitest"; + +const repoRoot = path.resolve(path.dirname(fileURLToPath(import.meta.url)), ".."); + +function read(relativePath: string): string { + return readFileSync(path.join(repoRoot, relativePath), "utf8"); +} + +/** + * A name read through one of `src/config.ts`'s `env*` helpers. The helper + * suffix is optional so the plain `env()` reads count too, and `\b` plus the + * lowercase spelling keeps `warnInvalidEnv("...")` out of the set. + */ +const ENV_READ = /\benv(?:Str|OptStr|Int|Bool|List)?\(\s*"([A-Z][A-Z0-9_]*)"/g; + +/** A token that reads as an environment-variable name in documentation. */ +const DOCUMENTED_NAME = /\b(?:OPENCODE_[A-Z0-9_]+|HOST|PORT)\b/g; + +/** The variables `src/config.ts` reads. */ +function codeVariables(): Set { + const names = new Set(); + for (const match of read("src/config.ts").matchAll(ENV_READ)) { + const name = match[1]; + if (name !== undefined) names.add(name); + } + return names; +} + +/** The variables a document mentions. */ +function documentedVariables(markdown: string): Set { + // `[[OPENCODE_TOOL_CALL]]` is a prompt envelope echoed in the documentation, + // not an environment variable; drop the sentinels before scanning. + const text = markdown.replace(/\[\[[^\]]*\]\]/g, ""); + const names = new Set(); + for (const match of text.matchAll(DOCUMENTED_NAME)) { + const name = match[0]; + if (name !== undefined) names.add(name); + } + return names; +} + +/** The names of `expected` that `present` does not contain, sorted for a readable diff. */ +function missing(expected: ReadonlySet, present: ReadonlySet): string[] { + return [...expected].filter((name) => !present.has(name)).sort(); +} + +/** The README's `## Configuration summary` section, up to the next level-2 heading. */ +function configurationSummary(markdown: string): string { + const start = markdown.indexOf("## Configuration summary"); + if (start < 0) throw new Error("README.md has no '## Configuration summary' section"); + const end = markdown.indexOf("\n## ", start + 1); + return end < 0 ? markdown.slice(start) : markdown.slice(start, end); +} + +const CODE_VARIABLES = codeVariables(); +const ENV_EXAMPLE = documentedVariables(read(".env.example")); +const CONFIGURATION_DOC = documentedVariables(read("docs/CONFIGURATION.md")); +const README_TEXT = read("README.md"); + +describe("environment-variable documentation", () => { + it("finds the variables src/config.ts reads", () => { + // A broken extraction must not turn every check below into a silent no-op. + expect(CODE_VARIABLES.size).toBeGreaterThanOrEqual(40); + for (const name of ["HOST", "PORT", "OPENCODE_API_KEYS", "OPENCODE_WORKDIR"]) { + expect(CODE_VARIABLES.has(name), `${name} was not parsed out of src/config.ts`).toBe(true); + } + }); + + it("documents every variable from src/config.ts in .env.example", () => { + expect(missing(CODE_VARIABLES, ENV_EXAMPLE)).toEqual([]); + }); + + it("documents every variable from src/config.ts in docs/CONFIGURATION.md", () => { + expect(missing(CODE_VARIABLES, CONFIGURATION_DOC)).toEqual([]); + }); + + it("names every variable from src/config.ts in README.md", () => { + // The README table is deliberately a summary and delegates completeness to + // `docs/CONFIGURATION.md`, so the guard is that the document names every + // variable somewhere. A variable a reader cannot discover is drift too. + expect(missing(CODE_VARIABLES, documentedVariables(README_TEXT))).toEqual([]); + }); + + it("documents no variable that src/config.ts does not read", () => { + // `OPENCODE_API_URL` is read by `scripts/smoke.mjs` and the integration + // suite, not by the configuration module; it is documented in the README's + // Development section, so only the configuration table and the two + // exhaustive files are checked here. + expect(missing(ENV_EXAMPLE, CODE_VARIABLES)).toEqual([]); + expect(missing(CONFIGURATION_DOC, CODE_VARIABLES)).toEqual([]); + expect(missing(documentedVariables(configurationSummary(README_TEXT)), CODE_VARIABLES)).toEqual([]); + }); +}); diff --git a/test/metrics.test.ts b/test/metrics.test.ts new file mode 100644 index 0000000..508a23a --- /dev/null +++ b/test/metrics.test.ts @@ -0,0 +1,112 @@ +/** + * HTTP-level tests for the Prometheus scrape endpoint (`GET /metrics`). + * + * The endpoint is authenticated like every other route. `OPENCODE_METRICS_PUBLIC` + * turns the key requirement off, and a configured `OPENCODE_METRICS_TOKEN` turns + * it back on for scrapers that must not hold a general API key (see `src/auth.ts` + * and the operational-endpoint table in `docs/API.md`). + */ +import { describe, expect, it } from "vitest"; +import { buildServer } from "../src/server.js"; +import { createTestContext } from "./helpers/context.js"; + +const AUTH = { authorization: "Bearer test-key" }; +const SCRAPE_TOKEN = "scrape-secret"; +/** Prefix of every series the endpoint exposes. */ +const SERIES_PREFIX = "opencode_api_"; + +interface ErrorBody { + error: { code?: string; type?: string }; +} + +describe("GET /metrics when metrics are disabled", () => { + it("answers 404 metrics_disabled for an authenticated caller", async () => { + const ctx = createTestContext({ config: { metricsEnabled: false } }); + const app = await buildServer(ctx); + try { + const response = await app.inject({ method: "GET", url: "/metrics", headers: AUTH }); + + expect(response.statusCode).toBe(404); + const body = response.json() as ErrorBody; + expect(body.error.code).toBe("metrics_disabled"); + } finally { + await app.close(); + } + }); + + it("still requires authentication before reporting the endpoint disabled", async () => { + const ctx = createTestContext({ config: { metricsEnabled: false } }); + const app = await buildServer(ctx); + try { + const response = await app.inject({ method: "GET", url: "/metrics" }); + + // Authentication is checked for every non-public path before routing, so a + // disabled endpoint is not an unauthenticated liveness signal. + expect(response.statusCode).toBe(401); + } finally { + await app.close(); + } + }); +}); + +describe("GET /metrics authentication", () => { + it("rejects an anonymous scrape when the endpoint is not public", async () => { + const ctx = createTestContext({ config: { metricsEnabled: true, metricsPublic: false } }); + const app = await buildServer(ctx); + try { + const denied = await app.inject({ method: "GET", url: "/metrics" }); + expect(denied.statusCode).toBe(401); + expect((denied.json() as ErrorBody).error.type).toBeDefined(); + + const allowed = await app.inject({ method: "GET", url: "/metrics", headers: AUTH }); + expect(allowed.statusCode).toBe(200); + expect(allowed.headers["content-type"]).toContain("text/plain"); + expect(allowed.body).toContain(SERIES_PREFIX); + expect(allowed.body).toContain(`${SERIES_PREFIX}http_requests_total`); + } finally { + await app.close(); + } + }); + + it("serves an anonymous scrape when OPENCODE_METRICS_PUBLIC is set and no token is configured", async () => { + const ctx = createTestContext({ config: { metricsEnabled: true, metricsPublic: true } }); + const app = await buildServer(ctx); + try { + const response = await app.inject({ method: "GET", url: "/metrics" }); + + expect(response.statusCode).toBe(200); + expect(response.headers["content-type"]).toContain("text/plain"); + // Prometheus text exposition of the documented `opencode_api_*` series. + expect(response.body).toContain(SERIES_PREFIX); + } finally { + await app.close(); + } + }); + + it("requires the configured scrape token, then still accepts a general API key", async () => { + const ctx = createTestContext({ + config: { metricsEnabled: true, metricsPublic: true, metricsToken: SCRAPE_TOKEN }, + }); + const app = await buildServer(ctx); + try { + const missing = await app.inject({ method: "GET", url: "/metrics" }); + expect(missing.statusCode).toBe(401); + + const wrong = await app.inject({ method: "GET", url: "/metrics", headers: { "x-api-key": "not-the-token" } }); + expect(wrong.statusCode).toBe(401); + + const token = await app.inject({ method: "GET", url: "/metrics", headers: { "x-api-key": SCRAPE_TOKEN } }); + expect(token.statusCode).toBe(200); + expect(token.body).toContain(SERIES_PREFIX); + + // A configured token makes the endpoint authenticated again even though + // `metricsPublic` is set, but a general key is still accepted so a script + // does not need two credentials. + const general = await app.inject({ method: "GET", url: "/metrics", headers: AUTH }); + expect(general.statusCode).toBe(200); + expect(general.body).toContain(SERIES_PREFIX); + } finally { + await app.close(); + } + }); +}); \ No newline at end of file diff --git a/test/parity.test.ts b/test/parity.test.ts new file mode 100644 index 0000000..1460213 --- /dev/null +++ b/test/parity.test.ts @@ -0,0 +1,610 @@ +/** + * Streamed-vs-buffered parity for the four completion surfaces. + * + * `AGENTS.md` makes "both paths always" a non-negotiable invariant: a surface + * that only handles one of them is otherwise caught by luck. Every case below + * runs the *same* scripted turn — reasoning, answer text, one bridged tool call + * and usage — twice, once with `stream: false` and once with `stream: true`, and + * compares a canonical projection of the two responses: answer text, reasoning, + * the assistant/message id contract, the finish/stop reason, usage totals and, + * for `/v1/responses`, the `output[]` item order and ids. + * + * Gateway-generated ids are random per response, so `normaliseId()` collapses + * their random suffix and the comparison asserts the documented id shape instead + * of an impossible literal equality. Ids that originate upstream (the tool-call + * id, the Anthropic thinking signature) are compared verbatim. + */ +import { describe, expect, it } from "vitest"; +import { buildServer } from "../src/server.js"; +import { EMPTY_USAGE, type CompletionEvent, type InternalRequest, type Usage } from "../src/types/internal.js"; +import { createTestContext, parseSse, parseSseJson } from "./helpers/context.js"; + +const AUTH = { authorization: "Bearer test-key", "content-type": "application/json" }; +const MODEL = "opencode/deepseek-v4.1-flash-free"; + +/** Upstream ids the scripted turn reports; stable across both requests. */ +const UPSTREAM_SESSION_ID = "ses_parity"; +const UPSTREAM_MESSAGE_ID = "msg_parity"; +const TOOL_CALL_ID = "call_parity"; + +const USAGE: Usage = { + ...EMPTY_USAGE, + inputTokens: 21, + outputTokens: 9, + reasoningTokens: 4, + cacheReadTokens: 3, + cacheWriteTokens: 1, + totalTokens: 34, +}; + +/** The one turn every surface runs, streamed and buffered. */ +function parityScript(request: InternalRequest): CompletionEvent[] { + return [ + { + kind: "start", + sessionId: UPSTREAM_SESSION_ID, + messageId: UPSTREAM_MESSAGE_ID, + model: request.model, + agent: "build", + reusedSession: false, + reasoningEnabled: true, + }, + { kind: "reasoning_delta", text: "Let me ", ordinal: 0 }, + { kind: "reasoning_delta", text: "think.", ordinal: 0 }, + { kind: "text_delta", text: "The answer ", ordinal: 0 }, + { kind: "text_delta", text: "is 42.", ordinal: 0 }, + { kind: "tool_calls", calls: [{ id: TOOL_CALL_ID, name: "lookup", arguments: '{"q":"parity"}' }] }, + { kind: "usage", usage: USAGE }, + { kind: "end", finishReason: "tool_calls", usage: USAGE, messageId: UPSTREAM_MESSAGE_ID }, + ]; +} + +// ------------------------------------------------------------- projection --- + +interface ToolCallView { + id: string; + name: string; + arguments: string; +} + +interface OutputItemView { + type: string; + id: string; + callId: string | null; +} + +interface CanonicalTurn { + responseId: string; + text: string; + reasoning: string; + finishReason: unknown; + usage: unknown; + toolCalls: ToolCallView[]; + /** `/v1/responses` only: `output[]` item order, ids and the stable call id. */ + outputItems?: OutputItemView[]; + /** `/v1/messages` only: the content-block contract, in order. */ + contentBlocks?: Array>; +} + +/** + * Collapse the random suffix of a gateway-generated id. + * + * The id itself cannot be equal across two HTTP requests, but the documented + * shape must be: `chatcmpl-`, `cmpl-`, `resp_`, `msg_`. + * Upstream-supplied ids contain no long hex run and survive verbatim. + */ +function normaliseId(id: string): string { + return id.replace(/[0-9a-f]{16,}/g, ""); +} + +// -------------------------------------------------------------- narrowing --- + +function asRecord(value: unknown, what: string): Record { + if (typeof value !== "object" || value === null || Array.isArray(value)) { + throw new Error(`Expected ${what} to be an object, received ${JSON.stringify(value)}`); + } + return value as Record; +} + +function asArray(value: unknown, what: string): unknown[] { + if (!Array.isArray(value)) { + throw new Error(`Expected ${what} to be an array, received ${JSON.stringify(value)}`); + } + return value; +} + +function asString(value: unknown, what: string): string { + if (typeof value !== "string") { + throw new Error(`Expected ${what} to be a string, received ${JSON.stringify(value)}`); + } + return value; +} + +function asNumber(value: unknown, what: string): number { + if (typeof value !== "number" || !Number.isFinite(value)) { + throw new Error(`Expected ${what} to be a number, received ${JSON.stringify(value)}`); + } + return value; +} + +/** Text of an optional string field; anything else (absent, null) is empty. */ +function asText(value: unknown): string { + return typeof value === "string" ? value : ""; +} + +interface SseFrame { + event?: string; + json: Record; +} + +function sseFrames(body: string): SseFrame[] { + return parseSseJson>(body).map((frame) => { + const record: SseFrame = { json: frame.json }; + if (frame.event !== undefined) record.event = frame.event; + return record; + }); +} + +function readOpenAiToolCall(value: unknown): ToolCallView { + const call = asRecord(value, "tool_call"); + const fn = asRecord(call["function"], "tool_call.function"); + return { + id: asString(call["id"], "tool_call.id"), + name: asString(fn["name"], "tool_call.function.name"), + arguments: asString(fn["arguments"], "tool_call.function.arguments"), + }; +} + +function readOpenAiToolCalls(value: unknown): ToolCallView[] { + if (value === undefined || value === null) return []; + return asArray(value, "tool_calls").map(readOpenAiToolCall); +} + +/** The chunk id shared by every streamed chunk of one response. */ +function streamChunkId(chunks: Array>): string { + const ids = new Set(chunks.map((chunk) => asString(chunk["id"], "chunk.id"))); + expect(ids.size, "every streamed chunk must carry the same response id").toBe(1); + return normaliseId([...ids][0] ?? ""); +} + +// ---------------------------------------------------------------- surfaces --- + +interface SurfaceCase { + name: string; + url: string; + payload: (stream: boolean) => Record; + /** Did the scripted turn produce reasoning / a tool call on this surface? */ + expectsReasoning: boolean; + expectsToolCalls: boolean; + /** The documented wire value for an upstream `tool_calls` finish reason. */ + expectedFinishReason: unknown; + /** The documented usage projection of `USAGE` on this surface. */ + expectedUsage: unknown; + buffered: (body: Record) => CanonicalTurn; + streamed: (body: string) => CanonicalTurn; +} + +const CHAT_TOOL = { + type: "function", + function: { + name: "lookup", + description: "Look something up", + parameters: { type: "object", properties: { q: { type: "string" } } }, + }, +}; + +const RESPONSES_TOOL = { + type: "function", + name: "lookup", + description: "Look something up", + parameters: { type: "object", properties: { q: { type: "string" } } }, +}; + +const ANTHROPIC_TOOL = { + name: "lookup", + description: "Look something up", + input_schema: { type: "object", properties: { q: { type: "string" } } }, +}; + +const CHAT: SurfaceCase = { + name: "POST /v1/chat/completions", + url: "/v1/chat/completions", + expectsReasoning: true, + expectsToolCalls: true, + expectedFinishReason: "tool_calls", + expectedUsage: { + prompt_tokens: 21, + completion_tokens: 13, + total_tokens: 34, + completion_tokens_details: { reasoning_tokens: 4 }, + prompt_tokens_details: { cached_tokens: 3 }, + }, + payload: (stream) => ({ + model: MODEL, + messages: [{ role: "user", content: "Say hello." }], + reasoning_effort: "high", + tools: [CHAT_TOOL], + tool_choice: "auto", + stream, + ...(stream ? { stream_options: { include_usage: true } } : {}), + }), + buffered: (body) => { + const choice = asRecord(asArray(body["choices"], "choices")[0], "choices[0]"); + const message = asRecord(choice["message"], "choices[0].message"); + return { + responseId: normaliseId(asString(body["id"], "id")), + text: asText(message["content"]), + reasoning: asText(message["reasoning_content"]), + finishReason: choice["finish_reason"], + usage: body["usage"], + toolCalls: readOpenAiToolCalls(message["tool_calls"]), + }; + }, + streamed: (body) => { + const chunks = sseFrames(body).map((frame) => frame.json); + + let text = ""; + let reasoning = ""; + let finishReason: unknown = null; + let usage: unknown; + const toolCalls: ToolCallView[] = []; + for (const chunk of chunks) { + for (const value of asArray(chunk["choices"], "chunk.choices")) { + const choice = asRecord(value, "chunk choice"); + const delta = asRecord(choice["delta"], "chunk delta"); + text += asText(delta["content"]); + reasoning += asText(delta["reasoning_content"]); + toolCalls.push(...readOpenAiToolCalls(delta["tool_calls"])); + if (choice["finish_reason"] !== null && choice["finish_reason"] !== undefined) { + finishReason = choice["finish_reason"]; + } + } + if (chunk["usage"] !== undefined) usage = chunk["usage"]; + } + + expect(parseSse(body).at(-1)?.data).toBe("[DONE]"); + return { responseId: streamChunkId(chunks), text, reasoning, finishReason, usage, toolCalls }; + }, +}; + +function responsesTurn(body: Record): CanonicalTurn { + const output = asArray(body["output"], "output").map((item) => asRecord(item, "output item")); + const reasoning = output + .filter((item) => item["type"] === "reasoning") + .map((item) => + asArray(item["summary"], "reasoning summary") + .map((part) => asText(asRecord(part, "summary part")["text"])) + .join(""), + ) + .join(""); + const toolCalls = output + .filter((item) => item["type"] === "function_call") + .map((item) => ({ + id: asString(item["call_id"], "function_call.call_id"), + name: asString(item["name"], "function_call.name"), + arguments: asString(item["arguments"], "function_call.arguments"), + })); + + return { + responseId: normaliseId(asString(body["id"], "id")), + text: asText(body["output_text"]), + reasoning, + finishReason: body["status"], + usage: body["usage"], + toolCalls, + outputItems: output.map((item) => ({ + type: asString(item["type"], "item.type"), + id: normaliseId(asString(item["id"], "item.id")), + callId: typeof item["call_id"] === "string" ? item["call_id"] : null, + })), + }; +} + +const RESPONSES: SurfaceCase = { + name: "POST /v1/responses", + url: "/v1/responses", + expectsReasoning: true, + expectsToolCalls: true, + expectedFinishReason: "completed", + expectedUsage: { + input_tokens: 21, + output_tokens: 13, + total_tokens: 34, + input_tokens_details: { cached_tokens: 3 }, + output_tokens_details: { reasoning_tokens: 4 }, + }, + payload: (stream) => ({ + model: MODEL, + input: "Say hello.", + reasoning: { effort: "high" }, + tools: [RESPONSES_TOOL], + stream, + }), + buffered: responsesTurn, + streamed: (body) => { + const frames = sseFrames(body); + const terminal = frames.find((frame) => + ["response.completed", "response.incomplete", "response.failed"].includes(asString(frame.json["type"], "type")), + ); + expect(terminal, "the stream must end with a terminal response event").toBeDefined(); + expect(terminal?.json["type"]).toBe("response.completed"); + const response = asRecord(terminal?.json["response"], "terminal response"); + + // `response.created` opens the response and the terminal payload must report + // the same id: the stream may not silently rename the turn at the end. + const created = frames.find((frame) => frame.json["type"] === "response.created"); + expect(asRecord(created?.json["response"], "response.created.response")["id"]).toBe(response["id"]); + + // `response.output_item.done` announces the ids the terminal payload must + // reuse, in the same order: that lifecycle parity is what O9 got wrong. + const doneItems = frames + .filter((frame) => frame.json["type"] === "response.output_item.done") + .map((frame) => asRecord(frame.json["item"], "output_item.done item")); + const outputItems = asArray(response["output"], "terminal output").map((item) => asRecord(item, "output item")); + expect(doneItems.map((item) => item["id"])).toEqual(outputItems.map((item) => item["id"])); + expect(doneItems.map((item) => item["type"])).toEqual(outputItems.map((item) => item["type"])); + + return responsesTurn(response); + }, +}; + +const COMPLETIONS: SurfaceCase = { + name: "POST /v1/completions", + url: "/v1/completions", + // The legacy wire format has no reasoning or tool-call representation, so the + // scripted turn is reduced to text and usage on both paths. + expectsReasoning: false, + expectsToolCalls: false, + expectedFinishReason: "tool_calls", + expectedUsage: { + prompt_tokens: 21, + completion_tokens: 13, + total_tokens: 34, + completion_tokens_details: { reasoning_tokens: 4 }, + prompt_tokens_details: { cached_tokens: 3 }, + }, + payload: (stream) => ({ + model: MODEL, + prompt: "Say hello.", + stream, + ...(stream ? { stream_options: { include_usage: true } } : {}), + }), + buffered: (body) => { + const choice = asRecord(asArray(body["choices"], "choices")[0], "choices[0]"); + return { + responseId: normaliseId(asString(body["id"], "id")), + text: asText(choice["text"]), + reasoning: "", + finishReason: choice["finish_reason"], + usage: body["usage"], + toolCalls: [], + }; + }, + streamed: (body) => { + const chunks = sseFrames(body).map((frame) => frame.json); + + let text = ""; + let finishReason: unknown = null; + let usage: unknown; + for (const chunk of chunks) { + for (const value of asArray(chunk["choices"], "chunk.choices")) { + const choice = asRecord(value, "chunk choice"); + text += asText(choice["text"]); + if (choice["finish_reason"] !== null && choice["finish_reason"] !== undefined) { + finishReason = choice["finish_reason"]; + } + } + if (chunk["usage"] !== undefined) usage = chunk["usage"]; + } + + expect(parseSse(body).at(-1)?.data).toBe("[DONE]"); + return { responseId: streamChunkId(chunks), text, reasoning: "", finishReason, usage, toolCalls: [] }; + }, +}; + +/** Normalised view of one Anthropic content block, buffered or streamed. */ +interface AnthropicBlock { + type: string; + text: string; + thinking: string; + signature: string; + toolId: string; + toolName: string; + input: string; +} + +function emptyAnthropicBlock(type: string): AnthropicBlock { + return { type, text: "", thinking: "", signature: "", toolId: "", toolName: "", input: "" }; +} + +function anthropicTurn( + id: string, + stopReason: unknown, + usage: unknown, + blocks: AnthropicBlock[], +): CanonicalTurn { + return { + responseId: normaliseId(id), + text: blocks.filter((block) => block.type === "text").map((block) => block.text).join(""), + reasoning: blocks.filter((block) => block.type === "thinking").map((block) => block.thinking).join(""), + finishReason: stopReason, + usage, + toolCalls: blocks + .filter((block) => block.type === "tool_use") + .map((block) => ({ id: block.toolId, name: block.toolName, arguments: block.input })), + contentBlocks: blocks.map((block) => ({ + type: block.type, + text: block.text, + thinking: block.thinking, + signature: block.signature, + toolId: block.toolId, + toolName: block.toolName, + input: block.input, + })), + }; +} + +function anthropicBlockFromWire(value: unknown): AnthropicBlock { + const block = asRecord(value, "content block"); + const type = asString(block["type"], "content block.type"); + const view = emptyAnthropicBlock(type); + if (type === "thinking") { + view.thinking = asText(block["thinking"]); + view.signature = asText(block["signature"]); + } else if (type === "text") { + view.text = asText(block["text"]); + } else if (type === "tool_use") { + view.toolId = asString(block["id"], "tool_use.id"); + view.toolName = asString(block["name"], "tool_use.name"); + view.input = JSON.stringify(block["input"]); + } + return view; +} + +const ANTHROPIC: SurfaceCase = { + name: "POST /v1/messages", + url: "/v1/messages", + expectsReasoning: true, + expectsToolCalls: true, + expectedFinishReason: "tool_use", + expectedUsage: { + input_tokens: 21, + output_tokens: 13, + cache_creation_input_tokens: 1, + cache_read_input_tokens: 3, + }, + payload: (stream) => ({ + model: MODEL, + max_tokens: 128, + stream, + thinking: { type: "enabled", budget_tokens: 2_048 }, + messages: [{ role: "user", content: "Say hello." }], + tools: [ANTHROPIC_TOOL], + }), + buffered: (body) => + anthropicTurn( + asString(body["id"], "id"), + body["stop_reason"], + body["usage"], + asArray(body["content"], "content").map(anthropicBlockFromWire), + ), + streamed: (body) => { + const frames = sseFrames(body); + const blocks = new Map(); + let id = ""; + let stopReason: unknown = null; + let usage: unknown; + + for (const frame of frames) { + const json = frame.json; + switch (json["type"]) { + case "message_start": { + const message = asRecord(json["message"], "message_start.message"); + id = asString(message["id"], "message_start.message.id"); + break; + } + case "content_block_start": { + const index = asNumber(json["index"], "content_block_start.index"); + const block = asRecord(json["content_block"], "content_block_start.content_block"); + const view = emptyAnthropicBlock(asString(block["type"], "content_block.type")); + view.toolId = asText(block["id"]); + view.toolName = asText(block["name"]); + blocks.set(index, view); + break; + } + case "content_block_delta": { + const index = asNumber(json["index"], "content_block_delta.index"); + const view = blocks.get(index); + expect(view, `content_block_delta for index ${index} must follow its content_block_start`).toBeDefined(); + if (view === undefined) break; + const delta = asRecord(json["delta"], "content_block_delta.delta"); + switch (delta["type"]) { + case "thinking_delta": + view.thinking += asText(delta["thinking"]); + break; + case "signature_delta": + view.signature = asText(delta["signature"]); + break; + case "text_delta": + view.text += asText(delta["text"]); + break; + case "input_json_delta": + view.input += asText(delta["partial_json"]); + break; + default: + break; + } + break; + } + case "message_delta": { + const delta = asRecord(json["delta"], "message_delta.delta"); + stopReason = delta["stop_reason"]; + usage = json["usage"]; + break; + } + default: + break; + } + } + + expect(frames.at(-1)?.json["type"]).toBe("message_stop"); + const ordered = [...blocks.entries()].sort(([left], [right]) => left - right); + // Block indexes are contiguous from 0, exactly like the buffered `content[]`. + expect(ordered.map(([index]) => index)).toEqual(ordered.map((_, position) => position)); + + return anthropicTurn( + id, + stopReason, + usage, + ordered.map(([, block]) => block), + ); + }, +}; + +const SURFACE_CASES: SurfaceCase[] = [CHAT, RESPONSES, COMPLETIONS, ANTHROPIC]; + +describe.each(SURFACE_CASES)("streamed/buffered parity — $name", (surface) => { + it("returns the same turn on both paths", async () => { + const ctx = createTestContext({ script: parityScript }); + const app = await buildServer(ctx); + try { + const buffered = await app.inject({ + method: "POST", + url: surface.url, + headers: AUTH, + payload: surface.payload(false), + }); + expect(buffered.statusCode, buffered.body).toBe(200); + + const streamed = await app.inject({ + method: "POST", + url: surface.url, + headers: AUTH, + payload: surface.payload(true), + }); + expect(streamed.statusCode, streamed.body).toBe(200); + expect(streamed.headers["content-type"]).toContain("text/event-stream"); + + const bufferedTurn = surface.buffered(buffered.json() as Record); + const streamedTurn = surface.streamed(streamed.body); + + // The comparison is only meaningful if the scripted turn actually + // exercised every ingredient the surface can carry. + expect(bufferedTurn.text).toBe("The answer is 42."); + expect(bufferedTurn.finishReason).toBe(surface.expectedFinishReason); + // Usage is compared against the documented projection, not just against + // the other path, so two identically wrong paths cannot pass. + expect(bufferedTurn.usage).toEqual(surface.expectedUsage); + if (surface.expectsReasoning) expect(bufferedTurn.reasoning).toBe("Let me think."); + if (surface.expectsToolCalls) { + expect(bufferedTurn.toolCalls).toEqual([ + { id: TOOL_CALL_ID, name: "lookup", arguments: '{"q":"parity"}' }, + ]); + } + + expect(streamedTurn).toEqual(bufferedTurn); + } finally { + await app.close(); + } + }); +}); \ No newline at end of file From dbfb48b6ad8e6406f8bfbd7b95589425489c4741 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Ph=E1=BA=A1m=20V=C4=83n=20=C4=90=E1=BB=8Bnh?= Date: Thu, 3 Dec 2026 12:09:22 +0700 Subject: [PATCH 08/12] ci: verify the Docker image and Windows, pin the actions The README documents a Docker deployment but no job built the image, so a broken Dockerfile could merge unnoticed, and the suite has Windows-only paths the Ubuntu matrix never runs. Add both jobs as additive entries: the three required check names and the 20.x and 22.x matrix entries are unchanged. Pin every action to the commit SHA of its release tag with the tag in a trailing comment, since a moved tag would silently change what runs in a workflow that holds a repository token, add a weekly Dependabot config for npm and github-actions, and keep pnpm audit --prod as the hard gate while reporting the dev toolchain advisories without blocking. --- .github/dependabot.yml | 33 +++++++++++++++ .github/workflows/ci.yml | 90 +++++++++++++++++++++++++++++++++++++--- Dockerfile | 3 ++ 3 files changed, 120 insertions(+), 6 deletions(-) create mode 100644 .github/dependabot.yml diff --git a/.github/dependabot.yml b/.github/dependabot.yml new file mode 100644 index 0000000..fbd4559 --- /dev/null +++ b/.github/dependabot.yml @@ -0,0 +1,33 @@ +# Dependabot keeps the dependency pins current. +# +# `ci.yml` pins every action to the commit SHA of a release tag, so without this +# file those pins would silently age. The commit prefixes mirror +# `CONTRIBUTING.md`: Dependabot pull requests are linted by the "Commit messages" +# job like any other, so `build(deps)` / `ci(deps)` are the valid spellings. +version: 2 +updates: + # Runtime and dev dependencies from package.json / pnpm-lock.yaml. + - package-ecosystem: npm + directory: "/" + schedule: + interval: weekly + open-pull-requests-limit: 10 + commit-message: + prefix: "build(deps)" + groups: + # Routine dev-tool bumps land as one pull request instead of one per + # package. Runtime dependencies keep individual pull requests because they + # change the shipped surface. + dev-dependencies: + dependency-type: development + update-types: ["minor", "patch"] + + # The actions used by .github/workflows/ci.yml; Dependabot rewrites the SHA + # and refreshes the trailing `# vN` comment. + - package-ecosystem: github-actions + directory: "/" + schedule: + interval: weekly + open-pull-requests-limit: 10 + commit-message: + prefix: "ci(deps)" diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index 0d720e3..598ce0b 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -14,6 +14,14 @@ concurrency: permissions: contents: read +# Every action is pinned to the commit SHA of the release tag named in the +# trailing comment; `.github/dependabot.yml` keeps the pins current. Never +# replace a pin with a floating `@vN` tag: this workflow holds a repository +# token, and a moved tag would silently change what runs. +# +# The required status checks on `main` are "Commit messages", +# "Verify (Node 20.x)" and "Verify (Node 22.x)". The `windows` and `docker` +# jobs below are additive and must never take over those names. jobs: commit-messages: name: Commit messages @@ -21,19 +29,19 @@ jobs: timeout-minutes: 10 steps: - name: Check out the full history - uses: actions/checkout@v7 + uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7 with: fetch-depth: 0 - name: Set up pnpm - uses: pnpm/action-setup@v6 + uses: pnpm/action-setup@73e46992e05b19abd31f2f3c20e0e7370d762115 # v6 with: # 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 + uses: actions/setup-node@8fccf151e3ba8038c300f83b40c8fd1e94f9c5ce # v7 with: node-version: 22.x cache: pnpm @@ -91,15 +99,15 @@ jobs: node: ["20.x", "22.x"] steps: - name: Check out the repository - uses: actions/checkout@v7 + uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7 - name: Set up pnpm - uses: pnpm/action-setup@v6 + uses: pnpm/action-setup@73e46992e05b19abd31f2f3c20e0e7370d762115 # v6 with: version: 12.25.1 - name: Set up Node.js ${{ matrix.node }} - uses: actions/setup-node@v7 + uses: actions/setup-node@8fccf151e3ba8038c300f83b40c8fd1e94f9c5ce # v7 with: node-version: ${{ matrix.node }} cache: pnpm @@ -123,3 +131,73 @@ jobs: - name: Audit the production dependencies run: pnpm audit --prod + + # The step above is the merge gate (`--prod` covers what ships). This one + # reports advisories in the dev toolchain too, without blocking: a + # vulnerable vitest or commitlint is worth seeing but not worth a red PR. + - name: Audit all dependencies (informational) + continue-on-error: true + run: pnpm audit + + # Windows coverage. The suite has platform-specific paths the Ubuntu matrix + # never runs: `OPEN_NOFOLLOW` collapses to 0 on Windows, the local-file read + # has a Windows fallback, and CLI discovery walks `%APPDATA%`/`%LOCALAPPDATA%`. + # The three media tests that pin POSIX `O_NOFOLLOW` semantics stay skipped here + # (`it.skipIf(platform === "win32")`) and keep running on Ubuntu; this job + # covers the rest of the suite. It is additive and not one of the required + # checks, but it is a real gate: a Windows-only regression must not merge. + windows: + name: Verify on Windows (Node 22.x) + runs-on: windows-latest + timeout-minutes: 20 + permissions: + contents: read + steps: + - name: Check out the repository + uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7 + + - name: Set up pnpm + uses: pnpm/action-setup@73e46992e05b19abd31f2f3c20e0e7370d762115 # v6 + with: + version: 12.25.1 + + - name: Set up Node.js 22.x + uses: actions/setup-node@8fccf151e3ba8038c300f83b40c8fd1e94f9c5ce # v7 + with: + node-version: 22.x + cache: pnpm + + - name: Install the dependencies + run: pnpm install --frozen-lockfile + + - name: Typecheck + run: pnpm typecheck + + - name: Build + run: pnpm build + + - name: Test + run: pnpm test + + # The README documents a Docker deployment; nothing verified the Dockerfile + # until this job existed, so a broken image could merge unnoticed. + docker: + name: Docker image + runs-on: ubuntu-latest + timeout-minutes: 20 + permissions: + contents: read + steps: + - name: Check out the repository + uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7 + + - name: Build the image + run: docker build --tag opencode-api:ci . + + # `env_file: .env` has to exist for the file to parse, and the repository + # does not ship a `.env`; the example file is a valid stand-in. This + # validates the compose contract the README documents. + - name: Validate the compose file + run: | + cp .env.example .env + docker compose config --quiet diff --git a/Dockerfile b/Dockerfile index 1f4a508..9b7a32b 100644 --- a/Dockerfile +++ b/Dockerfile @@ -25,6 +25,9 @@ RUN pnpm install --frozen-lockfile COPY tsconfig.json tsconfig.build.json ./ COPY src ./src +# `pnpm build` runs `scripts/clean-dist.mjs` before `tsc`, so the build stage +# needs the scripts directory too. +COPY scripts ./scripts RUN pnpm build # Produce a pruned, production-only dependency tree (dist is already built). From 6ec39ba2aa7a63ecf97a83aac2396a3d7f53c313 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Ph=E1=BA=A1m=20V=C4=83n=20=C4=90=E1=BB=8Bnh?= Date: Thu, 3 Dec 2026 12:09:22 +0700 Subject: [PATCH 09/12] build: clean the emitted dist and gate the integration run pnpm build now removes dist/ first, so a deleted or renamed source file cannot leave a stale module behind for smoke:dist to boot. The clean step lives in scripts/ because a Docker build stage runs it. pnpm test:all used to equal pnpm test: the integration suite skips itself when no gateway is configured, so the script silently degraded to a unit-only run. It now refuses to start, naming the two variables, instead of pretending the integration tests ran. --- package.json | 5 ++-- scripts/clean-dist.mjs | 19 +++++++++++++++ scripts/test-all.mjs | 53 ++++++++++++++++++++++++++++++++++++++++++ 3 files changed, 75 insertions(+), 2 deletions(-) create mode 100644 scripts/clean-dist.mjs create mode 100644 scripts/test-all.mjs diff --git a/package.json b/package.json index 88fe765..b5cbe89 100644 --- a/package.json +++ b/package.json @@ -45,14 +45,15 @@ "scripts": { "setup": "node scripts/init-env.mjs", "dev": "tsx watch src/index.ts", - "build": "tsc -p tsconfig.build.json", + "clean": "node scripts/clean-dist.mjs", + "build": "node scripts/clean-dist.mjs && tsc -p tsconfig.build.json", "start": "node dist/index.js", "typecheck": "tsc -p tsconfig.json --noEmit", "lint:commits": "commitlint --last --verbose", "test": "vitest run --exclude 'test/integration/**'", "test:watch": "vitest --exclude 'test/integration/**'", "test:integration": "vitest run test/integration", - "test:all": "vitest run", + "test:all": "node scripts/test-all.mjs", "smoke": "node scripts/smoke.mjs", "smoke:dist": "node scripts/smoke-dist.mjs" }, diff --git a/scripts/clean-dist.mjs b/scripts/clean-dist.mjs new file mode 100644 index 0000000..b821b52 --- /dev/null +++ b/scripts/clean-dist.mjs @@ -0,0 +1,19 @@ +#!/usr/bin/env node +/** + * Remove the emitted `dist/` tree. + * + * `pnpm build` runs this first. `tsc` overwrites the files it still emits but + * never deletes the output of a source file that was removed or renamed, so a + * stale module could survive into `pnpm start`, `pnpm smoke:dist` and the + * Docker image. Uses `node:fs` so cleaning needs no extra dependency. + * + * Exits 0 whether or not `dist/` existed. + */ +import { rmSync } from "node:fs"; +import path from "node:path"; +import { fileURLToPath } from "node:url"; + +const projectRoot = path.resolve(path.dirname(fileURLToPath(import.meta.url)), ".."); + +rmSync(path.join(projectRoot, "dist"), { recursive: true, force: true }); +console.log("clean: removed dist/"); diff --git a/scripts/test-all.mjs b/scripts/test-all.mjs new file mode 100644 index 0000000..3ba3b74 --- /dev/null +++ b/scripts/test-all.mjs @@ -0,0 +1,53 @@ +#!/usr/bin/env node +/** + * Run the whole test suite: the unit tests **and** the live integration suite. + * + * `vitest run` would do both on its own, but `test/integration/live.test.ts` + * skips itself when `OPENCODE_API_URL` and `OPENCODE_API_KEY` are unset, so + * `pnpm test:all` used to be exactly `pnpm test` while promising more. This + * wrapper makes the gate explicit and loud: + * + * pnpm test unit tests only; no gateway, credentials or CLI needed + * pnpm test:all unit + integration; requires a running gateway + * + * Exits 1 with instructions when the integration environment is incomplete, + * otherwise with vitest's own exit code. + */ +import { spawnSync } from "node:child_process"; +import { createRequire } from "node:module"; +import path from "node:path"; +import { fileURLToPath } from "node:url"; + +const projectRoot = path.resolve(path.dirname(fileURLToPath(import.meta.url)), ".."); + +/** The two variables the integration suite gates itself on. */ +const GATE = ["OPENCODE_API_URL", "OPENCODE_API_KEY"]; +const missing = GATE.filter((name) => (process.env[name] ?? "").trim() === ""); + +if (missing.length > 0) { + console.error( + [ + `test:all: ${missing.join(" and ")} must be set, otherwise the integration suite`, + "skips itself and this run would not be a full run.", + "", + "Start the gateway first (pnpm build && pnpm start), then point the suite at it:", + "", + " OPENCODE_API_URL=http://127.0.0.1:20123 \\", + " OPENCODE_API_KEY= \\", + " pnpm test:all", + "", + "Use `pnpm test` for the unit suite alone.", + ].join("\n"), + ); + process.exit(1); +} + +const vitestEntry = createRequire(import.meta.url).resolve("vitest/vitest.mjs"); +const result = spawnSync(process.execPath, [vitestEntry, "run"], { cwd: projectRoot, stdio: "inherit" }); + +if (result.error !== undefined) { + console.error(`test:all: could not start vitest: ${result.error.message}`); + process.exit(1); +} + +process.exit(result.status ?? 1); From 83de0c1d75857133fade65279265036dfd27ed35 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Ph=E1=BA=A1m=20V=C4=83n=20=C4=90=E1=BB=8Bnh?= Date: Thu, 3 Dec 2026 12:09:22 +0700 Subject: [PATCH 10/12] build: enable the unused-code and verbatim-module checks noUnusedLocals, noUnusedParameters and verbatimModuleSyntax now run in pnpm typecheck; the five dead declarations they found were removed, and EventHub keeps its constructor arity with an intentionally unused config parameter. exactOptionalPropertyTypes stays off: enabling it produces 55 errors that span the frozen internal contract, which is a separate change of its own. --- tsconfig.json | 8 +++++++- 1 file changed, 7 insertions(+), 1 deletion(-) diff --git a/tsconfig.json b/tsconfig.json index b8ffcc5..0cb8372 100644 --- a/tsconfig.json +++ b/tsconfig.json @@ -7,10 +7,12 @@ "types": ["node"], "strict": true, "noUncheckedIndexedAccess": true, + "noUnusedLocals": true, + "noUnusedParameters": true, "exactOptionalPropertyTypes": false, "noImplicitOverride": true, "noFallthroughCasesInSwitch": true, - "verbatimModuleSyntax": false, + "verbatimModuleSyntax": true, "esModuleInterop": true, "resolveJsonModule": true, "skipLibCheck": true, @@ -23,3 +25,7 @@ "include": ["src/**/*.ts", "test/**/*.ts", "vitest.config.ts"], "exclude": ["node_modules", "dist"] } + + + + From 5b266f8b5db2c286f81757c631d0f24d1ba70da9 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Ph=E1=BA=A1m=20V=C4=83n=20=C4=90=E1=BB=8Bnh?= Date: Thu, 3 Dec 2026 12:09:33 +0700 Subject: [PATCH 11/12] docs: align the reference with the hardened behaviour Bring every reference in line with the code in the same change that altered it: the new rate-limit and metrics-token variables and the private-media default in CONFIGURATION.md and the README summary, the rejected-versus-recorded field policy and x_opencode.unapplied in API.md, the Anthropic schema and status changes, count_tokens media accounting, the metrics table with the completion error_code dimension, and the operational-route behaviour that changed. ARCHITECTURE.md records the new internal facts: 404 preservation for session replay, the start backoff window and connect-phase bound, the one-handle Windows file check, the media content-encoding rule, the drain and closedSignal contract, the adapter helpers that the Responses surface shares with chat, and the outcome metrics. VERIFICATION.md gains a dated addendum so its historical findings are not read as the current state, and CONTRIBUTING.md documents what pnpm test:all now refuses to do. --- CONTRIBUTING.md | 5 +- README.md | 59 +++++++++++++--- docs/API.md | 157 +++++++++++++++++++++++++++++++++--------- docs/ARCHITECTURE.md | 144 +++++++++++++++++++++++++++++++------- docs/CONFIGURATION.md | 19 +++-- docs/VERIFICATION.md | 20 ++++++ 6 files changed, 330 insertions(+), 74 deletions(-) diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md index 8f835c9..0135660 100644 --- a/CONTRIBUTING.md +++ b/CONTRIBUTING.md @@ -33,7 +33,10 @@ cannot be merged. `pnpm test:integration` additionally needs a running gateway and consumes real upstream quota; it is skipped unless `OPENCODE_API_URL` and `OPENCODE_API_KEY` are -set. +set. `pnpm test:all` runs the unit suite and the integration suite in one +`vitest run`; because the integration tests skip themselves when no gateway is +configured, it refuses to start (exit 1, naming `OPENCODE_API_URL` and +`OPENCODE_API_KEY`) instead of silently degrading to a unit-only run. ## Ground rules diff --git a/README.md b/README.md index 543bc2e..46722d5 100644 --- a/README.md +++ b/README.md @@ -11,7 +11,11 @@ existing OpenAI or Anthropic SDK at it by changing only the base URL. ## Requirements -* **Node.js >= 20.11** (verified on Node 26) +* **Node.js >= 20.11** — the supported range is the CI matrix: Linux with Node + 20.x and 22.x, plus Windows with Node 22.x, which exercises the + Windows-specific paths (`O_NOFOLLOW` is unavailable there, CLI discovery walks + `%APPDATA%`/`%LOCALAPPDATA%`). The container image ships Node 22 + (`node:22-bookworm-slim`). * **pnpm** (the repository ships a `pnpm-lock.yaml`) * An installed **`opencode` CLI 2.x** on `PATH`, or an explicit path through `OPENCODE_BIN` (verified against **2.3.2** and **2.4.3**) @@ -468,19 +472,32 @@ model_disabled`. Query `GET /v1/models` instead of guessing. | `HOST` / `PORT` | `127.0.0.1` / `20123` | Listen address. | | `OPENCODE_API_KEYS` | `sk-dummy-123` | Accepted caller keys (comma separated). Replace the built-in default before exposing the port. | | `OPENCODE_ALLOW_NO_AUTH` | `false` | Start without keys (dangerous). | +| `OPENCODE_METRICS_TOKEN` | *(unset)* | Dedicated scrape token for `GET /metrics`; configuring it keeps that endpoint authenticated even with `OPENCODE_METRICS_PUBLIC=true`. | +| `OPENCODE_RATE_LIMIT_RPM` | `0` (disabled) | Per-minute request budget per API key; `0` turns rate limiting off. | +| `OPENCODE_RATE_LIMIT_BURST` | `0` (disabled) | Burst capacity allowed on top of the per-minute budget. | +| `OPENCODE_CORS_ORIGINS` | *(empty)* | Browser origins allowed to call the gateway; `*` allows every origin. | | `OPENCODE_SERVER_URL` / `OPENCODE_SERVER_PASSWORD` | *(unset)* | Explicit upstream server. | | `OPENCODE_AUTOSTART` | `true` | Spawn a private `opencode serve`. | | `OPENCODE_BIN` | *(unset)* | Path to the OpenCode CLI executable. | +| `OPENCODE_START_TIMEOUT_MS` | `30000` | Time allowed for the private upstream server to report readiness. | +| `OPENCODE_REQUEST_TIMEOUT_MS` | `600000` | Wall-clock budget for one upstream turn. | | `OPENCODE_WORKDIR` | `/workspace` | Directory the agent may work in. | | `OPENCODE_AGENT` | `build` | Default agent for API turns. | +| `OPENCODE_AGENT_MAX_STEPS` | *(unset)* | Maximum agent steps per turn. | | `OPENCODE_ALLOW_LOCAL_FILES` | `false` | Accept local-path attachments. | -| `OPENCODE_ALLOW_PRIVATE_MEDIA_URLS` | `true` | Allow remote media on private hosts (set `false` to close SSRF). | +| `OPENCODE_ALLOW_PRIVATE_MEDIA_URLS` | `false` | Allow remote media on private hosts (enabling it re-opens SSRF). | | `OPENCODE_MAX_ATTACHMENT_BYTES` | `20971520` | Per-request media budget. | | `OPENCODE_REASONING_DEFAULT` | `on-request` | Global reasoning policy. | | `OPENCODE_SESSION_CACHE` | `true` | Reuse upstream sessions. | +| `OPENCODE_SESSION_PERSIST` | `false` | Persist the session cache to `/sessions.json`. | +| `OPENCODE_MODEL_CACHE_TTL_MS` | `300000` | Model catalog cache lifetime. | | `OPENCODE_TOOL_BRIDGE_DENY_NATIVE_TOOLS` | `true` | Deny built-in agent tools when client tools are bridged. | | `OPENCODE_EXPOSE_NATIVE_TOOLS` | `false` | Stream `opencode.tool_call` events. | +| `OPENCODE_NATIVE_TOOL_EVENT` | `opencode.tool_call` | SSE event name for native tool activity. | | `OPENCODE_LOG_LEVEL` | `info` | Pino log level. | +| `OPENCODE_LOG_PRETTY` | `true` on a TTY | Pretty-print logs instead of JSON lines. | +| `OPENCODE_METRICS_ENABLED` | `true` | Prometheus collection; `false` makes `GET /metrics` answer `404`. | +| `OPENCODE_INSTANCE_ID` | `opencode-api-` | Instance identifier, and the fingerprint of the persisted session cache. | Every variable, with types, defaults and security notes: [docs/CONFIGURATION.md](docs/CONFIGURATION.md). @@ -547,13 +564,22 @@ Every variable, with types, defaults and security notes: `OPENCODE_TOOL_BRIDGE_DENY_NATIVE_TOOLS=true` (the default). Requests without `tools` are not restricted by this mechanism at all — bound them with `OPENCODE_AGENT_PERMISSIONS` and a read-only agent instead. -* **SSRF through remote media.** `OPENCODE_ALLOW_PRIVATE_MEDIA_URLS=true` - (the default) lets a caller make the gateway fetch `http://127.0.0.1:...`, - RFC1918 addresses, `169.254.169.254` metadata endpoints and similar. Set it to - `false` on any deployment reachable by untrusted clients. +* **SSRF through remote media.** `OPENCODE_ALLOW_PRIVATE_MEDIA_URLS` is `false` + by default. Setting it to `true` lets a caller make the gateway fetch + `http://127.0.0.1:...`, RFC1918 addresses, `169.254.169.254` metadata endpoints + and similar; the gateway then logs a startup error while `HOST` is not a + loopback address. Leave it `false` on any deployment reachable by untrusted + clients. * **Local file disclosure.** `OPENCODE_ALLOW_LOCAL_FILES=false` by default. If you enable it, keep `OPENCODE_ALLOWED_FILE_ROOTS` narrow and remember that - symlinks are resolved before the check. + symlinks are resolved before the check (on Windows a final symlink or junction + is refused and the opened handle is re-checked against the pre-open `lstat`). +* **Unbounded per-key traffic.** `OPENCODE_RATE_LIMIT_RPM=0` disables the + built-in limiter. Set it (with `OPENCODE_RATE_LIMIT_BURST`) on a shared + deployment so one key cannot drive unlimited paid upstream turns. +* **Anonymous metrics.** `OPENCODE_METRICS_PUBLIC=true` exposes model names and + traffic without authentication; prefer `OPENCODE_METRICS_TOKEN` and keep the + endpoint closed. * Put the gateway behind TLS, keep CORS origins explicit, and do not enable `OPENCODE_TRUST_PROXY` unless a proxy you control sets the forwarded headers. @@ -587,8 +613,14 @@ The compose file maps `20123:20123`, reads `.env`, mounts `${OPENCODE_DATA_DIR:-./.opencode-api}:/data` and `${OPENCODE_WORKDIR:-./workspace}:/workspace`, and sets `OPENCODE_DATA_DIR=/data`, `OPENCODE_WORKDIR=/workspace` and -`OPENCODE_BIN=/usr/local/bin/opencode`. The container runs as the non-root -`node` user, so the mounted directories must be writable by UID 1000. +`OPENCODE_BIN=/usr/local/bin/opencode`. + +The image itself is built from `node:22-bookworm-slim`, declares `/data` and +`/workspace` as volumes, defaults `HOST=0.0.0.0` and `PORT=20123`, ships a +`HEALTHCHECK` that probes `/health` with the bundled Node runtime, and runs as +the non-root `node` user (uid/gid 1000) — so the mounted directories must be +writable by UID 1000. CI builds the image on every pull request +(`.github/workflows/ci.yml`, job "Docker image") and validates this compose file. ## Development @@ -596,14 +628,19 @@ 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 and emit `src/` into `dist/` with `tsc -p tsconfig.build.json`. | +| `pnpm clean` | Remove `dist/`. | +| `pnpm build` | Remove `dist/` first, then type-check and emit `src/` into it with `tsc -p tsconfig.build.json`, so a removed or renamed source cannot leave stale output behind. | | `pnpm typecheck` | `tsc -p tsconfig.json --noEmit`. | | `pnpm test` | Unit tests (excludes `test/integration/**`). | | `pnpm test:integration` | Integration tests against a live gateway/upstream. | -| `pnpm test:all` | Everything. | +| `pnpm test:all` | Unit **and** integration tests. Refuses to start (exit 1) unless `OPENCODE_API_URL` and `OPENCODE_API_KEY` are set, because the integration suite skips itself without them. | | `pnpm lint:commits` | Lint the latest commit message against `commitlint.config.mjs`. | | `pnpm smoke` | Run `scripts/smoke.mjs` against a running gateway. | +`pnpm test:all` means what it says: instead of silently running the unit suite +only, it prints the missing variables and exits 1. Use `pnpm test` for the unit +suite alone and `pnpm test:integration` for the live suite alone. + `pnpm smoke` reads `OPENCODE_API_URL` (default `http://127.0.0.1:20123`) and `OPENCODE_API_KEY` (defaults to `sk-dummy-123`) and checks health, models, non-streaming chat, streaming chat and Anthropic messages: diff --git a/docs/API.md b/docs/API.md index 1ea6232..f678a3c 100644 --- a/docs/API.md +++ b/docs/API.md @@ -21,7 +21,7 @@ operational; it is summarised at the end of this document and in the README. | Name | Kind | Meaning | | --- | --- | --- | -| `x_opencode` | response field | Non-standard object carried by every buffered completion payload and by the `response` object of the `/v1/responses` SSE events (`response.created`, `response.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_opencode` | response field | Non-standard object carried by every buffered completion payload and by the `response` object of the `/v1/responses` SSE events (`response.created`, `response.in_progress`, `response.completed`, `response.failed`): `session_id`, `agent`, `variant`, `reused_session`, and `native_tool_calls` (an array on the OpenAI surfaces, a count on the Anthropic surface) plus `reasoning: {enabled, note}` on `/v1/chat/completions`. `unapplied` (array) names the generation knobs the request supplied that the gateway recorded but could not apply, in the fixed order `temperature, top_p, presence_penalty, frequency_penalty, seed, logit_bias, max_tokens, max_completion_tokens, max_output_tokens`; the key is omitted when none were supplied. The `/v1/chat/completions`, `/v1/completions` and Anthropic **streamed** sequences do not carry `x_opencode` (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. | @@ -34,16 +34,32 @@ Authentication is required on every endpoint in the table above. Send one of `OPENCODE_API_KEYS` is not configured; set your own before exposing the gateway. Query-string keys (`?api_key=`) are deliberately **not** supported because request URLs are logged. `/`, `/health`, `/ready` and `/healthz` are exempt (and `/metrics` -when `OPENCODE_METRICS_PUBLIC=true`). +when `OPENCODE_METRICS_PUBLIC=true` and no `OPENCODE_METRICS_TOKEN` is set, which +re-authenticates the endpoint in constant time). > **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 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`. +> validate, and the rows say exactly how each one behaves: +> +> * `stop` is honoured on `/v1/chat/completions` and `/v1/completions` (the +> visible text is truncated at the first delimiter, on both the buffered and the +> streamed path). +> * The generation knobs OpenCode's agent loop owns — `temperature`, `top_p`, +> `presence_penalty`, `frequency_penalty`, `seed`, `logit_bias`, `max_tokens`, +> `max_completion_tokens`, `max_output_tokens` — are accepted and recorded for +> client compatibility but cannot be applied. Every response names them in +> `x_opencode.unapplied`, so a caller can detect it instead of guessing. +> * A field that would change the *shape* of the response and cannot be emulated +> at all is rejected with `400 unsupported_parameter`, naming the field in +> `param` (see the individual rows: `logprobs`/`top_logprobs`, non-text +> `modalities`, `audio`, `prediction`, `store: true`, `web_search_options`, the +> legacy `functions`/`function_call`, `previous_response_id`, non-empty +> `include`, `best_of`, `suffix`, and any media `detail` other than `"auto"`). +> A 400 with an empty `param` is a malformed body. +> +> A malformed body is rejected with `400 invalid_request_error` naming the +> offending field in `param`. ## 1. `POST /v1/chat/completions` @@ -65,17 +81,19 @@ 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. `400 invalid_request` (`param: "tool_choice"`) when it requires a tool but `tools` is absent or empty. | +| `tool_choice` | `auto` \| `none` \| `required` \| `{type:"function",function:{name}}` | `auto` | Rendered into the bridge instructions. `400 invalid_request` (`param: "tool_choice"`) when it requires a tool but `tools` is absent or empty, or when it names a function the request never declared. | | `reasoning_effort` | string | *(unset)* | `none`, `minimal`, `low`, `medium`, `high`, `xhigh`, `max` plus aliases (`off`, `min`, `maximum`, ...). | | `reasoning.effort` | string | *(unset)* | 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 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`. | +| `max_tokens` / `max_completion_tokens` | number | *(unset)* | `max_completion_tokens` wins. Accepted and recorded, not enforced upstream: OpenCode's agent owns the generation budget. Listed in `x_opencode.unapplied` when supplied. | +| `temperature`, `top_p` | number | *(unset)* | Accepted and recorded, but not forwarded: OpenCode's agent loop owns the sampling parameters. Listed in `x_opencode.unapplied` when supplied. | +| `stop` | string \| string[] | *(unset)* | **Honoured on both paths**: the visible text is truncated at the first delimiter, empty strings are dropped. Generation upstream is not interrupted, so `usage` counts the full turn and `finish_reason` stays `stop`. | | `n` | number | `1` | **Only `1` is supported**; anything else returns `400 invalid_request`. | | `user`, `metadata`, `service_tier` | — | — | Accepted; not forwarded and **not logged**. `metadata` is carried on the internal request so a future surface can use it, but nothing reads it today. | | `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. | +| `seed`, `logprobs`, `logit_bias`, `presence_penalty`, `frequency_penalty` | — | — | `seed`, `logit_bias`, `presence_penalty` and `frequency_penalty` are accepted and recorded, and named in `x_opencode.unapplied` when supplied. `logprobs`/`top_logprobs` are **rejected** with `400 unsupported_parameter` unless they are disabled (`logprobs: false`), because the gateway cannot produce token-level scores. | +| `messages[].content[].image_url.detail` | string | `auto` | Only `"auto"` is accepted; the gateway cannot downscale media, so any other value is `400 unsupported_parameter` with `param: "messages"`. | +| `top_logprobs`, `modalities`, `audio`, `prediction`, `store`, `web_search_options`, `functions`, `function_call` | — | — | Rejected with `400 unsupported_parameter` naming the field, because the gateway cannot produce the response shape they ask for. `store: false` and `function_call: "none"` are accepted as no-ops, and `modalities: ["text"]` is accepted. | ### Response (`stream: false`) @@ -208,7 +226,7 @@ data: {"error":{"message":"The upstream completion ended with an error.","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; mid-stream the hint travels as `retry_after_ms` in the error frame instead) | +| `429` | `rate_limit_error` | `provider.free-limit`, `rate_limit_error`, `rate_limit_exceeded` (the gateway's own limiter; 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`, `upstream_unauthorized`, `upstream_invalid_json` | @@ -216,6 +234,10 @@ data: {"error":{"message":"The upstream completion ended with an error.","type": | `504` | `api_error` | `timeout_error`, `upstream_timeout` | | `500` | `api_error` | `internal_error` — an unexpected gateway failure; the message never contains credentials | +`unsupported_parameter` is also a valid `400` code: it names, in `param`, a +request field the gateway cannot honour. See the policy in "Reading this +reference". + ### curl ```bash @@ -247,17 +269,18 @@ reasoning mapping and tool bridging with the chat endpoint. | `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`, `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. | +| `instructions` | string | *(unset)* | Prepended as a `system` turn **and echoed** on the response object. | | `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:`. `400 invalid_request` (`param: "tool_choice"`) when it requires a tool but `tools` is absent or empty. | +| `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, or when it names a function the request never declared. | | `reasoning.effort` | string | *(unset)* | Same ladder as `reasoning_effort`. `reasoning.summary` is echoed only. | -| `max_output_tokens`, `temperature`, `top_p`, `metadata`, `truncation` | — | — | Accepted and echoed back; `truncation` defaults to `"disabled"` and is **not applied** (the gateway never trims history), and the other four are echoed but not forwarded to the provider. `metadata` is not logged. | +| `max_output_tokens`, `temperature`, `top_p`, `metadata`, `truncation` | — | — | Accepted and echoed back; `truncation` defaults to `"disabled"` and is **not applied** (the gateway never trims history), and the other four are echoed but not forwarded to the provider. `metadata` is not logged. `max_output_tokens`, `temperature` and `top_p` are named in `x_opencode.unapplied` when supplied. | | `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. | +| `previous_response_id` | string | *(unset)* | **Rejected** with `400 unsupported_parameter`: the gateway keeps no response store, so resend the full `input`. The successful response echoes it as `null`. | +| `store` | boolean | `false` | `store: false` is accepted and echoed (nothing is persisted); `store: true` is rejected with `400 unsupported_parameter`. | | `text.format` | object | *(unset)* | `{"type":"text"}`, `{"type":"json_object"}` or `{"type":"json_schema",name,schema}`. Rendered into the prompt like the chat `response_format`; see "JSON output mode". | -| `include`, `service_tier`, `top_logprobs`, `user` | — | — | Accepted for compatibility; no effect. | +| `include`, `top_logprobs`, `modalities`, `audio`, `prediction`, `web_search_options`, `functions`, `function_call`, `seed`, `presence_penalty`, `frequency_penalty`, `logit_bias` | — | — | The generation knobs (`seed`, penalties, `logit_bias`) are accepted and recorded, and named in `x_opencode.unapplied` when supplied. Everything else in this row is rejected with `400 unsupported_parameter` naming the field: `include` must be empty, `logprobs`/`top_logprobs` cannot be produced, an audio modality cannot be answered, and the legacy `functions`/`function_call` shape is not emulated. `function_call: "none"`, `store: false`, `logprobs: false` and `include: []` are accepted as no-ops. | +| `input[].content[].detail` | string | `auto` | Only `"auto"` is accepted; the gateway cannot downscale media, so any other value is `400 unsupported_parameter` with `param: "input"`. | `item_reference` items are skipped (they point at stored responses the gateway does not keep). `reasoning` items are accepted and ignored: a caller may resend a @@ -385,19 +408,30 @@ data: {"type":"response.completed","sequence_number":8,"response":{"id":"resp_.. 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 - `response.output_item.done` with `output_index: 0`. + and `response.reasoning_summary_part.done`. The reasoning item is announced + first, with `response.output_item.added` at `output_index: 0` and status + `in_progress`, so every `output_index` a client sees is opened before its first + delta; the closing item then appears as `response.output_item.done` with + `output_index: 0` and status `completed`. * The message item occupies `output_index: 1` when a reasoning item precedes it. + Text that arrives only in the consolidated `text_end` event still gets its + `output_item.added`/`content_part.added` pair, so `output[0]` always matches + `output_text`. * Tool calls are emitted at the end of the stream as `response.output_item.added` (status `in_progress`), one `response.function_call_arguments.delta` carrying the whole argument string, `response.function_call_arguments.done`, then `response.output_item.done` with status `completed`. * A length-limited turn ends with `event: response.incomplete` instead of - `response.completed`. + `response.completed`. So does a turn the provider filtered: the response object + then reports `status: "incomplete"` with + `incomplete_details: {"reason": "content_filter"}` (a length limit reports + `{"reason": "max_output_tokens"}`), and the message item is closed with + `status: "incomplete"`. * A failed turn ends with a terminal `event: response.failed` carrying the final - response object with `status: "failed"` and its `error` object. The flat - `event: error` frame is also emitted for backwards compatibility: + response object with `status: "failed"` and its `error` object. Its `usage` is + `null` — not zeros — when the turn failed before any usage event arrived. The + flat `event: error` frame is also emitted for backwards compatibility: ``` event: response.failed @@ -437,10 +471,14 @@ the wire format. Use `/v1/chat/completions` for anything new. | `n` | number | `1` | Only `1` is supported; any other value is `400 invalid_request`. | | `stream` | boolean | `false` | Emit `text_completion` SSE chunks terminated by `data: [DONE]`. | | `stream_options.include_usage` | boolean | `false` | Adds a final usage-only chunk (`choices: []`). | -| `max_tokens`, `temperature`, `stop` | — | *(unset)* | Accepted and recorded; the OpenCode agent owns the generation budget, so they are not enforced upstream. | +| `max_tokens`, `temperature` | — | *(unset)* | Accepted and recorded; the OpenCode agent owns the generation budget and the sampling parameters, so they are not applied. Both are named in `x_opencode.unapplied` when supplied. | +| `stop` | string \| string[] | *(unset)* | **Honoured on both paths**: the visible text is truncated at the first delimiter and `finish_reason` stays `stop`. Generation upstream is not interrupted. | +| `presence_penalty`, `frequency_penalty`, `seed`, `logit_bias` | — | *(unset)* | Accepted and recorded, not applied; named in `x_opencode.unapplied` when supplied. | | `user` | string | — | Accepted and ignored (correlation is done with `x-request-id`). | | `echo` | boolean | `false` | `true` is rejected with `400 unsupported_parameter` (the prompt is rewritten before it reaches the model). | -| `suffix`, `best_of`, `logprobs` | — | — | Not supported; unknown fields are ignored. | +| `suffix`, `best_of` | — | — | Rejected with `400 unsupported_parameter` naming the field. | +| `logprobs`, `top_logprobs` | — | — | Rejected with `400 unsupported_parameter` unless disabled (`logprobs: false` or `0`), because the gateway cannot produce token-level scores. | +| `modalities`, `audio`, `prediction`, `store: true`, `web_search_options`, `functions`, `function_call` | — | — | Rejected with `400 unsupported_parameter` naming the field; the legacy completion API cannot answer those shapes. `store: false` and `function_call: "none"` are accepted as no-ops. | `x-conversation-id` works exactly as on `/v1/chat/completions`. @@ -519,14 +557,14 @@ Anthropic Messages API. | `tool_use` block | `{id,name,input}` | — | Assistant messages only; `input` is serialised to the argument string. | | `tool_result` block | `{tool_use_id, content?, is_error?}` | — | User messages only. `content` is a string or `text`/`image`/`document` blocks. 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. | +| `max_tokens` | integer ≥ 1 | — | Required by the Anthropic schema and validated (zero and negative values are `400 invalid_request` with `param: "max_tokens"`); the upper bound is 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.) | +| `thinking` | object | *(unset)* | `{type:"enabled",budget_tokens}` or `{type:"disabled"}`. (The adapter validates `budget_tokens`; the non-standard `effort` key is accepted and mapped exactly like the top-level `reasoning_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. `400 invalid_request` (`param: "tool_choice"`) when it requires a tool but `tools` is absent or empty. | +| `tool_choice` | `{type:"auto"}` \| `{type:"any"}` \| `{type:"none"}` \| `{type:"tool",name}` | auto | `any` maps to a required call, `tool` to a named call. Any of `auto`, `any` and `tool` additionally accepts `disable_parallel_tool_use: true`, which caps the turn at one tool call. `400 invalid_request` (`param: "tool_choice"`) when it requires a tool but `tools` is absent or empty, or when a named tool was never declared. | | `temperature`, `top_p`, `metadata.user_id` | — | *(unset)* | Accepted and recorded; not forwarded to the provider (the OpenCode agent owns sampling), and `metadata` is **not** logged. | | `top_k`, `service_tier`, `container`, `mcp_servers` | — | — | Accepted and ignored. | | `cache_control` | object | — | Accepted on text/image/document/tool blocks and ignored. | @@ -573,6 +611,14 @@ Anthropic Messages API. Its `signature` is `base64("opencode-api:")` — a deterministic placeholder, not a cryptographic attestation. * `x_opencode.native_tool_calls` is a **count** on this surface. +* A turn the upstream reports as failed is **not** a normal response: a buffered + request answers `502 api_error` with the Anthropic error body, and a streamed + turn ends with an `error` event (`api_error`) instead of + `message_delta`/`message_stop`, so a partial answer is never presented as a + completed one. +* A turn the upstream reports as cancelled keeps `stop_reason: "end_turn"` but + sets `x_opencode.interrupted: true`; the streamed form carries + `x_opencode: {"interrupted": true}` on the final `message_delta`. * Bridged tool calls become `tool_use` blocks `{type:"tool_use",id,name,input}` where `input` is the parsed arguments object (an empty object when the arguments are not a JSON object). @@ -628,6 +674,14 @@ data: {"type":"content_block_stop","index":2} 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. + +`message_start.message.usage` is always +`{"input_tokens": 0, "output_tokens": 0}`: the gateway learns usage only when the +turn ends. The authoritative totals — `input_tokens`, `output_tokens` (thinking +tokens included), `cache_creation_input_tokens` and `cache_read_input_tokens` — +arrive in the final `message_delta.usage`, so SDK cost accounting must read usage +from `message_delta`, not from `message_start`. + 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: @@ -690,13 +744,18 @@ is still resolved, so an unknown model returns `404`. } ``` +`method` is `"mixed"`, or `"mixed+media"` when inline media was charged. + The number is an **approximation**: OpenCode exposes no tokenizer endpoint, so 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 -placeholder instead. The `x_opencode` object marks the value as an estimate so +`1`. Media blocks are not downloaded for this endpoint: an inline `base64` block +is charged `ceil(decodedBytes / 750)` bytes-per-token, while a `url` block +contributes only a short placeholder because its size is unknown. +`x_opencode.method` is `"mixed+media"` when inline media was present and +`"mixed"` otherwise. The `x_opencode` object marks the value as an estimate so callers can decide whether it is accurate enough. ### Errors @@ -863,14 +922,46 @@ These are not model surfaces; they report or control gateway state. | `GET` | `/health` | public | `{status:"ok", service, version, uptimeSeconds, upstream:{ready, source}}` — liveness only, never calls upstream. | | `GET` | `/ready` | public | `200 {status:"ready", ..., upstream:{ready,source,url,models}}` only when an upstream endpoint is resolved **and** a model catalogue is already cached; otherwise `503 {status:"unavailable", ..., upstream:{ready:false,...,error}}`. Reads cached state only, so an anonymous probe cannot trigger upstream work. Force a refresh with `POST /admin/models/refresh`. | | `GET` | `/healthz` | public | Minimal liveness alias `{status:"ok", service, version}`. | -| `GET` | `/metrics` | key, unless `OPENCODE_METRICS_PUBLIC=true` | Prometheus text exposition (`opencode_api_*`). `404 metrics_disabled` when `OPENCODE_METRICS_ENABLED=false`. | -| `GET` | `/admin/status` | key | Service version, uptime, a config subset, upstream status (URL/pid/last error), catalogue counts and session-cache counts. | +| `GET` | `/metrics` | key or `OPENCODE_METRICS_TOKEN`, unless `OPENCODE_METRICS_PUBLIC=true` **and** no token is configured | Prometheus text exposition (`opencode_api_*`). `404 metrics_disabled` when `OPENCODE_METRICS_ENABLED=false`. | +| `GET` | `/admin/status` | key | Service version, uptime, a config subset, upstream status (URL/pid/last error/`stderrTail` — the last 50 stderr lines of the supervised server), catalogue counts and session-cache counts. | | `GET` | `/admin/config` | key | The effective configuration, with `auth.apiKeyCount`, `auth.usingDefaultApiKey` and `upstream.passwordConfigured` instead of the secrets themselves. `upstream.url`, timeouts, media limits, session settings and reasoning defaults are included. | | `POST` | `/admin/models/refresh` | key | Forces a catalogue reload and returns `{refreshedAt, models, providers, agents}`. | | `GET` | `/admin/sessions` | key | Every cached sticky session: key, session id, model, agent, variant, delivered/reused counts, `busy`, timestamps. | | `DELETE` | `/admin/sessions` | key | Drops every cached session; returns `{cleared}`. | | `POST` | `/admin/upstream/restart` | key | Invalidates the endpoint, stops the spawned server if there is one, and resolves a new one; returns `{url, source, pid}`. | +When `OPENCODE_RATE_LIMIT_RPM` is non-zero every authenticated request is charged +against a per-key token bucket (with a separate bucket for `/admin/*`). A +rejected request answers `429` with `error.code: "rate_limit_exceeded"` and a +`retry-after` header in seconds. `/health`, `/ready`, `/healthz` and `/` are never +rate limited. + +### Metrics + +`GET /metrics` exposes the `opencode_api_` series below (Prometheus text format; +`OPENCODE_METRICS_ENABLED=false` answers `404 metrics_disabled`). + +| Series | Type | Labels | +| --- | --- | --- | +| `http_requests_total`, `http_request_duration_seconds` | counter, histogram | `method`, `route`, `status` | +| `upstream_requests_total`, `upstream_request_duration_seconds` | counter, histogram | `operation`, `outcome` | +| `tokens_total` | counter | `model`, `direction` | +| `completions_total` | counter | `surface`, `model`, `stream`, `finish_reason`, `error_code` | +| `active_streams` | gauge | `surface` | +| `upstream_restarts_total` | counter | `reason` ∈ `initial` \| `stale` \| `invalidated` \| `restart` | +| `session_cache_entries` | gauge | `state` ∈ `entries` \| `busy` | +| `event_stream_connected` | gauge | — | +| `event_stream_reconnects_total` | counter | `reason` ∈ `idle` \| `ended` \| `rejected` | +| `event_frames_dropped_total` | counter | `reason` ∈ `no_session` \| `no_subscriber` \| `malformed` | +| `rate_limit_rejections_total` | counter | `scope` ∈ `api` \| `admin` | + +`completions_total` counts **every** exit, including failures: +`finish_reason` stays within the documented finish reasons (`stop`, `length`, +`tool_calls`, `content_filter`, `error`, `cancelled`) and a failure adds the +gateway's own error code in `error_code` (empty on success) — so a lost event +stream is `finish_reason="error", error_code="event_stream_lost"`, never a +finish reason of its own. + ## JSON output mode OpenCode offers no per-request output-schema control: the client's tools cannot diff --git a/docs/ARCHITECTURE.md b/docs/ARCHITECTURE.md index 58644c2..28c4811 100644 --- a/docs/ARCHITECTURE.md +++ b/docs/ARCHITECTURE.md @@ -147,9 +147,14 @@ interrupts the session and fails the turn with `503 event_stream_lost` instead o 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 -other exit cancel the response body reader, and `#controller` is cleared when a -connection attempt returns. +tests); the connection attempt itself is bounded by the same watchdog, so an +upstream that accepts the socket and never writes a response head cannot park the +hub indefinitely. Expiry fails the connection so the loop reconnects. `stop()` and +every other exit cancel the response body reader and zero the +`event_stream_connected` gauge, and `#controller` is cleared when a connection +attempt returns. The reconnect delay is reset only after a connection has actually +delivered `server.connected`, so an accept-then-close upstream backs off instead of +being polled four times a second. ### 2.5 Free-tier limits @@ -202,8 +207,12 @@ 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. +a while. `stop` is now consumed by the Anthropic surface and by the OpenAI chat +and completions adapters (see §6), which truncate the visible text at the first +delimiter; `maxTokens`, `temperature` and `topP` stay recorded-but-not-forwarded +on the Anthropic surface, while the OpenAI surfaces accept the generation knobs +only for client compatibility and report them in `x_opencode.unapplied` so the +caller can see they were not applied. Every reference doc says so per surface. ### 4.2 `src/errors.ts` (frozen) @@ -219,12 +228,18 @@ fromUpstreamError(input): ApiError toApiError(value, fallbackMessage?): ApiError ``` +`fromUpstreamError()` preserves an upstream `404` as `not_found_error` (not as a +caller-fault `400`), because the sticky-session replay path in `runCompletion()` +must recognise a vanished session and retry on a fresh one; every other upstream +4xx except `408`/`429` is still reported as `invalid_request_error`. + ### 4.3 `src/upstream/*` (frozen) ```ts -class UpstreamProcess { resolve(): Promise; status(); invalidate(reason); stop(); shutdown(); markStale(reason) } +class UpstreamProcess { resolve(): Promise; status(): UpstreamStatus; 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); + createSession(payload, options?: { signal?: AbortSignal }); getSession(id); getMessages(id); + prompt(id, text, files?, options?: { signal?: AbortSignal }); interrupt(id); deleteSession(id); generate(id, prompt, opts); ping() } class EventHub { start(); stop(); ensureConnected(timeoutMs); subscribe(sessionId, listener); onReconnect(cb) } class ModelRegistry { catalog(force?); list(); agents(); providers(); find(name); resolve(name); @@ -246,9 +261,12 @@ 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`, -`listProviders`, `listAgents`) use a short dedicated timeout -(`OpencodeClientOptions.catalogueTimeoutMs`, default 10 s) rather than the +replacement instead of retrying a dead URL. A failed start is remembered: after a +spawn or readiness failure `resolve()` fails fast with `503 upstream_unavailable` +for a bounded, exponentially growing window (at most 30 s) instead of respawning +once per incoming request, and the window resets after a successful start. +Catalogue calls (`listModels`, `listProviders`, `listAgents`) use a short dedicated +timeout (`OpencodeClientOptions.catalogueTimeoutMs`, default 10 s) rather than the 600 s turn budget. `SessionStore.acquire({ fresh: true })` skips cached candidates while keeping the conversation key, so a stale-session replay caches its replacement where the next turn of that conversation will find it. @@ -260,6 +278,13 @@ 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`. +`UpstreamStatus` carries the usual endpoint/binary/last-error fields plus +`stderrTail?: string[]` (the last ≤ 50 stderr lines of the supervised child, +cleared on every spawn), which `GET /admin/status` returns unchanged. The child's +stdout/stderr are otherwise inspected through a bounded tail only: once readiness +has been published the pattern scan stops entirely, so a chatty long-lived server +cannot grow the buffer or the per-chunk cost. + `/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 @@ -267,6 +292,20 @@ 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. +`collectCompletion()` adopts a consolidated `text_end` / `reasoning_end` payload +only when it is **longer** than the text accumulated from deltas, so a provider +that reports the whole answer in the terminal event (and sends no deltas) is not +lost, while a step-level event that repeats a shorter fragment never truncates the +answer. The streamed surfaces apply the same rule independently. + +`completions_total` records an outcome for every exit, including failures: +`finish_reason` stays within the documented `FinishReason` values and a failure +adds a bounded `error_code` label (the gateway's own `ApiError.code`), so a lost +event stream is counted as `finish_reason="error", error_code="event_stream_lost"` +rather than as its own finish reason. `upstream_restarts_total{reason}` is +classified once per published server (`initial`, `stale`, `invalidated`, +`restart`). + ### 4.4 `src/adapter/common/*` (frozen) ```ts @@ -282,9 +321,13 @@ parseAssistantText(text): {text, calls}, parseToolCallBody(body): ToolCall[], normaliseArguments(args): string, renderTranscript(messages): string, renderToolResult(message): string, class ToolCallFilter +// `class ToolCallFilter` exposes `get scannedCharacters()`, a diagnostic counter +// that pins the linear scan of a bridged tool-call envelope. + // `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. +// absent or empty, and when `tool_choice` names a function the request never +// declared, so the check runs once for every surface. // usage.ts EMPTY_USAGE, toUsage(tokens), addUsage(a, b), estimateTokens(text), estimateConversationTokens(parts) @@ -310,6 +353,8 @@ export function resolveAttachments(sources: readonly MediaSource[], config: Conf ): Promise<{ attachments: Attachment[]; omitted: OmittedAttachment[] }>; export function formatOmissionNote(omitted: readonly OmittedAttachment[], limits: MediaBudgetLimits): string; export function buildDataUri(attachment: Pick): string; +export function isPrivateHost(host: string): boolean; +export function isWithinRoots(candidate: string, roots: readonly string[]): boolean; // mime.ts export function kindFromMime(mime: string): AttachmentKind; @@ -323,21 +368,37 @@ export function extensionToMime(extension: string): string | undefined; ``` Rules: reject `http(s)` when `config.allowRemoteMediaUrls` is false; reject -private/loopback hosts when `config.allowPrivateMediaUrls` is false; reject local -paths when `config.allowLocalFiles` is false and when the resolved real path is -outside `config.allowedFileRoots`; enforce `config.maxAttachmentBytes` while -streaming the download (do not buffer unbounded) and again after reading a local -file (the `stat` size can be stale). When private URLs are blocked the remote -download is dialled with `node:http`/`node:https` and a `lookup` callback pinned -to the validated address, so the guard and the connection cannot disagree (DNS -rebinding); redirects are followed manually with per-hop re-validation. +private/loopback hosts when `config.allowPrivateMediaUrls` is false (the shipped +default, so the guard is active out of the box); reject local paths when +`config.allowLocalFiles` is false and when the resolved real path is outside +`config.allowedFileRoots`; enforce `config.maxAttachmentBytes` while streaming the +download (do not buffer unbounded) and again after reading a local file (the +`stat` size can be stale). When private URLs are blocked the remote download is +dialled with `node:http`/`node:https` and a `lookup` callback pinned to the +validated address, so the guard and the connection cannot disagree (DNS +rebinding); redirects are followed manually with per-hop re-validation. The +download requests `accept-encoding: identity` and rejects any other +`content-encoding` with `400 attachment_download_failed`, because the byte caps +bound the bytes as received and a compressed body would otherwise be inlined and +labelled as media. + +`isPrivateHost()` normalises the address itself before classifying it: any IPv6 +spelling (full, compressed, IPv4-mapped, IPv4-compatible, dotted tail) is expanded +first, then IPv4 is canonicalised, then loopback, RFC1918, link-local, unique-local, +multicast, `0.0.0.0`, `100.64/10` and the cloud-metadata ranges are matched. +`isWithinRoots()` compares resolved real paths, so a caller must `realpath` the +candidate first. Both are exported for the media path and for tests; the media +code never relies on `new URL()` having canonicalised the hostname. 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. +bytes cannot come from a path that was swapped after the check. Windows exposes no +`O_NOFOLLOW`, so there the final component is `lstat`-checked for a symlink or +junction before the open and the opened handle's `dev`/`ino` are compared with the +pre-open `lstat`, refusing the read on any mismatch. `ENOENT`/`ENOTDIR` map to 400 +`attachment_not_found` and `EACCES`/`EPERM`/`ELOOP`/`EISDIR`/`EBUSY` to 400 +`invalid_attachment`; hard links inside a root and a swapped parent directory +remain outside the guarantee. Attachment caps are enforced **before** anything is fetched. Each request creates one `MediaBudget` (from `config.maxAttachments` and `config.maxAttachmentBytes`) @@ -384,6 +445,14 @@ export function registerAnthropicMessageRoutes(app: FastifyInstance, ctx: AppCon export function registerAnthropicCountTokenRoutes(app: FastifyInstance, ctx: AppContext): void; // POST /v1/messages/count_tokens ``` +`src/adapter/openai/chat.ts` additionally exports the helpers the Responses +adapter imports for the same behaviour: `MessageMediaDraft`, `resolveMessageMedia` +(one request-wide `resolveAttachments()` call shared by chat and responses, so +attachments of different messages download concurrently while the budget and the +omission report keep their declaration-order semantics), and +`StopSequenceFilter` / `truncateAtStopSequences` (the `stop` truncation used by +both OpenAI paths). + Shared helpers each adapter may use: * `ctx.completion.run(request, completionDeps(ctx), { signal })` → `AsyncGenerator` @@ -421,6 +490,12 @@ tests can substitute a scripted runner (`test/helpers/context.ts`). * 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), + * `await writer.drain()` after the frames of a turn so a slow reader applies + backpressure instead of growing an unbounded queue; `drain()` resolves on the + socket `drain` event or after `SseWriterOptions.drainTimeoutMs` (default + 5000 ms) when the socket is not backed up, and `writer.closedSignal` is + aborted when the connection dies, so a dead reader stops the producer even + without `createDisconnectSignal()`, * 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 @@ -446,7 +521,28 @@ tests can substitute a scripted runner (`test/helpers/context.ts`). `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. + prefix and therefore gets a fresh session. The OpenAI chat and completions + adapters honour `stop` the same way and keep their documented `finish_reason`. +* Fields the gateway cannot honour are never silently ignored: the OpenAI surfaces + accept the generation knobs (`temperature`, `top_p`, `max_tokens`, + `max_completion_tokens`, `max_output_tokens`, `presence_penalty`, + `frequency_penalty`, `seed`, `logit_bias`) for client compatibility and list + them in `x_opencode.unapplied` on the final payload, and they reject every field + that would change the shape of the response (`logprobs`/`top_logprobs` when + requested, non-text `modalities`, `audio`, `prediction`, `store: true`, + `web_search_options`, legacy `functions`/`function_call`, + `previous_response_id`, non-empty `include`, `best_of`, `suffix`, and any + `detail` other than `"auto"`) with `400 unsupported_parameter` naming the field + in `param`. +* `/v1/responses` reports a filtered turn as `status: "incomplete"` with + `incomplete_details.reason: "content_filter"`, keeps `created_at` constant for + the whole response, echoes `instructions`, announces the reasoning item with + `response.output_item.added` at `output_index: 0`, and reports `usage: null` + (rather than zeros) when a failed turn never produced a usage event. +* Anthropic: a turn the upstream reports as failed is a `502 api_error` when + buffered and a terminal `error` event when streamed — never a normal + `message_delta`/`message_stop`; a cancelled turn keeps `stop_reason: "end_turn"` + and marks `x_opencode.interrupted: true`. * 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 diff --git a/docs/CONFIGURATION.md b/docs/CONFIGURATION.md index 6db3d40..75080de 100644 --- a/docs/CONFIGURATION.md +++ b/docs/CONFIGURATION.md @@ -26,6 +26,8 @@ variable. (Discovery and the spawned CLI read the variables listed in | `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. 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. | +| `OPENCODE_RATE_LIMIT_RPM` | integer ≥ 0 | `0` | Sustained requests per minute allowed per authenticated API key; `0` disables the limiter. `/admin/*` uses its own separate bucket. | Bounds how many paid upstream turns one key can trigger. A rejected request answers `429 rate_limit_error` (`code: rate_limit_exceeded`) with a `retry-after` header. | +| `OPENCODE_RATE_LIMIT_BURST` | integer ≥ 0 | `0` | Token-bucket capacity per API key; `0` derives `max(1, ceil(rpm / 6))`. Ignored when `OPENCODE_RATE_LIMIT_RPM=0`. | A large burst allows that many concurrent turns per key before throttling starts. | ## Authentication @@ -34,7 +36,8 @@ variable. (Discovery and the spawned CLI read the variables listed in | `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. | +| `OPENCODE_METRICS_PUBLIC` | boolean | `false` | Exempt `GET /metrics` from authentication. | Metrics expose model names, route traffic and token volumes, so this is only safe when `HOST` is a loopback address; otherwise set `OPENCODE_METRICS_TOKEN` instead of exposing the endpoint anonymously. | +| `OPENCODE_METRICS_TOKEN` | string | *(unset)* | Dedicated scrape credential for `GET /metrics`, compared in constant time before the `OPENCODE_METRICS_PUBLIC` bypass. When set, `/metrics` requires it even if `OPENCODE_METRICS_PUBLIC=true`; a valid general API key is still accepted. | Lets a Prometheus scraper read metrics without handing it a general-purpose key. Prefer it over making the endpoint public. | Keys are presented as `Authorization: Bearer `, `x-api-key: `, `Authorization: Basic ` (key as the username). Query-string keys (`?api_key=`) are deliberately **not** supported because request URLs end up in access logs. @@ -84,17 +87,20 @@ existing custom key. | Variable | Type | Default | Description | Security implication | | --- | --- | --- | --- | --- | -| `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_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`. On Windows, where `O_NOFOLLOW` is `0`, a final component that `lstat` reports as a symlink or junction is refused, and the opened handle's `dev`/`ino` are compared with the pre-open `lstat` before any byte is read. | 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_ALLOW_PRIVATE_MEDIA_URLS` | boolean | `false` | Allow remote media on private, loopback and link-local addresses. **Leave `false` on any deployment reachable from the network.** Setting it to `true` is an SSRF primitive against the host network and cloud metadata endpoints; when it is enabled while `HOST` is not a loopback address the gateway logs a startup error naming the exposure (it still starts). | The default closes SSRF against `127.0.0.1`-hosted services and cloud metadata endpoints. Enable it only when every URL source is trusted and the gateway is not reachable from an untrusted network. | | `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; -uploads are always inlined for OpenCode as a `data:` URI. See the README section -"Vision and media input". +uploads are always inlined for OpenCode as a `data:` URI. A remote download that +answers a non-`identity` `content-encoding` is rejected with +`400 attachment_download_failed`: the byte caps bound the bytes as received, so a +compressed body is never inlined and never labelled as media. See the README +section "Vision and media input". ## Reasoning, tools and observability @@ -155,5 +161,8 @@ OPENCODE_ALLOW_LOCAL_FILES=false OPENCODE_AGENT_PERMISSIONS=[{"action":"*","resource":"*","effect":"ask"}] OPENCODE_EXPOSE_NATIVE_TOOLS=false OPENCODE_METRICS_PUBLIC=false +OPENCODE_METRICS_TOKEN= +OPENCODE_RATE_LIMIT_RPM=60 +OPENCODE_RATE_LIMIT_BURST=10 OPENCODE_CORS_ORIGINS=https://your-app.example ``` diff --git a/docs/VERIFICATION.md b/docs/VERIFICATION.md index eb0e1ac..793a8a1 100644 --- a/docs/VERIFICATION.md +++ b/docs/VERIFICATION.md @@ -237,3 +237,23 @@ Not fixed, deliberately: is delivered in the error frame instead (`retry_after_ms`); * `OPENCODE_AGENT_MAX_STEPS` counts agent steps, not model tokens; it is a safety valve, not a token budget. + +### Addendum — hardening pass of 2026-12-03 + +Recorded here so this report is not read as the current state. The full change set +is in the git history; the entries that touch the findings above are: + +* **F-14 is closed.** `SseWriter` now exposes `drain()` and `closedSignal`; every + streaming surface awaits `drain()` after each event and a dead reader aborts the + producer, so the completion queue behind the writer is bounded + (`docs/ARCHITECTURE.md` §5). +* **F-02 is enforced by default.** `OPENCODE_ALLOW_PRIVATE_MEDIA_URLS` now + defaults to `false`, and a remote download that answers a non-`identity` + `content-encoding` is rejected instead of being inlined as media. +* **F-03's replay path is reachable.** `fromUpstreamError()` preserves an upstream + `404` as `not_found_error` instead of collapsing it into a caller-fault `400`, so + a sticky session that vanished with its upstream server is replayed on a fresh + one rather than failing the turn. +* `stop` is now honoured on `/v1/chat/completions` and `/v1/completions`, and the + generation knobs the gateway cannot apply are named in `x_opencode.unapplied` + instead of being silently dropped (`docs/API.md`). From f487e7a3e4963f72d9be85b3466bcd7222dfa950 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Ph=E1=BA=A1m=20V=C4=83n=20=C4=90=E1=BB=8Bnh?= Date: Thu, 3 Dec 2026 12:13:57 +0700 Subject: [PATCH 12/12] fix(media): canonicalise the allowed roots before the path check The local-file containment check canonicalised the candidate with realpath but compared it against lexically resolved roots. On Windows a root reached through an 8.3 short name or a junction - exactly what os.tmpdir() returns on a CI runner - resolves to a different string than a file below it, so every legitimate local attachment was rejected with attachment_path_forbidden. Canonicalise each root the same way as the candidate, keeping the lexical form when a root does not exist yet, and pin it with a test that resolves a file through a directory link. --- src/media/resolve.ts | 17 ++++++++++++++++- test/media.test.ts | 33 +++++++++++++++++++++++++++++++++ 2 files changed, 49 insertions(+), 1 deletion(-) diff --git a/src/media/resolve.ts b/src/media/resolve.ts index 28ad4f9..2d5b12d 100644 --- a/src/media/resolve.ts +++ b/src/media/resolve.ts @@ -783,7 +783,22 @@ async function resolveLocalFile( }); } - if (!isWithinRoots(realPath, config.allowedFileRoots)) { + // The candidate is canonicalised, so the roots must be too: on Windows a root + // reached through an 8.3 short name or a junction (`RUNNER~1`, a mapped temp + // directory) resolves to a different string than `realpath` returns for a file + // inside it, which would reject every file under a legitimate root. A root that + // cannot be resolved (it does not exist yet) keeps its lexical form. + const roots = await Promise.all( + config.allowedFileRoots.map(async (root) => { + try { + return await fsp.realpath(path.resolve(root)); + } catch { + return path.resolve(root); + } + }), + ); + + if (!isWithinRoots(realPath, roots)) { throw ApiError.badRequest( `Attachment path is outside the allowed roots (${config.allowedFileRoots.join(", ")}).`, { code: "attachment_path_forbidden", param: field }, diff --git a/test/media.test.ts b/test/media.test.ts index 94ddd37..ff5cc31 100644 --- a/test/media.test.ts +++ b/test/media.test.ts @@ -613,6 +613,39 @@ describe("resolveAttachment", () => { expect(attachment.name).toBe("image.png"); }); + // A root that is itself a link (a junction on Windows, a directory symlink + // elsewhere, and an 8.3 short name on a CI runner) resolves to a different + // string than a file below it, so the roots have to be canonicalised before + // the containment check or every file under a legitimate root is rejected. + it("accepts a file below a root that is itself a directory link", async (ctx) => { + const target = await fsp.mkdtemp(path.join(os.tmpdir(), "opencode-api-link-target-")); + const link = `${target}-link`; + try { + await fsp.symlink(target, link, process.platform === "win32" ? "junction" : "dir"); + } catch (error) { + await fsp.rm(target, { recursive: true, force: true }); + const code = (error as NodeJS.ErrnoException).code; + // Creating a link needs a privilege this environment may not grant; the + // containment check itself is still covered by the other local-file tests. + if (code === "EPERM" || code === "EACCES" || code === "ENOTSUP") { + ctx.skip(); + return; + } + throw error; + } + try { + await fsp.writeFile(path.join(target, "image.png"), PNG_BUFFER); + const attachment = await resolveAttachment( + { path: path.join(link, "image.png") }, + config({ allowLocalFiles: true, allowedFileRoots: [link] }), + ); + expect(attachment.mime).toBe("image/png"); + } finally { + await fsp.rm(link, { recursive: true, force: true }); + await fsp.rm(target, { recursive: true, force: true }); + } + }); + 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