From fe5137447b26b4c9a474907af44c58c6f9255761 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: Sat, 5 Dec 2026 17:12:46 +0700 Subject: [PATCH 1/9] fix(upstream): keep the turn lifecycle and supervision honest Seven defects found by the second audit of the upstream layer: - `session.execution.interrupted`, and `session.idle` with outcome `interrupted`, ended the turn as a normal `stop`, so an incomplete answer was returned as complete and counted as a success. `FinishReason` already has a `cancelled` member that the Anthropic surface keys `x_opencode.interrupted` on; both branches now set it. - the first `prepare()` dropped the caller's abort signal, so a disconnect while a session was being created parked the handler for the full request budget before creating (and deleting) a session for a caller that was already gone. - a completed turn committed, and with `OPENCODE_SESSION_PERSIST=true` wrote to disk, a session record even when the sticky cache was disabled, where nothing can ever reuse it. That path now records nothing and deletes the session it created. - the first-token watchdog ignored `session.step.started` and every `session.tool.*` frame, so a request whose agent was running a long native command was killed with a false "produced no output". - a spawn `error` never re-checked the process-exit registry once the start promise settled, so a dead instance was retained for the lifetime of the process. - a 2xx body without a usable `data` field escaped `createSession()` and `prompt()` as a bare `TypeError` (HTTP 500) instead of `503 upstream_invalid_json`. - the supervised child's log file was appended to for the whole life of the server and across restarts; it is now rotated at `OPENCODE_UPSTREAM_LOG_MAX_BYTES` (default 32 MiB, `0` disables the cap), seeded from the file that survived an earlier run. `OPENCODE_LOG_LEVEL` also accepts `silent` now: `scripts/smoke-dist.mjs` already used it and pino already understood it, so the closed set was narrower than the logger and warned on every smoke run. --- .env.example | 6 + README.md | 16 +- docs/CONFIGURATION.md | 7 +- src/config.ts | 14 +- src/upstream/client.ts | 29 +- src/upstream/completion.ts | 87 ++++- src/upstream/process.ts | 79 ++++- test/upstream-invariants.test.ts | 548 +++++++++++++++++++++++++++++++ 8 files changed, 746 insertions(+), 40 deletions(-) create mode 100644 test/upstream-invariants.test.ts diff --git a/.env.example b/.env.example index 8279a33..e3c104a 100644 --- a/.env.example +++ b/.env.example @@ -122,6 +122,12 @@ PORT=20123 # Budget for the first text/reasoning delta (default 3 min). # OPENCODE_FIRST_TOKEN_TIMEOUT_MS=180000 +# Cap on `/logs/opencode-.log` (default 32 MiB). The supervised +# server's stdout/stderr is appended for its whole life and across restarts, so +# the file is rotated (truncated) once it would exceed this many bytes. Set 0 to +# keep it unbounded. +# OPENCODE_UPSTREAM_LOG_MAX_BYTES=33554432 + # --------------------------------------------------------------------------- # Agent and workspace # --------------------------------------------------------------------------- diff --git a/README.md b/README.md index 6727c27..06c2e31 100644 --- a/README.md +++ b/README.md @@ -489,6 +489,7 @@ model_disabled`. Query `GET /v1/models` instead of guessing. | `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_UPSTREAM_LOG_MAX_BYTES` | `33554432` | Cap on `/logs/opencode-.log`; the file is truncated and reopened past it, `0` keeps it unbounded. | | `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. | @@ -526,11 +527,14 @@ Every variable, with types, defaults and security notes: `session_cache_entries`, `event_stream_connected`, `event_stream_reconnects_total`, `event_frames_dropped_total`, `rate_limit_rejections_total`, plus process defaults. Requires a key unless `OPENCODE_METRICS_PUBLIC=true` is set **and** no - `OPENCODE_METRICS_TOKEN` is configured: a configured token is always required, - even when the endpoint is public, so a general API key is never handed to a - scraper. `/metrics` is charged to the same rate-limit bucket as the API routes, - so an anonymous scraper cannot walk every collector without limit; only the - liveness probes and `OPTIONS` stay exempt. + `OPENCODE_METRICS_TOKEN` is configured. With a token configured the endpoint is + never anonymous: the token is accepted (and checked first), and a valid general + API key is still accepted, so a scraper can be given either. While + `OPENCODE_RATE_LIMIT_RPM` is non-zero `/metrics` is charged to the same + rate-limit bucket as the API routes, so an anonymous scraper cannot walk every + collector without limit; with the default `OPENCODE_RATE_LIMIT_RPM=0` the + limiter is off for every route. Only the liveness probes and `OPTIONS` stay + exempt. * **`/admin/*`** — `/admin/status` (config, upstream binary and URL, catalog counts, session count), `/admin/config` (effective configuration with API keys and the upstream password redacted), `/admin/models/refresh`, `/admin/sessions` @@ -686,7 +690,7 @@ opencode-api/ # package name; the project is "OpenCode API" ├── src/ │ ├── adapter/ │ │ ├── anthropic/ # /v1/messages, /v1/messages/count_tokens -│ │ ├── common/ # reasoning mapping, tool bridge, usage maths +│ │ ├── common/ # reasoning mapping, tool bridge, stop delimiters, usage maths │ │ └── openai/ # /v1/chat/completions, /v1/responses, /v1/completions, /v1/models, /v1/embeddings │ ├── http/ # SSE writer, client-disconnect signal │ ├── media/ # data URI, remote fetch, local path resolution diff --git a/docs/CONFIGURATION.md b/docs/CONFIGURATION.md index 4be26a4..82c1ade 100644 --- a/docs/CONFIGURATION.md +++ b/docs/CONFIGURATION.md @@ -75,7 +75,8 @@ ignores the mode). | `OPENCODE_SERVER_ARGS` | CSV list | *(empty)* | Extra arguments appended to `opencode serve --hostname ... --port ...`. | Passing `--standalone` breaks startup (rejected by opencode 2.x). | | `OPENCODE_START_TIMEOUT_MS` | integer ≥ 1000 | `30000` | Time allowed for the private server to report readiness. | — | | `OPENCODE_REQUEST_TIMEOUT_MS` | integer ≥ 1000 | `600000` | Wall-clock budget for one upstream turn; on expiry the session is interrupted. | — | -| `OPENCODE_FIRST_TOKEN_TIMEOUT_MS` | integer ≥ 1000 | `180000` | Budget for the first text/reasoning delta of a turn. | — | +| `OPENCODE_FIRST_TOKEN_TIMEOUT_MS` | integer ≥ 1000 | `180000` | Budget for the first text/reasoning delta of a turn. It is re-armed by every upstream liveness frame — text and reasoning deltas, a step start and native tool activity — so a turn that is actively running tools is not killed for "producing no output". | — | +| `OPENCODE_UPSTREAM_LOG_MAX_BYTES` | integer ≥ 0 | `33554432` (32 MiB) | Cap on `/logs/opencode-.log`. The file is truncated and reopened once the cap would be crossed, so the most recent output is kept instead of growing the file without bound; `0` disables the cap. | The file holds the supervised server's stdout/stderr with the upstream password and any `Authorization` header redacted; a bound keeps a chatty server from filling the disk. | ## Agent and workspace @@ -91,7 +92,7 @@ ignores the mode). | Variable | Type | Default | Description | Security implication | | --- | --- | --- | --- | --- | | `OPENCODE_DATA_DIR` | path | `./.opencode-api` | Gateway state directory: upstream logs, optional session file. | Contains upstream log output and is treated as sensitive; the supervised server's password is redacted before it is written to `/logs/opencode-.log` and before it can appear in an error message or in `GET /admin/status`. Keep the directory private anyway. | -| `OPENCODE_SESSION_CACHE` | boolean | `true` | Reuse the OpenCode session that already holds the conversation prefix. | Reuse is strictly prefix-checked; a mismatch replays the conversation on a fresh session. Disable for fully stateless routing. | +| `OPENCODE_SESSION_CACHE` | boolean | `true` | Reuse the OpenCode session that already holds the conversation prefix. | Reuse is strictly prefix-checked; a mismatch replays the conversation on a fresh session. Disable for fully stateless routing: nothing is recorded, `OPENCODE_SESSION_PERSIST` writes no file, and the session created for a turn is deleted as soon as the turn ends. | | `OPENCODE_SESSION_TTL_MS` | integer ≥ 1000 | `1800000` (30 min) | Idle lifetime of a cached session. | Longer lifetimes keep session state in memory longer. | | `OPENCODE_SESSION_MAX` | integer ≥ 1 | `500` | Maximum cached sessions (least recently used are evicted). | — | | `OPENCODE_SESSION_PERSIST` | boolean | `false` | Persist the session cache to `/sessions.json`. | The file records session ids, message prefixes and the `OPENCODE_INSTANCE_ID` of the writer. A `ses_*` id is only valid inside the upstream server that created it, so a file written by another instance is ignored on load; because the default instance id contains the gateway pid, a restart starts with an empty cache. Pin `OPENCODE_INSTANCE_ID` to keep the cache across restarts — only correct for a long-lived upstream (`OPENCODE_SERVER_URL`). Keep the data directory private. | @@ -126,7 +127,7 @@ section "Vision and media input". | `OPENCODE_EXPOSE_NATIVE_TOOLS` | boolean | `false` | Stream native OpenCode tool activity as SSE events (see `OPENCODE_NATIVE_TOOL_EVENT`). | Native tool payloads can reveal file paths and command input/output from the agent's workspace. | | `OPENCODE_NATIVE_TOOL_EVENT` | string | `opencode.tool_call` | SSE event name used for native tool activity. | — | | `OPENCODE_REASONING_FIELD` | `reasoning_content` \| `both` | `reasoning_content` | `POST /v1/chat/completions` only: when `both`, the adapter emits an extra `reasoning` alias next to `reasoning_content` on messages and deltas. Read into `Config.reasoningField`. | — | -| `OPENCODE_LOG_LEVEL` | string | `info` | Pino level: `fatal`, `error`, `warn`, `info`, `debug`, `trace`. Unrecognised values fall back to `info` and log a warning naming the variable. | `debug`/`trace` add upstream request metadata, connection diagnostics and fragments of malformed upstream frames; no prompt text or credential is ever logged. | +| `OPENCODE_LOG_LEVEL` | string | `info` | Pino level: `silent`, `fatal`, `error`, `warn`, `info`, `debug`, `trace` (`silent` disables all output; `scripts/smoke-dist.mjs` uses it). Unrecognised values fall back to `info` and log a warning naming the variable. | `debug`/`trace` add upstream request metadata, connection diagnostics and fragments of malformed upstream frames; no prompt text or credential is ever logged. | | `OPENCODE_LOG_PRETTY` | boolean | `true` when stdout is a TTY | Pretty-print logs instead of JSON lines. | Needs `pino-pretty`, which is a dev dependency; without it the gateway falls back to JSON instead of failing. | | `OPENCODE_METRICS_ENABLED` | boolean | `true` | Enable Prometheus collection; when false, `GET /metrics` answers `404`. | — | | `OPENCODE_INSTANCE_ID` | string | `opencode-api-` | Identifier for this gateway instance. Also the fingerprint of the persisted session cache (`OPENCODE_SESSION_PERSIST`). | Changing it invalidates the persisted session cache. | diff --git a/src/config.ts b/src/config.ts index d36edfd..f72df1a 100644 --- a/src/config.ts +++ b/src/config.ts @@ -66,6 +66,13 @@ export interface Config { readonly upstreamStartTimeoutMs: number; readonly upstreamRequestTimeoutMs: number; readonly upstreamFirstTokenTimeoutMs: number; + /** + * Cap, in bytes, on `/logs/opencode-.log`; `0` keeps the file + * unbounded. The file is appended to for the whole life of the supervised + * child (and across restarts, which reuse the same port names), so without a + * bound continuous traffic grows it without limit. + */ + readonly upstreamLogMaxBytes: number; /** Directory handed to OpenCode as the session location. */ readonly workdir: string; @@ -283,8 +290,12 @@ function parseTrustProxy(): Config["trustProxy"] { * `src/logger.ts` hands the value straight to pino, which throws on anything * outside this set — an internals stack trace instead of a configuration * message. Validating here keeps the failure a warning and a fallback. + * + * `silent` is included because pino supports it (`pino.levels.values.silent`) + * and `scripts/smoke-dist.mjs` uses it to keep the smoke output readable; the + * closed set must not be narrower than what the logger can actually take. */ -const LOG_LEVELS: readonly string[] = ["trace", "debug", "info", "warn", "error", "fatal"]; +const LOG_LEVELS: readonly string[] = ["trace", "debug", "info", "warn", "error", "fatal", "silent"]; function envLogLevel(name: string, fallback: string): string { const raw = env(name); @@ -519,6 +530,7 @@ export function loadConfig(overrides: Partial = {}): Config { upstreamStartTimeoutMs: envInt("OPENCODE_START_TIMEOUT_MS", 30_000, 1000), upstreamRequestTimeoutMs: envInt("OPENCODE_REQUEST_TIMEOUT_MS", 600_000, 1000), upstreamFirstTokenTimeoutMs: envInt("OPENCODE_FIRST_TOKEN_TIMEOUT_MS", 180_000, 1000), + upstreamLogMaxBytes: envInt("OPENCODE_UPSTREAM_LOG_MAX_BYTES", 32 * 1024 * 1024, 0), workdir, agent: envStr("OPENCODE_AGENT", "build"), diff --git a/src/upstream/client.ts b/src/upstream/client.ts index 6d14184..2b9d75a 100644 --- a/src/upstream/client.ts +++ b/src/upstream/client.ts @@ -257,7 +257,7 @@ export class OpencodeClient { operation: "session.create", ...(options.signal === undefined ? {} : { signal: options.signal }), }); - return response.data; + return requireData(response); } async getSession(sessionId: string): Promise { @@ -293,7 +293,7 @@ export class OpencodeClient { ...(options.signal === undefined ? {} : { signal: options.signal }), }, ); - return response.data; + return requireData(response); } async interrupt(sessionId: string): Promise { @@ -306,7 +306,12 @@ export class OpencodeClient { } async deleteSession(sessionId: string): Promise { - await this.request(`/api/session/${encodeURIComponent(sessionId)}`, { + // No `requireData()`: this method never dereferences the payload — the + // documented contract is only that the upstream accepted the DELETE — and + // the exact success shape of `/api/session/{id}` with `DELETE` is not part of + // the verified protocol surface (a plain JSON object satisfies `request()`), + // so demanding a `data` field could fail a delete that actually succeeded. + await this.request>(`/api/session/${encodeURIComponent(sessionId)}`, { method: "DELETE", operation: "session.delete", timeoutMs: 15_000, @@ -365,6 +370,24 @@ function isJsonObject(value: unknown): value is Record { return typeof value === "object" && value !== null && !Array.isArray(value); } +/** + * Read the `{ data: object }` field of a 2xx envelope. + * + * `request()` only proves that the body is a JSON object, so `{}` and + * `{"data":null}` still pass it; every caller of this helper dereferences + * `data`, which used to escape as a bare `TypeError` — an HTTP 500 outside the + * `ApiError` taxonomy — instead of the upstream failure it is. + */ +function requireData(response: { data?: unknown }): T { + const data = response.data; + if (typeof data !== "object" || data === null || Array.isArray(data)) { + throw ApiError.unavailable("OpenCode returned a malformed JSON response.", { + code: "upstream_invalid_json", + }); + } + return data as T; +} + function duration(metrics: Metrics, operation: string, startedAt: bigint): void { const seconds = Number(process.hrtime.bigint() - startedAt) / 1e9; metrics.upstreamDuration.observe({ operation }, seconds); diff --git a/src/upstream/completion.ts b/src/upstream/completion.ts index d3d3791..f0ddbe1 100644 --- a/src/upstream/completion.ts +++ b/src/upstream/completion.ts @@ -120,7 +120,14 @@ export async function* runCompletion( // `try` so a failure in either is counted exactly once; `prepared` staying // `undefined` is what distinguishes a pre-flight failure below. resolved = await deps.models.resolve(request.model); - prepared = await prepare(resolved, request, deps, agent, { forceFresh: false }); + // The caller's signal reaches `createSession()` exactly like the replay + // below: without it a disconnect while `POST /api/session` is in flight + // parked the handler for the full request budget, then created (and + // immediately deleted) a session for a caller that was already gone. + prepared = await prepare(resolved, request, deps, agent, { + forceFresh: false, + ...(options.signal ? { signal: options.signal } : {}), + }); try { yield* execute(prepared, deps, options); @@ -560,6 +567,20 @@ async function* execute( let firstTokenDeadline = Date.now() + config.upstreamFirstTokenTimeoutMs; let gapDeadline: number | undefined; + /** + * Restart the first-token watchdog. + * + * The watchdog bounds a *silent* upstream, not an unproductive one: a + * request that declares no client tools keeps the unrestricted agent, so a + * long native `bash`/`webfetch` step emits `session.tool.*` frames and no + * text, and killing that turn with "produced no output" was factually wrong. + * `sawText` is deliberately left alone, so a model that hangs right after + * `session.step.started` — liveness once, then silence — is still bounded. + */ + const refreshFirstTokenDeadline = (): void => { + firstTokenDeadline = Date.now() + config.upstreamFirstTokenTimeoutMs; + }; + for (;;) { const remaining = deadline - Date.now(); if (streamGap) { @@ -649,6 +670,7 @@ async function* execute( switch (event.type) { case "session.step.started": { stepCount += 1; + refreshFirstTokenDeadline(); if (messageId === "" && typeof data["assistantMessageID"] === "string") { messageId = data["assistantMessageID"]; } @@ -665,7 +687,7 @@ async function* execute( const delta = typeof data["delta"] === "string" ? data["delta"] : ""; if (delta === "") break; sawText = true; - firstTokenDeadline = Date.now() + config.upstreamFirstTokenTimeoutMs; + refreshFirstTokenDeadline(); const ordinal = numberValue(data["ordinal"]); if (filter) { const forwarded = filter.push(delta); @@ -716,7 +738,7 @@ async function* execute( const delta = typeof data["delta"] === "string" ? data["delta"] : ""; if (delta === "") break; sawText = true; - firstTokenDeadline = Date.now() + config.upstreamFirstTokenTimeoutMs; + refreshFirstTokenDeadline(); collectedReasoning.push(delta); if (prepared.decision.reasoningEnabled) { yield { kind: "reasoning_delta", text: delta, ordinal: numberValue(data["ordinal"]) }; @@ -737,6 +759,7 @@ async function* execute( } case "session.tool.input.started": { + refreshFirstTokenDeadline(); const id = stringValue(data["id"]); const name = stringValue(data["name"]); if (name !== "") toolNames.set(id, name); @@ -751,6 +774,7 @@ async function* execute( } case "session.tool.called": { + refreshFirstTokenDeadline(); const id = stringValue(data["id"]); const activity: NativeToolActivity = { id, @@ -763,6 +787,7 @@ async function* execute( } case "session.tool.success": { + refreshFirstTokenDeadline(); const id = stringValue(data["id"]); const activity: NativeToolActivity = { id, @@ -774,6 +799,7 @@ async function* execute( } case "session.tool.failed": { + refreshFirstTokenDeadline(); const id = stringValue(data["id"]); const activity: NativeToolActivity = { id, @@ -818,6 +844,13 @@ async function* execute( } case "session.execution.interrupted": { + // The upstream cancelled the turn (provider-side cancellation, or the + // shared server cancelling the session). Falling through to `finalise()` + // reported it as a normal `stop`, so the caller saw HTTP 200, + // `stop_reason: end_turn` and a success in `completions_total` for an + // answer that was cut short. `"cancelled"` is the `FinishReason` the + // Anthropic surface keys `x_opencode.interrupted` on. + finishReason = "cancelled"; yield* finalise(); return; } @@ -825,12 +858,16 @@ async function* execute( case "session.execution.succeeded": case "session.execution.stopped": case "session.idle": { - if (event.type === "session.idle" && typeof data["outcome"] === "string" && data["outcome"] === "failed") { + const outcome = event.type === "session.idle" ? stringValue(data["outcome"]) : ""; + if (outcome === "failed") { const error = structuredError(data["error"]); recordError(error); yield { kind: "error", error }; return; } + // `session.idle` reports `interrupted` for a turn the server cancelled + // without emitting `session.execution.interrupted`. + if (outcome === "interrupted") finishReason = "cancelled"; yield* finalise(); return; } @@ -878,20 +915,36 @@ async function* execute( metrics.tokens.inc({ model: prepared.resolved.canonical, direction: "reasoning" }, usage.reasoningTokens); } - sessions.commit(key, sessionId, { - model: prepared.resolved.canonical, - agent: prepared.agent, - variant: prepared.decision.variant, - messages: prepared.request.messages, - toolsHash: prepared.toolsHash, - permissionProfile: prepared.permissionProfile, - }); + if (config.sessionCacheEnabled) { + sessions.commit(key, sessionId, { + model: prepared.resolved.canonical, + agent: prepared.agent, + variant: prepared.decision.variant, + messages: prepared.request.messages, + toolsHash: prepared.toolsHash, + permissionProfile: prepared.permissionProfile, + }); + } else { + // `acquire()` refuses every candidate while the cache is disabled, so + // this session was created for this turn and nothing owns it: the + // commit would fill the store (and `sessions.json`) that + // `OPENCODE_SESSION_CACHE=false` is documented to bypass, and no + // eviction hook would ever delete the upstream session. Best effort, + // exactly like the failed-turn path below. + void client.deleteSession(sessionId).catch((error: unknown) => { + log.debug( + { sessionId, err: error instanceof Error ? error.message : String(error) }, + "could not delete the upstream session of a cache-disabled turn", + ); + }); + } - // 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. + // Set only after the session is settled — committed, or deleted on the + // cache-disabled path: 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 { diff --git a/src/upstream/process.ts b/src/upstream/process.ts index f6fd6a6..37447a7 100644 --- a/src/upstream/process.ts +++ b/src/upstream/process.ts @@ -449,6 +449,11 @@ export class UpstreamProcess { if (this.#starting) return this.#starting; this.#starting = this.#resolveInternal().finally(() => { this.#starting = undefined; + // A failed spawn emits `error` and no `exit`, and its handler runs while + // this promise is still in flight, so that release attempt is refused. + // Re-checking here is what drops a dead instance from the process-exit + // registry instead of retaining its config, logger and tail forever. + this.#releaseExitHookIfIdle(); }); return this.#starting; } @@ -873,13 +878,67 @@ export class UpstreamProcess { // destroyed and later writes are skipped; `#stderrTail` keeps feeding so // diagnostics survive a broken log file. let logActive = true; - const logStream = fs.createWriteStream(path.join(logDir, `opencode-${port}.log`), { flags: "a" }); - logStream.on("error", (error: Error) => { - if (!logActive) return; - logActive = false; - this.#log.warn({ err: error.message, port }, "could not write the OpenCode server log file"); - logStream.destroy(); - }); + const logPath = path.join(logDir, `opencode-${port}.log`); + /** + * Open the child's log file, keeping the last write failure sticky. + * + * The stream opens asynchronously and is replaced on rotation, so the + * `'error'` handler is installed per stream. + */ + const openLogStream = (flags: "a" | "w"): fs.WriteStream => { + const stream = fs.createWriteStream(logPath, { flags }); + stream.on("error", (error: Error) => { + if (!logActive) return; + logActive = false; + this.#log.warn({ err: error.message, port }, "could not write the OpenCode server log file"); + stream.destroy(); + }); + return stream; + }; + let logStream = openLogStream("a"); + /** + * Bytes already in the current file; reset by every rotation. + * + * Seeded from the file that survived an earlier gateway run, so the cap + * bounds the file itself rather than "what this process appended": the port + * names are reused, and without the seed every restart could add another cap + * worth of output to a file that is already full. + */ + let logBytes = 0; + try { + logBytes = fs.statSync(logPath).size; + } catch { + /* the file does not exist yet */ + } + + /** + * Truncate the log file once it outgrows `OPENCODE_UPSTREAM_LOG_MAX_BYTES`. + * + * The child appends for its whole lifetime and the same ten port names are + * reused across gateway restarts, so an unbounded file grows forever. The + * replaced stream is destroyed rather than ended: its buffered tail belongs + * to the file being discarded, and a late flush would only append it again + * (the old descriptor was opened with `O_APPEND`). + */ + const rotateLog = (): void => { + const previous = logStream; + logStream = openLogStream("w"); + logBytes = 0; + previous.destroy(); + }; + + /** Append already-redacted text, rotating first when it would cross the cap. */ + const writeLogText = (text: string): void => { + if (!logActive || text.length === 0) return; + const payload = redactUpstreamSecret(text); + const size = Buffer.byteLength(payload); + const cap = this.#config.upstreamLogMaxBytes; + // A single chunk larger than the cap is still written whole; the next one + // rotates, so the file stays bounded by the cap plus one chunk. + if (cap > 0 && logBytes > 0 && logBytes + size > cap) rotateLog(); + logStream.write(payload); + logBytes += size; + }; /** * Append a chunk to the log file with the credential masked. @@ -904,7 +963,7 @@ export class UpstreamProcess { const cut = Math.max(0, boundary - hold); const writeable = pending.slice(0, cut); redactionCarry = pending.slice(cut); - if (writeable.length > 0) logStream.write(redactUpstreamSecret(writeable)); + if (writeable.length > 0) writeLogText(writeable); // Residual risk, by design: if the child separates `server password` from // its value by more than `LOG_REDACTION_CARRY_CHARS` characters of // whitespace, the marker reaches the file in one write and the value in a @@ -914,9 +973,9 @@ export class UpstreamProcess { /** Write the carried tail, so the file ends on a complete line. */ const flushLog = (): void => { if (!logActive || redactionCarry.length === 0) return; - const tail = redactUpstreamSecret(redactionCarry); + const tail = redactionCarry; redactionCarry = ""; - logStream.write(tail); + writeLogText(tail); }; /** diff --git a/test/upstream-invariants.test.ts b/test/upstream-invariants.test.ts new file mode 100644 index 0000000..a45ee2b --- /dev/null +++ b/test/upstream-invariants.test.ts @@ -0,0 +1,548 @@ +/** + * Upstream-layer regression tests for `IMPROVEMENT_PROPOSALS.md` U-01 … U-07. + * + * Each block fails against the code before its fix. The completion block drives + * the real `runCompletion` through a scripted event source, the process block + * scripts the `opencode serve` child (nothing is spawned), and the client block + * answers from a real HTTP listener. + */ +import { EventEmitter } from "node:events"; +import fs from "node:fs"; +import http from "node:http"; +import type { AddressInfo } from "node:net"; +import os from "node:os"; +import path from "node:path"; +import { PassThrough } from "node:stream"; +import { afterEach, describe, expect, it, vi } from "vitest"; +import type { Config } from "../src/config.js"; +import { createLogger } from "../src/logger.js"; +import { createMetrics } from "../src/metrics/registry.js"; +import type { CompletionEvent, InternalRequest } from "../src/types/internal.js"; +import type { OpencodeEvent, OpencodeSessionInfo } from "../src/types/opencode.js"; +import { OpencodeClient } from "../src/upstream/client.js"; +import { collectCompletion, runCompletion, type CompletionDeps } from "../src/upstream/completion.js"; +import { EventHub, type EventListener } from "../src/upstream/events.js"; +import { ModelRegistry } from "../src/upstream/models.js"; +import { UpstreamProcess, type SpawnedChild } from "../src/upstream/process.js"; +import { SessionStore } from "../src/upstream/sessions.js"; +import { defaultModels, testConfig } from "./helpers/context.js"; + +const tempDirs: string[] = []; + +function tempDir(prefix: string): string { + const dir = fs.mkdtempSync(path.join(os.tmpdir(), prefix)); + tempDirs.push(dir); + return dir; +} + +afterEach(() => { + vi.useRealTimers(); + for (const dir of tempDirs.splice(0)) fs.rmSync(dir, { recursive: true, force: true }); +}); + +const tick = (): Promise => new Promise((resolve) => setTimeout(resolve, 10)); + +// ---------------------------------------------------------------- completion --- + +const SESSION: OpencodeSessionInfo = { + id: "ses_test", + projectID: "project", + cost: 0, + tokens: { input: 0, output: 0, reasoning: 0, cache: { read: 0, write: 0 } }, + time: { created: 0, updated: 0 }, + location: { directory: "/tmp" }, +}; + +/** One scripted frame and the delay before the harness delivers it. */ +interface ScriptStep { + event: OpencodeEvent; + delayMs?: number; +} + +interface CompletionHarness { + deps: CompletionDeps; + sessions: SessionStore; + /** Options passed to `createSession()`, in call order. */ + createSessionOptions: Array<{ signal?: AbortSignal }>; + deletedSessions: string[]; + interruptCalls: string[]; +} + +/** + * Completion dependencies over a scripted event source. + * + * Kept local to this file (rather than added to `test/helpers/context.ts`) + * because it drives the real orchestrator, which the shared helper deliberately + * replaces with a scripted runner. + */ +function completionHarness( + script: (sessionId: string, call: number) => ScriptStep[], + configOverrides: Parameters[0] = {}, +): CompletionHarness { + const config = testConfig({ modelCacheTtlMs: 60_000, ...configOverrides }); + const log = createLogger(config); + const metrics = createMetrics({ enabled: false }); + + const listeners = new Map>(); + const createSessionOptions: Array<{ signal?: AbortSignal }> = []; + const deletedSessions: string[] = []; + const interruptCalls: string[] = []; + let callCount = 0; + + const deliver = (sessionId: string, step: ScriptStep): void => { + for (const listener of listeners.get(sessionId) ?? []) listener(step.event); + }; + + 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 client = { + async listModels() { + return defaultModels(); + }, + async listProviders() { + return [ + { id: "opencode", name: "OpenCode", activation: "enabled", package: "@opencode/ai/providers/openai-compatible" }, + ]; + }, + async listAgents() { + return [{ id: "build", name: "Build", mode: "primary", hidden: false, request: {} }]; + }, + async createSession(_payload: Record, options: { signal?: AbortSignal } = {}) { + createSessionOptions.push(options); + return SESSION; + }, + async prompt(sessionId: string) { + for (const step of script(sessionId, callCount++)) { + if (step.delayMs === undefined) queueMicrotask(() => deliver(sessionId, step)); + else setTimeout(() => deliver(sessionId, step), step.delayMs); + } + return { id: "msg_user" }; + }, + async interrupt(sessionId: string) { + interruptCalls.push(sessionId); + }, + async deleteSession(sessionId: string) { + deletedSessions.push(sessionId); + }, + } as unknown as OpencodeClient; + + const models = new ModelRegistry(client, config, log); + const sessions = new SessionStore(config, log, metrics); + + return { + deps: { client, events, models, sessions, config, log, metrics }, + sessions, + createSessionOptions, + deletedSessions, + interruptCalls, + }; +} + +function frame(type: string, data: Record = {}): OpencodeEvent { + return { id: `evt_${type}`, type, data: { sessionID: "ses_test", ...data } }; +} + +function completionRequest(overrides: Partial = {}): InternalRequest { + return { + surface: "openai.chat", + model: "opencode/seaglass-alpha-free", + messages: [{ role: "user", text: "Hello" }], + stream: false, + tools: [], + ...overrides, + }; +} + +/** A canonical single-step turn that ends successfully. */ +function textTurn(text: string): ScriptStep[] { + return [ + { event: frame("session.step.started", { assistantMessageID: "msg_a1" }) }, + { event: frame("session.text.delta", { assistantMessageID: "msg_a1", ordinal: 0, delta: text }) }, + { + event: frame("session.step.ended", { + assistantMessageID: "msg_a1", + finish: "stop", + tokens: { input: 10, output: 2, reasoning: 0, cache: { read: 0, write: 0 } }, + }), + }, + { event: frame("session.execution.succeeded", { assistantMessageID: "msg_a1" }) }, + ]; +} + +/** The `finish_reason` label of the single `completions_total` series. */ +function lastEnd(events: CompletionEvent[]): Extract | undefined { + for (let index = events.length - 1; index >= 0; index -= 1) { + const event = events[index]; + if (event?.kind === "end") return event; + } + return undefined; +} + +describe("U-01 interrupted turns are reported as cancelled", () => { + it("maps session.execution.interrupted to finishReason cancelled", async () => { + const harness = completionHarness(() => [ + { event: frame("session.step.started", { assistantMessageID: "msg_a1" }) }, + { event: frame("session.text.delta", { assistantMessageID: "msg_a1", ordinal: 0, delta: "partial" }) }, + { event: frame("session.execution.interrupted", { assistantMessageID: "msg_a1" }) }, + ]); + + const collected = await collectCompletion(completionRequest(), harness.deps); + + // The provider-side cancellation used to fall through to `finalise()` with + // `"stop"`, so the caller saw a complete answer and the metric counted a + // success; `"cancelled"` is what the Anthropic surface keys + // `x_opencode.interrupted` on. + expect(collected.finishReason).toBe("cancelled"); + expect(collected.text).toBe("partial"); + }); + + it("maps session.idle with outcome interrupted to finishReason cancelled", async () => { + const harness = completionHarness(() => [ + { event: frame("session.step.started", { assistantMessageID: "msg_a1" }) }, + { event: frame("session.text.delta", { assistantMessageID: "msg_a1", ordinal: 0, delta: "partial" }) }, + { event: frame("session.idle", { outcome: "interrupted" }) }, + ]); + + const seen: CompletionEvent[] = []; + for await (const event of runCompletion(completionRequest(), harness.deps)) seen.push(event); + + expect(lastEnd(seen)?.finishReason).toBe("cancelled"); + }); + + it("keeps a successful turn a normal stop", async () => { + const harness = completionHarness(() => textTurn("done")); + const collected = await collectCompletion(completionRequest(), harness.deps); + expect(collected.finishReason).toBe("stop"); + }); +}); + +describe("U-02 the caller's signal reaches the first createSession", () => { + it("threads the caller signal into the first prepare()", async () => { + const harness = completionHarness(() => textTurn("ok")); + const controller = new AbortController(); + + const iterator = runCompletion(completionRequest({ conversationKey: "signal-conv" }), harness.deps, { + signal: controller.signal, + }); + // `prepare()` runs before the generator's first yield, so `createSession()` + // has already been called when the `start` event arrives. + const first = await iterator.next(); + expect(first.done).toBe(false); + + // Only the replay path used to pass the signal, so a disconnect while + // `POST /api/session` was in flight could not cancel it. + expect(harness.createSessionOptions[0]?.signal).toBe(controller.signal); + + controller.abort(); + await iterator.return(undefined); + }); +}); + +describe("U-03 a cache-disabled turn stays stateless", () => { + it("commits nothing, deletes the session it created and writes no state", async () => { + vi.useFakeTimers(); + const dataDir = tempDir("opencode-cache-off-"); + const harness = completionHarness(() => textTurn("ok"), { + sessionCacheEnabled: false, + sessionPersist: true, + dataDir, + }); + + const collected = await collectCompletion(completionRequest({ conversationKey: "stateless-conv" }), harness.deps); + expect(collected.finishReason).toBe("stop"); + + // `acquire()` refuses every candidate, but `finalise()` still committed the + // session: the store, the gauge and `sessions.json` reported a cache that + // `OPENCODE_SESSION_CACHE=false` documents as fully stateless. + expect(harness.sessions.size()).toBe(0); + expect(harness.deletedSessions).toEqual(["ses_test"]); + + // Past the debounce that a commit would have armed. + vi.advanceTimersByTime(2_000); + expect(fs.existsSync(path.join(dataDir, "sessions.json"))).toBe(false); + }); +}); + +describe("U-04 the first-token watchdog only bounds a silent upstream", () => { + it("lets a turn that emits native tool activity outlive the text deadline", async () => { + const harness = completionHarness( + () => [ + { event: frame("session.step.started", { assistantMessageID: "msg_a1" }) }, + { event: frame("session.tool.input.started", { id: "tool_1", name: "bash" }), delayMs: 80 }, + { event: frame("session.tool.called", { id: "tool_1", input: { command: "ls" } }), delayMs: 160 }, + { event: frame("session.tool.success", { id: "tool_1", content: "file" }), delayMs: 240 }, + { event: frame("session.execution.succeeded", { assistantMessageID: "msg_a1" }), delayMs: 320 }, + ], + { upstreamFirstTokenTimeoutMs: 150, upstreamRequestTimeoutMs: 5_000 }, + ); + + const collected = await collectCompletion(completionRequest(), harness.deps); + + // Only text and reasoning refreshed the deadline, so a long native tool step + // was killed after 150 ms with the factually wrong "produced no output". + expect(collected.finishReason).toBe("stop"); + expect(collected.nativeTools.map((activity) => activity.status)).toEqual(["started", "called", "succeeded"]); + }); + + it("still fails a turn that goes quiet right after step.started", async () => { + const harness = completionHarness(() => [{ event: frame("session.step.started", { assistantMessageID: "msg_a1" }) }], { + upstreamFirstTokenTimeoutMs: 120, + upstreamRequestTimeoutMs: 300, + }); + + await expect(collectCompletion(completionRequest(), harness.deps)).rejects.toMatchObject({ status: 504 }); + expect(harness.interruptCalls).toContain("ses_test"); + }); + + it("still fails a turn that produces no frames at all", async () => { + const harness = completionHarness(() => [], { + upstreamFirstTokenTimeoutMs: 120, + upstreamRequestTimeoutMs: 300, + }); + + await expect(collectCompletion(completionRequest(), harness.deps)).rejects.toMatchObject({ status: 504 }); + }); +}); + +// ------------------------------------------------------------------ process --- + +/** Stand-in for a spawned `opencode serve` child. */ +class ScriptedChild extends EventEmitter { + readonly pid: number; + readonly stdout = new PassThrough(); + readonly stderr = new PassThrough(); + exitCode: number | null = null; + + constructor(pid: number) { + super(); + this.pid = pid; + } + + kill(): boolean { + if (this.exitCode !== null) return false; + this.exitCode = 0; + setImmediate(() => this.emit("exit", 0, "SIGTERM")); + return true; + } +} + +interface ProcessHarness { + upstream: UpstreamProcess; + children: ScriptedChild[]; + config: Config; +} + +function processHarness( + options: { dataDir?: string; upstreamLogMaxBytes?: number; spawnError?: boolean } = {}, +): ProcessHarness { + const children: ScriptedChild[] = []; + const config = testConfig({ + dataDir: options.dataDir ?? os.tmpdir(), + workdir: os.tmpdir(), + upstreamAutostart: true, + upstreamStartTimeoutMs: 2_000, + ...(options.upstreamLogMaxBytes === undefined ? {} : { upstreamLogMaxBytes: options.upstreamLogMaxBytes }), + }); + const log = createLogger(config); + const metrics = createMetrics({ enabled: false }); + + const upstream = new UpstreamProcess(config, log, metrics, { + findBinary: () => "/fake/opencode", + discover: async () => undefined, + probe: async () => "ok", + spawn: (_command, args) => { + const child = new ScriptedChild(6_000 + children.length); + children.push(child); + if (options.spawnError === true) { + child.emit("error", new Error("spawn EACCES")); + return child as unknown as SpawnedChild; + } + const port = args[args.indexOf("--port") + 1] ?? "0"; + setImmediate(() => { + child.stdout.write(`server listening on http://127.0.0.1:${port}\n`); + child.stdout.write("server password fake-password\n"); + }); + return child as unknown as SpawnedChild; + }, + }); + + return { upstream, children, config }; +} + +/** Read the log file once it contains `marker`. */ +async function readFileUntil(file: string, marker: string): Promise { + for (let attempt = 0; attempt < 200; attempt += 1) { + if (fs.existsSync(file)) { + const text = fs.readFileSync(file, "utf8"); + if (text.includes(marker)) return text; + } + await tick(); + } + return fs.existsSync(file) ? fs.readFileSync(file, "utf8") : ""; +} + +/** + * Read the log file once its length has stopped changing. + * + * A rotation rewrites the file, so the exact content depends on where the + * redaction carry happened to cut; only the bound is asserted. + */ +async function readStableFile(file: string): Promise { + let previous = ""; + let stableFor = 0; + for (let attempt = 0; attempt < 200; attempt += 1) { + const text = fs.existsSync(file) ? fs.readFileSync(file, "utf8") : ""; + stableFor = text.length > 0 && text.length === previous.length ? stableFor + 1 : 0; + if (stableFor >= 3) return text; + previous = text; + await tick(); + } + return previous; +} + +/** Write `count` distinguishable chunks to the child's stdout. */ +function writeChunks(child: ScriptedChild, count: number): void { + for (let index = 0; index < count; index += 1) { + child.stdout.write(`${String(index).padStart(4, "0")}-${"x".repeat(60)}\n`); + } +} + +describe("U-05 a failed spawn releases the exit registry", () => { + it("drops the instance after the spawn error settles", async () => { + const before = UpstreamProcess.liveInstanceCount; + const harness = processHarness({ spawnError: true }); + + await expect(harness.upstream.resolve()).rejects.toMatchObject({ code: "upstream_unavailable" }); + // `#starting` is cleared by the `.finally()`; the release attempt inside the + // `error` handler is refused because that promise was still in flight, so + // the instance used to stay in the static set for the process lifetime. + await tick(); + expect(UpstreamProcess.liveInstanceCount).toBe(before); + }); +}); + +describe("U-07 the child log file is bounded", () => { + it("truncates the log once it outgrows the configured cap", async () => { + const dataDir = tempDir("opencode-logcap-"); + const harness = processHarness({ dataDir, upstreamLogMaxBytes: 256 }); + await harness.upstream.resolve(); + + const child = harness.children[0]; + if (!child) throw new Error("expected a spawned child"); + writeChunks(child, 40); + + const logFile = path.join(dataDir, "logs", `opencode-${harness.config.upstreamPort}.log`); + const written = await readStableFile(logFile); + + // 40 × 65 bytes of chunks alone are ~2.6 kB; the cap must keep the file + // near one chunk over the cap instead of growing for the child's lifetime. + expect(written.length).toBeGreaterThan(0); + expect(written.length).toBeLessThan(1_000); + await harness.upstream.stop(); + }); + + it("keeps appending when the cap is disabled", async () => { + const dataDir = tempDir("opencode-logno-"); + const harness = processHarness({ dataDir, upstreamLogMaxBytes: 0 }); + await harness.upstream.resolve(); + + const child = harness.children[0]; + if (!child) throw new Error("expected a spawned child"); + writeChunks(child, 40); + + const logFile = path.join(dataDir, "logs", `opencode-${harness.config.upstreamPort}.log`); + const written = await readFileUntil(logFile, "0039-"); + + expect(written).toContain("0000-"); + expect(written.length).toBeGreaterThan(2_000); + await harness.upstream.stop(); + }); +}); + +// ------------------------------------------------------------------- client --- + +interface MalformedUpstream { + client: OpencodeClient; + close: () => Promise; +} + +/** A real HTTP listener that answers every request with `body` and HTTP 200. */ +async function malformedUpstream(body: string): Promise { + const server = http.createServer((_request, response) => { + response.writeHead(200, { "content-type": "application/json" }); + response.end(body); + }); + await new Promise((resolve) => server.listen(0, "127.0.0.1", resolve)); + const { port } = server.address() as AddressInfo; + + const config = testConfig({ upstreamRequestTimeoutMs: 2_000 }); + const upstream = { + resolve: async () => ({ url: `http://127.0.0.1:${port}`, password: undefined, source: "env" as const }), + markStale: () => undefined, + reprobe: () => undefined, + } as unknown as UpstreamProcess; + + return { + client: new OpencodeClient(upstream, config, createLogger(config), createMetrics({ enabled: false })), + close: async () => { + server.closeAllConnections(); + await new Promise((resolve) => server.close(() => resolve())); + }, + }; +} + +describe("U-06 a 2xx body without a usable data field is an ApiError", () => { + it("rejects an empty envelope from createSession with upstream_invalid_json", async () => { + for (const body of ["{}", '{"data":null}']) { + const fixture = await malformedUpstream(body); + try { + await expect(fixture.client.createSession({})).rejects.toMatchObject({ + status: 503, + code: "upstream_invalid_json", + }); + } finally { + await fixture.close(); + } + } + }); + + it("rejects prompt the same way instead of a bare TypeError", async () => { + const fixture = await malformedUpstream('{"data":null}'); + try { + await expect(fixture.client.prompt("ses_1", "hi")).rejects.toMatchObject({ + status: 503, + code: "upstream_invalid_json", + }); + } finally { + await fixture.close(); + } + }); + + it("keeps deleteSession best-effort, because it never dereferences the payload", async () => { + // The documented contract of a delete is only that the upstream accepted the + // DELETE; its success body is not part of the verified protocol, so a 2xx + // JSON object without a `data` field must not turn a successful cleanup into + // a rejection. + for (const body of ["{}", '{"data":null}', '{"data":true}']) { + const fixture = await malformedUpstream(body); + try { + await expect(fixture.client.deleteSession("ses_1")).resolves.toBeUndefined(); + } finally { + await fixture.close(); + } + } + }); +}); From eda3c372087a63ccb4b9a8c87e3f3b987c8b4dbf 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: Sat, 5 Dec 2026 17:12:46 +0700 Subject: [PATCH 2/9] fix(openai): bound the stop delimiters and reject empty turns The streamed stop filters re-scanned their held lookahead window for every declared delimiter on every delta, and nothing bounded the number or the length of those delimiters: a 1.3 MB body carrying 20 000 near-matching 64-byte sequences blocked the event loop for about 6 s on a 64 KiB answer, against the default 64 MiB body limit. `stop` is now capped at 16 entries, 256 characters each and 1024 characters in total, shared by the three stop-capable surfaces through the new `src/adapter/common/stop.ts`; past a cap the request is `400 invalid_request` naming the field. An empty entry keeps its historical meaning and is dropped by both paths again, so the streamed filter can no longer truncate an answer at offset 0. A request whose messages all normalised to nothing ran a billed turn on the literal `"Continue."` and answered `200`, although `docs/API.md` already promised the opposite for `/v1/responses`, and `/v1/messages` rejects it with COR-05. The chat and Responses surfaces now drop a message or input item that carries no text, no media and no tool call, and reject an empty result with `400 invalid_request` naming `messages` / `input`. The check runs after media resolution, so a media-only message whose attachment was omitted still keeps the omission note. `/v1/responses` applied the already-pulled `start` event only after emitting `response.created` / `response.in_progress`, so both head frames carried an empty `x_opencode.session_id`/`agent` while the terminal object carried the real values. The event is now applied before the head frames, idempotently, with the pre-flight error guard still first. --- src/adapter/common/stop.ts | 79 ++++++ src/adapter/openai/chat.ts | 59 +++- src/adapter/openai/completions.ts | 16 +- src/adapter/openai/responses.ts | 45 ++- test/openai-validation.test.ts | 437 ++++++++++++++++++++++++++++++ 5 files changed, 611 insertions(+), 25 deletions(-) create mode 100644 src/adapter/common/stop.ts create mode 100644 test/openai-validation.test.ts diff --git a/src/adapter/common/stop.ts b/src/adapter/common/stop.ts new file mode 100644 index 0000000..7a86105 --- /dev/null +++ b/src/adapter/common/stop.ts @@ -0,0 +1,79 @@ +/** + * Caller-supplied stop delimiters, shared by every surface that honours them. + * + * `stop` (`/v1/chat/completions`, `/v1/completions`) and `stop_sequences` + * (`/v1/messages`) are enforced by the adapters themselves: the upstream agent + * loop cannot be handed a delimiter, so the visible assistant text is truncated + * at the first match. Each streaming filter re-scans its held lookahead window + * — at most `longest delimiter - 1` characters plus the new delta — for every + * declared sequence on every delta, and the buffered twin scans the whole answer + * once, so both are linear in the number of declared sequences. + * + * Nothing used to bound that number or the length of one entry, while the + * request body is allowed to be tens of megabytes: a request with 20 000 + * near-matching 64-byte sequences blocked the event loop for ~6 s on a 64 KiB + * answer, stalling every concurrent turn. The caps below keep a legitimate + * caller unchanged (real delimiters are a handful of short strings) and make + * the per-delta cost bounded by `MAX_STOP_SEQUENCES * MAX_STOP_SEQUENCE_LENGTH`. + * + * Empty entries keep their historical meaning: they are dropped rather than + * rejected, so a client that sends `[""]` is not broken by this change. + */ +import { ApiError } from "../../errors.js"; + +/** Maximum number of delimiters one request may declare. */ +export const MAX_STOP_SEQUENCES = 16; + +/** Maximum length, in characters, of one delimiter. */ +export const MAX_STOP_SEQUENCE_LENGTH = 256; + +/** Maximum combined length, in characters, of all delimiters of one request. */ +export const MAX_STOP_SEQUENCE_BYTES = 1024; + +/** + * Normalise the `stop` / `stop_sequences` field of a request body. + * + * Accepts the two spellings the OpenAI surfaces allow (a single string or an + * array) and returns the delimiters that should be enforced. An empty entry is + * dropped, exactly as `normaliseStop()` used to do. `null` is accepted as + * "absent" because the surfaces tolerate it on an optional field. An entry, a + * count or a combined size past the documented caps is `400 invalid_request` + * naming `param`, so the caller learns which field to shrink instead of paying + * for a turn that then stalls the gateway. + */ +export function normaliseStopSequences( + value: string | readonly string[] | null | undefined, + param: string, +): string[] { + if (value === undefined || value === null) return []; + const entries = typeof value === "string" ? [value] : value; + const sequences = entries.filter((entry) => entry.length > 0); + + if (sequences.length > MAX_STOP_SEQUENCES) { + throw ApiError.badRequest( + `\`${param}\` accepts at most ${MAX_STOP_SEQUENCES} entries; ${sequences.length} were supplied.`, + { code: "invalid_request", param }, + ); + } + + let total = 0; + for (const sequence of sequences) { + if (sequence.length > MAX_STOP_SEQUENCE_LENGTH) { + throw ApiError.badRequest( + `\`${param}\` entries may be at most ${MAX_STOP_SEQUENCE_LENGTH} characters long.`, + { code: "invalid_request", param }, + ); + } + total += sequence.length; + } + + if (total > MAX_STOP_SEQUENCE_BYTES) { + throw ApiError.badRequest( + `\`${param}\` may declare at most ${MAX_STOP_SEQUENCE_BYTES} characters across all entries; ` + + `${total} were supplied.`, + { code: "invalid_request", param }, + ); + } + + return sequences; +} \ No newline at end of file diff --git a/src/adapter/openai/chat.ts b/src/adapter/openai/chat.ts index a3beefa..5deb876 100644 --- a/src/adapter/openai/chat.ts +++ b/src/adapter/openai/chat.ts @@ -10,6 +10,7 @@ import { randomUUID } from "node:crypto"; import type { FastifyInstance, FastifyReply, FastifyRequest } from "fastify"; import { z } from "zod"; import { reasoningFromEffort } from "../common/reasoning.js"; +import { normaliseStopSequences } from "../common/stop.js"; import type { Config } from "../../config.js"; import { completionDeps, type AppContext } from "../../context.js"; import { ApiError, toApiError, toOpenAiError } from "../../errors.js"; @@ -463,6 +464,26 @@ function assertMediaRoles(messages: ChatMessage[]): void { } } +/** + * True when a normalised message carries something the upstream prompt can use. + * + * A-03, the OpenAI twin of COR-05 on `/v1/messages`: a message whose normalised + * form has no text, no attachment and no tool call is dropped before the turn + * runs, so `content: ""`, `content: null` and `content: []` cannot turn into an + * empty prompt answered 200. A `role: "tool"` message keeps its `toolCallId` as + * content, because the transcript has to pair it with the assistant call that + * produced it — the same reason the Anthropic surface always keeps a + * `tool_result`. + */ +export function hasRenderableContent(message: InternalMessage): boolean { + return ( + message.text.trim().length > 0 || + (message.attachments?.length ?? 0) > 0 || + (message.toolCalls?.length ?? 0) > 0 || + message.toolCallId !== undefined + ); +} + // ----------------------------------------------------------------- routes --- export function registerOpenAiChatRoutes(app: FastifyInstance, ctx: AppContext): void { @@ -532,7 +553,21 @@ async function buildRequest( // 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 messages = (await resolveMessageMedia(drafts, config, { signal, budget, field: "messages" })).filter( + hasRenderableContent, + ); + + // A-03, mirroring COR-05 on `/v1/messages`: a message whose normalised form + // carries no text, no attachment and no tool call is dropped (an empty + // `content` used to become an empty internal turn), and a request whose + // messages all drop that way is a `400 invalid_request` naming `messages` + // instead of a billed turn run on the literal `"Continue."` fallback. + if (messages.length === 0) { + throw ApiError.badRequest("At least one message must carry text, media or a tool call.", { + code: "invalid_request", + param: "messages", + }); + } const internal: InternalRequest = { surface: "openai.chat", @@ -563,8 +598,13 @@ async function buildRequest( const maxTokens = body.max_completion_tokens ?? body.max_tokens; if (typeof maxTokens === "number") internal.maxTokens = maxTokens; - const stop = normaliseStop(body.stop); - if (stop !== undefined && stop.length > 0) internal.stop = stop; + // A-01: the shared helper enforces the documented caps (`MAX_STOP_SEQUENCES`, + // `MAX_STOP_SEQUENCE_LENGTH`, `MAX_STOP_SEQUENCE_BYTES`) with a `400 + // invalid_request` naming `stop`, so an unbounded delimiter list can no longer + // make the streamed filter quadratic per delta. Empty entries keep their + // historical meaning and are dropped rather than rejected. + const stop = normaliseStopSequences(body.stop, "stop"); + if (stop.length > 0) internal.stop = stop; if (body.parallel_tool_calls !== undefined) internal.parallelToolCalls = body.parallel_tool_calls; @@ -964,8 +1004,11 @@ export class StopSequenceFilter { #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); + // Empty entries are dropped for parity with the buffered + // `truncateAtStopSequences`: an empty string matches at offset 0, so keeping + // one would truncate every answer to nothing on the streamed path only. + this.#sequences = sequences.filter((entry) => entry.length > 0); + this.#hold = Math.max(0, this.#sequences.reduce((longest, entry) => Math.max(longest, entry.length), 0) - 1); } /** True once a delimiter has been seen; later text is dropped. */ @@ -1280,12 +1323,6 @@ function invalidRequestFromZod(error: z.ZodError): ApiError { }); } -function normaliseStop(stop: string | string[] | undefined): string[] | undefined { - if (stop === undefined) return undefined; - if (typeof stop === "string") return stop.length > 0 ? [stop] : []; - return stop.filter((entry) => entry.length > 0); -} - /** Read a non-empty, trimmed request header. Shared with the legacy surface. */ export function headerValue(request: FastifyRequest, name: string): string | undefined { const raw = request.headers[name]; diff --git a/src/adapter/openai/completions.ts b/src/adapter/openai/completions.ts index a3756b9..bd813e5 100644 --- a/src/adapter/openai/completions.ts +++ b/src/adapter/openai/completions.ts @@ -14,6 +14,7 @@ import { randomUUID } from "node:crypto"; import type { FastifyInstance, FastifyReply } from "fastify"; import { z } from "zod"; +import { normaliseStopSequences } from "../common/stop.js"; import { completionDeps, type AppContext } from "../../context.js"; import { ApiError, toApiError, toOpenAiError } from "../../errors.js"; import { createDisconnectSignal } from "../../http/disconnect.js"; @@ -191,18 +192,17 @@ function buildRequest(body: CompletionRequest, resolved: ResolvedModel): Interna if (typeof body.max_tokens === "number") internal.maxTokens = body.max_tokens; if (typeof body.service_tier === "string") internal.serviceTier = body.service_tier; - const stop = normaliseStop(body.stop); - if (stop !== undefined && stop.length > 0) internal.stop = stop; + // A-01: the shared helper enforces the documented caps (`MAX_STOP_SEQUENCES`, + // `MAX_STOP_SEQUENCE_LENGTH`, `MAX_STOP_SEQUENCE_BYTES`) with a `400 + // invalid_request` naming `stop`, so an unbounded delimiter list can no longer + // make the streamed filter quadratic per delta. Empty entries keep their + // historical meaning and are dropped rather than rejected. + const stop = normaliseStopSequences(body.stop, "stop"); + if (stop.length > 0) internal.stop = stop; return internal; } -function normaliseStop(stop: string | string[] | undefined): string[] | undefined { - if (stop === undefined) return undefined; - if (typeof stop === "string") return stop.length > 0 ? [stop] : []; - return stop.filter((entry) => entry.length > 0); -} - // --------------------------------------------------------- non-streaming out --- function completionBody(collected: CollectedCompletion, unapplied: readonly string[] = []): Record { diff --git a/src/adapter/openai/responses.ts b/src/adapter/openai/responses.ts index 9fcc9f1..7ca2781 100644 --- a/src/adapter/openai/responses.ts +++ b/src/adapter/openai/responses.ts @@ -48,6 +48,7 @@ import { EMPTY_USAGE } from "../common/usage.js"; import { assertHonouredParameters, assertMediaRole, + hasRenderableContent, rejectUnsupported, resolveMessageMedia, unappliedParameters, @@ -654,10 +655,21 @@ async function prepare( // grows past the engine's argument limit (~125 000 elements), which a body // far below `bodyLimitBytes` can reach with minimal input items. for (const message of await mapInputItems(body.input, ctx, signal, budget)) { - messages.push(message); + // A-03, mirroring COR-05 on `/v1/messages`: an item whose normalised form + // carries no text, no attachment and no tool call is dropped, so + // `input: [{role:"user",content:[]}]` and `input: [{type:"item_reference"}]` + // cannot run a billed turn on the literal `"Continue."` fallback. + if (hasRenderableContent(message)) messages.push(message); } } + if (messages.length === 0) { + throw ApiError.badRequest( + "At least one input item must carry text, media or a tool call.", + { code: "invalid_request", param: "input" }, + ); + } + const tools: ToolDefinition[] = (body.tools ?? []).map((tool) => ({ name: tool.name, parameters: tool.parameters ?? { type: "object", properties: {} }, @@ -1400,6 +1412,24 @@ function sendFailure(writer: SseWriter, prepared: Prepared, state: StreamState, emitFrame(writer, state, "error", (sequence) => errorFrame(error, sequence)); } +/** A pulled `start` event: the only event carrying the session identity. */ +type StartEvent = Extract; + +/** + * Apply a `start` event to the streamed state. + * + * Extracted so the head frames can carry the real session identity (A-04): the + * event is applied once right after the pre-flight error guard and again when + * the event loop reaches it, so the assignment must stay idempotent. + */ +function applyStart(state: StreamState, event: StartEvent): void { + state.sessionId = event.sessionId; + state.agent = event.agent ?? state.agent; + state.variant = event.variant ?? null; + state.reusedSession = event.reusedSession; + state.reasoningEnabled = event.reasoningEnabled; +} + async function pipeEvents( events: AsyncGenerator, writer: SseWriter, @@ -1436,6 +1466,13 @@ async function pipeEvents( throw first.value.error; } + // A-04: `response.created` / `response.in_progress` carry the session + // identity, so the already-pulled `start` event is applied to `state` before + // they are emitted. The pre-flight guard above stays first, so a turn that + // fails before its first real event still commits no head and the client sees + // the HTTP status instead of a 200 SSE head with empty `x_opencode` fields. + if (!first.done && first.value.kind === "start") applyStart(state, first.value); + emitFrame(writer, state, "response.created", (sequence) => ({ type: "response.created", sequence_number: sequence, @@ -1452,11 +1489,7 @@ async function pipeEvents( const event = result.value; switch (event.kind) { case "start": - state.sessionId = event.sessionId; - state.agent = event.agent ?? state.agent; - state.variant = event.variant ?? null; - state.reusedSession = event.reusedSession; - state.reasoningEnabled = event.reasoningEnabled; + applyStart(state, event); break; case "reasoning_delta": { diff --git a/test/openai-validation.test.ts b/test/openai-validation.test.ts new file mode 100644 index 0000000..ad23580 --- /dev/null +++ b/test/openai-validation.test.ts @@ -0,0 +1,437 @@ +/** + * Regression tests for the OpenAI-side findings of the improvement round. + * + * A-01 — the caller-supplied `stop` list was unbounded, so the streamed filter + * became quadratic per delta (and an empty entry truncated every answer to + * nothing); the caps now live in `src/adapter/common/stop.ts`. + * A-03 — a chat / Responses request whose messages all normalise to nothing ran + * a billed turn on the literal `"Continue."` fallback and answered 200. + * A-04 — the `/v1/responses` head frames reported an unresolved `x_opencode` + * because the pulled `start` event was applied after them. + * + * Every test here fails without its fix. + */ +import { afterEach, describe, expect, it } from "vitest"; +import { StopSequenceFilter, truncateAtStopSequences } from "../src/adapter/openai/chat.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"; +import { createTestContext, parseSseJson } from "./helpers/context.js"; + +const AUTH = { authorization: "Bearer test-key" }; +const MODEL = "opencode/deepseek-v4.1-flash-free"; +const PNG_BASE64 = + "iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAYAAAAfFcSJAAAADUlEQVR42mP8z8BQDwAEhQGAhKmMIQAAAABJRU5ErkJggg=="; +const PNG_DATA_URI = `data:image/png;base64,${PNG_BASE64}`; + +const USAGE: Usage = { ...EMPTY_USAGE, inputTokens: 12, outputTokens: 4, totalTokens: 16 }; + +/** The scripted turn every accepted case runs. */ +function script(request: InternalRequest): CompletionEvent[] { + return [ + { + kind: "start", + sessionId: "ses_validation", + messageId: "msg_validation", + model: request.model, + agent: "build", + reusedSession: false, + reasoningEnabled: false, + }, + { kind: "text_delta", text: "Hello", ordinal: 0 }, + { kind: "end", finishReason: "stop", usage: USAGE, messageId: "msg_validation" }, + ]; +} + +interface OpenAiErrorBody { + error: { code: string; param?: string }; +} + +/** The single SSE frame of `type`, when the stream produced one. */ +function frameOfType(body: string, type: string): T | undefined { + return parseSseJson(body).find((frame) => (frame.json as { type?: string }).type === type)?.json; +} + +afterEach(() => { + delete process.env["OPENCODE_REASONING_FIELD"]; +}); + +describe("A-01 — caller-supplied stop delimiters are capped", () => { + it("rejects more than 16 `stop` entries on the chat surface", 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: Array.from({ length: 17 }, (_unused, index) => `delimiter-${index}`), + }, + }); + + expect(response.statusCode).toBe(400); + const body = response.json() as OpenAiErrorBody; + expect(body.error.code).toBe("invalid_request"); + expect(body.error.param).toBe("stop"); + await app.close(); + }); + + it("rejects a single `stop` entry longer than 256 characters", 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: "x".repeat(257) }, + }); + + expect(response.statusCode).toBe(400); + const body = response.json() as OpenAiErrorBody; + expect(body.error.code).toBe("invalid_request"); + expect(body.error.param).toBe("stop"); + await app.close(); + }); + + it("rejects a combined `stop` length over 1024 characters", async () => { + const app = await buildServer(createTestContext()); + const response = await app.inject({ + method: "POST", + url: "/v1/chat/completions", + headers: AUTH, + // Five entries inside the per-entry cap, 1250 characters in total. + payload: { + model: MODEL, + messages: [{ role: "user", content: "hi" }], + stop: Array.from({ length: 5 }, () => "y".repeat(250)), + }, + }); + + expect(response.statusCode).toBe(400); + const body = response.json() as OpenAiErrorBody; + expect(body.error.code).toBe("invalid_request"); + expect(body.error.param).toBe("stop"); + await app.close(); + }); + + it("rejects an unbounded `stop` list on the legacy completions surface too", async () => { + const app = await buildServer(createTestContext()); + const response = await app.inject({ + method: "POST", + url: "/v1/completions", + headers: AUTH, + payload: { + model: MODEL, + prompt: "hi", + stop: Array.from({ length: 17 }, (_unused, index) => `delimiter-${index}`), + }, + }); + + expect(response.statusCode).toBe(400); + const body = response.json() as OpenAiErrorBody; + expect(body.error.code).toBe("invalid_request"); + expect(body.error.param).toBe("stop"); + await app.close(); + }); + + it("keeps accepting a delimiter list exactly at the caps", async () => { + const captured: InternalRequest[] = []; + const app = await buildServer(createTestContext({ script, onRun: (request) => captured.push(request) })); + // 16 entries × 64 characters = 1024 characters, the documented maximum. + const stop = Array.from({ length: 16 }, () => "z".repeat(64)); + const response = await app.inject({ + method: "POST", + url: "/v1/chat/completions", + headers: AUTH, + payload: { model: MODEL, messages: [{ role: "user", content: "hi" }], stop }, + }); + + expect(response.statusCode).toBe(200); + expect(captured[0]?.stop).toEqual(stop); + await app.close(); + }); + + it("does not truncate at an empty delimiter, on either path", () => { + // `stop: ""` used to match at offset 0 on the streamed path, so the answer + // was empty there while the buffered twin kept all of it. + const filter = new StopSequenceFilter(["", "END"]); + expect(filter.push("hello ENDtail")).toBe("hello "); + expect(filter.matched).toBe(true); + + // The buffered twin already skipped empty entries; both paths must agree. + expect(truncateAtStopSequences("hello ENDtail", ["", "END"])).toBe("hello "); + + // A filter built from empty entries only forwards everything. + const noop = new StopSequenceFilter(["", ""]); + expect(noop.push("kept")).toBe("kept"); + expect(noop.matched).toBe(false); + }); +}); + +describe("A-03 — a request whose content all drops is rejected", () => { + it.each([ + ["an empty string", ""], + ["null", null], + ["an empty part array", []], + ])("rejects a chat request whose only message has %s content", async (_label, content) => { + const captured: InternalRequest[] = []; + const app = await buildServer(createTestContext({ script, 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 }] }, + }); + + expect(response.statusCode).toBe(400); + const body = response.json() as OpenAiErrorBody; + expect(body.error.code).toBe("invalid_request"); + expect(body.error.param).toBe("messages"); + // The caller must not have paid for an empty prompt. + expect(captured).toHaveLength(0); + await app.close(); + }); + + it("rejects an all-empty chat request on the streamed path too", 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: "" }], stream: true }, + }); + + // No SSE head may be committed for a validation failure. + expect(response.statusCode).toBe(400); + expect(response.headers["content-type"]).toContain("application/json"); + expect(response.body).not.toContain("data:"); + await app.close(); + }); + + it("still runs a tool_calls-only assistant message", async () => { + const captured: InternalRequest[] = []; + const app = await buildServer(createTestContext({ script, onRun: (request) => captured.push(request) })); + const response = await app.inject({ + method: "POST", + url: "/v1/chat/completions", + headers: AUTH, + payload: { + model: MODEL, + messages: [ + { + role: "assistant", + content: null, + tool_calls: [{ id: "call_1", type: "function", function: { name: "lookup", arguments: "{}" } }], + }, + ], + }, + }); + + expect(response.statusCode).toBe(200); + expect(captured[0]?.messages).toHaveLength(1); + expect(captured[0]?.messages[0]?.toolCalls).toEqual([{ id: "call_1", name: "lookup", arguments: "{}" }]); + await app.close(); + }); + + it("still runs a tool result", async () => { + const captured: InternalRequest[] = []; + const app = await buildServer(createTestContext({ script, onRun: (request) => captured.push(request) })); + const response = await app.inject({ + method: "POST", + url: "/v1/chat/completions", + headers: AUTH, + payload: { + model: MODEL, + messages: [ + { + role: "assistant", + content: null, + tool_calls: [{ id: "call_1", type: "function", function: { name: "lookup", arguments: "{}" } }], + }, + { role: "tool", tool_call_id: "call_1", name: "lookup", content: "42" }, + ], + }, + }); + + expect(response.statusCode).toBe(200); + expect(captured[0]?.messages.map((message) => message.role)).toEqual(["assistant", "tool"]); + expect(captured[0]?.messages[1]?.toolCallId).toBe("call_1"); + await app.close(); + }); + + it("still runs a media-only user message", async () => { + const captured: InternalRequest[] = []; + const app = await buildServer(createTestContext({ script, 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: [{ type: "image_url", image_url: { url: PNG_DATA_URI } }] }], + }, + }); + + expect(response.statusCode).toBe(200); + expect(captured[0]?.messages[0]?.text).toBe(""); + expect(captured[0]?.messages[0]?.attachments).toHaveLength(1); + await app.close(); + }); + + it.each([ + ["an empty string", ""], + ["an empty part array", []], + ])("rejects a Responses input whose only item carries %s", async (_label, content) => { + const captured: InternalRequest[] = []; + const app = await buildServer(createTestContext({ script, onRun: (request) => captured.push(request) })); + const response = await app.inject({ + method: "POST", + url: "/v1/responses", + headers: AUTH, + payload: { model: MODEL, input: [{ role: "user", content }] }, + }); + + expect(response.statusCode).toBe(400); + const body = response.json() as OpenAiErrorBody; + expect(body.error.code).toBe("invalid_request"); + expect(body.error.param).toBe("input"); + expect(captured).toHaveLength(0); + await app.close(); + }); + + it("rejects a Responses input that only references an unreachable item", async () => { + const captured: InternalRequest[] = []; + const app = await buildServer(createTestContext({ script, onRun: (request) => captured.push(request) })); + const response = await app.inject({ + method: "POST", + url: "/v1/responses", + headers: AUTH, + payload: { model: MODEL, input: [{ type: "item_reference", id: "msg_never_stored" }] }, + }); + + expect(response.statusCode).toBe(400); + const body = response.json() as OpenAiErrorBody; + expect(body.error.code).toBe("invalid_request"); + expect(body.error.param).toBe("input"); + expect(captured).toHaveLength(0); + await app.close(); + }); + + it("still runs a media-only Responses input item", async () => { + const captured: InternalRequest[] = []; + const app = await buildServer(createTestContext({ script, onRun: (request) => captured.push(request) })); + const response = await app.inject({ + method: "POST", + url: "/v1/responses", + headers: AUTH, + payload: { + model: MODEL, + input: [{ role: "user", content: [{ type: "input_image", image_url: PNG_DATA_URI }] }], + }, + }); + + expect(response.statusCode).toBe(200); + expect(captured[0]?.messages[0]?.attachments).toHaveLength(1); + await app.close(); + }); + + it("still runs a Responses function_call_output", async () => { + const captured: InternalRequest[] = []; + const app = await buildServer(createTestContext({ script, onRun: (request) => captured.push(request) })); + const response = await app.inject({ + method: "POST", + url: "/v1/responses", + headers: AUTH, + payload: { + model: MODEL, + input: [{ type: "function_call_output", call_id: "call_1", output: "42" }], + }, + }); + + expect(response.statusCode).toBe(200); + expect(captured[0]?.messages).toHaveLength(1); + expect(captured[0]?.messages[0]?.role).toBe("tool"); + expect(captured[0]?.messages[0]?.toolCallId).toBe("call_1"); + await app.close(); + }); +}); + +describe("A-04 — the Responses head frames carry the resolved session identity", () => { + it("reports the pulled start event in response.created and response.in_progress", async () => { + const app = await buildServer( + createTestContext({ + script: () => [ + { + kind: "start", + sessionId: "ses_head", + messageId: "msg_head", + model: MODEL, + agent: "plan", + variant: "high", + reusedSession: true, + reasoningEnabled: false, + }, + { kind: "text_delta", text: "Hi", ordinal: 0 }, + { kind: "end", finishReason: "stop", usage: USAGE, messageId: "msg_head" }, + ], + }), + ); + + const response = await app.inject({ + method: "POST", + url: "/v1/responses", + headers: AUTH, + payload: { model: MODEL, input: "hi", stream: true }, + }); + + expect(response.statusCode).toBe(200); + interface HeadFrame { + response: { + x_opencode: { session_id: string; agent: string; variant: string | null; reused_session: boolean }; + }; + } + for (const type of ["response.created", "response.in_progress"]) { + const frame = frameOfType(response.body, type); + expect(frame, `${type} must be emitted`).toBeDefined(); + expect(frame?.response.x_opencode).toEqual({ + session_id: "ses_head", + agent: "plan", + variant: "high", + reused_session: true, + native_tool_calls: [], + }); + } + + // The terminal frame keeps the same identity. + const completed = frameOfType(response.body, "response.completed"); + expect(completed?.response.x_opencode.session_id).toBe("ses_head"); + await app.close(); + }); + + it("still commits no head when the first event is a pre-flight error", async () => { + const app = await buildServer( + createTestContext({ + script: () => [ + { + kind: "error", + error: ApiError.unavailable("OpenCode event stream is not connected.", { + code: "event_stream_unavailable", + }), + }, + ], + }), + ); + + const response = await app.inject({ + method: "POST", + url: "/v1/responses", + headers: AUTH, + payload: { model: MODEL, input: "hi", stream: true }, + }); + + expect(response.statusCode).toBe(503); + expect(response.headers["content-type"]).toContain("application/json"); + expect(response.body).not.toContain("response.created"); + await app.close(); + }); +}); From 0351888624c7d99645a357676803c1239b087082 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: Sat, 5 Dec 2026 17:12:46 +0700 Subject: [PATCH 3/9] fix(anthropic): close the block before a stream error A mid-stream `error` event, the real failure path from the orchestrator (timeouts, `event_stream_lost`, queue overflow, step and execution failures), was written after returning immediately, leaving every content block the turn had opened without its `content_block_stop`. The Anthropic `error` frame carries no partial message, so the client could not close or reassemble the block at all. The in-band error branch and the outer catch now flush the stop-sequence lookahead and close the open block first, exactly like the `finishReason: "error"` path, and reorder nothing else. The surface also resolved one media block per `Promise.all` instead of through the shared bounded pool, so a `/v1/messages` request could hold `maxAttachments x maxAttachmentBytes` in flight (320 MiB by default) rather than the pool's 80 MiB, and a hard failure left its siblings downloading. Every block that needs bytes now goes through one pooled `resolveAttachments()` call and is mapped back by declaration order, keeping the omission semantics: an omitted source keeps the placeholder its slot was seeded with. `stop_sequences` uses the shared caps from `src/adapter/common/stop.ts`, and the P-24 scan-cost regression now drives 20 000 deltas at the documented 256-character cap instead of a 64 KiB sequence the cap rejects. --- src/adapter/anthropic/messages.ts | 175 +++++++++---- test/anthropic-streaming.test.ts | 406 ++++++++++++++++++++++++++++++ test/anthropic.test.ts | 29 ++- 3 files changed, 548 insertions(+), 62 deletions(-) create mode 100644 test/anthropic-streaming.test.ts diff --git a/src/adapter/anthropic/messages.ts b/src/adapter/anthropic/messages.ts index 1a32411..5304aad 100644 --- a/src/adapter/anthropic/messages.ts +++ b/src/adapter/anthropic/messages.ts @@ -21,10 +21,11 @@ import { ApiError, toAnthropicError, toApiError } from "../../errors.js"; import { createDisconnectSignal } from "../../http/disconnect.js"; import { SseWriter } from "../../http/sse.js"; import { - AttachmentOmittedError, createMediaBudget, - resolveAttachment, + resolveAttachments, type MediaBudget, + type MediaSource, + type OmittedAttachment, } from "../../media/resolve.js"; import type { CollectedCompletion } from "../../upstream/completion.js"; import type { @@ -38,6 +39,7 @@ import type { } from "../../types/internal.js"; import { EMPTY_USAGE } from "../../types/internal.js"; import { reasoningFromEffort, reasoningFromThinking } from "../common/reasoning.js"; +import { normaliseStopSequences } from "../common/stop.js"; /** Metrics label used by this surface. */ export const ANTHROPIC_MESSAGES_SURFACE = "anthropic.messages"; @@ -486,6 +488,7 @@ function withToolError(label: boolean, text: string): string { return text.length > 0 ? `[tool error]\n${text}` : "[tool error]"; } +/** The placeholder text a media block contributes when its bytes are not sent. */ function mediaPlaceholder(block: MediaBlock): string { const source = block.source; const hint = source.type === "url" ? source.url : (source.media_type ?? ""); @@ -493,42 +496,107 @@ function mediaPlaceholder(block: MediaBlock): string { } /** - * Turn one media block into an `Attachment`, or into text when the block - * carries inline text (`document` with a `text` source) or media resolution is - * switched off. + * The resolvable source of a media block. + * + * Returns nothing for a block that carries no bytes (`document` with a `text` + * source), which is rendered as text instead of being fetched. */ -async function resolveMediaBlock(block: MediaBlock, options: ToInternalOptions): Promise { - if (block.type === "document" && block.source.type === "text") { - // Anthropic's inline-text document source carries plain text, not bytes. - return [block.title, block.context, block.source.data] - .filter((part): part is string => typeof part === "string" && part.length > 0) - .join("\n"); - } - if (options.resolveMedia === false) return mediaPlaceholder(block); - +function mediaSourceOf(block: MediaBlock): MediaSource | undefined { const source = block.source; - try { - if (source.type === "base64") { - return await resolveAttachment({ base64: source.data, mime: source.media_type }, options.ctx.config, { - field: "messages", - signal: options.signal, - ...(options.budget !== undefined ? { budget: options.budget } : {}), - }); + if (source.type === "base64") return { base64: source.data, mime: source.media_type }; + if (source.type === "url") return { url: source.url }; + return undefined; +} + +/** + * Resolve the media blocks of one message through the shared download pool. + * + * Every block that needs bytes is handed to one `resolveAttachments()` call, so + * the downloads run through the request's bounded worker pool (four by default) + * instead of one unbounded `Promise.all` per block, and the byte budget is + * enforced before the pool dials a source. A block that needs no fetch — an + * inline-text document, or any block when resolution is switched off — fills its + * slot immediately and keeps its declaration position; a source the budget + * refuses comes back in `omitted` and keeps the placeholder its slot was seeded + * with, so an omitted block is announced rather than dropped. + */ +async function resolveBlockMedia( + content: readonly ContentBlock[], + options: ToInternalOptions, +): Promise<{ media: Array; toolResultMedia: Array> }> { + const mediaBlocks = content.filter( + (block): block is MediaBlock => + block.type === "image" || block.type === "document" || block.type === "audio" || block.type === "video", + ); + const toolResultBlocks = content.filter((block): block is ToolResultBlock => block.type === "tool_result"); + const nestedToolResultMedia = toolResultBlocks.map((block) => toolResultMediaBlocks(block.content)); + + // Every slot starts as the placeholder it falls back to, so an omission or an + // unfetchable source needs no special case when the results are mapped back. + const media: Array = mediaBlocks.map((block) => mediaPlaceholder(block)); + const toolResultMedia: Array> = nestedToolResultMedia.map((blocks) => + blocks.map((block) => mediaPlaceholder(block)), + ); + + // One callback per scheduled fetch, in declaration order: it fills the slot the + // block owns once the pool has resolved that source. + const pending: Array<(value: Attachment | string) => void> = []; + const sources: MediaSource[] = []; + const schedule = (block: MediaBlock, assign: (value: Attachment | string) => void): void => { + if (block.type === "document" && block.source.type === "text") { + // Anthropic's inline-text document source carries plain text, not bytes. + assign( + [block.title, block.context, block.source.data] + .filter((part): part is string => typeof part === "string" && part.length > 0) + .join("\n"), + ); + return; } - if (source.type === "url") { - return await resolveAttachment({ url: source.url }, options.ctx.config, { - field: "messages", - signal: options.signal, - ...(options.budget !== undefined ? { budget: options.budget } : {}), + if (options.resolveMedia === false) return; + const source = mediaSourceOf(block); + if (source === undefined) return; + pending.push(assign); + sources.push(source); + }; + + // Top-level blocks first, then the ones nested in a `tool_result`, both in + // declaration order: that is the order the slots were claimed in before the + // pool, and it decides which block an exhausted count budget omits. + for (const [index, block] of mediaBlocks.entries()) { + schedule(block, (value) => { + media[index] = value; + }); + } + for (const [blockIndex, blocks] of nestedToolResultMedia.entries()) { + const slots = toolResultMedia[blockIndex]; + if (slots === undefined) continue; + for (const [nestedIndex, block] of blocks.entries()) { + schedule(block, (value) => { + slots[nestedIndex] = value; }); } - } catch (error) { - // A block the request budget cannot fit is announced, not fetched: the model - // still learns that something was there, and the turn continues. - if (error instanceof AttachmentOmittedError) return mediaPlaceholder(block); - throw error; } - return mediaPlaceholder(block); + + const resolved = + sources.length > 0 + ? await resolveAttachments(sources, options.ctx.config, { + field: "messages", + ...(options.signal !== undefined ? { signal: options.signal } : {}), + ...(options.budget !== undefined ? { budget: options.budget } : {}), + }) + : { attachments: [] as Attachment[], omitted: [] as OmittedAttachment[] }; + + const omitted = new Set(resolved.omitted.map((entry) => entry.index)); + let attachmentIndex = 0; + for (const [index, assign] of pending.entries()) { + // An omitted source keeps the placeholder seeded above. + if (omitted.has(index)) continue; + const attachment = resolved.attachments[attachmentIndex]; + attachmentIndex += 1; + if (attachment !== undefined) assign(attachment); + } + + return { media, toolResultMedia }; } function mapToolChoice(choice: AnthropicRequestInput["tool_choice"]): InternalRequest["toolChoice"] { @@ -616,23 +684,14 @@ export async function toInternalRequest( // turn `collectAttachments` forwards upstream. const toolResultAttachments: Attachment[] = []; - // Media resolution is the only asynchronous part of a message. The top-level - // blocks and the image/document blocks nested in a tool_result are resolved - // concurrently and re-assembled in declaration order. - const mediaBlocks = message.content.filter( - (block): block is MediaBlock => - block.type === "image" || block.type === "document" || block.type === "audio" || block.type === "video", + // Media resolution is the only asynchronous part of a message. Every block + // that needs bytes goes through one pooled `resolveAttachments()` call, so + // the downloads share the bounded pool instead of fanning out one request + // per block, and the results are re-assembled in declaration order. + const { media: resolvedMedia, toolResultMedia: resolvedToolResultMedia } = await resolveBlockMedia( + message.content, + scoped, ); - const toolResultBlocks = message.content.filter( - (block): block is ToolResultBlock => block.type === "tool_result", - ); - const nestedToolResultMedia = toolResultBlocks.map((block) => toolResultMediaBlocks(block.content)); - const [resolvedMedia, resolvedToolResultMedia] = await Promise.all([ - Promise.all(mediaBlocks.map((block) => resolveMediaBlock(block, scoped))), - Promise.all( - nestedToolResultMedia.map((blocks) => Promise.all(blocks.map((block) => resolveMediaBlock(block, scoped)))), - ), - ]); let mediaCursor = 0; let toolResultCursor = 0; @@ -758,9 +817,12 @@ export async function toInternalRequest( if (body.temperature !== undefined) request.temperature = body.temperature; if (body.top_p !== undefined) request.topP = body.top_p; if (body.max_tokens !== undefined) request.maxTokens = body.max_tokens; - // An empty sequence would match at position 0 and truncate every turn, so - // empty entries are dropped before the value reaches the internal request. - const stopSequences = (body.stop_sequences ?? []).filter((sequence) => sequence.length > 0); + // `normaliseStopSequences()` drops an empty entry — one would match at + // position 0 and truncate every turn — and bounds the entry count, the length + // of one entry and the combined size, because the streamed filter scans every + // declared sequence on every delta. The caps and their error are shared with + // the OpenAI surfaces. + const stopSequences = normaliseStopSequences(body.stop_sequences, "stop_sequences"); if (stopSequences.length > 0) request.stop = stopSequences; const toolChoice = mapToolChoice(body.tool_choice); if (toolChoice !== undefined) request.toolChoice = toolChoice; @@ -1305,6 +1367,12 @@ async function streamAnthropicMessage( } case "error": { if (!opened) throw event.error; + // Whatever the step already delivered is still real content, and an + // Anthropic `error` frame carries no partial message: returning + // before the flush and the block stop left the client with a block + // it could never close. Mirror the `finishReason: "error"` path. + sendText(stopFilter.flush()); + closeOpen(); send(anthropicErrorFrame(event.error), "error"); return reply; } @@ -1318,6 +1386,11 @@ async function streamAnthropicMessage( } } catch (error) { if (!opened) throw error; + // The response head is committed and a block may still be open: close it + // before the terminal `error` frame, exactly like the in-band failure + // paths above, so the client can assemble the partial message. + sendText(stopFilter.flush()); + closeOpen(); send(anthropicErrorFrame(toApiError(error, "OpenCode completion failed.")), "error"); return reply; } diff --git a/test/anthropic-streaming.test.ts b/test/anthropic-streaming.test.ts new file mode 100644 index 0000000..25d3c80 --- /dev/null +++ b/test/anthropic-streaming.test.ts @@ -0,0 +1,406 @@ +/** + * Regressions for three Anthropic-surface audit findings on + * `src/adapter/anthropic/messages.ts`: + * + * - A-01: `stop_sequences` is bounded by the shared caps in + * `src/adapter/common/stop.ts` instead of an ad-hoc filter. + * - A-02: a mid-stream failure flushes the stop filter and closes the content + * block it left open before the terminal `error` frame. + * - A-06: the media blocks of a message are resolved through the bounded + * download pool of `resolveAttachments()` instead of one `Promise.all` fan-out. + * + * Everything runs against the scripted completion runner of + * `test/helpers/context.ts`; the only real socket is the loopback media fixture + * of the A-06 tests, because the pool size is only observable while downloads + * are actually in flight. + */ +import { createServer } from "node:http"; +import type { FastifyInstance } from "fastify"; +import { afterEach, describe, expect, it } from "vitest"; + +import { parseAnthropicMessagesBody, toInternalRequest } from "../src/adapter/anthropic/messages.js"; +import { ApiError } from "../src/errors.js"; +import { buildServer } from "../src/server.js"; +import type { CompletionEvent, InternalRequest } from "../src/types/internal.js"; +import { createTestContext, parseSse, type TestContextOptions } from "./helpers/context.js"; + +const AUTH = { authorization: "Bearer test-key" }; +const MODEL = "deepseek-v4.1-flash-free"; +const CANONICAL_MODEL = "opencode/deepseek-v4.1-flash-free"; +/** 1x1 PNG, used by the loopback media fixture. */ +const PNG_1X1 = + "iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAYAAAAfFcSJAAAADUlEQVR42mP8z8BQDwAEhQGAhKmMIQAAAABJRU5ErkJggg=="; + +interface AnthropicErrorBody { + type: string; + error: { type: string; message: string }; +} + +interface StreamFrame { + type: string; + index?: number; + content_block?: { type?: string }; + delta?: { type?: string; text?: string; stop_sequence?: string | null }; +} + +const apps: FastifyInstance[] = []; + +afterEach(async () => { + await Promise.all(apps.splice(0).map((app) => app.close())); +}); + +async function serverWith(options: TestContextOptions = {}): Promise { + const ctx = createTestContext(options); + const app = await buildServer(ctx); + apps.push(app); + return app; +} + +async function post( + app: FastifyInstance, + payload: unknown, + headers: Record = {}, +): Promise<{ statusCode: number; body: string }> { + const response = await app.inject({ + method: "POST", + url: "/v1/messages", + headers: { ...AUTH, "content-type": "application/json", ...headers }, + payload: payload as object, + }); + return { statusCode: response.statusCode, body: response.body }; +} + +function startEvent(reasoningEnabled = false): CompletionEvent { + return { + kind: "start", + sessionId: "ses_stream_regression", + messageId: "msg_stream_regression", + model: CANONICAL_MODEL, + agent: "build", + reusedSession: false, + reasoningEnabled, + }; +} + +function messageBody(extra: Record = {}, stream = false): Record { + return { + model: MODEL, + max_tokens: 16, + stream, + messages: [{ role: "user", content: "hi" }], + ...extra, + }; +} + +/** JSON payloads of an SSE body, in frame order. */ +function payloadsOf(body: string): StreamFrame[] { + return parseSse(body).map((frame) => JSON.parse(frame.data) as StreamFrame); +} + +/** + * An `events` list that throws on its third pull. + * + * `ctx.completion.run()` yields the first two events and then rejects, which is + * the outer-catch path of `streamAnthropicMessage()`: the response head is + * already committed and a text block is open when the upstream stream dies. + */ +function explodingEvents(): CompletionEvent[] { + let step = 0; + const iterable: Iterable = { + [Symbol.iterator](): Iterator { + return { + next(): IteratorResult { + step += 1; + if (step === 1) return { done: false, value: startEvent() }; + if (step === 2) return { done: false, value: { kind: "text_delta", text: "partial", ordinal: 0 } }; + throw new Error("upstream event stream failed"); + }, + }; + }, + }; + return iterable as unknown as CompletionEvent[]; +} + +describe("stop_sequences caps (A-01)", () => { + it("rejects more entries than the documented maximum with 400 invalid_request", async () => { + const app = await serverWith(); + + const response = await post( + app, + messageBody({ + stop_sequences: Array.from({ length: 17 }, (_unused, index) => `stop-${index}`), + }), + ); + + expect(response.statusCode).toBe(400); + const error = JSON.parse(response.body) as AnthropicErrorBody; + expect(error.error.type).toBe("invalid_request_error"); + expect(error.error.message).toContain("stop_sequences"); + expect(error.error.message).toContain("at most 16"); + }); + + it("rejects one entry past the length cap and a total past the size cap", async () => { + const ctx = createTestContext(); + const body = (stop_sequences: string[]) => + parseAnthropicMessagesBody(messageBody({ stop_sequences })); + + await expect( + toInternalRequest(body(["x".repeat(257)]), { ctx, model: MODEL }), + ).rejects.toMatchObject({ code: "invalid_request", param: "stop_sequences" }); + + await expect( + toInternalRequest(body(Array.from({ length: 5 }, () => "x".repeat(250))), { ctx, model: MODEL }), + ).rejects.toMatchObject({ code: "invalid_request", param: "stop_sequences" }); + }); + + it("accepts the documented boundary and still drops empty entries", async () => { + const ctx = createTestContext(); + const body = (stop_sequences: string[]) => + parseAnthropicMessagesBody(messageBody({ stop_sequences })); + + // 16 entries of 64 characters: exactly at both caps. + const atCap = await toInternalRequest( + body(Array.from({ length: 16 }, () => "x".repeat(64))), + { ctx, model: MODEL }, + ); + expect(atCap.stop).toHaveLength(16); + + // An empty entry is dropped rather than rejected, so it can never match at + // position 0 and truncate the whole turn. + const emptied = await toInternalRequest(body(["", "END"]), { ctx, model: MODEL }); + expect(emptied.stop).toEqual(["END"]); + }); +}); + +describe("mid-stream failure closes the open block (A-02)", () => { + it("emits content_block_stop before the terminal error frame", async () => { + const events: CompletionEvent[] = [ + startEvent(), + { kind: "text_delta", text: "partial", ordinal: 0 }, + { kind: "error", error: ApiError.unavailable("Model is unavailable.") }, + ]; + const app = await serverWith({ script: () => events }); + + const response = await post(app, messageBody({}, true)); + + expect(response.statusCode).toBe(200); + const frames = parseSse(response.body); + expect(frames.map((frame) => frame.event)).toEqual([ + "message_start", + "content_block_start", + "content_block_delta", + "content_block_stop", + "error", + ]); + + const payloads = payloadsOf(response.body); + const start = payloads.find((payload) => payload.type === "content_block_start"); + const stop = payloads.find((payload) => payload.type === "content_block_stop"); + expect(stop?.index).toBe(start?.index ?? -1); + + // The partial text still reaches the caller before the failure. + const visible = payloads + .filter((payload) => payload.delta?.type === "text_delta") + .map((payload) => payload.delta?.text ?? "") + .join(""); + expect(visible).toBe("partial"); + }); + + it("flushes a withheld stop-sequence suffix before closing on error", async () => { + const events: CompletionEvent[] = [ + startEvent(), + { kind: "text_delta", text: "hello", ordinal: 0 }, + { kind: "error", error: ApiError.unavailable("Model is unavailable.") }, + ]; + const app = await serverWith({ script: () => events }); + + // "END" makes the filter hold the two-character suffix "lo"; the failure + // must release it before the block closes instead of losing it. + const response = await post(app, messageBody({ stop_sequences: ["END"] }, true)); + + expect(response.statusCode).toBe(200); + const frames = parseSse(response.body); + expect(frames.map((frame) => frame.event)).toEqual([ + "message_start", + "content_block_start", + "content_block_delta", + "content_block_delta", + "content_block_stop", + "error", + ]); + + const payloads = payloadsOf(response.body); + const visible = payloads + .filter((payload) => payload.delta?.type === "text_delta") + .map((payload) => payload.delta?.text ?? "") + .join(""); + expect(visible).toBe("hello"); + }); + + it("closes the open block when the upstream stream throws mid-turn", async () => { + const app = await serverWith({ script: () => explodingEvents() }); + + const response = await post(app, messageBody({}, true)); + + expect(response.statusCode).toBe(200); + const frames = parseSse(response.body); + expect(frames.map((frame) => frame.event)).toEqual([ + "message_start", + "content_block_start", + "content_block_delta", + "content_block_stop", + "error", + ]); + const payloads = payloadsOf(response.body); + const start = payloads.find((payload) => payload.type === "content_block_start"); + const stop = payloads.find((payload) => payload.type === "content_block_stop"); + expect(stop?.index).toBe(start?.index ?? -1); + }); + + it("still answers with an HTTP status when the failure precedes the first frame", async () => { + const events: CompletionEvent[] = [{ kind: "error", error: ApiError.unavailable("nope") }]; + const app = await serverWith({ script: () => events }); + + const response = await post(app, messageBody({}, true)); + + // No frame was written, so the failure is still a real HTTP status rather + // than an SSE `error` frame. + expect(response.statusCode).toBe(503); + expect(response.body).not.toContain("event:"); + const error = JSON.parse(response.body) as AnthropicErrorBody; + expect(error.error.type).toBe("overloaded_error"); + }); +}); + +interface MediaFixture { + /** `http://127.0.0.1:` of the fixture. */ + readonly base: string; + /** `127.0.0.1:`, the prefix of every `Attachment.origin` it serves. */ + readonly originBase: string; + /** Paths dialled so far, and the highest concurrent request count seen. */ + readonly state: { hits: string[]; maxConcurrent: number; inFlight: number }; + close(): Promise; +} + +/** + * A loopback media fixture whose responses are held for `delayMs`. + * + * The hold is what makes the download-pool size observable: every request of a + * fan-out is issued in one synchronous burst, so all of them are in flight long + * before the first response of the burst is written, and the highest concurrent + * count the fixture saw is the real fan-out width. A wait on the wall clock is + * never asserted — only the counter — so a slow runner can only make the count + * smaller, never let an over-wide fan-out pass. + */ +async function startMediaFixture(delayMs: number): Promise { + const state = { hits: [] as string[], maxConcurrent: 0, inFlight: 0 }; + + const server = createServer((request, response) => { + state.inFlight += 1; + state.maxConcurrent = Math.max(state.maxConcurrent, state.inFlight); + state.hits.push(request.url ?? ""); + response.once("close", () => { + state.inFlight -= 1; + }); + setTimeout(() => { + if (response.writableEnded || response.destroyed) return; + response.writeHead(200, { "content-type": "image/png" }); + response.end(Buffer.from(PNG_1X1, "base64")); + }, delayMs); + }); + + await new Promise((resolve) => server.listen(0, "127.0.0.1", resolve)); + const address = server.address(); + if (address === null || typeof address === "string") throw new Error("media fixture did not bind a TCP port"); + + return { + base: `http://127.0.0.1:${address.port}`, + originBase: `127.0.0.1:${address.port}`, + state, + close: async () => { + server.closeAllConnections(); + await new Promise((resolve) => server.close(() => resolve())); + }, + }; +} + +describe("pooled media resolution (A-06)", () => { + it("resolves every block of a message through the documented pool of four", async () => { + const fixture = await startMediaFixture(250); + const capture: { request?: InternalRequest } = {}; + const app = await serverWith({ + // The fixture only exists on loopback, which the default configuration + // refuses; this test is about the download pool. + config: { allowPrivateMediaUrls: true }, + onRun: (request) => { + capture.request = request; + }, + }); + + try { + const response = await post(app, { + ...messageBody(), + messages: [ + { + role: "user", + content: Array.from({ length: 8 }, (_unused, index) => ({ + type: "image", + source: { type: "url", url: `${fixture.base}/image-${index}.png` }, + })), + }, + ], + }); + + expect(response.statusCode).toBe(200); + // Every block is still resolved, in declaration order. + const attachments = capture.request?.messages[0]?.attachments ?? []; + expect(attachments.map((attachment) => attachment.origin)).toEqual( + Array.from({ length: 8 }, (_unused, index) => `${fixture.originBase}/image-${index}.png`), + ); + // Eight blocks, one pooled call: at most the documented four downloads are + // ever in flight, and the pool is actually used (a serial resolver would + // report one). + expect(fixture.state.maxConcurrent).toBe(4); + } finally { + await fixture.close(); + } + }); + + it("announces a block the budget omits in declaration order", async () => { + const fixture = await startMediaFixture(1); + const capture: { request?: InternalRequest } = {}; + const app = await serverWith({ + config: { allowPrivateMediaUrls: true, maxAttachments: 2 }, + onRun: (request) => { + capture.request = request; + }, + }); + + try { + const response = await post(app, { + ...messageBody(), + messages: [ + { + role: "user", + content: ["a", "b", "c"].map((name) => ({ + type: "image", + source: { type: "url", url: `${fixture.base}/${name}.png` }, + })), + }, + ], + }); + + expect(response.statusCode).toBe(200); + const attachments = capture.request?.messages[0]?.attachments ?? []; + expect(attachments.map((attachment) => attachment.origin)).toEqual([ + `${fixture.originBase}/a.png`, + `${fixture.originBase}/b.png`, + ]); + // The third block is announced as a placeholder instead of being dialled. + expect(capture.request?.messages[0]?.text).toContain(`[image: ${fixture.base}/c.png]`); + expect([...fixture.state.hits].sort()).toEqual(["/a.png", "/b.png"]); + } finally { + await fixture.close(); + } + }); +}); diff --git a/test/anthropic.test.ts b/test/anthropic.test.ts index df2abd7..02da0bf 100644 --- a/test/anthropic.test.ts +++ b/test/anthropic.test.ts @@ -14,6 +14,7 @@ import { toInternalRequest, truncateAtStopSequence, } from "../src/adapter/anthropic/messages.js"; +import { MAX_STOP_SEQUENCE_LENGTH } from "../src/adapter/common/stop.js"; import { buildServer } from "../src/server.js"; import { EMPTY_USAGE, type CompletionEvent, type InternalRequest, type Usage } from "../src/types/internal.js"; import { createTestContext, defaultScript, parseSse, type TestContextOptions } from "./helpers/context.js"; @@ -1696,17 +1697,22 @@ describe("streamed content blocks (P-22, P-23)", () => { }); describe("stop-sequence scan cost (P-24)", () => { - it("streams a 64 KiB near-match in bounded time, with linear scanned work", async () => { - // `#heldSuffixLength()` walked every suffix length of the pending text and - // sliced at each step, so a tail that shared a long prefix with a stop - // sequence cost O(n^2): 64 KiB took ~5 s of blocked event loop. The hold - // rule is now O(1) per delta (the same one `StopSequenceFilter` in - // `src/adapter/openai/chat.ts` uses), so the scan must stay linear. - const sequence = "a".repeat(64 * 1024); - const nearMatch = `${"a".repeat(64 * 1024 - 1)}b`; + it("streams a many-delta near-match in bounded time, with linear scanned work", async () => { + // The filter holds back only `longest sequence - 1` characters and re-scans + // that bounded window on every delta. It used to walk every suffix length of + // the pending text and slice at each step, so a tail that shared a prefix + // with a sequence cost O(longest^2) per delta: at the documented + // 256-character cap that is ~65k character operations for *every* delta, + // because the near-match below ends in "b" and no suffix of it is a prefix + // of the sequence, so the walk had to try every length before giving up. + // 20 000 such deltas cost ~1.4 s against the previous implementation, while + // the bounded rule scans a constant window and stays in the tens of ms. + const sequence = "a".repeat(MAX_STOP_SEQUENCE_LENGTH); + const delta = `${"a".repeat(MAX_STOP_SEQUENCE_LENGTH - 1)}b`; + const deltas = 20_000; const events: CompletionEvent[] = [ START, - { kind: "text_delta", text: nearMatch, ordinal: 0 }, + ...Array.from({ length: deltas }, (): CompletionEvent => ({ kind: "text_delta", text: delta, ordinal: 0 })), { kind: "usage", usage: usage(1, 1) }, { kind: "end", finishReason: "stop", usage: usage(1, 1), messageId: "msg_hardening" }, ]; @@ -1729,8 +1735,9 @@ describe("stop-sequence scan cost (P-24)", () => { .map((frame) => frame.delta?.text ?? "") .join(""); // No match, so the held tail is released unchanged. - expect(visible).toBe(nearMatch); - // ~5 s before the fix; a quadratic implementation cannot pass this bound. + expect(visible).toBe(delta.repeat(deltas)); + // ~1.4 s with the per-delta suffix walk; a per-delta quadratic scan cannot + // pass this bound while every allowed sequence is at most 256 characters. expect(elapsed).toBeLessThan(1_000); }); }); From 0db7b1abdffe11d566b4e530c0bd39dd283b2cd4 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: Sat, 5 Dec 2026 17:12:46 +0700 Subject: [PATCH 4/9] fix(server): harden auth, timeouts and media guards - A throttled authentication failure answers `429`, and the error handler logged everything that is neither `>= 500` nor `401` at `debug`: once the always-on failed-auth bucket was drained, a credential-guessing flood disappeared from the default log level. The limiter marks the requests it throttled and the error handler audits them at `warn` with the same fields as the `401`; status, `retry-after`, body and `code` are unchanged. - `isAuthorized()` digested both operands on every iteration, i.e. `2 x N` SHA-256 per request (about 0.9 ms at 1000 keys) for a value that never changes between requests. The configured digests are memoised per `Config` and the presented value is digested once, while every `timingSafeEqual` over a fixed-width digest still runs, so the timing property is preserved. - `applyRequestTimeout()` installed its callback with `IncomingMessage#setTimeout`, whose listener Node only emits while the body is still incomplete: for a buffered completion the callback never ran and the socket was reclaimed by a Node-internal fallback instead of the gateway's own bound. The timer now lives on the socket. - A non-base64 `data:` URI was decoded before the byte cap was applied, so an oversized payload materialised up to three times its length before its `400`; the encoded length is now refused first, mirroring the base64 branch. The post-decode check stays authoritative. - The RFC 2765 IPv4-translated prefix `::ffff:0:a.b.c.d`, whose last 32 bits can embed a private IPv4 address, fell through the IPv6 prefix checks and was classified public. Every IPv4-embedding prefix is decoded now, and unrelated public literals stay public. --- src/auth.ts | 55 +++++-- src/http/rateLimit.ts | 23 +++ src/http/timeout.ts | 22 ++- src/media/resolve.ts | 62 ++++++-- src/server.ts | 15 +- test/http-guards.test.ts | 332 +++++++++++++++++++++++++++++++++++++++ 6 files changed, 471 insertions(+), 38 deletions(-) create mode 100644 test/http-guards.test.ts diff --git a/src/auth.ts b/src/auth.ts index 696564c..7f47c18 100644 --- a/src/auth.ts +++ b/src/auth.ts @@ -158,17 +158,49 @@ function safeEqual(left: string, right: string): boolean { return timingSafeEqual(digest(left), digest(right)); } +/** + * Digests of the configured keys, memoised per `Config`. + * + * `loadConfig()` freezes the key arrays and a `Config` is long-lived, so the N + * configured digests are built once per configuration instead of once per + * request. `WeakMap` keeps a replaced configuration collectable, the idiom + * already used by `requestPaths` and by `keySets` in `http/rateLimit.ts`. + */ +const apiKeyDigests = new WeakMap(); +const adminKeyDigests = new WeakMap(); + +function configuredDigests( + cache: WeakMap, + config: Config, + keys: readonly string[], +): readonly Buffer[] { + const memo = cache.get(config); + if (memo !== undefined) return memo; + const digests = keys.map((key) => digest(key)); + cache.set(config, digests); + return digests; +} + +/** + * Compare a presented digest against every configured digest. + * + * Every entry is evaluated, over equal-width SHA-256 digests: a short-circuiting + * `some`/`find` would stop at the matching key and leak its position through the + * timing profile. The presented value is digested once, before this loop. + */ +function matchesAnyDigest(candidate: Buffer, expected: readonly Buffer[]): boolean { + let matched = false; + for (const configured of expected) { + if (timingSafeEqual(configured, candidate)) matched = true; + } + return matched; +} + export function isAuthorized(config: Config, presented: string | undefined): boolean { if (config.allowNoAuth) return true; if (config.apiKeys.length === 0) return false; if (!presented) return false; - // Every configured key is evaluated: `some` stops at the matching key, which - // leaks its position through the timing profile. - let matched = false; - for (const key of config.apiKeys) { - if (safeEqual(key, presented)) matched = true; - } - return matched; + return matchesAnyDigest(digest(presented), configuredDigests(apiKeyDigests, config, config.apiKeys)); } /** True for `/admin` and every route below it. */ @@ -188,12 +220,9 @@ export function isAdminAuthorized(config: Config, presented: string | undefined) if (config.allowNoAuth) return true; if (config.adminApiKeys.length === 0) return isAuthorized(config, presented); if (!presented) return false; - // As in `isAuthorized`, every key is evaluated without short-circuiting. - let matched = false; - for (const key of config.adminApiKeys) { - if (safeEqual(key, presented)) matched = true; - } - return matched; + // As in `isAuthorized`, every key is evaluated without short-circuiting and the + // configured digests come from the per-Config memo. + return matchesAnyDigest(digest(presented), configuredDigests(adminKeyDigests, config, config.adminApiKeys)); } /** diff --git a/src/http/rateLimit.ts b/src/http/rateLimit.ts index 50666b1..01d636e 100644 --- a/src/http/rateLimit.ts +++ b/src/http/rateLimit.ts @@ -234,6 +234,27 @@ export function createRateLimiters(config: Config, now?: () => number): RateLimi }; } +/** + * Requests the failed-authentication limiter answered with a `429`. + * + * A `WeakSet`, so nothing keeps a request (or its headers) alive and no + * credential is retained. The classification only feeds the audit line: the wire + * response is unchanged. + */ +const authRateLimited = new WeakSet(); + +/** + * True when `chargeFailedAuth` throttled this request instead of answering `401`. + * + * The error handler uses it to keep a sustained guessing flood auditable at + * `warn`: a `429` is neither `>= 500` nor `401`, so without this marker the + * rejections that follow a drained failed-auth bucket fall to `debug` and + * disappear at the default `info` level. + */ +export function wasAuthRateLimited(request: FastifyRequest): boolean { + return authRateLimited.has(request); +} + /** * Charge the failed-authentication buckets, calling it once per rejected request. * @@ -253,6 +274,7 @@ export function chargeFailedAuth(limiters: RateLimiters, request: FastifyRequest // what stops aggregate guessing, and it answers 429 for everyone once spent. const globalRetryAfterMs = limiters.authGlobal.take(AUTH_GLOBAL_BUCKET); if (globalRetryAfterMs === undefined) return; + authRateLimited.add(request); const globalSeconds = Math.ceil(globalRetryAfterMs / 1000); throw new ApiError( 429, @@ -261,6 +283,7 @@ export function chargeFailedAuth(limiters: RateLimiters, request: FastifyRequest { code: "rate_limit_exceeded", retryAfterMs: globalRetryAfterMs }, ); } + authRateLimited.add(request); throw new ApiError( 429, "rate_limit_error", diff --git a/src/http/timeout.ts b/src/http/timeout.ts index 046545a..edadae8 100644 --- a/src/http/timeout.ts +++ b/src/http/timeout.ts @@ -116,8 +116,14 @@ export function armBodyDeadline( /** * 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. + * The bound has to be attached to the socket. `IncomingMessage#setTimeout(ms, cb)` + * registers the callback on the *message*, and Node only forwards a socket + * `timeout` event to the message while the request is still incomplete + * (`!req.complete`); a buffered completion already has its body, so that callback + * never ran and only Node's internal fallback reclaimed the socket instead of the + * gateway's own bound. `socket.setTimeout(ms, cb)` puts the timer and its + * callback on the object the timeout actually fires on. Both calls are guarded, + * because test doubles may implement neither. */ export function applyRequestTimeout( request: FastifyRequest, @@ -136,10 +142,14 @@ export function applyRequestTimeout( 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. + if (typeof socket?.setTimeout === "function") { + socket.setTimeout(timeoutMs, onTimeout); + } else { + raw.setTimeout(timeoutMs, onTimeout); + } + // `socket.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); }); diff --git a/src/media/resolve.ts b/src/media/resolve.ts index e1b646d..206f290 100644 --- a/src/media/resolve.ts +++ b/src/media/resolve.ts @@ -559,6 +559,13 @@ function resolveDataUri(source: MediaSource, config: Config, field: string, limi assertEncodedWithinLimit(encoded, field, limitBytes); buffer = decodeBase64(encoded, field); } else { + // A payload of L characters decodes to at most 3L bytes (one `%XX` escape is + // three characters and at most one 3-byte UTF-8 sequence), so anything over + // this bound can never fit: refuse it before `decodeURIComponent()` + // materialises the decoded string, mirroring the base64 branch's + // encoded-length check. `assertWithinBudget()` below stays the authoritative + // check on the decoded bytes. + if (payload.length > limitBytes * 3 + 8) throw attachmentTooLarge(field, limitBytes); try { buffer = Buffer.from(decodeURIComponent(payload), "utf8"); } catch { @@ -1177,6 +1184,20 @@ function stripBase64Whitespace(payload: string): string { return payload.replace(/\s+/g, ""); } +/** + * The 400 an oversized attachment payload is refused with. + * + * Shared by the encoded-length guards (base64 and non-base64) and + * `assertWithinBudget()`, so a payload refused before decoding and one refused + * after it report the same status, code, param and message shape. + */ +function attachmentTooLarge(field: string, limitBytes: number): ApiError { + return ApiError.badRequest(`Attachment payload is larger than the ${limitBytes}-byte limit.`, { + code: "attachment_too_large", + param: field, + }); +} + /** * Refuse a base64 payload that cannot decode to the byte limit, on its encoded * length alone. @@ -1189,12 +1210,7 @@ function stripBase64Whitespace(payload: string): string { */ function assertEncodedWithinLimit(payload: string, field: string, limitBytes: number): void { const maxEncoded = Math.ceil((limitBytes * 4) / 3) + 4; - if (payload.length > maxEncoded) { - throw ApiError.badRequest(`Attachment payload is larger than the ${limitBytes}-byte limit.`, { - code: "attachment_too_large", - param: field, - }); - } + if (payload.length > maxEncoded) throw attachmentTooLarge(field, limitBytes); } const BASE64_ALPHABET = /^[A-Za-z0-9+/=_\-\s]*$/; @@ -1398,7 +1414,18 @@ export function isPrivateHost(hostname: string): boolean { return isPrivateIpv6(host); } -/** Convert an IPv4-mapped or IPv4-compatible IPv6 literal to dotted IPv4. */ +/** + * Convert an IPv4-embedding IPv6 literal to dotted IPv4. + * + * Three spellings put an IPv4 address in the last 32 bits: IPv4-mapped + * (`::ffff:a.b.c.d`, `g5 === 0xffff`), IPv4-compatible (`::a.b.c.d`, `g5 === 0`), + * and the RFC 2765 SIIT / IPv4-translated form (`::ffff:0:a.b.c.d`, which has the + * marker in `g4`). The first two are recognised by the prefix alone; the third is + * why `::ffff:0:169.254.169.254` used to fall through the IPv6 checks and be + * reported public. Only these embedding prefixes are decoded — the last 32 bits + * of an arbitrary public literal are not an embedded IPv4 address (`2001:db8::1` + * ends in `0.0.0.1` but stays public). + */ function embeddedIpv4(host: string): string | undefined { if (!host.includes(":")) return undefined; const groups = expandIpv6(host); @@ -1413,9 +1440,14 @@ function embeddedIpv4(host: string): string | undefined { 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; + const zeroPrefix = g0 === 0 && g1 === 0 && g2 === 0 && g3 === 0; + const mapped = zeroPrefix && g4 === 0 && g5 === 0xffff; + const compatible = zeroPrefix && g4 === 0 && g5 === 0; + // RFC 2765 `::ffff:0:0/96`: the `0xffff` marker moves to `g4`, the IPv4 + // address stays in the last 32 bits. The whole `0000::/8` block is reserved, so + // admitting every `g5` here cannot classify a globally routable address. + const translated = zeroPrefix && g4 === 0xffff; + if (!mapped && !compatible && !translated) return undefined; return `${(g6 >> 8) & 0xff}.${g6 & 0xff}.${(g7 >> 8) & 0xff}.${g7 & 0xff}`; } @@ -1515,10 +1547,12 @@ function isPrivateIpv6(host: string): boolean { // (64:ff9b::/96) and 6to4 (2002::/16). if (host.startsWith("64:ff9b:") || host.startsWith("2002:")) return true; // The last 32 bits of a literal that is not caught above can still be an - // IPv4 address (an IPv4-mapped or IPv4-compatible form the prefix checks do - // not cover): classify it through the IPv4 rules instead of trusting the - // outer spelling. `embeddedIpv4()` only returns a value when the whole - // literal is such a form, so a plain `2001:db8::1` stays public. + // embedded IPv4 address (the IPv4-mapped, IPv4-compatible and RFC 2765 SIIT + // forms): classify it through the IPv4 rules instead of trusting the outer + // spelling. `embeddedIpv4()` only returns a value for those embedding + // prefixes, so a plain `2001:db8::1` stays public. `isPrivateHost()` already + // applies the same conversion before this function is reached; this is the + // defence-in-depth check for a caller that reaches `isPrivateIpv6()` directly. const embedded = embeddedIpv4(host); if (embedded !== undefined) { const octets = parseIpv4(embedded); diff --git a/src/server.ts b/src/server.ts index b8addc9..1432681 100644 --- a/src/server.ts +++ b/src/server.ts @@ -15,7 +15,7 @@ import { classifyPath, requireApiKey } from "./auth.js"; import type { AppContext } from "./context.js"; import type { Config } from "./config.js"; import { ApiError, toAnthropicError, toApiError, toOpenAiError } from "./errors.js"; -import { createRateLimiters, requireRateLimit } from "./http/rateLimit.js"; +import { createRateLimiters, requireRateLimit, wasAuthRateLimited } from "./http/rateLimit.js"; import { applyRequestTimeout, armBodyDeadline, clearBodyDeadline } from "./http/timeout.js"; import { registerAdminRoutes } from "./routes/admin.js"; import { registerHealthRoutes } from "./routes/health.js"; @@ -257,13 +257,18 @@ export async function buildServer(ctx: AppContext): Promise { if (apiError.status >= 500) { request.log.error({ err: error, code: apiError.code }, "request failed"); - } else if (apiError.status === 401) { + } else if (apiError.status === 401 || wasAuthRateLimited(request)) { // An authentication rejection is an audit event, not debug noise: it must - // be visible at the default `info` level. Neither the presented credential - // nor any header is logged — only the request id and the route. + // be visible at the default `info` level. The throttled form (a 429 from + // the failed-auth limiter, which is charged on the rejection path) is the + // same event once the caller has spent its budget, so it is audited too. + // Neither the presented credential nor any header is logged — only the + // request id and the route. request.log.warn( { requestId: request.id, method: request.method, route: request.routeOptions?.url ?? "unmatched" }, - "request rejected: authentication failed", + apiError.status === 401 + ? "request rejected: authentication failed" + : "request rejected: authentication throttled", ); } else { request.log.debug({ code: apiError.code, message: apiError.message }, "request rejected"); diff --git a/test/http-guards.test.ts b/test/http-guards.test.ts new file mode 100644 index 0000000..9c7ed8a --- /dev/null +++ b/test/http-guards.test.ts @@ -0,0 +1,332 @@ +/** + * Security and HTTP-guard findings from `IMPROVEMENT_PROPOSALS.md` + * (F-01 … F-05). + * + * F-01, F-02 and F-03 are only observable off the wire: an audit line, a hash + * count and the object a timeout listener is attached to. Those cases therefore + * spy on `node:crypto` or drive the exported helpers with request/reply doubles, + * while F-01 still asserts the unchanged 429 response and F-04/F-05 go through + * the real media resolver. No test logs or asserts on a credential. + */ +import { EventEmitter } from "node:events"; +import type { FastifyReply, FastifyRequest } from "fastify"; +import pino, { type DestinationStream } from "pino"; +import { afterEach, describe, expect, it, vi } from "vitest"; +import { isAdminAuthorized, isAuthorized } from "../src/auth.js"; +import { loggerOptions, type Logger } from "../src/logger.js"; +import type { Config } from "../src/config.js"; +import { ApiError } from "../src/errors.js"; +import { applyRequestTimeout } from "../src/http/timeout.js"; +import { isPrivateHost, resolveAttachment, type MediaSource } from "../src/media/resolve.js"; +import { buildServer } from "../src/server.js"; +import { createTestContext, testConfig } from "./helpers/context.js"; + +/** A `node:crypto` spy recording digests and comparisons. */ +const cryptoProbe = vi.hoisted(() => ({ + hashCalls: 0, + compareCalls: [] as Array<{ left: number; right: number }>, +})); + +vi.mock("node:crypto", async (importOriginal) => { + const actual = await importOriginal(); + return { + ...actual, + createHash: ((...args: Parameters) => { + cryptoProbe.hashCalls += 1; + return actual.createHash(...args); + }) as typeof actual.createHash, + timingSafeEqual: (left: Buffer, right: Buffer): boolean => { + cryptoProbe.compareCalls.push({ left: left.length, right: right.length }); + return actual.timingSafeEqual(left, right); + }, + }; +}); + +/** A pino logger whose lines are collected in memory. */ +function collectingLogger(logLevel: Config["logLevel"]): { log: Logger; lines: string[] } { + const lines: string[] = []; + const destination = { + write: (line: string) => { + lines.push(line); + }, + } as unknown as DestinationStream; + // The configuration only feeds `loggerOptions`; a second context supplies the + // app itself, exactly as `test/admin.test.ts` does for its audit-line case. + const config = createTestContext({ config: { logLevel } }).config; + const log: Logger = pino(loggerOptions(config), destination); + return { log, lines }; +} + +afterEach(() => { + vi.restoreAllMocks(); +}); + +// ---------------------------------------------------------------------- F-01 --- + +describe("F-01 a throttled authentication failure stays auditable at warn", () => { + it("logs the 429 rejection too, without changing the wire response", async () => { + const { log, lines } = collectingLogger("warn"); + const ctx = createTestContext(); + const app = await buildServer({ ...ctx, log }); + try { + const attempts = []; + for (let index = 0; index < 11; index += 1) { + attempts.push( + await app.inject({ + method: "GET", + url: "/v1/models", + headers: { authorization: "Bearer wrong-key" }, + remoteAddress: "203.0.113.7", + }), + ); + } + + // The 401 → 429 transition is unchanged: ten priced attempts, then the + // per-address failed-auth bucket answers 429. + expect(attempts.slice(0, 10).map((attempt) => attempt.statusCode)).toEqual(new Array(10).fill(401)); + const throttled = attempts[10]; + if (throttled === undefined) throw new Error("expected a throttled attempt"); + expect(throttled.statusCode).toBe(429); + expect(Number(throttled.headers["retry-after"])).toBeGreaterThanOrEqual(1); + // The wire shape must stay byte-compatible with the pre-fix response. + expect(throttled.json()).toMatchObject({ + error: { type: "rate_limit_error", code: "rate_limit_exceeded", param: null }, + }); + + // Both rejection kinds are audit events at the default `info` level; the + // throttled one used to be logged at `debug` and disappear at `warn`. + const audit = lines.join(""); + const warned = lines.join("").trim().split("\n"); + expect(warned).toHaveLength(11); + for (const line of warned) expect(line).toContain('"level":40'); + expect(audit.match(/authentication failed/g)).toHaveLength(10); + expect(audit.match(/authentication throttled/g)).toHaveLength(1); + // Neither the credential nor the transport header is ever logged. + expect(audit).not.toContain("wrong-key"); + expect(audit).not.toContain("Bearer"); + } finally { + await app.close(); + } + }); + + it("does not treat an ordinary rate-limit rejection as an authentication event", async () => { + const { log, lines } = collectingLogger("warn"); + const ctx = createTestContext({ config: { rateLimitRpm: 1, rateLimitBurst: 1 } }); + const app = await buildServer({ ...ctx, log }); + try { + const first = await app.inject({ method: "GET", url: "/v1/models", headers: { authorization: "Bearer test-key" } }); + expect(first.statusCode).toBe(200); + const limited = await app.inject({ method: "GET", url: "/v1/models", headers: { authorization: "Bearer test-key" } }); + expect(limited.statusCode).toBe(429); + expect(lines.join("")).not.toContain("authentication"); + expect(lines.join("")).not.toContain("test-key"); + } finally { + await app.close(); + } + }); +}); + +// ---------------------------------------------------------------------- F-02 --- + +describe("F-02 configured key digests are memoised and the presented value is hashed once", () => { + it("hashes each configured key once per Config, not once per request", () => { + const config = createTestContext().config; + const keyed = { ...config, apiKeys: Object.freeze(["test-key", "alpha", "beta"]) } as Config; + + cryptoProbe.hashCalls = 0; + cryptoProbe.compareCalls = []; + expect(isAuthorized(keyed, "test-key")).toBe(true); + // Three configured keys plus the presented value: the configured digests are + // built once for this Config. + expect(cryptoProbe.hashCalls).toBe(4); + // `some()` would stop at the matching first key; every key is still compared. + expect(cryptoProbe.compareCalls).toHaveLength(3); + for (const call of cryptoProbe.compareCalls) { + expect(call.left, "digests must stay fixed width").toBe(32); + expect(call.right, "digests must stay fixed width").toBe(32); + } + + cryptoProbe.hashCalls = 0; + cryptoProbe.compareCalls = []; + expect(isAuthorized(keyed, "not-a-key")).toBe(false); + // Only the presented value is hashed on the request path; the N configured + // digests came from the per-Config memo. + expect(cryptoProbe.hashCalls).toBe(1); + expect(cryptoProbe.compareCalls).toHaveLength(3); + }); + + it("memoises the admin key digests without short-circuiting", () => { + const config = createTestContext().config; + const keyed = { + ...config, + apiKeys: Object.freeze(["general-key"]), + adminApiKeys: Object.freeze(["operator-key", "second-key"]), + } as Config; + + cryptoProbe.hashCalls = 0; + cryptoProbe.compareCalls = []; + expect(isAdminAuthorized(keyed, "operator-key")).toBe(true); + expect(cryptoProbe.hashCalls).toBe(3); + expect(cryptoProbe.compareCalls).toHaveLength(2); + + cryptoProbe.hashCalls = 0; + cryptoProbe.compareCalls = []; + expect(isAdminAuthorized(keyed, "operator-key")).toBe(true); + expect(cryptoProbe.hashCalls).toBe(1); + expect(cryptoProbe.compareCalls).toHaveLength(2); + }); +}); + +// ---------------------------------------------------------------------- F-03 --- + +interface TimeoutFixture { + readonly socketEvents: EventEmitter & { setTimeout: (ms: number, callback: () => void) => void }; + readonly socketTimeouts: number[]; + readonly messageTimeouts: number[]; + readonly destroyed: () => number; + readonly close: () => void; +} + +/** + * Apply the request bound to doubles that record where the timer landed. + * + * The message double deliberately records (instead of forwarding) a + * `setTimeout` call, so the test can tell the message attachment from the socket + * one — which is the whole defect: Node only forwards a socket `timeout` to the + * message while the request body is incomplete. + */ +function applyTimeout(body: unknown, timeoutMs = 50): TimeoutFixture { + const socketEvents = new EventEmitter() as TimeoutFixture["socketEvents"]; + const socketTimeouts: number[] = []; + socketEvents.setTimeout = (ms, callback) => { + socketTimeouts.push(ms); + socketEvents.once("timeout", callback); + }; + + const messageTimeouts: number[] = []; + let destroyed = 0; + const raw = { + complete: true, + socket: socketEvents, + setTimeout: (ms?: number) => { + messageTimeouts.push(ms ?? 0); + }, + destroy: () => { + destroyed += 1; + }, + }; + const replyEvents = new EventEmitter(); + const request = { raw, body } as unknown as FastifyRequest; + const reply = { raw: replyEvents } as unknown as FastifyReply; + + applyRequestTimeout(request, reply, { upstreamRequestTimeoutMs: timeoutMs }); + + return { + socketEvents, + socketTimeouts, + messageTimeouts, + destroyed: () => destroyed, + close: () => replyEvents.emit("close"), + }; +} + +describe("F-03 the buffered-request timeout is armed on the socket", () => { + it("attaches the bound to the socket, so a buffered request is destroyed by it", () => { + const fixture = applyTimeout({ stream: false }); + + expect(fixture.socketTimeouts).toEqual([50]); + // Pre-fix the call landed on the IncomingMessage, where a buffered request's + // `timeout` event is never emitted, so the gateway's bound never fired. + expect(fixture.messageTimeouts).toEqual([]); + expect(fixture.socketEvents.listenerCount("timeout")).toBe(1); + + fixture.socketEvents.emit("timeout"); + expect(fixture.destroyed()).toBe(1); + }); + + it("drops the socket listener on close and leaves a streaming request unbounded", () => { + const buffered = applyTimeout({ stream: false }); + buffered.close(); + expect(buffered.socketEvents.listenerCount("timeout")).toBe(0); + + const streamed = applyTimeout({ stream: true }); + expect(streamed.socketTimeouts).toEqual([]); + // A streaming response keeps the documented "no bound" behaviour. + expect(streamed.messageTimeouts).toEqual([0]); + expect(streamed.socketEvents.listenerCount("timeout")).toBe(0); + }); +}); + +// ---------------------------------------------------------------------- F-04 --- + +async function mediaFailure(source: MediaSource, config: Config): Promise { + try { + await resolveAttachment(source, config); + } catch (error) { + expect(error).toBeInstanceOf(ApiError); + return error as ApiError; + } + throw new Error("expected the attachment to be rejected"); +} + +describe("F-04 an oversized non-base64 data URI is refused before decoding", () => { + it("rejects on the encoded length, before decodeURIComponent can allocate", async () => { + const limit = 64; + const config = testConfig({ maxAttachmentBytes: limit }); + // `%ZZ` is not a valid escape. Pre-fix this oversized payload reached + // `decodeURIComponent()`, which threw and reported `invalid_attachment`; the + // encoded-length guard refuses it as too large without decoding a byte. + const payload = `%ZZ${"a".repeat(limit * 3 + 6)}`; + expect(payload.length).toBeGreaterThan(limit * 3 + 8); + + const error = await mediaFailure({ dataUri: `data:text/plain,${payload}` }, config); + expect(error.status).toBe(400); + expect(error.code).toBe("attachment_too_large"); + // The same shape the base64 branch reports for an oversized payload. + expect(error.message).toContain(`${limit}-byte limit`); + expect(error.message).not.toContain("percent-encoding"); + }); + + it("keeps the post-decode budget as the authoritative check", async () => { + const config = testConfig({ maxAttachmentBytes: 16 }); + // 48 characters decode to 48 bytes: inside the 3L + 8 encoded bound, so only + // the decoded-byte check can refuse it. + const error = await mediaFailure({ dataUri: `data:text/plain,${"a".repeat(48)}` }, config); + expect(error.status).toBe(400); + expect(error.code).toBe("attachment_too_large"); + }); + + it("still decodes a non-base64 data URI that fits", async () => { + const config = testConfig({ maxAttachmentBytes: 64 }); + const attachment = await resolveAttachment({ dataUri: "data:text/plain,%41%42%43" }, config); + expect(attachment.data).toBe(Buffer.from("ABC").toString("base64")); + expect(attachment.size).toBe(3); + }); +}); + +// ---------------------------------------------------------------------- F-05 --- + +describe("F-05 the IPv4-translated (SIIT) form is classified through its last 32 bits", () => { + it("treats the RFC 2765 prefix as private and keeps public spellings public", () => { + for (const host of [ + "::ffff:0:169.254.169.254", + "::ffff:0:a9fe:a9fe", + "0:0:0:0:ffff:0:a9fe:a9fe", + "::ffff:0:127.0.0.1", + "::ffff:0:10.0.0.1", + ]) { + expect(isPrivateHost(host), `${host} must be private`).toBe(true); + } + + for (const host of [ + "2001:db8::1", + "2001:0db8:0:0:0:0:0:1", + "::ffff:8.8.8.8", + "::ffff:0:808:808", + "::ffff:0:8.8.8.8", + "2606:4700:4700::1111", + ]) { + expect(isPrivateHost(host), `${host} must stay public`).toBe(false); + } + }); +}); \ No newline at end of file From 2ad8f2baaee2d4185a5f5ba217c1dfda37685b18 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: Sat, 5 Dec 2026 17:12:46 +0700 Subject: [PATCH 5/9] fix(config): detect every spelling of a configured key `pnpm setup` only understood a bare `OPENCODE_API_KEYS=` line at the start of a line, so an `export OPENCODE_API_KEYS=...`, an `OPENCODE_API_KEYS: ...` or an `OPENCODE_API_KEY=...` assignment was invisible to it. It then appended a duplicate line, and because `dotenv` resolves duplicate keys last-wins the gateway accepted `sk-dummy-123` instead of the operator's secret, silently replacing it or publishing the repository's key next to it. The script now parses the file with dotenv's own parser, treats a non-default value in either spelling as already configured, and rewrites every matching line in place instead of appending a duplicate. --- scripts/init-env.mjs | 94 ++++++++++-- test/setup-scripts.test.ts | 284 +++++++++++++++++++++++++++++++++++++ 2 files changed, 368 insertions(+), 10 deletions(-) create mode 100644 test/setup-scripts.test.ts diff --git a/scripts/init-env.mjs b/scripts/init-env.mjs index bc26d47..a5b604a 100644 --- a/scripts/init-env.mjs +++ b/scripts/init-env.mjs @@ -10,6 +10,21 @@ * - Never silently overwrites a key you already configured: pass `--force` to * replace an existing non-default key. * + * "Already configured" is decided by parsing the file the way the gateway does + * (`dotenv.parse`, so duplicate keys resolve last-wins) and looking at both + * accepted spellings, `OPENCODE_API_KEYS` and its `OPENCODE_API_KEY` alias. A + * non-default value in either spelling blocks a rewrite unless `--force` is + * passed - otherwise a key written as `export OPENCODE_API_KEYS=…`, + * `OPENCODE_API_KEYS: …` or `OPENCODE_API_KEY=…` used to be invisible here and + * the script appended `OPENCODE_API_KEYS=sk-dummy-123`, either silently + * replacing the operator's secret (last-wins) or publishing the default key + * alongside it. + * + * When a rewrite is allowed, *every* line that assigns either spelling is + * replaced in place, so no stale value survives and no duplicate is appended. + * A single `OPENCODE_API_KEYS=` line is only appended when the file assigns + * neither variable at all. The file is written owner-only (0600). + * * Usage: * pnpm setup * pnpm setup -- --random @@ -21,7 +36,63 @@ import path from "node:path"; import { fileURLToPath } from "node:url"; const DEFAULT_API_KEY = "sk-dummy-123"; -const KEY_PATTERN = /^([ \t]*OPENCODE_API_KEYS[ \t]*=[ \t]*)(.*)$/m; +/** Both accepted spellings; `OPENCODE_API_KEYS` is the documented one. */ +const KEY_NAMES = ["OPENCODE_API_KEYS", "OPENCODE_API_KEY"]; +/** + * A line that assigns either spelling, captured as `[full, prefix, value]`. + * + * Mirrors the subset of `dotenv`'s grammar the gateway reads: optional + * indentation, an optional `export `, the key name, then either `=` (with + * optional padding) or `:` followed by whitespace. A `:` with no space after it + * is not a separator for `dotenv`, so it is not one here either. + */ +const KEY_LINE_PATTERN = /^([ \t]*(?:export[ \t]+)?OPENCODE_API_KEYS?[ \t]*(?:=[ \t]*|:[ \t]+))(.*)$/gm; + +/** + * Parse `.env` exactly as the gateway does. + * + * `dotenv` is a runtime dependency of the gateway, so the import succeeds in a + * normal checkout. It is resolved dynamically because a copy of this script can + * be run on its own (the SEC-15 regression copies it into a temporary directory + * that has no `node_modules`); the fallback reproduces `dotenv`'s grammar so + * both paths agree. + * + * @param {string} content + * @returns {Promise>} + */ +async function parseEnvFile(content) { + try { + const { parse } = await import("dotenv"); + return parse(content); + } catch { + return fallbackParseEnv(content); + } +} + +/** + * `dotenv`'s parser (v17), inlined for the standalone-copy case only. + * + * @param {string} source + * @returns {Record} + */ +function fallbackParseEnv(source) { + const parsed = {}; + const line = /(?:^|^)\s*(?:export\s+)?([\w.-]+)(?:\s*=\s*?|:\s+?)(\s*'(?:\\'|[^'])*'|\s*"(?:\\"|[^"])*"|\s*`(?:\\`|[^`])*`|[^#\r\n]+)?\s*(?:#.*)?(?:$|$)/gm; + const lines = source.toString().replace(/\r\n?/gm, "\n"); + let match; + while ((match = line.exec(lines)) !== null) { + const key = match[1]; + let value = match[2] || ""; + value = value.trim(); + const maybeQuote = value[0]; + value = value.replace(/^(['"`])([\s\S]*)\1$/gm, "$2"); + if (maybeQuote === '"') { + value = value.replace(/\\n/g, "\n").replace(/\\r/g, "\r"); + } + parsed[key] = value; + } + return parsed; +} const args = new Set(process.argv.slice(2)); const useRandom = args.has("--random"); @@ -37,12 +108,12 @@ if (!fs.existsSync(examplePath)) { } const existing = fs.existsSync(envPath) ? fs.readFileSync(envPath, "utf8") : undefined; -const match = existing === undefined ? null : KEY_PATTERN.exec(existing); -const currentValue = match?.[2]?.trim() ?? ""; - -const isDefault = currentValue === "" || currentValue === DEFAULT_API_KEY; +const parsed = existing === undefined ? {} : await parseEnvFile(existing); +/** Spellings that currently carry a non-empty value. */ +const configuredNames = KEY_NAMES.filter((name) => (parsed[name] ?? "").trim() !== ""); +const isDefault = configuredNames.every((name) => (parsed[name] ?? "").trim() === DEFAULT_API_KEY); if (existing !== undefined && !isDefault && !force) { - console.log(`.env already exists at ${envPath} with a custom OPENCODE_API_KEYS value.`); + console.log(`.env already exists at ${envPath} with a custom ${configuredNames.join(" / ")} value.`); console.log("Leaving it untouched. Use `pnpm setup -- --random --force` to replace it."); process.exit(0); } @@ -56,15 +127,18 @@ const template = existing ?? fs.readFileSync(examplePath, "utf8"); // applies at creation time. const PRIVATE_MODE = 0o600; -if (!KEY_PATTERN.test(template)) { - // The file exists but has no OPENCODE_API_KEYS line (empty file, or a .env - // written by hand): append it rather than failing. +if (template.match(KEY_LINE_PATTERN) === null) { + // The file exists but assigns neither spelling (empty file, or a .env written + // by hand): append one canonical line rather than failing. const separator = template.length === 0 || template.endsWith("\n") ? "" : "\n"; fs.writeFileSync(envPath, `${template}${separator}OPENCODE_API_KEYS=${key}\n`, { encoding: "utf8", mode: PRIVATE_MODE }); fs.chmodSync(envPath, PRIVATE_MODE); console.log(`Wrote ${envPath} (appended OPENCODE_API_KEYS).`); } else { - fs.writeFileSync(envPath, template.replace(KEY_PATTERN, `$1${key}`), { encoding: "utf8", mode: PRIVATE_MODE }); + // Replace the value on every matching line (both spellings, `export` prefix + // and both separators) instead of appending a duplicate. + const rewritten = template.replace(KEY_LINE_PATTERN, (_line, prefix) => `${prefix}${key}`); + fs.writeFileSync(envPath, rewritten, { encoding: "utf8", mode: PRIVATE_MODE }); fs.chmodSync(envPath, PRIVATE_MODE); console.log(`Wrote ${envPath}`); } diff --git a/test/setup-scripts.test.ts b/test/setup-scripts.test.ts new file mode 100644 index 0000000..d017dce --- /dev/null +++ b/test/setup-scripts.test.ts @@ -0,0 +1,284 @@ +/** + * `scripts/init-env.mjs` and `scripts/smoke.mjs` are plain ESM scripts, not + * modules the suite can import, so they are driven as subprocesses. + * + * The setup tests pin I-01: the "already configured" check has to understand + * every spelling `dotenv` accepts (`export …=`, the `…: ` separator and the + * `OPENCODE_API_KEY` alias) and must replace the key in place instead of + * appending a duplicate that publishes `sk-dummy-123` or overwrites the + * operator's secret (duplicate keys resolve last-wins). + * + * The smoke test pins I-05: the request deadline has to outlive the response + * head, otherwise a stream that stalls after `200 text/event-stream` hangs the + * script forever. + */ +import { spawn, spawnSync } from "node:child_process"; +import { + cpSync, + lstatSync, + mkdirSync, + mkdtempSync, + readFileSync, + rmSync, + statSync, + symlinkSync, + unlinkSync, + writeFileSync, +} from "node:fs"; +import http from "node:http"; +import type { AddressInfo } from "node:net"; +import { tmpdir } from "node:os"; +import path from "node:path"; +import { parse as parseEnv } from "dotenv"; +import { afterEach, describe, expect, it } from "vitest"; + +const REPO_ROOT = process.cwd(); +const DEFAULT_API_KEY = "sk-dummy-123"; +const CUSTOM_API_KEY = "my-real-secret"; + +const temporaryRoots: string[] = []; + +/** + * A throwaway project root holding the script and `.env.example`. + * + * `withNodeModules` links the repository's `node_modules` so the script's + * `import("dotenv")` resolves exactly like a real checkout; without it the + * script has to fall back to its inlined parser, which is the case the SEC-15 + * regression exercises. + */ +function makeProject(content: string | undefined, withNodeModules = true): string { + const root = mkdtempSync(path.join(tmpdir(), "opencode-api-setup-")); + temporaryRoots.push(root); + mkdirSync(path.join(root, "scripts"), { recursive: true }); + cpSync(path.join(REPO_ROOT, "scripts", "init-env.mjs"), path.join(root, "scripts", "init-env.mjs")); + cpSync(path.join(REPO_ROOT, ".env.example"), path.join(root, ".env.example")); + if (withNodeModules) { + // A Windows directory symlink needs elevation; a junction does not. + symlinkSync( + path.join(REPO_ROOT, "node_modules"), + path.join(root, "node_modules"), + process.platform === "win32" ? "junction" : "dir", + ); + } + if (content !== undefined) writeFileSync(path.join(root, ".env"), content); + return root; +} + +function runSetup(root: string, args: string[] = []) { + const result = spawnSync(process.execPath, [path.join(root, "scripts", "init-env.mjs"), ...args], { + cwd: root, + encoding: "utf8", + timeout: 30_000, + }); + expect(result.error).toBeUndefined(); + return result; +} + +function envFile(root: string): string { + return readFileSync(path.join(root, ".env"), "utf8"); +} + +/** The lines that assign one of the two accepted spellings. */ +function keyLines(content: string): string[] { + return content.split("\n").filter((line) => /^[ \t]*(?:export[ \t]+)?OPENCODE_API_KEYS?[ \t]*(?:=[ \t]*|:[ \t]+)/.test(line)); +} + +afterEach(() => { + while (temporaryRoots.length > 0) { + const root = temporaryRoots.pop(); + if (root === undefined) continue; + // Remove the `node_modules` link first: a recursive delete must never be + // pointed at the checkout's dependencies. + const linked = path.join(root, "node_modules"); + if (lstatSync(linked, { throwIfNoEntry: false })?.isSymbolicLink()) unlinkSync(linked); + rmSync(root, { recursive: true, force: true }); + } +}); + +/** + * Every spelling `dotenv` reads: the documented variable with both separators, + * the `export ` prefix, and the `OPENCODE_API_KEY` alias. + */ +const SPELLINGS = [ + { name: "OPENCODE_API_KEYS=", line: `OPENCODE_API_KEYS=${CUSTOM_API_KEY}`, variable: "OPENCODE_API_KEYS" }, + { name: "export OPENCODE_API_KEYS=", line: `export OPENCODE_API_KEYS=${CUSTOM_API_KEY}`, variable: "OPENCODE_API_KEYS" }, + { name: "OPENCODE_API_KEYS: ", line: `OPENCODE_API_KEYS: ${CUSTOM_API_KEY}`, variable: "OPENCODE_API_KEYS" }, + { name: "OPENCODE_API_KEY=", line: `OPENCODE_API_KEY=${CUSTOM_API_KEY}`, variable: "OPENCODE_API_KEY" }, +] as const; + +describe("I-01 setup sees every spelling of a configured key", () => { + it.each(SPELLINGS)("leaves a custom `$name` value untouched without --force", ({ line, variable }) => { + const root = makeProject(`${line}\nOTHER=keep-me\n`); + + const result = runSetup(root); + + expect(result.status).toBe(0); + // Before the fix an `export`/`:`/alias line was invisible, so the script + // appended `OPENCODE_API_KEYS=sk-dummy-123` and last-wins parsing then + // replaced the operator's secret with the published default key. + expect(envFile(root)).toBe(`${line}\nOTHER=keep-me\n`); + expect(parseEnv(envFile(root))[variable]).toBe(CUSTOM_API_KEY); + }); + + it.each(SPELLINGS)("rewrites `$name` in place (never a duplicate) with --force", ({ line, variable }) => { + const root = makeProject(`${line}\nOTHER=keep-me\n`); + + const result = runSetup(root, ["--force"]); + + expect(result.status).toBe(0); + const content = envFile(root); + expect(keyLines(content)).toHaveLength(1); + expect(parseEnv(content)).toEqual({ [variable]: DEFAULT_API_KEY, OTHER: "keep-me" }); + }); + + it("treats the alias as configured when both spellings are present", () => { + // `OPENCODE_API_KEYS` is default but the alias carries the real secret: the + // alias used to be ignored and the default key was published alongside it. + const root = makeProject(`OPENCODE_API_KEYS=${DEFAULT_API_KEY}\nOPENCODE_API_KEY=${CUSTOM_API_KEY}\n`); + + const result = runSetup(root); + + expect(result.status).toBe(0); + expect(parseEnv(envFile(root))["OPENCODE_API_KEY"]).toBe(CUSTOM_API_KEY); + }); + + it("replaces both spellings at once when they are both default", () => { + const root = makeProject(`OPENCODE_API_KEYS=${DEFAULT_API_KEY}\nOPENCODE_API_KEY=${DEFAULT_API_KEY}\n`); + + const result = runSetup(root, ["--random", "--force"]); + + expect(result.status).toBe(0); + const parsed = parseEnv(envFile(root)); + expect(keyLines(envFile(root))).toHaveLength(2); + expect(parsed["OPENCODE_API_KEYS"]).toMatch(/^\S+$/); + expect(parsed["OPENCODE_API_KEY"]).toBe(parsed["OPENCODE_API_KEYS"]); + expect(parsed["OPENCODE_API_KEYS"]).not.toBe(DEFAULT_API_KEY); + }); + + it("appends exactly one canonical line when the file assigns neither spelling", () => { + const root = makeProject("FOO=bar\nOPENCODE_API_KEY_HINT=nope\n"); + + const result = runSetup(root); + + expect(result.status).toBe(0); + const content = envFile(root); + expect(keyLines(content)).toEqual([`OPENCODE_API_KEYS=${DEFAULT_API_KEY}`]); + expect(parseEnv(content)).toEqual({ FOO: "bar", OPENCODE_API_KEY_HINT: "nope", OPENCODE_API_KEYS: DEFAULT_API_KEY }); + }); + + it.skipIf(process.platform === "win32")("keeps writing .env owner-only (0600)", () => { + const root = makeProject(undefined); + + expect(runSetup(root, ["--random"]).status).toBe(0); + + expect(statSync(path.join(root, ".env")).mode & 0o777).toBe(0o600); + expect(parseEnv(envFile(root))["OPENCODE_API_KEYS"]).toMatch(/^\S+$/); + }); + + it("behaves the same when the script cannot resolve `dotenv`", () => { + // A standalone copy (the SEC-15 regression, or this project vendored into + // another tree) has no `node_modules`; the inlined fallback parser has to + // agree with `dotenv` on the same spellings. + const root = makeProject(`export OPENCODE_API_KEYS=${CUSTOM_API_KEY}\n`, false); + + expect(runSetup(root).status).toBe(0); + expect(envFile(root)).toBe(`export OPENCODE_API_KEYS=${CUSTOM_API_KEY}\n`); + + expect(runSetup(root, ["--force"]).status).toBe(0); + expect(parseEnv(envFile(root))).toEqual({ OPENCODE_API_KEYS: DEFAULT_API_KEY }); + }); +}); + +describe("I-05 smoke bounds a stream that stalls after the response head", () => { + /** + * Run a script asynchronously: `spawnSync` would block this process's event + * loop, so the fixture server below could never answer the child. + */ + function runScript(script: string, env: Record, timeoutMs: number) { + return new Promise<{ code: number | null; signal: string | null; stdout: string; timedOut: boolean }>((resolve) => { + const child = spawn(process.execPath, [path.join(REPO_ROOT, script)], { + cwd: REPO_ROOT, + env: { ...process.env, ...env }, + }); + let stdout = ""; + let timedOut = false; + child.stdout.on("data", (chunk: Buffer) => { + stdout += chunk.toString("utf8"); + }); + const timer = setTimeout(() => { + timedOut = true; + child.kill("SIGKILL"); + }, timeoutMs); + child.once("close", (code, signal) => { + clearTimeout(timer); + resolve({ code, signal, stdout, timedOut }); + }); + }); + } + + it( + "fails within the stream deadline instead of hanging", + async () => { + const server = http.createServer((request, response) => { + const chunks: Buffer[] = []; + request.on("data", (chunk: Buffer) => chunks.push(chunk)); + request.on("end", () => { + const url = request.url ?? ""; + const body = Buffer.concat(chunks).toString("utf8"); + const json = (status: number, payload: unknown) => { + response.writeHead(status, { "content-type": "application/json" }); + response.end(JSON.stringify(payload)); + }; + if (url === "/health") { + json(200, { status: "ok" }); + } else if (url === "/v1/models") { + json(200, { data: [{ id: "test/model" }] }); + } else if (url === "/v1/chat/completions" && body.includes('"stream":true')) { + // Answer the head and one frame, then never finish: only the request + // deadline can end this read. + response.writeHead(200, { "content-type": "text/event-stream" }); + response.write('data: {"choices":[{"delta":{"content":"po"}}]}\n\n'); + } else if (url === "/v1/chat/completions") { + json(200, { + choices: [{ message: { content: "pong" }, finish_reason: "stop" }], + usage: { prompt_tokens: 1, completion_tokens: 1 }, + }); + } else if (url === "/v1/messages") { + json(200, { content: [{ type: "text", text: "pong" }], stop_reason: "end_turn" }); + } else { + json(404, { error: { message: "not found" } }); + } + }); + }); + await new Promise((resolve) => server.listen(0, "127.0.0.1", resolve)); + + try { + const { port } = server.address() as AddressInfo; + const result = await runScript( + "scripts/smoke.mjs", + { + OPENCODE_API_URL: `http://127.0.0.1:${port}`, + OPENCODE_API_KEY: "smoke-test-key", + SMOKE_HEALTH_TIMEOUT_MS: "5000", + SMOKE_REQUEST_TIMEOUT_MS: "5000", + SMOKE_STREAM_TIMEOUT_MS: "1000", + }, + 25_000, + ); + + // Before the fix the deadline died with the response head and this run + // never ended: the harness had to kill it. + expect(result.timedOut).toBe(false); + expect(result.code).toBe(1); + expect(result.signal).toBeNull(); + expect(result.stdout).toContain("PASS GET /health"); + expect(result.stdout).toContain("FAIL POST /v1/chat/completions (streaming)"); + expect(result.stdout).toContain("timed out after 1000ms"); + } finally { + server.closeAllConnections(); + await new Promise((resolve) => server.close(() => resolve())); + } + }, + 30_000, + ); +}); From 4ab65aa03c08ad3cf49208dbd81846cd72a6f182 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: Sat, 5 Dec 2026 17:12:46 +0700 Subject: [PATCH 6/9] fix(server): fail the smoke run when shutdown fails `pnpm smoke:dist` never looked at the child's exit status, so a failed or hung shutdown still exited 0 while the documentation presented the script as the clean-shutdown check. It now arms an exit listener before the SIGTERM, bounds the wait for the drain, and fails on a non-zero code or on a shutdown that outlives its watchdog. `pnpm smoke` cleared its abort timer as soon as the response headers arrived, which left a stream that stalls mid-body unbounded; the deadline now covers the body read. --- scripts/smoke-dist.mjs | 71 +++++++++++++++++++++++++++++++++++--- scripts/smoke.mjs | 77 +++++++++++++++++++++++++++++++++++++----- 2 files changed, 135 insertions(+), 13 deletions(-) diff --git a/scripts/smoke-dist.mjs b/scripts/smoke-dist.mjs index 4ec6736..c61d030 100644 --- a/scripts/smoke-dist.mjs +++ b/scripts/smoke-dist.mjs @@ -11,7 +11,10 @@ * and `OPENCODE_SERVER_URL` stays unset, so startup never touches upstream. * - `/health` is public and unauthenticated by design. * - * Exits 0 when `/health` answers 200, 1 otherwise. + * Exits 0 when `/health` answers 200 *and* the child exits 0 after the SIGTERM + * the script sends; a non-zero exit code or a shutdown that outlives + * `SMOKE_SHUTDOWN_TIMEOUT_MS` fails the run too, so the documented clean + * shutdown has an automated carrier. */ import { spawn } from "node:child_process"; import path from "node:path"; @@ -20,6 +23,7 @@ import { fileURLToPath } from "node:url"; const projectRoot = path.resolve(path.dirname(fileURLToPath(import.meta.url)), ".."); const port = Number(process.env["SMOKE_PORT"] ?? 20199); const timeoutMs = Number(process.env["SMOKE_TIMEOUT_MS"] ?? 20_000); +const shutdownTimeoutMs = Number(process.env["SMOKE_SHUTDOWN_TIMEOUT_MS"] ?? 10_000); const child = spawn(process.execPath, [path.join(projectRoot, "dist", "index.js")], { cwd: projectRoot, @@ -29,6 +33,8 @@ const child = spawn(process.execPath, [path.join(projectRoot, "dist", "index.js" PORT: String(port), OPENCODE_API_KEYS: "smoke-test-key", OPENCODE_AUTOSTART: "false", + // `silent` is an accepted level (`LOG_LEVELS` in src/config.ts) *and* a + // pino level, so this quiets the boot without an invalid-value warning. OPENCODE_LOG_LEVEL: "silent", OPENCODE_METRICS_ENABLED: "false", OPENCODE_DATA_DIR: path.join(projectRoot, ".opencode-api", "smoke"), @@ -63,12 +69,48 @@ async function waitForHealth() { throw new Error(`/health did not answer 200 within ${timeoutMs} ms (last attempt: ${lastError})`); } +/** + * Resolve with the child's exit outcome at most `timeoutMs` from now. + * + * The `exit` listener is attached synchronously, before the caller signals the + * child, so an exit that happens during or immediately after `kill()` cannot be + * missed. `timedOut` distinguishes "still running" from "exited with code null + * because a signal killed it". + * + * A child that ignores SIGTERM would otherwise keep this process alive (the + * child handle is ref'd), so the watchdog escalates to SIGKILL and releases the + * handle: the timeout has to *end the run*, not just be reported. + * + * @param {number} timeoutMs + * @returns {Promise<{ code: number | null, signal: NodeJS.Signals | null, timedOut: boolean }>} + */ +function waitForExit(timeoutMs) { + if (child.exitCode !== null || child.signalCode !== null) { + return Promise.resolve({ code: child.exitCode, signal: child.signalCode, timedOut: false }); + } + return new Promise((resolve) => { + /** @param {number | null} code @param {NodeJS.Signals | null} signal */ + function onExit(code, signal) { + clearTimeout(timer); + resolve({ code, signal, timedOut: false }); + } + const timer = setTimeout(() => { + child.removeListener("exit", onExit); + child.kill("SIGKILL"); + child.unref(); + resolve({ code: null, signal: null, timedOut: true }); + }, timeoutMs); + child.once("exit", onExit); + }); +} + /** Ask the child to shut down; the process exits when its own drain finishes. */ function stopChild() { stopRequested = true; if (child.exitCode === null) child.kill("SIGTERM"); } +let healthError; try { const response = await waitForHealth(); const body = await response.json(); @@ -76,10 +118,29 @@ try { throw new Error(`unexpected /health body: ${JSON.stringify(body)}`); } console.log(`smoke: dist/index.js answered /health with version ${body.version}`); - process.exitCode = 0; } catch (error) { + healthError = error; +} + +// I-04: the documented "clean SIGTERM shutdown" was unverified - nothing read +// the exit code, so a failed or hung shutdown still exited 0. Arm the listener +// before the signal, then bound the wait. +const exited = waitForExit(shutdownTimeoutMs); +stopChild(); +const outcome = await exited; + +if (healthError !== undefined) { + process.exitCode = 1; + console.error(`smoke: ${healthError instanceof Error ? healthError.message : String(healthError)}`); +} +if (outcome.timedOut) { + process.exitCode = 1; + console.error(`smoke: the gateway did not exit within ${shutdownTimeoutMs} ms after SIGTERM`); +} else if (outcome.code !== 0) { process.exitCode = 1; - console.error(`smoke: ${error instanceof Error ? error.message : String(error)}`); -} finally { - stopChild(); + console.error( + `smoke: the gateway exited with ${outcome.signal !== null ? `signal ${outcome.signal}` : `code ${outcome.code}`} after SIGTERM`, + ); +} else if (healthError === undefined) { + console.log("smoke: the gateway shut down cleanly after SIGTERM"); } diff --git a/scripts/smoke.mjs b/scripts/smoke.mjs index 5417364..17bae55 100644 --- a/scripts/smoke.mjs +++ b/scripts/smoke.mjs @@ -14,15 +14,19 @@ * OPENCODE_API_URL base URL of the gateway (default http://127.0.0.1:20123) * OPENCODE_API_KEY API key to send; defaults to the gateway's built-in * development key `sk-dummy-123` (a warning is printed) + * SMOKE_REQUEST_TIMEOUT_MS bound on a buffered request (default 180000) + * SMOKE_STREAM_TIMEOUT_MS bound on the streamed request, body included + * (default 180000) + * SMOKE_HEALTH_TIMEOUT_MS bound on `GET /health` (default 10000) * * Exit code: 0 when every check passes, 1 otherwise. */ const DEFAULT_URL = "http://127.0.0.1:20123"; const PROMPT = "Reply with exactly the word: pong"; -const REQUEST_TIMEOUT_MS = 180_000; -const STREAM_TIMEOUT_MS = 180_000; -const HEALTH_TIMEOUT_MS = 10_000; +const REQUEST_TIMEOUT_MS = Number(process.env.SMOKE_REQUEST_TIMEOUT_MS ?? 180_000); +const STREAM_TIMEOUT_MS = Number(process.env.SMOKE_STREAM_TIMEOUT_MS ?? 180_000); +const HEALTH_TIMEOUT_MS = Number(process.env.SMOKE_HEALTH_TIMEOUT_MS ?? 10_000); const options = parseArgs(process.argv.slice(2)); @@ -184,12 +188,18 @@ async function run(name, fn) { * @param {"GET" | "POST"} method * @param {string} path * @param {{ body?: unknown, timeoutMs?: number, auth?: boolean, extraHeaders?: Record }} [init] + * @returns {Promise} */ async function request(method, path, init = {}) { const url = `${baseUrl}${path}`; const timeoutMs = init.timeoutMs ?? REQUEST_TIMEOUT_MS; const controller = new AbortController(); const timer = setTimeout(() => controller.abort(), timeoutMs); + const describe = (error) => { + const reason = error instanceof Error ? error.message : String(error); + const hint = /abort/i.test(reason) ? ` (timed out after ${timeoutMs}ms)` : ""; + return `request to ${method} ${url} failed: ${reason}${hint}`; + }; try { const response = await fetch(url, { method, @@ -200,16 +210,67 @@ async function request(method, path, init = {}) { ...(init.body === undefined ? {} : { body: JSON.stringify(init.body) }), signal: controller.signal, }); - return response; + if (response.body === null) { + clearTimeout(timer); + return response; + } + // The deadline has to outlive the response head: `fetch()` resolves as soon + // as the headers land, so clearing the timer here left a stream that stalls + // *after* a 200 + `text/event-stream` bounded by nothing and hung the + // script. The timer now stays armed until the body settles, which bounds + // `readSse()` too, and a stall aborts the read with a timeout message. + const guarded = guardBody(response.body, timer, describe); + return new Response(guarded, { + status: response.status, + statusText: response.statusText, + headers: response.headers, + }); } catch (error) { - const reason = error instanceof Error ? error.message : String(error); - const hint = /abort/i.test(reason) ? ` (timed out after ${timeoutMs}ms)` : ""; - throw new Error(`request to ${method} ${url} failed: ${reason}${hint}`); - } finally { clearTimeout(timer); + throw new Error(describe(error)); } } +/** + * Re-emit `stream` while `timer` is still armed, and clear it once the body + * settles (end of body, error, or cancellation). + * + * `pull()` keeps the source's backpressure: one chunk is read per pull, so this + * does not buffer the body in memory. + * + * @param {ReadableStream} stream + * @param {ReturnType} timer + * @param {(error: unknown) => string} describe + * @returns {ReadableStream} + */ +function guardBody(stream, timer, describe) { + const reader = stream.getReader(); + return new ReadableStream({ + async pull(controller) { + try { + const { value, done } = await reader.read(); + if (done) { + clearTimeout(timer); + controller.close(); + return; + } + controller.enqueue(value); + } catch (error) { + clearTimeout(timer); + controller.error(new Error(describe(error))); + } + }, + async cancel(reason) { + clearTimeout(timer); + try { + await reader.cancel(reason); + } catch { + /* the source already errored */ + } + }, + }); +} + /** @param {Response} response */ async function json(response) { const text = await response.text(); From 815dbec5c48b474cd8d520d03f0f02ba1bdb0a6c 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: Sat, 5 Dec 2026 17:12:46 +0700 Subject: [PATCH 7/9] fix(server): classify the expanded loopback spellings `isLoopbackHost()` only knew the compressed `::1` spelling, so the expanded `0:0:0:0:0:0:0:1` and the IPv4-mapped `::ffff:7f00:1` were treated as network-reachable: the published-default-key guard refused a bind no other machine can reach, and the SSRF/metrics warnings fired on a loopback interface. `node:net`'s `BlockList` now classifies the address, and every spelling that is not genuinely loopback still fails closed. --- src/startup.ts | 36 +++++++++++++++++++++++++++++++----- test/startup.test.ts | 40 ++++++++++++++++++++++++++++++++++++++++ 2 files changed, 71 insertions(+), 5 deletions(-) diff --git a/src/startup.ts b/src/startup.ts index dd20dbf..6c36958 100644 --- a/src/startup.ts +++ b/src/startup.ts @@ -4,6 +4,7 @@ * Kept free of side effects so a unit test can assert what an operator is told * without booting the gateway or loading `.env`. */ +import { BlockList, isIP } from "node:net"; import path from "node:path"; import { DEFAULT_API_KEY } from "./config.js"; @@ -28,15 +29,40 @@ export function defaultApiKeyNote(projectRoot: string): string { ); } -/** 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"]); +/** The only host *name* that is loopback; every other accepted form is a literal. */ +const LOOPBACK_HOSTNAME = "localhost"; + +/** + * The loopback address space, checked with `node:net`'s `BlockList` so every + * valid spelling of the same address classifies identically. + * + * A string set used to be enough for `127.0.0.1`/`::1` plus one IPv4-mapped + * form, so the RFC 5952 expanded literal `0:0:0:0:0:0:0:1` and the mapped + * hexadecimal form `::ffff:7f00:1` were reported as network-reachable: the + * fail-closed guard refused a loopback bind, and the SSRF/metrics warnings + * fired on an interface no other machine can reach. + * + * `127.0.0.0/8` covers the whole IPv4 loopback block; `::1` the IPv6 one; and + * `::ffff:127.0.0.0/104` the IPv4-mapped range. `BlockList` compares parsed + * addresses, never strings, and every form outside these ranges stays + * non-loopback (fail-closed). + */ +const LOOPBACK_ADDRESSES = new BlockList(); +LOOPBACK_ADDRESSES.addSubnet("127.0.0.0", 8, "ipv4"); +LOOPBACK_ADDRESSES.addAddress("::1", "ipv6"); +LOOPBACK_ADDRESSES.addSubnet("::ffff:127.0.0.0", 104, "ipv6"); /** True when `host` binds the loopback interface only. */ export function isLoopbackHost(host: string): boolean { + // A bracketed IPv6 literal (`[::1]`) is the URL form; the brackets are not + // part of the address. 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); + if (normalised === LOOPBACK_HOSTNAME) return true; + const family = isIP(normalised); + if (family === 4) return LOOPBACK_ADDRESSES.check(normalised, "ipv4"); + if (family === 6) return LOOPBACK_ADDRESSES.check(normalised, "ipv6"); + // A malformed literal (`127.1`, a DNS name) is not loopback by accident. + return false; } /** diff --git a/test/startup.test.ts b/test/startup.test.ts index 9d810b3..aec8696 100644 --- a/test/startup.test.ts +++ b/test/startup.test.ts @@ -35,6 +35,16 @@ describe("defaultKeyExposureError", () => { } }); + it("does not refuse the expanded or IPv4-mapped spellings of loopback", () => { + // A string set used to know only `::1` and `[::1]`, so these three valid + // loopback spellings were treated as network-reachable and the guard + // refused a bind no other machine can reach. + for (const host of ["0:0:0:0:0:0:0:1", "[0:0:0:0:0:0:0:1]", "::ffff:7f00:1"]) { + expect(isLoopbackHost(host)).toBe(true); + expect(defaultKeyExposureError({ ...EXPOSED, host })).toBeUndefined(); + } + }); + it("allows an exposed bind with a real key", () => { expect(defaultKeyExposureError({ ...EXPOSED, usingDefaultApiKey: false })).toBeUndefined(); }); @@ -58,6 +68,36 @@ describe("isLoopbackHost", () => { expect(isLoopbackHost("192.168.1.10")).toBe(false); expect(isLoopbackHost("127.0.0.1.evil.example")).toBe(false); }); + + it("classifies every loopback spelling and stays fail-closed otherwise (I-06)", () => { + for (const host of [ + "127.0.0.1", + "127.9.9.9", + "::1", + "[::1]", + "0:0:0:0:0:0:0:1", + "[0:0:0:0:0:0:0:1]", + "::ffff:127.0.0.1", + "::ffff:7f00:1", + "localhost", + "LOCALHOST", + ]) { + expect(isLoopbackHost(host), host).toBe(true); + } + for (const host of [ + "0.0.0.0", + "::", + "8.8.8.8", + "2001:db8::1", + "::ffff:8.8.8.8", + "127.1", + "127.0.0.1.evil.example", + "gateway.example.com", + "", + ]) { + expect(isLoopbackHost(host), host).toBe(false); + } + }); }); describe("existing notes stay unchanged in shape", () => { From 6662930af69f11bf14eec5905babac760235bf6d 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: Sat, 5 Dec 2026 17:12:46 +0700 Subject: [PATCH 8/9] ci: drop the checkout token before installing The workflow pins every action to a commit SHA because each job runs with a repository token, but none of the four checkouts set `persist-credentials: false`, so that token stayed in `.git/config` while `pnpm install --frozen-lockfile` executed dependency build scripts (esbuild's install script is explicitly allowed). --- .github/workflows/ci.yml | 10 ++++++++++ 1 file changed, 10 insertions(+) diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index a33b248..37bd403 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -32,6 +32,10 @@ jobs: uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7 with: fetch-depth: 0 + # Every job runs `pnpm install --frozen-lockfile` with dependency build + # scripts allowed, so the checkout must not leave the repository token + # in `.git/config` for those scripts to read. + persist-credentials: false - name: Set up pnpm uses: pnpm/action-setup@73e46992e05b19abd31f2f3c20e0e7370d762115 # v6 @@ -100,6 +104,8 @@ jobs: steps: - name: Check out the repository uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7 + with: + persist-credentials: false - name: Set up pnpm uses: pnpm/action-setup@73e46992e05b19abd31f2f3c20e0e7370d762115 # v6 @@ -155,6 +161,8 @@ jobs: steps: - name: Check out the repository uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7 + with: + persist-credentials: false - name: Set up pnpm uses: pnpm/action-setup@73e46992e05b19abd31f2f3c20e0e7370d762115 # v6 @@ -192,6 +200,8 @@ jobs: steps: - name: Check out the repository uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7 + with: + persist-credentials: false - name: Build the image run: docker build --tag opencode-api:ci . From 1a10f1110b4eb5b42891775841929339f85d5428 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: Sat, 5 Dec 2026 17:12:46 +0700 Subject: [PATCH 9/9] docs: record the second audit pass and its contracts `docs/API.md` now documents the `stop`/`stop_sequences` caps, the `400 invalid_request` an empty turn is rejected with on the chat and Responses surfaces, the `content_block_stop` that precedes a terminal Anthropic `error` frame, the streamed block order (arrival order, against the buffered `thinking` -> `text` -> `tool_use`), the interrupted-turn reporting, and the `/v1/responses` head frames that carry the resolved `x_opencode` values. `docs/ARCHITECTURE.md` follows every changed contract: the interrupted-turn `cancelled` finish reason, the signal that now reaches the first session creation, the cache-disabled turn that records and persists nothing, the first-token watchdog that counts upstream liveness, the bounded upstream log file, the `{ data: ... }` envelope validation, and the new `src/adapter/common/stop.ts` in the frozen `adapter/common` contract. `docs/VERIFICATION.md` gains the addendum for this pass with the commands that were run and the current counts (40 modules, 80 emitted files, 37 unit test files, 861 passing tests, 52 environment variables). --- docs/API.md | 37 ++++++++++++++----- docs/ARCHITECTURE.md | 88 +++++++++++++++++++++++++++++++++++++++++++- docs/VERIFICATION.md | 72 ++++++++++++++++++++++++++++++++++++ 3 files changed, 187 insertions(+), 10 deletions(-) diff --git a/docs/API.md b/docs/API.md index 78eef34..35aa7d1 100644 --- a/docs/API.md +++ b/docs/API.md @@ -87,7 +87,7 @@ with a `retry-after` header once that budget is spent. | Field | Type | Default | Notes | | --- | --- | --- | --- | | `model` | string | — | Required. `provider/model`, bare model id, optional `#variant` suffix. The model is resolved **before** the response starts, so an unknown or disabled model always yields a JSON `404`/`400`, never a broken stream. | -| `messages` | array | — | Required, at least one. Roles `system`, `developer`, `user`, `assistant`, `tool`. | +| `messages` | array | — | Required, at least one. Roles `system`, `developer`, `user`, `assistant`, `tool`. A message that carries no text, no media and no tool call (nor a `tool_call_id`) is dropped, and a request whose messages all drop that way is `400 invalid_request` with `param: "messages"` rather than an empty prompt answered `200`. | | `messages[].content` | string \| array \| null | — | String, or parts: `text`, `image_url`, `video_url`, `input_audio`, `file`, `document`. | | `messages[].content[].image_url.url` | string | — | `data:` URI or `http(s)://` URL (remote URLs are fetched and inlined). A bare filesystem path is not accepted here. | | `messages[].content[].video_url.url` | string | — | Same two forms. | @@ -106,7 +106,7 @@ with a `retry-after` header once that budget is spent. | `reasoning.effort` | string | *(unset)* | Used when `reasoning_effort` is absent. | | `max_tokens` / `max_completion_tokens` | number | *(unset)* | `max_completion_tokens` wins. Accepted and recorded, not enforced upstream: OpenCode's agent owns the generation budget. Listed in `x_opencode.unapplied` when supplied. | | `temperature`, `top_p` | number | *(unset)* | Accepted and recorded, but not forwarded: OpenCode's agent loop owns the sampling parameters. Listed in `x_opencode.unapplied` when supplied. | -| `stop` | string \| string[] | *(unset)* | **Honoured on both paths**: the visible text is truncated at the first delimiter, empty strings are dropped. Generation upstream is not interrupted, so `usage` counts the full turn and `finish_reason` stays `stop`. | +| `stop` | string \| string[] | *(unset)* | **Honoured on both paths**: the visible text is truncated at the first delimiter, empty strings are dropped. Bounded, because the streamed filter scans every declared delimiter on every delta: at most **16 entries**, each at most **256 characters**, **1024 characters** in total; past that the request is `400 invalid_request` with `param: "stop"`. 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. `service_tier` is recorded and named in `x_opencode.unapplied` when supplied. | | `parallel_tool_calls` | boolean | `true` | `false` makes the tool bridge ask the model for at most one bridged tool call per turn; `true`/absent allows several. | @@ -163,8 +163,12 @@ with a `retry-after` header once that budget is spent. * `finish_reason` is `stop`, `length`, `tool_calls` or `content_filter`. A turn the upstream ended with `error` is a failure, not a completion: the buffered form answers `502 api_error` / `upstream_error`, and the streamed form ends - with the error frame below instead of a finish chunk or `[DONE]`. Only - `cancelled` (client disconnect) is reported as `stop`. + with the error frame below instead of a finish chunk or `[DONE]`. A turn the + upstream **interrupted** (provider-side cancellation, or the shared server + cancelling the session) has no dedicated OpenAI finish reason and is therefore + reported as `stop`; `completions_total` still counts it as + `finish_reason="cancelled"`, and `/v1/messages` keeps the distinction as + `stop_reason: "end_turn"` plus `x_opencode.interrupted: true`. * `x_opencode.native_tool_calls` lists native OpenCode tool activity as `{id, name, status, input?, error?}` with `status` in `started`, `input`, `called`, `succeeded`, `failed`. @@ -288,7 +292,7 @@ reasoning mapping and tool bridging with the chat endpoint. | Field | Type | Default | Notes | | --- | --- | --- | --- | | `model` | string | — | Required and non-empty: `model: ""` is `400 invalid_request` with `param: "model"`. Same naming rules as chat. | -| `input` | string \| array | — | Required, and a non-empty string or array: `input: []` is `400 invalid_request` with `param: "input"` rather than an empty prompt. Items: `message` (`{role, content}`, `type` optional), `function_call`, `function_call_output`, `reasoning`, `item_reference`. Roles: `user`, `assistant`, `system`, `developer`. | +| `input` | string \| array | — | Required, and a non-empty string or array: `input: []` is `400 invalid_request` with `param: "input"` rather than an empty prompt. Items: `message` (`{role, content}`, `type` optional), `function_call`, `function_call_output`, `reasoning`, `item_reference`. Roles: `user`, `assistant`, `system`, `developer`. An item that carries no text, no media and no tool call is dropped, and an input whose items all drop that way (for example a lone `item_reference`) is `400 invalid_request` with `param: "input"`. | | `input[].content` parts | — | — | `input_text`, `output_text`, `summary_text` (text is used), `refusal` (the refusal text is used), `input_image`, `input_file`, `input_audio`, `video_url`. | | `instructions` | string | *(unset)* | Prepended as a `system` turn **and echoed** on the response object. | | `stream` | boolean | `false` | Emit the typed SSE sequence. | @@ -407,7 +411,7 @@ the JSON. `sequence_number` is a monotonically increasing counter. ``` event: response.created -data: {"type":"response.created","sequence_number":0,"response":{"id":"resp_...","object":"response","status":"in_progress","model":"opencode/deepseek-v4.1-flash-free","output":[],"x_opencode":{"session_id":"","agent":"build","variant":null,"reused_session":false,"native_tool_calls":[]}}} +data: {"type":"response.created","sequence_number":0,"response":{"id":"resp_...","object":"response","status":"in_progress","model":"opencode/deepseek-v4.1-flash-free","output":[],"x_opencode":{"session_id":"ses_...","agent":"build","variant":null,"reused_session":false,"native_tool_calls":[]}}} event: response.in_progress data: {"type":"response.in_progress","sequence_number":1,"response":{...}} @@ -515,7 +519,7 @@ the wire format. Use `/v1/chat/completions` for anything new. | `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`, `top_p` | — | *(unset)* | Accepted and recorded; the OpenCode agent owns the generation budget and the sampling parameters, so they are not applied. All are named in `x_opencode.unapplied` when supplied. | -| `stop` | string \| string[] | *(unset)* | **Honoured on both paths**: the visible text is truncated at the first delimiter and `finish_reason` stays `stop`. Generation upstream is not interrupted. | +| `stop` | string \| string[] | *(unset)* | **Honoured on both paths**: the visible text is truncated at the first delimiter and `finish_reason` stays `stop`. Same caps as `/v1/chat/completions` (16 entries, 256 characters each, 1024 in total; `400 invalid_request` with `param: "stop"` past that). 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. | | `service_tier`, `user` | string | — | Accepted and ignored (`user` correlation is done with `x-request-id`); `service_tier` is named in `x_opencode.unapplied` when supplied. | | `echo` | boolean | `false` | `true` is rejected with `400 unsupported_parameter` (the prompt is rewritten before it reaches the model). | @@ -601,7 +605,7 @@ Anthropic Messages API. | `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` | 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. | +| `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. Bounded, because the streamed filter scans every declared sequence on every delta: at most **16 entries**, each at most **256 characters**, **1024 characters** in total; past that the request is `400 invalid_request` with `param: "stop_sequences"`. 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"}`. `budget_tokens` must be an **integer ≥ 1**, and `type:"enabled"` without it is `400 invalid_request` with `param: "thinking.budget_tokens"`, matching the Anthropic contract. (The non-standard `effort` key is accepted and mapped exactly like the top-level `reasoning_effort`; a request using only `effort` does not need a budget.) | @@ -730,13 +734,28 @@ arrive in the final `message_delta.usage`, so SDK cost accounting must read usag 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: +raised before the first frame is reported with a real HTTP status. Whatever the +turn had already delivered is still real content: a block that was open is closed +with its `content_block_stop` (and any text the `stop_sequences` lookahead was +still holding is flushed as a final `text_delta`) **before** the `error` frame, so +the client can assemble the partial message. The `error` frame itself carries no +partial message. ``` +event: content_block_stop +data: {"type":"content_block_stop","index":0} + event: error data: {"type":"error","error":{"type":"overloaded_error","message":"Model is unavailable"}} ``` +Streamed block order follows arrival: each block opens at the index free when its +first delta arrives, so a turn that emits text before reasoning streams +`[text, thinking]`. The buffered `content` array is always ordered `thinking` → +`text` → `tool_use`, so the two paths agree for the usual reasoning-then-text turn +and a client that assembles `content[]` from a stream must not assume the buffered +order. + ### Errors Anthropic shape, selected by the request path (`/v1/messages*`): diff --git a/docs/ARCHITECTURE.md b/docs/ARCHITECTURE.md index c379ba6..463df0e 100644 --- a/docs/ARCHITECTURE.md +++ b/docs/ARCHITECTURE.md @@ -318,6 +318,16 @@ timeout (`OpencodeClientOptions.catalogueTimeoutMs`, default 10 s) rather than t candidates while keeping the conversation key, so a stale-session replay caches its replacement where the next turn of that conversation will find it. +A 2xx body must be a JSON object (checked once in `request()`). The two methods +whose callers dereference the documented `{ data: … }` envelope — `createSession()` +and `prompt()` — additionally reject a body whose `data` is missing, `null` or not +an object with `503 upstream_invalid_json`, so a truncated or proxied answer is +reported as an upstream failure instead of escaping as a bare `TypeError` (HTTP +500) outside the `ApiError` taxonomy. `deleteSession()` is deliberately exempt: it +never reads the payload, and the success shape of `DELETE /api/session/{id}` is +not part of the verified protocol surface, so demanding a `data` field there could +fail a delete that actually succeeded. + `execute()`'s `finally` settles the sticky record on every exit. When the turn did not complete it releases the record; a session that was **created for that turn** (`!prepared.reused`) has no record yet, so the release finds nothing and the @@ -327,6 +337,33 @@ a best-effort `deleteSession()`, so a first turn that fails (429, timeout, disconnect, `event_stream_lost`) leaves no orphan. Reused sessions keep being deleted by the session-store eviction hook. +With `OPENCODE_SESSION_CACHE=false` the turn is genuinely stateless: a completed +turn neither commits nor persists a record (the store stays empty, no +`sessions.json` is written) and the session created for it is deleted best-effort +instead, because nothing would ever reuse it and no eviction hook exists to +release it. `acquire()` never hands out a candidate in that mode, so the delete +can never race a reuse. + +The caller's abort signal reaches **every** upstream call of a turn, including +the very first `createSession()`. It used to be threaded only into the +stale-session replay, so a client that disconnected while the initial session was +being created kept the handler (and the upstream call) alive for the full +`OPENCODE_REQUEST_TIMEOUT_MS` and then created-and-deleted a session for a caller +that was already gone. + +The first-token watchdog bounds a **silent** upstream, not an unproductive one: +`OPENCODE_FIRST_TOKEN_TIMEOUT_MS` is re-armed by every liveness frame — a text or +reasoning delta, a `session.step.started` and each `session.tool.*` event — so a +turn whose agent is running a long native command is not killed with "produced no +output". `sawText` still disables the watchdog once real output exists, and a turn +that emits `session.step.started` and then goes silent is still bounded. + +`session.execution.interrupted`, and `session.idle` with +`outcome: "interrupted"`, end the turn with `finishReason: "cancelled"` instead of +a normal `stop`; `finalise()`'s `bridgedToolCalls > 0` precedence still wins, and +the Anthropic surface renders `cancelled` as `end_turn` plus +`x_opencode.interrupted: true`. + `stop()` is deliberately **non-terminal**: `POST /admin/upstream/restart` and the retry paths call `stop()`/`invalidate()` and then `resolve()` again, and `test/process.test.ts` pins that. It also terminates a child that has been spawned @@ -359,7 +396,12 @@ failure message, to the ring-buffer push and, authoritatively, to password has to be parsed out of it — and the log stream carries an `'error'` handler, so a full disk or an unwritable log directory degrades to one warning and a disabled log file instead of an uncaught exception that kills every in-flight -turn. +turn. The file itself is bounded: its size is measured on open (so a file left by +an earlier run counts) and it is truncated and reopened once appending a chunk +would cross `OPENCODE_UPSTREAM_LOG_MAX_BYTES` (default 32 MiB, `0` disables the +cap), which keeps a chatty long-lived server from filling the disk. A single chunk +larger than the cap is still written whole, so the file is bounded by the cap plus +one chunk. `/sessions.json` is an envelope `{ version, fingerprint, records }` where `fingerprint` is `Config.instanceId`. A `ses_*` id only exists inside the upstream @@ -440,6 +482,19 @@ renderToolResult(message): string, class ToolCallFilter(allowedNames?: Iterable< // reasoning`; the wire `total_tokens` is wider, because each surface folds // `cache_read`/`cache_write` into its prompt (or keeps the Anthropic split). EMPTY_USAGE, toUsage(tokens), addUsage(a, b), estimateTokens(text), estimateConversationTokens(parts) + +// stop.ts +// Caller-supplied stop delimiters, shared by `/v1/chat/completions`, +// `/v1/completions` and `/v1/messages`. Each streaming stop filter re-scans its +// held lookahead window for every declared sequence on every delta, so the +// field is bounded: `MAX_STOP_SEQUENCES` (16), `MAX_STOP_SEQUENCE_LENGTH` (256) +// and `MAX_STOP_SEQUENCE_BYTES` (1024, combined). `normaliseStopSequences()` +// accepts the string and array spellings, drops empty entries (their historical +// meaning) and throws `400 invalid_request` naming `param` past a cap, so an +// unbounded delimiter list can no longer block the event loop for seconds per +// request. +MAX_STOP_SEQUENCES, MAX_STOP_SEQUENCE_LENGTH, MAX_STOP_SEQUENCE_BYTES, +normaliseStopSequences(value, param): string[] ``` ### 4.5 `src/media/*` (owned by the media workstream) @@ -765,3 +820,34 @@ tests can substitute a scripted runner (`test/helpers/context.ts`). authenticated. * `GET /admin/config` returns the effective configuration with the API keys and the upstream password redacted (`apiKeyCount`, `passwordConfigured`). +* Every completion surface rejects a request that normalises to **no** message + content with `400 invalid_request`: `/v1/messages` names `messages` + ("At least one message must carry text, media or a tool result"), the OpenAI + chat surface names `messages` and `/v1/responses` names `input`. A message/input + item that carries no text, no attachment and no tool call (or tool-call id) is + dropped first, so `content: ""`, `content: []` and an `item_reference`-only + `input` can no longer reach the orchestrator and be answered 200 from the + literal `"Continue."` fallback. The check runs after media resolution, so a + media-only message whose attachment was omitted still carries the omission note + and is kept. +* The Anthropic streamed form closes whatever content block it opened before it + writes a terminal `error` frame — both the in-band `kind: "error"` event and an + exception thrown by the event iterator — mirroring the `finishReason: "error"` + path. The `error` frame carries no partial message, so returning before the + `content_block_stop` left the client with a block it could never close; any + text withheld by the stop-sequence lookahead is flushed first. +* `/v1/responses` applies the already-pulled `start` event to the stream state + **before** `response.created` / `response.in_progress`, so both head frames and + the `response.completed` object carry the same `x_opencode.session_id`, + `agent`, `variant` and `reused_session`. The pre-flight `error` guard stays + first, so a turn that fails before its first real event still commits no SSE + head and the client sees the HTTP status. The `start` application is + idempotent, because the loop applies the same event when it reaches it. +* Anthropic block order: the buffered `content` array is always ordered + `thinking` → `text` → `tool_use`, while the **streamed** form announces each + block at the index that is free when its first delta arrives. For the usual + reasoning-then-text turn the two agree; a turn that emits text and only later + reasoning streams `[text, thinking]`. The streamed order is the deliberate + latency trade-off documented in `docs/VERIFICATION.md`; clients that assemble + `content[]` from a stream must not assume the buffered order. `docs/API.md` + states this per surface. diff --git a/docs/VERIFICATION.md b/docs/VERIFICATION.md index 5bb589a..047a10f 100644 --- a/docs/VERIFICATION.md +++ b/docs/VERIFICATION.md @@ -383,3 +383,75 @@ This pass fixed, with a regression test for each: `UpstreamProcess` leaves the process-exit registry once it owns no child (`test/process.test.ts`); the CLI and `service.json` discovery paths have unit coverage at last (`test/discovery.test.ts`). + +### Addendum — second audit-and-fix pass of 2026-12-05 + +A second independent audit was run against `1f09d7b` (four read-only workstreams: security, +upstream layer, surface adapters, infrastructure + documentation drift). Every candidate was +re-verified against the code and the existing tests before being accepted; the accepted set, the +reasoning and the two re-scoped items are summarised below. This addendum is the authoritative **current** state and supersedes the numbers above. + +| Command | Result | +| --- | --- | +| `pnpm typecheck` | **PASS** — `$ tsc -p tsconfig.json --noEmit`, exit 0 | +| `pnpm build` | **PASS** — `tsc -p tsconfig.build.json`, exit 0, **80** files emitted into `dist/` (40 modules + 40 source maps) | +| `pnpm test` | **PASS** — **37** files, **861 passed**, 2 skipped (863) | +| `pnpm exec vitest run test/docs-consistency.test.ts` | **PASS** — 1 file, **16** tests | +| `pnpm smoke:dist` | **PASS** — `dist/index.js answered /health with version 1.0.0`, then `the gateway shut down cleanly after SIGTERM` (the exit status is now checked) | +| `pnpm audit --prod` | **PASS** — `No known vulnerabilities found` | + +Numbers quoted earlier in this document that have since changed: + +* `src/config.ts` reads **52** environment variables, and all 52 are listed in + `.env.example`, `docs/CONFIGURATION.md` and `README.md`. +* The unit suite is **37 files / 861 passed / 2 skipped**, up from 32 files and 792 passed. + `test/anthropic-streaming.test.ts`, `test/http-guards.test.ts`, `test/openai-validation.test.ts`, + `test/setup-scripts.test.ts` and `test/upstream-invariants.test.ts` are new. +* `src/` has **40** modules (the new `src/adapter/common/stop.ts`), emitting **80** files. +* The `GET /` index in `docs/API.md` still lists **19** entries; with `GET /` itself that is + exactly the **20** routes `src/` registers. + +This pass fixed, with a regression test for each (the pre-fix failure of every new test was +verified before the fix was applied): + +* **High** — `session.execution.interrupted` (and `session.idle {outcome:"interrupted"}`) ended a + turn as a normal `stop`, so an interrupted answer was returned as complete and counted as a + success although `FinishReason` has a `cancelled` member and the Anthropic surface already keys + `x_opencode.interrupted` on it (`test/upstream-invariants.test.ts`); an unbounded caller-supplied + `stop`/`stop_sequences` list made the streamed stop filters quadratic per delta (measured ~6 s of + blocked event loop for a 1.3 MB body), now capped at 16 entries / 256 characters each / 1024 + characters in total with `400 invalid_request` + (`test/openai-validation.test.ts`, `test/anthropic-streaming.test.ts`); `pnpm setup` could not see + an `export OPENCODE_API_KEYS=…`, `OPENCODE_API_KEYS: …` or `OPENCODE_API_KEY=…` assignment, so it + appended a duplicate that `dotenv` resolved last-wins — silently replacing the operator's secret + with the published `sk-dummy-123` (`test/setup-scripts.test.ts`). +* **Medium** — the first `prepare()` dropped the caller's abort signal, so a disconnect during + session creation parked the handler for the full request budget; a completed turn committed (and, + with `OPENCODE_SESSION_PERSIST=true`, wrote to disk) a session record even with + `OPENCODE_SESSION_CACHE=false`, where nothing would ever reuse it — the cache-disabled path now + records nothing and deletes the session it created; the first-token watchdog ignored + `session.step.started` and every `session.tool.*` frame, so a tool-only turn was killed with a + false "produced no output"; the Anthropic stream left the open content block dangling when a + mid-stream `error` event arrived after a delta; a chat/Responses request whose messages all + normalised to nothing ran a billed turn on the literal `"Continue."` and answered `200`, now + `400 invalid_request` naming `messages`/`input`. +* **Low / hardening** — a spawn `error` kept the `UpstreamProcess` in the process-exit registry; a + 2xx body without a usable `data` field escaped as a bare `TypeError` (HTTP 500) from + `createSession`/`prompt`; the supervised child's log file grew without bound (now rotated at + `OPENCODE_UPSTREAM_LOG_MAX_BYTES`, default 32 MiB, measured across restarts); + `/v1/responses` emitted `response.created`/`response.in_progress` with an unresolved `x_opencode` + although the `start` event was already in hand; the Anthropic surface bypassed the bounded media + download pool; `isLoopbackHost()` missed the expanded and IPv4-mapped spellings of loopback; + `pnpm smoke:dist` could not see a failed shutdown and `pnpm smoke` never bounded a body that + stalled after the headers; the CI checkouts kept the repository token while dependency build + scripts ran; a throttled authentication failure was logged at `debug`, so a guessing flood went + unaudited; `isAuthorized()` re-hashed the presented credential once per configured key; the + buffered-request socket bound installed a callback that could never run; a non-base64 `data:` URI + was decoded before the size cap; and the RFC 2765 IPv4-translated prefix `::ffff:0:a.b.c.d` was + classified public. +* **Documentation** — the README's `/metrics` paragraph claimed two guarantees the code does not + provide; the Anthropic streamed block order (arrival order) is now documented next to the + buffered `thinking` → `text` → `tool_use` order; the `stop`/`stop_sequences` caps, the + empty-content rule, the `error`-frame block closing and the `/v1/responses` head-frame + `x_opencode` values are in `docs/API.md`; every changed contract is in + `docs/ARCHITECTURE.md`.