From 304600f599e79fdb32ad37baa8a1078263ac0fc7 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 14:30:41 +0700 Subject: [PATCH 01/10] fix: bound rejected bodies and stop upstream credential leaks Arm the body-receipt deadline in the earliest `onRequest` hook. Fastify runs `preParsing` only while no earlier hook ended the request, and both the authenticator and the rate limiter reject from `onRequest`, so the deadline was never installed for a rejected request: an unauthenticated caller could dribble a body forever and hold a socket for free. The deadline now survives the response `close` while the body is still arriving. Reject an `OPENCODE_SERVER_URL` that embeds credentials at startup. Node refuses a request whose URL carries userinfo, so such a deployment could never reach its upstream, and the password was echoed by `/admin/config` and `/admin/status` and every completion failure message. `OPENCODE_SERVER_PASSWORD` is the documented way to authenticate. Warn when `OPENCODE_METRICS_PUBLIC` publishes `/metrics` anonymously on a host reachable from the network, matching the fail-loud note the private-media switch already gets. Each fix has a regression test that fails without it. --- docs/CONFIGURATION.md | 12 +++++-- src/config.ts | 36 +++++++++++++++++++- src/http/timeout.ts | 23 ++++++++++--- src/index.ts | 10 +++++- src/server.ts | 20 ++++++----- src/startup.ts | 30 +++++++++++++++++ test/admin.test.ts | 78 ++++++++++++++++++++++++++++++++++++++++--- test/config.test.ts | 22 ++++++++++++ test/startup.test.ts | 19 +++++++++++ 9 files changed, 228 insertions(+), 22 deletions(-) diff --git a/docs/CONFIGURATION.md b/docs/CONFIGURATION.md index dd85bc4..4be26a4 100644 --- a/docs/CONFIGURATION.md +++ b/docs/CONFIGURATION.md @@ -38,7 +38,7 @@ variable. (Discovery and the spawned CLI read the variables listed in | `OPENCODE_API_KEY` | string | *(unset)* | Single-key alias appended to `OPENCODE_API_KEYS`. | Same as above; convenient for local use only. | | `OPENCODE_ALLOW_NO_AUTH` | boolean | `false` | Accept every caller, ignoring keys. | Full unauthenticated access to every model and to the OpenCode agent. Use only on a trusted loopback host. | | `OPENCODE_ADMIN_API_KEYS` | CSV list | *(unset)* | Optional operator credential tier. When non-empty, `/admin` and `/admin/*` accept only these keys; a general `OPENCODE_API_KEYS` value is rejected there with `401`. Unset keeps the default behaviour (any accepted API key may call the admin routes). When set but empty (`OPENCODE_ADMIN_API_KEYS=","`) the gateway refuses to start, exactly like `OPENCODE_API_KEYS`. | The admin routes can restart the shared upstream (failing every in-flight turn) and drop the sticky-session cache. Give them a separate secret so a tenant key cannot. | -| `OPENCODE_METRICS_PUBLIC` | boolean | `false` | Exempt `GET /metrics` from authentication. | Metrics expose model names, route traffic and token volumes, so this is only safe when `HOST` is a loopback address; otherwise set `OPENCODE_METRICS_TOKEN` instead of exposing the endpoint anonymously. | +| `OPENCODE_METRICS_PUBLIC` | boolean | `false` | Exempt `GET /metrics` from authentication. | Metrics expose model names, route traffic and token volumes, so this is only safe when `HOST` is a loopback address; otherwise set `OPENCODE_METRICS_TOKEN` instead of exposing the endpoint anonymously. Enabling it on a non-loopback host with no token logs the exposure at `error` and prints a note to stderr at startup; the gateway still starts. | | `OPENCODE_METRICS_TOKEN` | string | *(unset)* | Dedicated scrape credential for `GET /metrics`, compared in constant time before the `OPENCODE_METRICS_PUBLIC` bypass. When set, `/metrics` requires it even if `OPENCODE_METRICS_PUBLIC=true`; a valid general API key is still accepted. | Lets a Prometheus scraper read metrics without handing it a general-purpose key. Prefer it over making the endpoint public. | Keys are presented as `Authorization: Bearer `, `x-api-key: `, @@ -66,7 +66,7 @@ ignores the mode). | Variable | Type | Default | Description | Security implication | | --- | --- | --- | --- | --- | -| `OPENCODE_SERVER_URL` | URL | *(unset)* | Explicit OpenCode server. When set, the gateway never spawns one and fails if the URL is unreachable. | Point only at a server you control; the gateway sends prompts and attachments to it. | +| `OPENCODE_SERVER_URL` | URL | *(unset)* | Explicit OpenCode server. When set, the gateway never spawns one and fails if the URL is unreachable. A URL that embeds credentials (`http://user:pass@host:port`) is refused at startup: Node rejects a request whose URL carries userinfo, so it could never be reached, and the credential would be echoed by `/admin/config`, `/admin/status` and the failure message. | Point only at a server you control; the gateway sends prompts and attachments to it. Use `OPENCODE_SERVER_PASSWORD` for authentication, never the URL. | | `OPENCODE_SERVER_PASSWORD` | string | *(unset)* | Password of the explicit server (`Authorization: Basic opencode:`). | Secret; required for any non-loopback server. | | `OPENCODE_AUTOSTART` | boolean | `true` | Spawn a private `opencode serve` when no explicit server is configured. | The child process inherits the gateway's environment, including its own provider credentials. | | `OPENCODE_BIN` | path | *(unset)* | Full path to the OpenCode CLI executable. | Prefer an absolute path to a binary you installed; the gateway executes it. | @@ -171,6 +171,14 @@ The gateway exits with code 1 (before it listens) when: network and accepting a key printed in this repository is the one combination that must never start silently; set a real key (or, for a throwaway trusted network, `OPENCODE_ALLOW_NO_AUTH=true`). +5. `OPENCODE_ADMIN_API_KEYS` is set but yields no usable key + (`OPENCODE_ADMIN_API_KEYS=","`), for the same reason as item 3: an operator + who configured the tier must not silently fall back to accepting general keys + on `/admin/*`; +6. `OPENCODE_SERVER_URL` embeds credentials (`http://user:pass@host:port`). It + cannot work — Node refuses a request whose URL carries userinfo — and the + password would otherwise reach `/admin/config`, `/admin/status` and every + caller-visible failure message. Set `OPENCODE_SERVER_PASSWORD` instead. A missing key on a loopback host is **not** fatal: with neither `OPENCODE_API_KEYS` nor `OPENCODE_API_KEY` set, the gateway starts with the diff --git a/src/config.ts b/src/config.ts index acdb70e..d36edfd 100644 --- a/src/config.ts +++ b/src/config.ts @@ -315,6 +315,40 @@ function envEnum(name: string, allowed: readonly T[], fallback return fallback; } +/** + * Validate `OPENCODE_SERVER_URL`. + * + * A URL carrying `user:password@` is rejected outright. It cannot work: the + * upstream client builds its requests with `new URL(...)` and `fetch()`, and + * Node refuses a request whose URL still carries credentials, so every + * completion would answer `503` while the password travels into the + * caller-visible failure message and into `GET /admin/config` and + * `GET /admin/status` (both reachable by any accepted key unless + * `OPENCODE_ADMIN_API_KEYS` is configured). Failing at startup names the + * variable and never echoes the value. + */ +function parseUpstreamUrl(): string | undefined { + const raw = envOptStr("OPENCODE_SERVER_URL"); + if (raw === undefined) return undefined; + + let parsed: URL; + try { + parsed = new URL(raw); + } catch { + // An unparseable value is left to the resolution path, which reports it as + // "not reachable" without echoing it; only credential-carrying values are + // fatal here. + return raw; + } + if (parsed.username !== "" || parsed.password !== "") { + throw new Error( + "OPENCODE_SERVER_URL must not embed credentials: Node refuses a request whose URL carries userinfo, " + + "so the upstream could never be reached. Set OPENCODE_SERVER_PASSWORD instead.", + ); + } + return raw; +} + /** Resolve a possibly-relative path against the current working directory. */ export function resolvePath(value: string): string { const expanded = value.startsWith("~") ? path.join(os.homedir(), value.slice(1)) : value; @@ -475,7 +509,7 @@ export function loadConfig(overrides: Partial = {}): Config { rateLimitBurst: envInt("OPENCODE_RATE_LIMIT_BURST", 0, 0), corsOrigins: Object.freeze(envList("OPENCODE_CORS_ORIGINS")), - upstreamUrl: envOptStr("OPENCODE_SERVER_URL"), + upstreamUrl: parseUpstreamUrl(), upstreamPassword: envOptStr("OPENCODE_SERVER_PASSWORD"), upstreamAutostart: envBool("OPENCODE_AUTOSTART", true), upstreamBin: envOptStr("OPENCODE_BIN"), diff --git a/src/http/timeout.ts b/src/http/timeout.ts index e844c12..aa278bf 100644 --- a/src/http/timeout.ts +++ b/src/http/timeout.ts @@ -3,11 +3,14 @@ * * Two separate bounds exist, because they cover different phases: * - * 1. `armBodyDeadline` — armed in `preParsing`, i.e. before Fastify reads the - * request body, and cleared as soon as the body has been parsed. It bounds - * *body receipt*: without it a caller can open a connection and dribble a - * body forever (an idle socket timer never fires while bytes keep arriving) - * while the gateway buffers up to `bodyLimitBytes` per connection. + * 1. `armBodyDeadline` — armed in the earliest `onRequest` hook, i.e. before + * Fastify reads the request body, and cleared as soon as the body has been + * parsed. It bounds *body receipt*: without it a caller can open a connection + * and dribble a body forever (an idle socket timer never fires while bytes + * keep arriving) while the gateway buffers up to `bodyLimitBytes` per + * connection. It must be armed before the authenticator: Fastify runs + * `preParsing` only while no earlier hook has ended the request, so a + * deadline armed there never protects a request rejected with a `401`. * 2. `applyRequestTimeout` — applied in `preHandler`, i.e. after the body is * known, and only for buffered requests. A buffered completion may not hold * a connection (and an upstream turn) forever, while an SSE response must @@ -66,6 +69,12 @@ export function clearBodyDeadline(request: FastifyRequest): void { * `reply.raw` closes, so a long `stream: true` completion — whose body was * received in milliseconds — is never destroyed by this deadline. * + * The close hook keeps the deadline only when the body never arrived in full. A + * request the authenticator rejected still has its response `close` while the + * client is dribbling the body, and that is exactly the connection this bound + * exists to reclaim; a request whose `IncomingMessage` is already `complete` has + * a deadline that is irrelevant from here on either way. + * * The timer is `unref`'d, so a pending deadline never keeps the process alive. */ export function armBodyDeadline( @@ -89,6 +98,10 @@ export function armBodyDeadline( bodyDeadlines.set(request, timer); reply.raw.once("close", () => { + // `complete` is false while the request body is still arriving. Disarming + // here would hand the dribbler back the connection it never finished: the + // response is already sent, so nothing else would ever release it. + if (request.raw.complete === false) return; clearBodyDeadline(request); }); } diff --git a/src/index.ts b/src/index.ts index 3147b0d..e01f6d7 100644 --- a/src/index.ts +++ b/src/index.ts @@ -22,7 +22,7 @@ import { ModelRegistry } from "./upstream/models.js"; import { UpstreamProcess } from "./upstream/process.js"; import { SessionStore } from "./upstream/sessions.js"; import { SERVICE_NAME, VERSION } from "./version.js"; -import { defaultApiKeyNote, defaultKeyExposureError, privateMediaUrlWarning } from "./startup.js"; +import { defaultApiKeyNote, defaultKeyExposureError, metricsPublicWarning, privateMediaUrlWarning } from "./startup.js"; /** Directory holding this file: `/dist` when built, `/src` under tsx. */ const moduleDir = path.dirname(fileURLToPath(import.meta.url)); @@ -81,6 +81,14 @@ async function main(): Promise { process.stderr.write(`\n${privateMediaWarning}\n\n`); } + const metricsWarning = metricsPublicWarning(config); + if (metricsWarning !== undefined) { + // Same class as the note above: an operator choice with a security + // consequence, reported loudly and never fatal. + log.error({ host: config.host, metricsPublic: true }, "the metrics endpoint is anonymous on a reachable host"); + process.stderr.write(`\n${metricsWarning}\n\n`); + } + const metrics = createMetrics({ enabled: config.metricsEnabled }); const upstream = new UpstreamProcess(config, log, metrics); const client = new OpencodeClient(upstream, config, log, metrics); diff --git a/src/server.ts b/src/server.ts index f01e59c..b8addc9 100644 --- a/src/server.ts +++ b/src/server.ts @@ -121,6 +121,18 @@ export async function buildServer(ctx: AppContext): Promise { forceCloseConnections: "idle", }) as unknown as FastifyInstance; + // ------------------------------------------------------------- timeout --- + // Body receipt is bounded before Fastify reads a single byte. This has to be an + // `onRequest` hook, and the *first* one: Fastify runs `preParsing` only when no + // earlier hook ended the request (`runPreParsing()` returns as soon as + // `reply.sent` is true), and both authentication and the rate limiter reject + // from `onRequest` below. Arming later left an anonymous caller's incomplete + // body — the slow-dribble case `OPENCODE_BODY_TIMEOUT_MS` documents — with no + // deadline at all, holding a socket and its buffers for free. + app.addHook("onRequest", async (request, reply) => { + armBodyDeadline(request, reply, ctx.config); + }); + // Every response — JSON, error and SSE alike — carries the request id. app.addHook("onRequest", async (request, reply) => { reply.header("x-request-id", request.id); @@ -204,14 +216,6 @@ export async function buildServer(ctx: AppContext): Promise { }), ); - // ------------------------------------------------------------- timeout --- - // Body receipt is bounded before Fastify reads a single byte: the deadline is - // armed in `preParsing` and cancelled as soon as the body is complete, so a - // caller cannot dribble a body forever while the gateway buffers it. - app.addHook("preParsing", async (request, reply) => { - armBodyDeadline(request, reply, ctx.config); - }); - // Buffered routes get a bounded socket timeout; streaming routes stay // unbounded so a long SSE answer is never cut off. This must stay a // `preHandler` because the bound depends on the parsed request body. Clearing diff --git a/src/startup.ts b/src/startup.ts index b4102ce..dd20dbf 100644 --- a/src/startup.ts +++ b/src/startup.ts @@ -86,3 +86,33 @@ export function privateMediaUrlWarning(config: { host: string; allowPrivateMedia "Set OPENCODE_ALLOW_PRIVATE_MEDIA_URLS=false unless every media URL source is trusted." ); } + +/** + * Warning printed when `/metrics` is anonymous on a host reachable from the + * network. + * + * `OPENCODE_METRICS_PUBLIC` is documented as safe only on a loopback bind, but — + * unlike the private-media switch beside it — it used to be honoured silently. + * The endpoint then publishes model names, per-route traffic, token volumes, the + * session-cache size and the instance id to anyone who can reach the port. The + * gateway does not refuse to start: publishing metrics is a deliberate choice, + * and the operator is told exactly what it means. A configured + * `OPENCODE_METRICS_TOKEN` re-authenticates the endpoint, so it silences the + * warning. + */ +export function metricsPublicWarning(config: { + host: string; + metricsEnabled: boolean; + metricsPublic: boolean; + metricsToken?: string; +}): string | undefined { + if (!config.metricsEnabled || !config.metricsPublic || config.metricsToken !== undefined) return undefined; + if (isLoopbackHost(config.host)) return undefined; + return ( + `OPENCODE_METRICS_PUBLIC is enabled while HOST=${config.host}, which is reachable from the network, and no ` + + "OPENCODE_METRICS_TOKEN is configured.\n" + + "Anonymous callers can read model names, route traffic and token volumes, the session-cache size and the " + + "instance id from GET /metrics.\n" + + "Set OPENCODE_METRICS_TOKEN (or bind HOST=127.0.0.1) unless the endpoint really is public." + ); +} diff --git a/test/admin.test.ts b/test/admin.test.ts index 81bf832..da57852 100644 --- a/test/admin.test.ts +++ b/test/admin.test.ts @@ -10,7 +10,7 @@ * the always-on failed-authentication limiter and the paths the request * limiter must never touch. */ -import { request as httpRequest } from "node:http"; +import { Agent, request as httpRequest } from "node:http"; import type { AddressInfo, Socket } from "node:net"; import pino, { type DestinationStream } from "pino"; import { describe, expect, it, vi } from "vitest"; @@ -402,12 +402,15 @@ interface SlowBody { } /** - * Send an authenticated chunked body that never finishes. + * Send a chunked body that never finishes. * * The body keeps growing, so the socket is never idle: an idle socket timer * cannot catch this, which is exactly why the body deadline is wall-clock. + * + * `headers` defaults to the authenticated set; `gapMs` widens the interval + * between chunks for a test that must outlive several configured deadlines. */ -function sendUnterminatedBody(port: number): SlowBody { +function sendUnterminatedBody(port: number, headers: Record = AUTH, gapMs = 10): SlowBody { let ready: (socket: Socket) => void = () => undefined; const socket = new Promise((resolve) => { ready = resolve; @@ -428,7 +431,7 @@ function sendUnterminatedBody(port: number): SlowBody { port, method: "POST", path: "/v1/chat/completions", - headers: { ...AUTH, "content-type": "application/json", "transfer-encoding": "chunked" }, + headers: { ...headers, "content-type": "application/json", "transfer-encoding": "chunked" }, }, (response) => { // A response means the body was accepted, which this test never expects. @@ -443,7 +446,7 @@ function sendUnterminatedBody(port: number): SlowBody { }); const ticker = setInterval(() => { request.write('10\r\n{"model":"x"}\r\n'); - }, 10); + }, gapMs); }); return { closed, socket }; @@ -467,6 +470,71 @@ describe("OPENCODE_BODY_TIMEOUT_MS bounds body receipt (SEC-14)", () => { await app.close(); } }); + + it("also bounds a body the authenticator already rejected", async () => { + // The 401 is sent from an `onRequest` hook, so Fastify never reaches + // `preParsing`: a deadline armed there would never be installed and the + // unauthenticated dribbler would hold the socket for free. + const ctx = createTestContext({ config: { bodyTimeoutMs: 300 } }); + const app = await buildServer(ctx); + await app.listen({ host: "127.0.0.1", port: 0 }); + const address = app.server.address() as AddressInfo; + const body = sendUnterminatedBody(address.port, {}); + try { + const outcome = await Promise.race([ + body.closed.then(() => "closed" as const), + new Promise<"still-open">((resolve) => setTimeout(() => resolve("still-open"), 1500)), + ]); + expect(outcome).toBe("closed"); + } finally { + (await body.socket).destroy(); + await app.close(); + } + }); + + it("leaves a keep-alive connection usable after the body was received", async () => { + // The control for the fix above: a request whose body did arrive must disarm + // the deadline, or a second request on the same connection — and a long + // `stream: true` response — would be destroyed after `bodyTimeoutMs`. + const ctx = createTestContext({ config: { bodyTimeoutMs: 200 } }); + const app = await buildServer(ctx); + await app.listen({ host: "127.0.0.1", port: 0 }); + const address = app.server.address() as AddressInfo; + + const responses: number[] = []; + const agent = new Agent({ keepAlive: true, maxSockets: 1 }); + const call = (): Promise => + new Promise((resolve, reject) => { + const request = httpRequest( + { + host: "127.0.0.1", + port: address.port, + method: "POST", + path: "/v1/models", + agent, + headers: { ...AUTH, "content-type": "application/json", "content-length": "2" }, + }, + (response) => { + response.resume(); + response.on("end", () => resolve(response.statusCode ?? 0)); + }, + ); + request.on("error", reject); + request.end("{}"); + }); + + try { + responses.push(await call()); + // Well past the configured deadline: a stale timer would have destroyed + // the pooled socket by now. + await new Promise((resolve) => setTimeout(resolve, 500)); + responses.push(await call()); + expect(responses).toEqual([404, 404]); + } finally { + agent.destroy(); + await app.close(); + } + }); }); describe("the body deadline never outlives body receipt (SEC-14)", () => { diff --git a/test/config.test.ts b/test/config.test.ts index 8f3af48..0794143 100644 --- a/test/config.test.ts +++ b/test/config.test.ts @@ -237,6 +237,28 @@ describe("explicitly empty key configuration", () => { }); }); +describe("OPENCODE_SERVER_URL", () => { + it("accepts a credential-free URL and passes it through unchanged", () => { + setEnv("OPENCODE_SERVER_URL", "http://10.0.0.5:20124"); + expect(config().upstreamUrl).toBe("http://10.0.0.5:20124"); + }); + + it("refuses a URL that embeds credentials, without echoing them", () => { + // Node rejects a request whose URL carries userinfo, so such a deployment + // could never reach its upstream — while the password travelled into every + // caller-visible failure message and into /admin/config and /admin/status. + setEnv("OPENCODE_SERVER_URL", "http://opencode:supersecret@10.0.0.5:20124"); + let thrown: Error | undefined; + try { + config(); + } catch (error) { + thrown = error as Error; + } + expect(thrown?.message).toMatch(/OPENCODE_SERVER_URL/); + expect(thrown?.message).not.toContain("supersecret"); + }); +}); + describe(".env.example", () => { const EXPECTED_ACTIVE = new Map([ ["OPENCODE_API_KEYS", DEFAULT_API_KEY], diff --git a/test/startup.test.ts b/test/startup.test.ts index 30cc623..9d810b3 100644 --- a/test/startup.test.ts +++ b/test/startup.test.ts @@ -12,6 +12,7 @@ import { defaultApiKeyNote, defaultKeyExposureError, isLoopbackHost, + metricsPublicWarning, privateMediaUrlWarning, } from "../src/startup.js"; @@ -71,6 +72,24 @@ describe("existing notes stay unchanged in shape", () => { }); }); +describe("metricsPublicWarning", () => { + const EXPOSED_METRICS = { host: "0.0.0.0", metricsEnabled: true, metricsPublic: true }; + + it("warns when /metrics is anonymous on a reachable host", () => { + const message = metricsPublicWarning(EXPOSED_METRICS); + expect(message).toBeDefined(); + expect(message).toContain("HOST=0.0.0.0"); + expect(message).toContain("OPENCODE_METRICS_TOKEN"); + }); + + it("stays silent on a loopback bind, with a token, or when metrics are off", () => { + expect(metricsPublicWarning({ ...EXPOSED_METRICS, host: "127.0.0.1" })).toBeUndefined(); + expect(metricsPublicWarning({ ...EXPOSED_METRICS, metricsToken: "scrape-secret" })).toBeUndefined(); + expect(metricsPublicWarning({ ...EXPOSED_METRICS, metricsEnabled: false })).toBeUndefined(); + expect(metricsPublicWarning({ ...EXPOSED_METRICS, metricsPublic: false })).toBeUndefined(); + }); +}); + describe("entry point ordering (COR-10)", () => { it("registers the shutdown signals, including SIGHUP, before the upstream warm-up", () => { // The entry point cannot be driven in a unit test without starting a real From 21d8b3e79a44c64b8e90bce1083ad6f98adbf172 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 14:49:15 +0700 Subject: [PATCH 02/10] fix(streaming): close response items and the anthropic block in order `/v1/responses` emitted the closing frames of an item in block order (reasoning, then message) while `output_index` is fixed when the item is announced. A turn that streams text before its reasoning announces the message at index 0 and the reasoning item at index 1, so the `response.output_item.done` frames arrived as 1,1,1,0,0,0 while the terminal `response.output` was sorted by index: a client assembling `output[]` from the `.done` frames got the reverse of one reading the result object. Each item now records its closing frames and they are emitted in ascending index order. `/v1/messages` returned as soon as it had written the terminal `error` frame for a failed turn, before flushing the withheld text and closing the blocks the turn had opened. An SDK that assembles the message on `content_block_stop` never finished it. The block is closed before the error event; no `message_delta`/`message_stop` is added, which `docs/API.md` forbids on that path. --- docs/API.md | 7 ++ src/adapter/anthropic/messages.ts | 6 ++ src/adapter/openai/responses.ts | 120 ++++++++++++++++++------------ test/anthropic.test.ts | 15 ++++ test/openai-responses.test.ts | 13 ++++ 5 files changed, 114 insertions(+), 47 deletions(-) diff --git a/docs/API.md b/docs/API.md index 2ec1d8a..df0f96c 100644 --- a/docs/API.md +++ b/docs/API.md @@ -457,6 +457,13 @@ data: {"type":"response.completed","sequence_number":8,"response":{"id":"resp_.. `response.function_call_arguments.delta` carrying the whole argument string, `response.function_call_arguments.done`, then `response.output_item.done` with status `completed`. +* Every `response.output_item.done` frame is emitted in ascending `output_index` + order, and the sequence of their `item.id` values equals + `response.completed.response.output` exactly. A turn that produces text before + its reasoning therefore announces the message at `output_index: 0` and the + reasoning item at `output_index: 1`, and closes them in that order too: a + client that assembles `output[]` from the `.done` frames sees the same array as + one that reads the terminal object. * A length-limited turn ends with `event: response.incomplete` instead of `response.completed`. So does a turn the provider filtered: the response object then reports `status: "incomplete"` with diff --git a/src/adapter/anthropic/messages.ts b/src/adapter/anthropic/messages.ts index ea2afda..1a32411 100644 --- a/src/adapter/anthropic/messages.ts +++ b/src/adapter/anthropic/messages.ts @@ -1326,6 +1326,12 @@ async function streamAnthropicMessage( // status is already committed, so the failure travels as an `error` event // instead of a synthetic `end_turn` the caller would read as success. if (finishReason === "error") { + // Whatever the step already delivered is still real content, and clients + // accumulate `content_block_stop` to assemble the message. Returning + // before this left every block opened during the turn dangling, so a + // failure after a text delta produced a stream the SDK could not close. + sendText(stopFilter.flush()); + closeOpen(); send( anthropicErrorFrame( new ApiError(502, "upstream_error", "The OpenCode turn failed before it could complete.", { diff --git a/src/adapter/openai/responses.ts b/src/adapter/openai/responses.ts index c43ca28..9fcc9f1 100644 --- a/src/adapter/openai/responses.ts +++ b/src/adapter/openai/responses.ts @@ -1698,6 +1698,18 @@ function finaliseStream(writer: SseWriter, prepared: Prepared, state: StreamStat // `response.completed` payload must reuse these exact ids, shapes and indexes, // not regenerate them, or clients cannot correlate the stream with the result. const items: Array<{ index: number; item: ResponseOutputItem }> = []; + /** + * An announced item's closing frames, held back until every item is known. + * + * The blocks below are written in a fixed order (reasoning, message, function + * calls), but an item's `output_index` is fixed when it is *announced*, and a + * turn that emits text before its reasoning announces the message first. Sending + * the held-back frames in block order then closed index 1 before index 0, while + * the terminal `output[]` is sorted by index — a client reading the `.done` + * frames and one reading the result object disagreed. The thunks keep each + * item's internal frame order (text, part, item) and only the items are sorted. + */ + const closings: Array<{ index: number; emit: () => void }> = []; const incompleteReasonForTurn = incompleteReason(state.finishReason); const failed = state.finishReason === "error"; @@ -1708,67 +1720,81 @@ function finaliseStream(writer: SseWriter, prepared: Prepared, state: StreamStat if (state.reasoningVisible && state.reasoningIndex !== undefined) { const outputIndex = state.reasoningIndex; const reasoningText = streamReasoning(state); + const reasoningClosed = state.reasoningClosed; // The summary is closed here rather than on every `reasoning_end`: upstream // emits one end event per step, and closing per step emitted several `.done` // frames for the same `summary_index`, each with a partial snapshot. - if (!state.reasoningClosed) { - state.reasoningClosed = true; - emitFrame(writer, state, "response.reasoning_summary_text.done", (sequence) => ({ - type: "response.reasoning_summary_text.done", - sequence_number: sequence, - item_id: state.reasoningId, - output_index: outputIndex, - summary_index: 0, - text: reasoningText, - })); - emitFrame(writer, state, "response.reasoning_summary_part.done", (sequence) => ({ - type: "response.reasoning_summary_part.done", - sequence_number: sequence, - item_id: state.reasoningId, - output_index: outputIndex, - summary_index: 0, - part: { type: "summary_text", text: reasoningText }, - })); - } + state.reasoningClosed = true; const item = reasoningItem(state.reasoningId, reasoningText, "completed"); - emitFrame(writer, state, "response.output_item.done", (sequence) => ({ - type: "response.output_item.done", - sequence_number: sequence, - output_index: outputIndex, - item, - })); + closings.push({ + index: outputIndex, + emit: () => { + if (!reasoningClosed) { + emitFrame(writer, state, "response.reasoning_summary_text.done", (sequence) => ({ + type: "response.reasoning_summary_text.done", + sequence_number: sequence, + item_id: state.reasoningId, + output_index: outputIndex, + summary_index: 0, + text: reasoningText, + })); + emitFrame(writer, state, "response.reasoning_summary_part.done", (sequence) => ({ + type: "response.reasoning_summary_part.done", + sequence_number: sequence, + item_id: state.reasoningId, + output_index: outputIndex, + summary_index: 0, + part: { type: "summary_text", text: reasoningText }, + })); + } + emitFrame(writer, state, "response.output_item.done", (sequence) => ({ + type: "response.output_item.done", + sequence_number: sequence, + output_index: outputIndex, + item, + })); + }, + }); items.push({ index: outputIndex, item }); } if (state.messageStarted && state.messageIndex !== undefined) { const outputIndex = state.messageIndex; const text = streamText(state); - emitFrame(writer, state, "response.output_text.done", (sequence) => ({ - type: "response.output_text.done", - sequence_number: sequence, - item_id: state.messageId, - output_index: outputIndex, - content_index: 0, - text, - })); - emitFrame(writer, state, "response.content_part.done", (sequence) => ({ - type: "response.content_part.done", - sequence_number: sequence, - item_id: state.messageId, - output_index: outputIndex, - content_index: 0, - part: { type: "output_text", text, annotations: [] }, - })); const item = messageItem(state.messageId, text, messageStatus); - emitFrame(writer, state, "response.output_item.done", (sequence) => ({ - type: "response.output_item.done", - sequence_number: sequence, - output_index: outputIndex, - item, - })); + closings.push({ + index: outputIndex, + emit: () => { + emitFrame(writer, state, "response.output_text.done", (sequence) => ({ + type: "response.output_text.done", + sequence_number: sequence, + item_id: state.messageId, + output_index: outputIndex, + content_index: 0, + text, + })); + emitFrame(writer, state, "response.content_part.done", (sequence) => ({ + type: "response.content_part.done", + sequence_number: sequence, + item_id: state.messageId, + output_index: outputIndex, + content_index: 0, + part: { type: "output_text", text, annotations: [] }, + })); + emitFrame(writer, state, "response.output_item.done", (sequence) => ({ + type: "response.output_item.done", + sequence_number: sequence, + output_index: outputIndex, + item, + })); + }, + }); items.push({ index: outputIndex, item }); } + // Close the already-announced items in the order they were announced. + for (const closing of [...closings].sort((left, right) => left.index - right.index)) closing.emit(); + // Function calls are the only items still opened at finalisation time, so they // continue the announcement order after whatever was emitted before. let nextIndex = items.reduce((highest, entry) => Math.max(highest, entry.index + 1), 0); diff --git a/test/anthropic.test.ts b/test/anthropic.test.ts index 41347b2..df2abd7 100644 --- a/test/anthropic.test.ts +++ b/test/anthropic.test.ts @@ -1411,6 +1411,21 @@ describe("failed and cancelled turns (A6)", () => { const payload = JSON.parse(frames.at(-1)?.data ?? "{}") as AnthropicErrorBody; expect(payload.type).toBe("error"); expect(payload.error.type).toBe("api_error"); + + // The text the step already delivered stays real content, and every block + // the turn opened has to be closed: returning early left the block dangling, + // so an SDK that assembles the message on `content_block_stop` never + // finished it. + const frameEvents = frames.map((frame) => frame.event); + expect(frameEvents.filter((event) => event?.startsWith("content_block") === true)).toEqual([ + "content_block_start", + "content_block_delta", + "content_block_stop", + ]); + const closing = frames.find((frame) => frame.event === "content_block_stop"); + expect(JSON.parse(closing?.data ?? "{}")).toMatchObject({ type: "content_block_stop", index: 0 }); + expect(frameEvents).not.toContain("message_delta"); + expect(frameEvents).not.toContain("message_stop"); }); it("keeps `cancelled` as end_turn but flags it as interrupted on both paths", async () => { diff --git a/test/openai-responses.test.ts b/test/openai-responses.test.ts index 031e8dd..d44ac6b 100644 --- a/test/openai-responses.test.ts +++ b/test/openai-responses.test.ts @@ -1730,6 +1730,19 @@ describe("POST /v1/responses (streaming)", () => { expect(final.output[0]?.content?.[0]?.text).toBe("Answer first."); expect(final.output[1]?.summary).toEqual([{ type: "summary_text", text: "thinking harder" }]); expect(final.output_text).toBe("Answer first."); + + // The closing frames follow the same order as the terminal `output[]`. They + // used to be emitted in the fixed reasoning/message block order, so a client + // that assembled items from `response.output_item.done` got the reverse of a + // client that read `response.completed.response.output`. + const doneIndexes = parsed + .filter((frame) => frame.json["type"] === "response.output_item.done") + .map((frame) => frame.json["output_index"]); + expect(doneIndexes).toEqual([0, 1]); + const doneIds = parsed + .filter((frame) => frame.json["type"] === "response.output_item.done") + .map((frame) => (frame.json["item"] as ResponseItem).id); + expect(doneIds).toEqual(final.output.map((item) => item.id)); }); it("adopts a step-level reasoning_end only when it is longer than the streamed deltas", async () => { From 87bcbf0e7d77733f17a4aefdebafae8ee5f1fa30 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 14:49:24 +0700 Subject: [PATCH 03/10] fix(reasoning): count reasoning tokens inside the output total `toUsage()` computed `totalTokens` as input + output + reasoning, while every surface derives its wire `total_tokens` (and Anthropic `output_tokens`) as prompt + completion with the thinking tokens already inside completion, which is what `docs/API.md` documents. The field is internal and unread today, so nothing on the wire changes; it is the value every future surface would read, and it was arithmetically inconsistent with the payloads built from the same event. --- docs/ARCHITECTURE.md | 3 ++ src/adapter/common/usage.ts | 11 +++++- test/usage.test.ts | 74 +++++++++++++++++++++++++++++++++++++ 3 files changed, 86 insertions(+), 2 deletions(-) create mode 100644 test/usage.test.ts diff --git a/docs/ARCHITECTURE.md b/docs/ARCHITECTURE.md index d18e297..537d21d 100644 --- a/docs/ARCHITECTURE.md +++ b/docs/ARCHITECTURE.md @@ -435,6 +435,9 @@ renderToolResult(message): string, class ToolCallFilter(allowedNames?: Iterable< // declared, so the check runs once for every surface. // usage.ts +// `Usage.totalTokens` is `inputTokens + outputTokens`: `reasoningTokens` is a +// subset of `outputTokens`, which is why every surface derives its wire +// `total_tokens` (and Anthropic `output_tokens`) the same way. EMPTY_USAGE, toUsage(tokens), addUsage(a, b), estimateTokens(text), estimateConversationTokens(parts) ``` diff --git a/src/adapter/common/usage.ts b/src/adapter/common/usage.ts index f8b4d03..5901ec5 100644 --- a/src/adapter/common/usage.ts +++ b/src/adapter/common/usage.ts @@ -6,7 +6,14 @@ import type { OpencodeTokenUsage } from "../../types/opencode.js"; export { EMPTY_USAGE }; -/** Convert upstream token accounting into the normalised shape. */ +/** + * Convert upstream token accounting into the normalised shape. + * + * `reasoningTokens` is a *subset* of `outputTokens` — every surface derives its + * wire total as `prompt + completion` with the thinking tokens counted inside + * `completion` (`docs/API.md` §Usage) — so `totalTokens` must not add it a second + * time. + */ export function toUsage(tokens: OpencodeTokenUsage | undefined): Usage { if (!tokens) return { ...EMPTY_USAGE }; const inputTokens = numberOrZero(tokens.input); @@ -20,7 +27,7 @@ export function toUsage(tokens: OpencodeTokenUsage | undefined): Usage { reasoningTokens, cacheReadTokens, cacheWriteTokens, - totalTokens: inputTokens + outputTokens + reasoningTokens, + totalTokens: inputTokens + outputTokens, }; } diff --git a/test/usage.test.ts b/test/usage.test.ts new file mode 100644 index 0000000..3e9ac2e --- /dev/null +++ b/test/usage.test.ts @@ -0,0 +1,74 @@ +/** + * Token accounting shared by every surface. + * + * `toUsage()` is the only conversion from the upstream `tokens` object into the + * normalised `Usage`, so the invariants the surfaces derive their wire values + * from are pinned here: reasoning is a subset of output, and `totalTokens` is the + * plain `prompt + completion` sum the OpenAI and Anthropic payloads document. + */ +import { describe, expect, it } from "vitest"; +import { EMPTY_USAGE, addUsage, toUsage } from "../src/adapter/common/usage.js"; + +describe("toUsage", () => { + it("counts reasoning inside output instead of adding it again", () => { + const usage = toUsage({ + input: 21, + output: 9, + reasoning: 4, + cache: { read: 3, write: 1 }, + }); + + expect(usage).toEqual({ + inputTokens: 21, + outputTokens: 9, + reasoningTokens: 4, + cacheReadTokens: 3, + cacheWriteTokens: 1, + // 21 + 9, not 21 + 9 + 4: every surface derives its wire `total_tokens` as + // `prompt + completion` with the thinking tokens already inside output. + totalTokens: 30, + }); + }); + + it("returns a fresh zeroed record when the upstream reports no tokens", () => { + const usage = toUsage(undefined); + expect(usage).toEqual(EMPTY_USAGE); + // Never the frozen singleton: callers accumulate into it with `addUsage`. + expect(usage).not.toBe(EMPTY_USAGE); + }); + + it("ignores values that are not finite numbers", () => { + const usage = toUsage({ + input: Number.NaN, + output: Number.POSITIVE_INFINITY, + reasoning: 5, + cache: { read: undefined as unknown as number, write: 2 }, + }); + expect(usage).toEqual({ + inputTokens: 0, + outputTokens: 0, + reasoningTokens: 5, + cacheReadTokens: 0, + cacheWriteTokens: 2, + totalTokens: 0, + }); + }); +}); + +describe("addUsage", () => { + it("keeps the total equal to the summed parts", () => { + const first = toUsage({ input: 10, output: 4, reasoning: 3, cache: { read: 1, write: 0 } }); + const second = toUsage({ input: 5, output: 6, reasoning: 2, cache: { read: 0, write: 1 } }); + const summed = addUsage(first, second); + + expect(summed.totalTokens).toBe(summed.inputTokens + summed.outputTokens); + expect(summed).toEqual({ + inputTokens: 15, + outputTokens: 10, + reasoningTokens: 5, + cacheReadTokens: 1, + cacheWriteTokens: 1, + totalTokens: 25, + }); + }); +}); From 52e77b320fe02f78bd8c1bd458f06b2ac6ea0a4d 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 14:49:41 +0700 Subject: [PATCH 04/10] perf(upstream): hash one session prefix pass and keep stderr lines `acquire()` joined and SHA-256'd one candidate's delivered prefix at a time, so a conversation under the full `MAX_CANDIDATES_PER_ROOT` records was re-serialised once per candidate - with base64 media, megabytes of avoidable copying per turn on the request path. The candidates' prefixes are nested, so one ascending pass now feeds a single hash stream and takes `Hash#copy().digest()` per length. The byte stream is unchanged, so persisted `prefixHash` values stay compatible. `StderrTail.push()` clamped the whole chunk to 8 KiB before splitting, which discarded every complete line a burst carried; splitting now walks back from the last terminator, so `/admin/status` keeps the last 50 lines it documents. The log-file redaction boundary scan is bounded to the suffix that can still grow into a marker, and the marker patterns are compiled once instead of per chunk, matching the documented promise that a chatty long-lived child costs no per-chunk full scan. An `UpstreamProcess` is dropped from the process-exit registry once it owns no child and has no start in flight; the registry is re-armed on the next spawn, so a host that builds and disposes gateways with the non-terminal `stop()` no longer retains each one. --- src/upstream/process.ts | 110 ++++++++++++++++++++++++++++---- src/upstream/sessions.ts | 109 +++++++++++++++++++++++++++++-- test/process.test.ts | 32 ++++++++++ test/sessions.test.ts | 35 +++++++++- test/upstream-proposals.test.ts | 21 ++++++ 5 files changed, 288 insertions(+), 19 deletions(-) diff --git a/src/upstream/process.ts b/src/upstream/process.ts index bdcd389..3e78c1b 100644 --- a/src/upstream/process.ts +++ b/src/upstream/process.ts @@ -178,12 +178,37 @@ export class StderrTail { } push(chunk: string): void { - // Clamp before splitting so the buffer never grows past the cap, and each - // splice below stays O(partial) instead of O(total bytes ever written). - this.#partial = clampTail(this.#partial + chunk, STDERR_PARTIAL_LIMIT_CHARS); - const parts = this.#partial.split("\n"); - this.#partial = parts.pop() ?? ""; - for (const part of parts) this.#append(part.replace(/\r$/, "")); + const pending = this.#partial + chunk; + // Only the newest lines matter (the ring keeps `#limit`), so walk back from + // the end and split just that suffix: clamping the whole chunk to 8 KiB + // before splitting used to discard every complete line a burst carried, so + // `/admin/status` showed a truncated blob instead of the last 50 lines. + const lastTerminator = pending.lastIndexOf("\n"); + if (lastTerminator === -1) { + // No complete line in this chunk: everything is still the partial tail. + this.#partial = clampTail(pending, STDERR_PARTIAL_LIMIT_CHARS); + return; + } + + // Whatever follows the final terminator has no newline yet: the partial tail. + this.#partial = clampTail(pending.slice(lastTerminator + 1), STDERR_PARTIAL_LIMIT_CHARS); + + // `found` is newest-first; the ring is a ring, but `lines` is documented and + // tested in chronological order. Only `#limit + 1` terminators are walked: + // anything older could never reach the ring. + const found: string[] = []; + let terminator = lastTerminator; + while (found.length < this.#limit + 1) { + const previous = pending.lastIndexOf("\n", terminator - 1); + const line = pending.slice(previous + 1, terminator).replace(/\r$/, ""); + found.push(clampTail(line, STDERR_PARTIAL_LIMIT_CHARS)); + if (previous === -1) break; + terminator = previous; + } + for (let index = found.length - 1; index >= 0; index -= 1) { + const line = found[index]; + if (line !== undefined) this.#append(line); + } } get lines(): string[] { @@ -211,6 +236,31 @@ function clampTail(value: string, limit: number): string { return value.length > limit ? value.slice(-limit) : value; } +/** + * Longest window of `text` that `partialMarkerLength()` has to inspect. + * + * A marker is a short literal, and the "marker + whitespace" alternative only + * matches a suffix, so nothing beyond the longest marker plus a run of trailing + * whitespace can change the answer. Bounding the window keeps a chatty long-lived + * child from lower-casing and regex-scanning every chunk in full; scanning a + * shorter window can only make the held tail *longer* (never a partial marker), + * which is the safe direction. + */ +const PARTIAL_MARKER_WINDOW = 96; + +/** Longer-window-safe suffix of `text`, for the boundary check. */ +function markerWindow(text: string): string { + return text.length > PARTIAL_MARKER_WINDOW ? text.slice(-PARTIAL_MARKER_WINDOW) : text; +} + +/** + * `marker\s+$` alternatives, compiled once. + * + * The boundary check runs for every chunk of the child's output, so building a + * fresh `RegExp` per marker per chunk was pure overhead. + */ +const PARTIAL_MARKER_PATTERNS: readonly RegExp[] = LOG_MARKERS.map((marker) => new RegExp(`${marker}\\s+$`)); + /** * Length of the longest suffix of `text` that could still grow into a marker. * @@ -218,6 +268,9 @@ function clampTail(value: string, limit: number): string { * write boundary must never fall inside `server password` or * `authorization: Basic` — otherwise the head of the marker reaches the disk * and the tail is redacted on its own, which leaves the credential readable. + * + * Only a suffix can matter, so callers pass a bounded window (`markerWindow`); + * the "marker followed by whitespace" alternative is likewise anchored at the end. */ function partialMarkerLength(text: string): number { const lower = text.toLowerCase(); @@ -227,9 +280,11 @@ function partialMarkerLength(text: string): number { for (let size = limit; size > longest; size -= 1) { if (lower.endsWith(marker.slice(0, size))) longest = size; } - // A marker followed by whitespace is still incomplete: the value the regex - // consumes has not arrived yet. - const spaced = new RegExp(`${marker}\\s+$`).exec(lower); + } + // A marker followed by whitespace is still incomplete: the value the regex + // consumes has not arrived yet. + for (const pattern of PARTIAL_MARKER_PATTERNS) { + const spaced = pattern.exec(lower); if (spaced) longest = Math.max(longest, spaced[0].length); } return longest; @@ -265,6 +320,18 @@ export class UpstreamProcess { static readonly #liveInstances = new Set(); static #exitHookInstalled = false; + /** + * Number of instances the process-exit hook still holds, exposed for tests. + * + * An instance is dropped once it has no live child and no start in flight, so a + * host that builds and disposes gateways with the deliberately non-terminal + * `stop()` does not retain each one (config, logger, metrics, stderr tail) for + * the lifetime of the process. It is installed again on the next spawn. + */ + static get liveInstanceCount(): number { + return UpstreamProcess.#liveInstances.size; + } + readonly #config: Config; readonly #log: Logger; readonly #metrics: Metrics; @@ -818,8 +885,10 @@ export class UpstreamProcess { if (!logActive) return; const pending = redactionCarry + chunk; const boundary = Math.max(0, pending.length - LOG_REDACTION_CARRY_CHARS); - // Never write a partial marker: the boundary moves back over it. - const hold = partialMarkerLength(pending.slice(0, boundary)); + // Never write a partial marker: the boundary moves back over it. Only the + // window before the boundary can still grow into one, so the scan does not + // touch the whole chunk. + const hold = partialMarkerLength(markerWindow(pending.slice(0, boundary))); const writeable = pending.slice(0, boundary - hold); redactionCarry = pending.slice(writeable.length); if (writeable.length > 0) logStream.write(redactUpstreamSecret(writeable)); @@ -923,6 +992,7 @@ export class UpstreamProcess { flushLog(); logStream.end(); finish(error); + this.#releaseExitHookIfIdle(); }); child.once("exit", (code, signal) => { flushLog(); @@ -935,9 +1005,11 @@ export class UpstreamProcess { `stderr: ${redactUpstreamSecret(stderr.text.trim().slice(-500))}`, ), ); + this.#releaseExitHookIfIdle(); return; } if (wasHandedOff) this.#onChildExit(child, code, signal); + this.#releaseExitHookIfIdle(); }); }); } @@ -960,6 +1032,22 @@ export class UpstreamProcess { }); } + /** + * Drop this instance from the exit-hook registry once it owns no child. + * + * The hook exists to SIGKILL a live child at process exit, so an instance with + * nothing left to kill has no reason to be retained. Without this, every + * instance a long-lived host builds and disposes with `stop()` (which is + * deliberately non-terminal) stayed in the static set forever, holding its + * config, logger, metrics and stderr tail. + * + * Idempotent, and `#installExitHook()` re-adds the instance on the next spawn. + */ + #releaseExitHookIfIdle(): void { + if (this.#liveChildren.size > 0 || this.#starting !== undefined) return; + UpstreamProcess.#liveInstances.delete(this); + } + /** SIGKILL every child this instance spawned that is still alive, except `skip`. */ #killLiveChildren(skip?: SpawnedChild): void { for (const child of this.#liveChildren) { diff --git a/src/upstream/sessions.ts b/src/upstream/sessions.ts index 93d6888..4f5be17 100644 --- a/src/upstream/sessions.ts +++ b/src/upstream/sessions.ts @@ -13,7 +13,7 @@ * keeps two clients that opened with the same prompt from evicting each other; * the prefix check picks the right candidate. */ -import { createHash } from "node:crypto"; +import { createHash, type Hash } from "node:crypto"; import fs from "node:fs"; import path from "node:path"; import type { Config } from "../config.js"; @@ -37,6 +37,18 @@ const UNKNOWN_PERMISSION_PROFILE = "unknown"; /** Sentinel for a record whose tool fingerprint is unknown. Never matches a request. */ const UNKNOWN_TOOLS_HASH = "unknown"; +/** + * Characters fed into prefix/whole-conversation digests, exposed for tests. + * + * `acquire()` used to join and hash one candidate's prefix at a time, so a + * conversation under the full `MAX_CANDIDATES_PER_ROOT` records was serialised + * once per candidate. Counting the characters proves the single ascending pass + * hashes each delivered message a bounded number of times instead. + */ +export const sessionHashStats = { + serialisedCharacters: 0, +}; + export interface SessionRecord { key: string; sessionId: string; @@ -197,6 +209,48 @@ export class SessionStore { let sawToolChange = false; let sawShrink = false; + /** + * Prefix hash per delivered count, computed in one ascending pass. + * + * A conversation can hold up to `MAX_CANDIDATES_PER_ROOT` records, so hashing + * each candidate's prefix separately joined and re-serialised the whole + * delivered transcript once per candidate — with media attachments that is + * megabytes of avoidable copying per turn. The candidates' prefixes are + * nested, so the digest up to each length is taken from a single hash stream + * fed one message at a time (`Hash#copy()` advances nothing). + */ + const verifiedPrefixHashes = new Map(); + const deliveredCounts = [ + ...new Set( + candidates + .filter( + (record) => + !record.busy && + record.model === input.model && + record.agent === input.agent && + record.variant === input.variant && + record.permissionProfile === input.permissionProfile && + record.toolsHash === input.toolsHash && + record.deliveredCount <= messages.length, + ) + .map((record) => record.deliveredCount), + ), + ].sort((left, right) => left - right); + if (deliveredCounts.length > 0) { + const hash = createHash("sha256"); + try { + hash.update("["); + let serialised = 0; + for (const count of deliveredCounts) { + serialised = hashFeedRange(hash, messages, serialised, count); + verifiedPrefixHashes.set(count, hash.copy().update("]").digest("hex")); + } + } finally { + // `createHash` holds an OpenSSL context; release it on every exit. + hash.destroy(); + } + } + for (const record of candidates) { if (record.busy) { sawBusy = true; @@ -222,8 +276,7 @@ export class SessionStore { sawShrink = true; continue; } - const prefix = messages.slice(0, record.deliveredCount); - if (hashMessages(prefix) !== record.prefixHash) continue; + if (verifiedPrefixHashes.get(record.deliveredCount) !== record.prefixHash) continue; let pending = messages.slice(record.deliveredCount); // The client echoes back the assistant turn the upstream session already @@ -699,13 +752,55 @@ function serialiseMessage(message: InternalMessage): string { return json; } -function serialiseMessages(messages: InternalMessage[]): string { - const parts = messages.map((message) => serialiseMessage(message)); - return `[${parts.join(",")}]`; +/** + * Feed `messages[from, to)` into `hash` as `JSON.stringify` would spell them. + * + * Shared by `hashMessages()` and the single ascending pass in `acquire()`, so both + * produce the same byte stream; the returned index lets the caller continue the + * same stream at the next prefix length. Every message fed is counted in + * `sessionHashStats`, which is what proves the prefixes are hashed in one pass. + */ +function hashFeedRange(hash: Hash, messages: InternalMessage[], from: number, to: number): number { + let index = from; + while (index < to) { + const message = messages[index]; + // `noUncheckedIndexedAccess` cannot see that the caller bounds `to` by the + // array length; a hole is impossible in an array built by `slice`/`map`, so + // skipping it cannot change the digest. + if (message !== undefined) { + const part = serialiseMessage(message); + sessionHashStats.serialisedCharacters += part.length; + hash.update(index === 0 ? part : `,${part}`); + } + index += 1; + } + return index; } +/** + * Hash the conversation exactly as `JSON.stringify(messages)` would. + * + * `JSON.stringify` of an array is `"[" + item,item + "]"` for every message + * shape this gateway builds, so the stream is assembled from the memoised + * per-message strings and is byte-identical to stringifying the array. Persisted + * prefix hashes and session keys therefore stay compatible with hashes written by + * earlier versions. + * + * The bytes are fed incrementally rather than joined first: `acquire()` hashes + * one prefix per cached candidate, and joining a conversation that carries + * base64 media copied megabytes it then threw away. + */ export function hashMessages(messages: InternalMessage[]): string { - return createHash("sha256").update(serialiseMessages(messages)).digest("hex"); + const hash = createHash("sha256"); + try { + hash.update("["); + hashFeedRange(hash, messages, 0, messages.length); + hash.update("]"); + return hash.digest("hex"); + } finally { + // `createHash` holds an OpenSSL context; release it on every exit. + hash.destroy(); + } } /** Stable hash of tool definitions, used to keep sessions tool-set specific. */ diff --git a/test/process.test.ts b/test/process.test.ts index a1c19e9..69b5fae 100644 --- a/test/process.test.ts +++ b/test/process.test.ts @@ -411,6 +411,38 @@ describe("UpstreamProcess", () => { expect(stderr.lines).toEqual(["line 7", "line 8", "line 9"]); }); + it("keeps the complete lines of one large chunk instead of dropping them", () => { + // Clamping before splitting discarded every complete line a burst carried, + // so a crash dump larger than the partial cap reached `/admin/status` as a + // single truncated blob. + const stderr = new StderrTail(50); + const burst = Array.from({ length: 100 }, (_, index) => `burst line ${index}`).join("\n"); + stderr.push(`${burst}\n${"z".repeat(1024 * 1024)}`); + + expect(stderr.lines.length).toBeGreaterThan(10); + expect(stderr.lines).toContain("burst line 99"); + // The unterminated tail is still clamped rather than retained whole. + expect(stderr.lines.every((line) => line.length <= 8 * 1024)).toBe(true); + }); + + it("drops the instance from the exit-hook registry once its child is gone", async () => { + // The registry exists so a process that builds many gateways installs exactly + // one exit listener; an instance with no live child has nothing left to kill + // and must not be retained (it holds the config, logger, metrics and tail). + const before = UpstreamProcess.liveInstanceCount; + const { process } = harness(); + + await process.resolve(); + expect(UpstreamProcess.liveInstanceCount).toBeGreaterThan(before); + + await process.stop(); + // The child's `exit` event is what releases the instance. + for (let attempt = 0; attempt < 50 && UpstreamProcess.liveInstanceCount !== before; attempt += 1) { + await new Promise((resolve) => setTimeout(resolve, 10)); + } + expect(UpstreamProcess.liveInstanceCount).toBe(before); + }); + it("exposes the child's recent stderr through status()", async () => { const { process } = harness({ ready: false, stderr: "provider config invalid\ntoken missing\n" }); diff --git a/test/sessions.test.ts b/test/sessions.test.ts index 3db7b7f..eee1ded 100644 --- a/test/sessions.test.ts +++ b/test/sessions.test.ts @@ -5,7 +5,7 @@ import path from "node:path"; import { afterEach, beforeEach, describe, expect, it, vi } from "vitest"; import { createLogger } from "../src/logger.js"; import { createMetrics } from "../src/metrics/registry.js"; -import { SessionStore, deriveKey, hashMessages, hashTools } from "../src/upstream/sessions.js"; +import { SessionStore, deriveKey, hashMessages, hashTools, sessionHashStats } from "../src/upstream/sessions.js"; import type { InternalMessage, ToolDefinition } from "../src/types/internal.js"; import { testConfig } from "./helpers/context.js"; @@ -789,4 +789,37 @@ describe("message serialisation", () => { createHash("sha256").update(JSON.stringify([messages[0]])).digest("hex"), ); }); + + it("verifies every candidate prefix from a single hashing pass", () => { + // The bug: `acquire()` joined and re-hashed one candidate's prefix at a time, + // so a conversation under the full `MAX_CANDIDATES_PER_ROOT` records was + // re-serialised once per candidate. With base64 media that is megabytes of + // avoidable copying per turn on the request path. + const sessions = store(); + const conversation: InternalMessage[] = Array.from({ length: 12 }, (_, index) => ({ + role: index % 2 === 0 ? "user" : "assistant", + text: `turn ${index}`, + })); + const first = sessions.acquire({ ...BASE_INPUT, messages: [conversation[0] as InternalMessage] }); + for (const [index, count] of [2, 4, 6, 8].entries()) { + sessions.commit(first.key, `ses_${index}`, { + ...BASE_INPUT, + messages: conversation.slice(0, count), + }); + } + + // Only what a caller would really hash: the prefix append cost is already + // pinned by the memoisation test above. + sessionHashStats.serialisedCharacters = 0; + const result = sessions.acquire({ ...BASE_INPUT, messages: conversation }); + // The longest delivered prefix is 8 messages; the shorter candidates reuse + // digests taken from the same stream instead of re-serialising 2+4+6+8. + const hashed = conversation + .slice(0, 8) + .reduce((total, message) => total + JSON.stringify(message).length, 0); + + expect(result.reused).toBe(true); + expect(result.sessionId).toBe("ses_3"); + expect(sessionHashStats.serialisedCharacters).toBe(hashed); + }); }); \ No newline at end of file diff --git a/test/upstream-proposals.test.ts b/test/upstream-proposals.test.ts index 3806afe..99d0f64 100644 --- a/test/upstream-proposals.test.ts +++ b/test/upstream-proposals.test.ts @@ -325,6 +325,27 @@ describe("U1 log-file redaction across a chunk boundary", () => { expect(written).toContain("server password [redacted]"); expect(written).not.toContain("super-secret"); }); + + it("still masks a marker inside a chunk far larger than the carry window", async () => { + // The boundary scan is given a bounded suffix window, so the decision must + // not depend on how much output precedes the boundary. A regression here + // writes the credential to the log file in plaintext. + const filler = "x".repeat(32 * 1024); + const { process, config, dataDir } = harness({ + readyMs: 100, + stderrChunks: [`${filler}server password leaked-secret\n${filler}`], + }); + + await process.resolve(); + await process.stop(); + + const logFile = path.join(dataDir, "logs", `opencode-${config.upstreamPort}.log`); + const written = await readFileEventually(logFile); + expect(written).toContain("server password [redacted]"); + expect(written).not.toContain("leaked-secret"); + // Nothing before the marker is dropped by bounding the scan window. + expect(written).toContain("x".repeat(1_000)); + }); }); // ------------------------------------------------------------------------ U2 --- From ee6e1fed15dee2130dfbd2e79bae6dfa77a01d1c 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 14:55:01 +0700 Subject: [PATCH 05/10] test(upstream): cover CLI and service-descriptor discovery `src/upstream/discovery.ts` resolves the `opencode` executable from PATH and the well-known install directories, parses `service.json` and checks a PID. Every other test injects both as seams, so the Windows `%APPDATA%`/`%LOCALAPPDATA%` branches and the descriptor parsing could regress with the suite green. The new cases drive the real functions against a temporary PATH and `XDG_STATE_HOME`/`XDG_CONFIG_HOME`. The integration file no longer reports a passing test that asserts nothing (`expect(true).toBe(true)`): without `OPENCODE_API_URL` and `OPENCODE_API_KEY` it reports its cases as skipped, which is what `pnpm test:all` already refuses to accept as a real run. --- test/discovery.test.ts | 139 ++++++++++++++++++++++++++++++++++ test/integration/live.test.ts | 10 ++- 2 files changed, 145 insertions(+), 4 deletions(-) create mode 100644 test/discovery.test.ts diff --git a/test/discovery.test.ts b/test/discovery.test.ts new file mode 100644 index 0000000..35a4588 --- /dev/null +++ b/test/discovery.test.ts @@ -0,0 +1,139 @@ +/** + * CLI and background-server discovery. + * + * `findOpencodeBinary()` and `readServiceDescriptor()` are the only code paths + * that touch the developer's machine, so `UpstreamProcess` takes both as seams in + * every other test. These cases drive the real functions against a temporary + * `PATH` and `XDG_STATE_HOME`/`XDG_CONFIG_HOME` instead, so the Windows + * `%APPDATA%`/`%LOCALAPPDATA%` and `service.json` branches cannot regress with the + * suite green. + */ +import { spawn } from "node:child_process"; +import fs from "node:fs"; +import os from "node:os"; +import path from "node:path"; +import { afterEach, describe, expect, it, vi } from "vitest"; +import { + findOpencodeBinary, + isProcessAlive, + readServiceDescriptor, + serviceDescriptorPaths, +} from "../src/upstream/discovery.js"; + +/** Executable name the module looks for on this platform. */ +const EXECUTABLE = process.platform === "win32" ? "opencode.exe" : "opencode"; + +const tempDirs: string[] = []; + +function tempDir(): string { + const dir = fs.mkdtempSync(path.join(os.tmpdir(), "opencode-discovery-")); + tempDirs.push(dir); + return dir; +} + +/** Create a regular file, so `isFile()` accepts it. */ +function createFile(file: string, contents = ""): void { + fs.mkdirSync(path.dirname(file), { recursive: true }); + fs.writeFileSync(file, contents, "utf8"); +} + +afterEach(() => { + vi.unstubAllEnvs(); + while (tempDirs.length > 0) { + const dir = tempDirs.pop(); + if (dir) fs.rmSync(dir, { recursive: true, force: true }); + } +}); + +describe("findOpencodeBinary", () => { + it("resolves an explicit path only when it is a file", () => { + const dir = tempDir(); + const binary = path.join(dir, EXECUTABLE); + createFile(binary); + + expect(findOpencodeBinary(binary)).toBe(binary); + expect(findOpencodeBinary(path.join(dir, "missing-opencode"))).toBeUndefined(); + // A directory is not an executable. + expect(findOpencodeBinary(dir)).toBeUndefined(); + }); + + it("finds the CLI on PATH before any well-known directory", () => { + const dir = tempDir(); + const binary = path.join(dir, EXECUTABLE); + createFile(binary); + vi.stubEnv("PATH", dir); + + expect(findOpencodeBinary()).toBe(binary); + }); +}); + +describe("serviceDescriptorPaths", () => { + it("honours XDG_STATE_HOME and XDG_CONFIG_HOME", () => { + const state = tempDir(); + const config = tempDir(); + vi.stubEnv("XDG_STATE_HOME", state); + vi.stubEnv("XDG_CONFIG_HOME", config); + + expect(serviceDescriptorPaths()).toEqual([ + path.join(state, "opencode", "service.json"), + path.join(config, "opencode", "service.json"), + ]); + }); +}); + +describe("readServiceDescriptor", () => { + it("reads the descriptor of a running background server", () => { + const state = tempDir(); + vi.stubEnv("XDG_STATE_HOME", state); + vi.stubEnv("XDG_CONFIG_HOME", tempDir()); + const file = path.join(state, "opencode", "service.json"); + createFile( + file, + JSON.stringify({ url: "http://127.0.0.1:20124", password: "pw", pid: 4242, version: "2.3.2", id: "svc_1" }), + ); + + expect(readServiceDescriptor()).toEqual({ + url: "http://127.0.0.1:20124", + password: "pw", + pid: 4242, + version: "2.3.2", + id: "svc_1", + }); + }); + + it("falls back to the config home and ignores a descriptor without a url", () => { + const state = tempDir(); + const config = tempDir(); + vi.stubEnv("XDG_STATE_HOME", state); + vi.stubEnv("XDG_CONFIG_HOME", config); + createFile(path.join(state, "opencode", "service.json"), JSON.stringify({ pid: 7 })); + createFile(path.join(config, "opencode", "service.json"), JSON.stringify({ url: "http://127.0.0.1:20125" })); + + expect(readServiceDescriptor()?.url).toBe("http://127.0.0.1:20125"); + }); + + it("ignores malformed JSON and a missing file", () => { + const state = tempDir(); + vi.stubEnv("XDG_STATE_HOME", state); + vi.stubEnv("XDG_CONFIG_HOME", tempDir()); + createFile(path.join(state, "opencode", "service.json"), "{not json"); + + expect(readServiceDescriptor()).toBeUndefined(); + }); +}); + +describe("isProcessAlive", () => { + it("treats a missing pid as dead and the running process as alive", () => { + expect(isProcessAlive(undefined)).toBe(false); + expect(isProcessAlive(process.pid)).toBe(true); + }); + + it("reports a process that already exited as dead", async () => { + const child = spawn(process.execPath, ["-e", "process.exit(0)"], { stdio: "ignore" }); + const pid = child.pid; + await new Promise((resolve) => child.once("exit", () => resolve())); + + expect(pid).toBeDefined(); + expect(isProcessAlive(pid)).toBe(false); + }); +}); diff --git a/test/integration/live.test.ts b/test/integration/live.test.ts index 3907a87..d845e84 100644 --- a/test/integration/live.test.ts +++ b/test/integration/live.test.ts @@ -229,8 +229,10 @@ describe.skipIf(!enabled)("live gateway", () => { }); }); -describe.skipIf(enabled)("live gateway (skipped)", () => { - it("explains how to enable the integration suite", () => { - expect(true).toBe(true); - }); +// Without `OPENCODE_API_URL`/`OPENCODE_API_KEY` the whole file is skipped. +// `pnpm test:all` refuses to start in that case instead of reporting a green +// suite, so this file deliberately reports skipped rather than passing a test +// that asserts nothing. +describe.skipIf(enabled)("live gateway", () => { + it.skip("needs OPENCODE_API_URL and OPENCODE_API_KEY", () => undefined); }); From b8cdd19a861dfe0c04322a7d3234c03f7c529107 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 14:55:11 +0700 Subject: [PATCH 06/10] docs: align the reference docs with the code `docs/API.md` labelled five `/admin/*` routes "admin key" although the tier is opt-in: with `OPENCODE_ADMIN_API_KEYS` unset any accepted key reaches them, which the same document's introduction, the configuration reference and `src/auth.ts` all say. The README endpoint table was missing `GET /v1/models/*`, the only route that can address a `provider/model` id, and its `{id}` row promised that form. It also omitted `pnpm start` and three source modules plus four of the five scripts from the project layout. `CONTRIBUTING.md` and `AGENTS.md` told contributors to run the checks CI runs but left out `pnpm smoke:dist` and `pnpm audit --prod`, both steps of the required `Verify` job. `docs/CONFIGURATION.md` called its startup-validation list exhaustive while omitting the `OPENCODE_ADMIN_API_KEYS` refusal and the credential check added for `OPENCODE_SERVER_URL`. `docs/ARCHITECTURE.md` now lists the third model route it owns, the frozen `MessageRole` type and the two `mime.ts` exports it was missing, and documents that `Usage.totalTokens` counts reasoning inside output. `.dockerignore` covers the runtime and scratch paths `.gitignore` has. --- .dockerignore | 7 +++++ AGENTS.md | 8 ++++-- CONTRIBUTING.md | 4 +++ README.md | 11 ++++++-- docs/API.md | 10 +++---- docs/ARCHITECTURE.md | 6 ++-- docs/VERIFICATION.md | 66 +++++++++++++++++++++++--------------------- 7 files changed, 68 insertions(+), 44 deletions(-) diff --git a/.dockerignore b/.dockerignore index c01eae0..ef1f14b 100644 --- a/.dockerignore +++ b/.dockerignore @@ -25,3 +25,10 @@ test .git-credentials coverage .vscode + +# Runtime state and scratch files `.gitignore` already covers; they must not be +# uploaded into the build context either. +.runtime +.opencode-api +.scratch-* +.pnpm-store diff --git a/AGENTS.md b/AGENTS.md index 1c9aef7..37c62af 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -130,9 +130,11 @@ These were verified against `opencode serve` 2.3.2; re-read 1. `pnpm typecheck` — clean. 2. `pnpm build` — clean. 3. `pnpm test` — green. -4. Docs updated when a contract, env var or wire format changed. -5. No secrets, no debug logging, no commented-out code, no scratch files +4. `pnpm smoke:dist` — the emitted `dist/` boots and answers `/health`. +5. `pnpm audit --prod` — no advisory in the shipped dependencies (the CI merge gate). +6. Docs updated when a contract, env var or wire format changed. +7. No secrets, no debug logging, no commented-out code, no scratch files (`.recon/`, `dist/`, `.opencode-api/` are ignored and should not be committed). -6. Commit with a Conventional Commit message, as described in +8. Commit with a Conventional Commit message, as described in `CONTRIBUTING.md` (for example `fix(sessions): release the slot after a timeout`); `pnpm lint:commits` checks it against `commitlint.config.mjs`. \ No newline at end of file diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md index 0135660..b8cea24 100644 --- a/CONTRIBUTING.md +++ b/CONTRIBUTING.md @@ -22,6 +22,8 @@ Run the same checks CI would run before opening a pull request: pnpm typecheck pnpm build pnpm test +pnpm smoke:dist # boots the emitted dist/ and probes /health +pnpm audit --prod # the merge gate for shipped dependencies pnpm lint:commits # lints your latest local commit message ``` @@ -191,6 +193,8 @@ Avoid: - [ ] `pnpm typecheck` passes. - [ ] `pnpm build` passes. - [ ] `pnpm test` passes. +- [ ] `pnpm smoke:dist` passes (it needs `pnpm build` first). +- [ ] `pnpm audit --prod` reports no advisory in the shipped dependencies. - [ ] New behaviour is covered by a test. - [ ] `docs/ARCHITECTURE.md` and the relevant reference doc are updated if a contract, an environment variable or a wire format changed. diff --git a/README.md b/README.md index e93b5b7..6727c27 100644 --- a/README.md +++ b/README.md @@ -187,7 +187,8 @@ When nothing is found the request fails with: | `POST` | `/v1/messages/count_tokens` | Anthropic token-count estimate for a Messages body. | | `POST` | `/v1/embeddings` | Always `501` — OpenCode exposes no embedding model. | | `GET` | `/v1/models` | List models, with gateway extensions: `name`, `context_length`, `max_output_tokens`, `capabilities`, `reasoning`, `status`, `enabled`. | -| `GET` | `/v1/models/{id}` | One model by `provider/model` or bare id. | +| `GET` | `/v1/models/{id}` | One model by bare id (`GET /v1/models/big-pickle`). | +| `GET` | `/v1/models/*` | One model by `provider/model`, for ids that contain a slash (`GET /v1/models/opencode/big-pickle`). | | `GET` | `/health` | Liveness plus upstream readiness snapshot (public). | | `GET` | `/ready` | Readiness from cached state: `200` only when an upstream server is resolved and a model catalog is already cached (public, never calls upstream). | | `GET` | `/healthz` | Minimal liveness alias (public). | @@ -655,6 +656,7 @@ writable by UID 1000. CI builds the image on every pull request | `pnpm dev` | Start with `tsx watch` and reload on change. | | `pnpm clean` | Remove `dist/`. | | `pnpm build` | Remove `dist/` first, then type-check and emit `src/` into it with `tsc -p tsconfig.build.json`, so a removed or renamed source cannot leave stale output behind. | +| `pnpm start` | Run the built `dist/index.js` (run `pnpm build` first). | | `pnpm typecheck` | `tsc -p tsconfig.json --noEmit`. | | `pnpm test` | Unit tests (excludes `test/integration/**`). | | `pnpm test:watch` | The same unit suite in watch mode. | @@ -697,10 +699,13 @@ opencode-api/ # package name; the project is "OpenCode API" │ ├── context.ts # shared application context │ ├── errors.ts # error taxonomy and wire shapes │ ├── index.ts # entry point -│ └── server.ts # Fastify assembly +│ ├── logger.ts # pino logger and secret redaction +│ ├── server.ts # Fastify assembly +│ ├── startup.ts # operator-facing startup guards and notes +│ └── version.ts # service name and version ├── test/ # vitest unit and integration tests ├── docs/ # API.md, CONFIGURATION.md, ARCHITECTURE.md, VERIFICATION.md -├── scripts/ # smoke.mjs, init-env.mjs +├── scripts/ # env setup, clean, smoke, smoke:dist, test:all ├── AGENTS.md # instructions for AI coding agents ├── CONTRIBUTING.md # workflow + commit message convention ├── LICENSE # MIT diff --git a/docs/API.md b/docs/API.md index df0f96c..4e76442 100644 --- a/docs/API.md +++ b/docs/API.md @@ -977,11 +977,11 @@ These are not model surfaces; they report or control gateway state. | `GET` | `/healthz` | public | Minimal liveness alias `{status:"ok", service, version}`. | | `GET` | `/metrics` | key or `OPENCODE_METRICS_TOKEN`, unless `OPENCODE_METRICS_PUBLIC=true` **and** no token is configured | Prometheus text exposition (`opencode_api_*`). `404 metrics_disabled` when `OPENCODE_METRICS_ENABLED=false`. | | `GET` | `/admin/status` | key (or `OPENCODE_ADMIN_API_KEYS` when configured) | Service version, uptime, a config subset, upstream status (URL/pid/last error/`stderrTail` — the last 50 stderr lines of the supervised server, with any `server password` value redacted), catalogue counts and session-cache counts. | -| `GET` | `/admin/config` | admin key | The effective configuration, with `auth.apiKeyCount`, `auth.usingDefaultApiKey` and `upstream.passwordConfigured` instead of the secrets themselves. `upstream.url`, timeouts, media limits, session settings and reasoning defaults are included. | -| `POST` | `/admin/models/refresh` | admin key | Forces a catalogue reload and returns `{refreshedAt, models, providers, agents}`. | -| `GET` | `/admin/sessions` | admin key | Every cached sticky session: key, session id, model, agent, variant, delivered/reused counts, `busy`, timestamps. | -| `DELETE` | `/admin/sessions` | admin key | Drops every cached session; returns `{cleared}`. | -| `POST` | `/admin/upstream/restart` | admin key | Invalidates the endpoint, stops the spawned server if there is one, and resolves a new one; returns `{url, source, pid}`. | +| `GET` | `/admin/config` | key (or `OPENCODE_ADMIN_API_KEYS` when configured) | The effective configuration, with `auth.apiKeyCount`, `auth.usingDefaultApiKey` and `upstream.passwordConfigured` instead of the secrets themselves. `upstream.url`, timeouts, media limits, session settings and reasoning defaults are included. | +| `POST` | `/admin/models/refresh` | key (or `OPENCODE_ADMIN_API_KEYS` when configured) | Forces a catalogue reload and returns `{refreshedAt, models, providers, agents}`. | +| `GET` | `/admin/sessions` | key (or `OPENCODE_ADMIN_API_KEYS` when configured) | Every cached sticky session: key, session id, model, agent, variant, delivered/reused counts, `busy`, timestamps. | +| `DELETE` | `/admin/sessions` | key (or `OPENCODE_ADMIN_API_KEYS` when configured) | Drops every cached session; returns `{cleared}`. | +| `POST` | `/admin/upstream/restart` | key (or `OPENCODE_ADMIN_API_KEYS` when configured) | Invalidates the endpoint, stops the spawned server if there is one, and resolves a new one; returns `{url, source, pid}`. | When `OPENCODE_RATE_LIMIT_RPM` is non-zero every authenticated request is charged against a per-key token bucket (with a separate bucket for `/admin/*`). A diff --git a/docs/ARCHITECTURE.md b/docs/ARCHITECTURE.md index 537d21d..a7d1b12 100644 --- a/docs/ARCHITECTURE.md +++ b/docs/ARCHITECTURE.md @@ -222,7 +222,7 @@ completion work. ### 4.1 `src/types/internal.ts` (frozen) `Surface`, `Attachment`, `AttachmentKind`, `ToolDefinition`, `ToolCall`, -`InternalMessage`, `ReasoningRequest`, `ResponseFormat`, +`MessageRole`, `InternalMessage`, `ReasoningRequest`, `ResponseFormat`, `InternalRequest`, `Usage`, `FinishReason`, `NativeToolActivity`, `CompletionEvent`. @@ -484,6 +484,8 @@ export function isVideo(mime: string): boolean; export function isPdf(mime: string): boolean; export function isTextual(mime: string): boolean; export function extensionToMime(extension: string): string | undefined; +export function mimeFromFileName(fileName: string): string | undefined; +export function normalise(mime: string): string; ``` Rules: reject `http(s)` when `config.allowRemoteMediaUrls` is false; reject @@ -572,7 +574,7 @@ export function registerOpenAiResponsesRoutes(app: FastifyInstance, ctx: AppCont export function registerOpenAiCompletionRoutes(app: FastifyInstance, ctx: AppContext): void; // POST /v1/completions // src/adapter/openai/models.ts -export function registerOpenAiModelRoutes(app: FastifyInstance, ctx: AppContext): void; // GET /v1/models, /v1/models/:id +export function registerOpenAiModelRoutes(app: FastifyInstance, ctx: AppContext): void; // GET /v1/models, /v1/models/:id, /v1/models/* // src/adapter/openai/embeddings.ts export function registerOpenAiEmbeddingRoutes(app: FastifyInstance, ctx: AppContext): void; // POST /v1/embeddings diff --git a/docs/VERIFICATION.md b/docs/VERIFICATION.md index 162ddc4..f2a91ce 100644 --- a/docs/VERIFICATION.md +++ b/docs/VERIFICATION.md @@ -341,41 +341,45 @@ this one is correct. | --- | --- | | `pnpm typecheck` | **PASS** — `$ tsc -p tsconfig.json --noEmit`, exit 0 | | `pnpm build` | **PASS** — `tsc -p tsconfig.build.json`, exit 0, **78** files emitted into `dist/` (39 modules + 39 source maps) | -| `pnpm test` | **PASS** — **30** files, **767 passed**, 2 skipped (769) | +| `pnpm test` | **PASS** — **32** files, **789 passed**, 2 skipped (791) | | `pnpm exec vitest run test/docs-consistency.test.ts` | **PASS** — 1 file, **16** tests | | `pnpm smoke:dist` | **PASS** — `dist/index.js answered /health with version 1.0.0`, then a clean SIGTERM shutdown | +| `pnpm audit --prod` | **PASS** — `No known vulnerabilities found` | Numbers quoted earlier in this document that have since changed: -* `src/config.ts` now reads **51** environment variables (was 49), and all 51 are - listed in `.env.example`, `docs/CONFIGURATION.md` and `README.md`. +* `src/config.ts` reads **51** environment variables, and all 51 are listed in + `.env.example`, `docs/CONFIGURATION.md` and `README.md`. * The `GET /` index in `docs/API.md` lists **19** entries; together with `GET /` itself that is exactly the **20** routes `src/` registers. -* The unit suite is **30 files / 767 passed / 2 skipped**, up from 25 files and - 657 passed; the guards in `test/docs-consistency.test.ts` are now 16. - -This pass fixed, with a regression test for each (details in the commit and in -`IMPROVEMENT_PROPOSALS.md` until that working file is removed): - -* **High** — the admin credential tier was bypassable with a percent-encoded path - (`/%61dmin/config`): classification now uses the matched route, not `request.url` - (`test/auth-surface.test.ts`); OpenAI `prompt_tokens`/`input_tokens` now fold - the cache buckets in, so `cached_tokens` can no longer exceed the prompt - (`test/parity.test.ts`, `test/openai-chat.test.ts`, `test/openai-responses.test.ts`, - `test/regressions.test.ts`); a terminal event left in flight by a previous turn - can no longer finalise the next turn on a sticky session - (`test/completion.test.ts`). -* **Medium** — media on a non-`user` message is rejected instead of downloaded - and dropped; a multi-element `/v1/completions` prompt is rejected instead of - silently joined; an empty or non-object 2xx upstream body is an - `upstream_invalid_json` failure instead of a `500`; a non-object SSE frame no - longer tears down the shared event stream; an abort during upstream resolution - now stops the request before it is issued; Anthropic `output_config` is mapped. -* **Low / hardening** — `json_schema.strict` and invalid `reasoning_effort` are - rejected instead of silently ignored; `/v1/responses` echoes `text.format` and - rejects an empty `model`; `/v1/completions` accepts `top_p`; `service_tier` is - recorded and named in `x_opencode.unapplied`; the Anthropic thinking signature is - keyed on the gateway message id on both paths; SSE field values are CR/LF-safe; - `isPrivateHost()` handles zone ids, unmapped IPv6 literals and trailing-dot - names; `OPENCODE_REASONING_FIELD` warns on a typo; the docs-consistency guard - also pins the documented `service`/`version`. +* The unit suite is **32 files / 789 passed / 2 skipped**, up from 25 files and + 657 passed; `test/usage.test.ts` and `test/discovery.test.ts` are new, and the + integration file no longer reports a passing test that asserts nothing. The + guards in `test/docs-consistency.test.ts` are 16. + +This pass fixed, with a regression test for each: + +* **High** — `/v1/responses` closed its items in block order rather than + `output_index` order, so a text-then-reasoning turn emitted the + `response.output_item.done` frames as `1,1,1,0,0,0` while + `response.completed.response.output` was sorted by index + (`test/openai-responses.test.ts`). +* **Medium** — `OPENCODE_BODY_TIMEOUT_MS` was armed in `preParsing`, which + Fastify never reaches for a request an `onRequest` hook rejected, so an + unauthenticated caller could dribble a body and hold a socket for free + (`test/admin.test.ts`); `OPENCODE_SERVER_URL` may no longer embed credentials, + which could never work and leaked the password into `/admin/config`, + `/admin/status` and every failure message (`test/config.test.ts`); the + Anthropic stream closed the blocks a failed turn had opened before sending its + terminal `error` frame (`test/anthropic.test.ts`); sticky-session prefix + verification joins and hashes the conversation once per turn instead of once + per cached candidate (`test/sessions.test.ts`). +* **Low / hardening** — `OPENCODE_METRICS_PUBLIC` on a network-reachable host now + warns at startup (`test/startup.test.ts`); `Usage.totalTokens` counts reasoning + inside the output total (`test/usage.test.ts`); `StderrTail` keeps the complete + lines of a burst instead of clamping before splitting, and the log-file + redaction boundary scan is bounded and compiled once + (`test/process.test.ts`, `test/upstream-proposals.test.ts`); an + `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`). From b891ebe6f43ab295d40a00e95283658effff1f6c 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 15:16:42 +0700 Subject: [PATCH 07/10] fix(reasoning): keep the thinking tokens in the internal total The previous commit asserted that reasoning is a subset of `Usage.outputTokens` and dropped it from `totalTokens`. That is the wire shape, not the internal one: upstream `tokens.output` excludes the thinking tokens, and every surface builds its own completion as `output + reasoning` (`src/adapter/openai/chat.ts`, `src/adapter/openai/responses.ts`, `src/adapter/anthropic/messages.ts`), while its prompt folds in the cache buckets. `totalTokens` is back to `input + output + reasoning`, now with a JSDoc, an architecture note and `test/usage.test.ts` stating why it is not any surface's `total_tokens`. --- docs/ARCHITECTURE.md | 7 ++++--- docs/VERIFICATION.md | 4 ++-- src/adapter/common/usage.ts | 13 ++++++++----- test/usage.test.ts | 24 ++++++++++++++---------- 4 files changed, 28 insertions(+), 20 deletions(-) diff --git a/docs/ARCHITECTURE.md b/docs/ARCHITECTURE.md index a7d1b12..c379ba6 100644 --- a/docs/ARCHITECTURE.md +++ b/docs/ARCHITECTURE.md @@ -435,9 +435,10 @@ renderToolResult(message): string, class ToolCallFilter(allowedNames?: Iterable< // declared, so the check runs once for every surface. // usage.ts -// `Usage.totalTokens` is `inputTokens + outputTokens`: `reasoningTokens` is a -// subset of `outputTokens`, which is why every surface derives its wire -// `total_tokens` (and Anthropic `output_tokens`) the same way. +// Upstream `tokens.output` excludes the thinking tokens and reports the cache +// buckets apart from `input`. `Usage.totalTokens` is `input + output + +// 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) ``` diff --git a/docs/VERIFICATION.md b/docs/VERIFICATION.md index f2a91ce..5bb589a 100644 --- a/docs/VERIFICATION.md +++ b/docs/VERIFICATION.md @@ -341,7 +341,7 @@ this one is correct. | --- | --- | | `pnpm typecheck` | **PASS** — `$ tsc -p tsconfig.json --noEmit`, exit 0 | | `pnpm build` | **PASS** — `tsc -p tsconfig.build.json`, exit 0, **78** files emitted into `dist/` (39 modules + 39 source maps) | -| `pnpm test` | **PASS** — **32** files, **789 passed**, 2 skipped (791) | +| `pnpm test` | **PASS** — **32** files, **792 passed**, 2 skipped (794) | | `pnpm exec vitest run test/docs-consistency.test.ts` | **PASS** — 1 file, **16** tests | | `pnpm smoke:dist` | **PASS** — `dist/index.js answered /health with version 1.0.0`, then a clean SIGTERM shutdown | | `pnpm audit --prod` | **PASS** — `No known vulnerabilities found` | @@ -352,7 +352,7 @@ Numbers quoted earlier in this document that have since changed: `.env.example`, `docs/CONFIGURATION.md` and `README.md`. * The `GET /` index in `docs/API.md` lists **19** entries; together with `GET /` itself that is exactly the **20** routes `src/` registers. -* The unit suite is **32 files / 789 passed / 2 skipped**, up from 25 files and +* The unit suite is **32 files / 792 passed / 2 skipped**, up from 25 files and 657 passed; `test/usage.test.ts` and `test/discovery.test.ts` are new, and the integration file no longer reports a passing test that asserts nothing. The guards in `test/docs-consistency.test.ts` are 16. diff --git a/src/adapter/common/usage.ts b/src/adapter/common/usage.ts index 5901ec5..ded50b1 100644 --- a/src/adapter/common/usage.ts +++ b/src/adapter/common/usage.ts @@ -9,10 +9,13 @@ export { EMPTY_USAGE }; /** * Convert upstream token accounting into the normalised shape. * - * `reasoningTokens` is a *subset* of `outputTokens` — every surface derives its - * wire total as `prompt + completion` with the thinking tokens counted inside - * `completion` (`docs/API.md` §Usage) — so `totalTokens` must not add it a second - * time. + * Upstream reports `output` *without* the thinking tokens, and the cache buckets + * separately from `input`. `totalTokens` is therefore the sum of the three + * token classes upstream reports — input, output and thinking — and is **not** + * the wire `total_tokens`: every surface builds its own prompt/completion pair + * (`input + cache_read + cache_write` and `output + reasoning`, see + * `docs/API.md` §Token accounting) and derives `total_tokens` from those, so the + * cache buckets appear on the wire but not here. */ export function toUsage(tokens: OpencodeTokenUsage | undefined): Usage { if (!tokens) return { ...EMPTY_USAGE }; @@ -27,7 +30,7 @@ export function toUsage(tokens: OpencodeTokenUsage | undefined): Usage { reasoningTokens, cacheReadTokens, cacheWriteTokens, - totalTokens: inputTokens + outputTokens, + totalTokens: inputTokens + outputTokens + reasoningTokens, }; } diff --git a/test/usage.test.ts b/test/usage.test.ts index 3e9ac2e..cd768ad 100644 --- a/test/usage.test.ts +++ b/test/usage.test.ts @@ -2,15 +2,16 @@ * Token accounting shared by every surface. * * `toUsage()` is the only conversion from the upstream `tokens` object into the - * normalised `Usage`, so the invariants the surfaces derive their wire values - * from are pinned here: reasoning is a subset of output, and `totalTokens` is the - * plain `prompt + completion` sum the OpenAI and Anthropic payloads document. + * normalised `Usage`. The invariants pinned here are the ones the surfaces rely + * on: upstream `output` excludes the thinking tokens, and the cache buckets are + * reported separately from `input`, so `totalTokens` is the sum of the three + * upstream token classes rather than any single surface's wire `total_tokens`. */ import { describe, expect, it } from "vitest"; import { EMPTY_USAGE, addUsage, toUsage } from "../src/adapter/common/usage.js"; describe("toUsage", () => { - it("counts reasoning inside output instead of adding it again", () => { + it("sums input, output and thinking, and keeps the cache buckets separate", () => { const usage = toUsage({ input: 21, output: 9, @@ -24,9 +25,11 @@ describe("toUsage", () => { reasoningTokens: 4, cacheReadTokens: 3, cacheWriteTokens: 1, - // 21 + 9, not 21 + 9 + 4: every surface derives its wire `total_tokens` as - // `prompt + completion` with the thinking tokens already inside output. - totalTokens: 30, + // 21 + 9 + 4: upstream `output` does not include the thinking tokens, so + // they are counted once here. The wire total is wider — 38 — because the + // surfaces fold the cache buckets into the prompt (25) and add the + // thinking tokens to the completion (13). + totalTokens: 34, }); }); @@ -50,7 +53,8 @@ describe("toUsage", () => { reasoningTokens: 5, cacheReadTokens: 0, cacheWriteTokens: 2, - totalTokens: 0, + // Thinking tokens are counted even when the other two classes are unusable. + totalTokens: 5, }); }); }); @@ -61,14 +65,14 @@ describe("addUsage", () => { const second = toUsage({ input: 5, output: 6, reasoning: 2, cache: { read: 0, write: 1 } }); const summed = addUsage(first, second); - expect(summed.totalTokens).toBe(summed.inputTokens + summed.outputTokens); + expect(summed.totalTokens).toBe(summed.inputTokens + summed.outputTokens + summed.reasoningTokens); expect(summed).toEqual({ inputTokens: 15, outputTokens: 10, reasoningTokens: 5, cacheReadTokens: 1, cacheWriteTokens: 1, - totalTokens: 25, + totalTokens: 30, }); }); }); From cc67de2443974ead5331236746693fa76a7c8e6f 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 15:16:51 +0700 Subject: [PATCH 08/10] fix(server): re-check body completeness when the deadline fires Keeping the deadline armed for a rejected request's dribble left one residual path: Node dumps the unread remainder of a rejected request and reuses the socket, so by the time the timer fired the connection could be serving a healthy `stream: true` response, which the timer then destroyed. The timer now repeats the completeness check before touching the socket, which keeps the dribble bound and spares the connection. --- src/http/timeout.ts | 9 ++++++++- test/admin.test.ts | 21 ++++++++++++++++++--- 2 files changed, 26 insertions(+), 4 deletions(-) diff --git a/src/http/timeout.ts b/src/http/timeout.ts index aa278bf..046545a 100644 --- a/src/http/timeout.ts +++ b/src/http/timeout.ts @@ -73,7 +73,9 @@ export function clearBodyDeadline(request: FastifyRequest): void { * request the authenticator rejected still has its response `close` while the * client is dribbling the body, and that is exactly the connection this bound * exists to reclaim; a request whose `IncomingMessage` is already `complete` has - * a deadline that is irrelevant from here on either way. + * a deadline that is irrelevant from here on either way. Because the connection + * survives such a rejection (Node dumps the unread remainder), the timer checks + * completeness again before destroying the socket. * * The timer is `unref`'d, so a pending deadline never keeps the process alive. */ @@ -89,6 +91,11 @@ export function armBodyDeadline( const timer = setTimer(() => { bodyDeadlines.delete(request); + // The body may have finished after this deadline was kept alive for a + // rejected request's dribble: Node dumps the unread remainder and keeps the + // connection, so the same socket can be serving a healthy long response by + // the time the timer fires. Destroying it then would cut that response off. + if (request.raw.complete !== false) return; const socket = request.raw.socket; // A stalled body is a protocol violation; the client gets a reset socket // rather than a response, exactly as with `requestTimeout`. diff --git a/test/admin.test.ts b/test/admin.test.ts index da57852..d8e9924 100644 --- a/test/admin.test.ts +++ b/test/admin.test.ts @@ -538,10 +538,10 @@ describe("OPENCODE_BODY_TIMEOUT_MS bounds body receipt (SEC-14)", () => { }); describe("the body deadline never outlives body receipt (SEC-14)", () => { - it("destroys the socket once the wall-clock deadline expires", async () => { + it("destroys the socket once the wall-clock deadline expires mid-body", async () => { const destroy = vi.fn(); const request = { - raw: { socket: { destroy } }, + raw: { socket: { destroy }, complete: false }, } as unknown as Parameters[0]; const reply = { raw: { once: () => undefined } } as unknown as Parameters[1]; @@ -552,10 +552,25 @@ describe("the body deadline never outlives body receipt (SEC-14)", () => { expect(destroy).toHaveBeenCalledTimes(1); }); + it("spares a socket whose body finished while the deadline was still armed", async () => { + // A rejected request can keep its connection: Node dumps the unread + // remainder and reuses the socket, which may be streaming a long response + // when the timer fires. The completeness of the body decides, at fire time. + const destroy = vi.fn(); + const request = { + raw: { socket: { destroy }, complete: true }, + } as unknown as Parameters[0]; + const reply = { raw: { once: () => undefined } } as unknown as Parameters[1]; + + armBodyDeadline(request, reply, { bodyTimeoutMs: 20 }); + await new Promise((resolve) => setTimeout(resolve, 60)); + expect(destroy).not.toHaveBeenCalled(); + }); + it("is inert once cleared, which is what the preHandler hook does", async () => { const destroy = vi.fn(); const request = { - raw: { socket: { destroy } }, + raw: { socket: { destroy }, complete: false }, } as unknown as Parameters[0]; const reply = { raw: { once: () => undefined } } as unknown as Parameters[1]; From b713b15b471e827ba6db939c25af54ae51382893 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 15:17:43 +0700 Subject: [PATCH 09/10] fix(upstream): keep a marker's introducer inside the log carry Three defects in the log-file redaction path, all around the boundary between two chunks: `pending.slice(0, boundary - hold)` treats a negative end as an offset from the end of the string, so a marker starting before the boundary was still written *past* it; the cut is clamped instead, which is what the comment already claimed. The bounded scan window could fall inside a long run of whitespace between `server password` and its value, where the `marker\s+$` alternative no longer sees the marker and the hold shrinks to zero. The window is now exactly the suffix that can affect the decision: the trailing whitespace run plus the longest marker. `StderrTail.push()` counted empty segments against its walk budget while `#append` drops them, so a burst ending in blank lines could exhaust the walk before reaching a line that was complete in the same chunk. --- src/upstream/process.ts | 56 ++++++++++++++++++++++----------- test/process.test.ts | 11 +++++++ test/upstream-proposals.test.ts | 21 +++++++++++++ 3 files changed, 69 insertions(+), 19 deletions(-) diff --git a/src/upstream/process.ts b/src/upstream/process.ts index 3e78c1b..f6fd6a6 100644 --- a/src/upstream/process.ts +++ b/src/upstream/process.ts @@ -194,14 +194,18 @@ export class StderrTail { this.#partial = clampTail(pending.slice(lastTerminator + 1), STDERR_PARTIAL_LIMIT_CHARS); // `found` is newest-first; the ring is a ring, but `lines` is documented and - // tested in chronological order. Only `#limit + 1` terminators are walked: - // anything older could never reach the ring. + // tested in chronological order. Only non-empty lines count against the + // budget: `#append` drops empty segments, so counting them let a burst of + // blank lines consume the whole walk and lose a real line that was complete + // in the same chunk. const found: string[] = []; let terminator = lastTerminator; - while (found.length < this.#limit + 1) { - const previous = pending.lastIndexOf("\n", terminator - 1); + while (found.length < this.#limit) { + // `lastIndexOf` clamps a negative index to 0, so a leading newline would + // otherwise report the same position forever. + const previous = terminator <= 0 ? -1 : pending.lastIndexOf("\n", terminator - 1); const line = pending.slice(previous + 1, terminator).replace(/\r$/, ""); - found.push(clampTail(line, STDERR_PARTIAL_LIMIT_CHARS)); + if (line.length > 0) found.push(clampTail(line, STDERR_PARTIAL_LIMIT_CHARS)); if (previous === -1) break; terminator = previous; } @@ -236,21 +240,26 @@ function clampTail(value: string, limit: number): string { return value.length > limit ? value.slice(-limit) : value; } +/** Longest marker the boundary check has to recognise. */ +const LONGEST_LOG_MARKER = LOG_MARKERS.reduce((longest, marker) => Math.max(longest, marker.length), 0); + /** - * Longest window of `text` that `partialMarkerLength()` has to inspect. + * The part of `text` that can still change the boundary decision. * - * A marker is a short literal, and the "marker + whitespace" alternative only - * matches a suffix, so nothing beyond the longest marker plus a run of trailing - * whitespace can change the answer. Bounding the window keeps a chatty long-lived - * child from lower-casing and regex-scanning every chunk in full; scanning a - * shorter window can only make the held tail *longer* (never a partial marker), - * which is the safe direction. + * `partialMarkerLength()` only inspects a suffix: a partial marker (at most + * `LONGEST_LOG_MARKER` characters) or a complete marker followed by trailing + * whitespace, which the `marker\s+$` alternative matches. This returns exactly + * that suffix — the trailing whitespace run plus that many characters before it + * — so the decision is identical to scanning the whole string while a chatty + * long-lived child no longer has every chunk lower-cased and regex-scanned in + * full. Keeping the whole whitespace run matters: a truncated run would shrink + * `hold` below the match, and the boundary could then fall between a marker and + * the value it introduces. */ -const PARTIAL_MARKER_WINDOW = 96; - -/** Longer-window-safe suffix of `text`, for the boundary check. */ function markerWindow(text: string): string { - return text.length > PARTIAL_MARKER_WINDOW ? text.slice(-PARTIAL_MARKER_WINDOW) : text; + let start = text.length; + while (start > 0 && /\s/.test(text[start - 1] ?? "")) start -= 1; + return text.slice(Math.max(0, start - LONGEST_LOG_MARKER)); } /** @@ -886,12 +895,21 @@ export class UpstreamProcess { const pending = redactionCarry + chunk; const boundary = Math.max(0, pending.length - LOG_REDACTION_CARRY_CHARS); // Never write a partial marker: the boundary moves back over it. Only the - // window before the boundary can still grow into one, so the scan does not + // suffix before the boundary can still grow into one, so the scan does not // touch the whole chunk. const hold = partialMarkerLength(markerWindow(pending.slice(0, boundary))); - const writeable = pending.slice(0, boundary - hold); - redactionCarry = pending.slice(writeable.length); + // `slice(0, negative)` counts back from the end, which would write *past* + // this boundary when the marker starts before it; clamp so the whole + // marker and its introducer stay in the carry instead. + 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)); + // 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 + // later one, where the per-write mask no longer sees the marker. The CLI + // prints a single space; `status()` redacts on read regardless. }; /** Write the carried tail, so the file ends on a complete line. */ const flushLog = (): void => { diff --git a/test/process.test.ts b/test/process.test.ts index 69b5fae..74f6f3e 100644 --- a/test/process.test.ts +++ b/test/process.test.ts @@ -443,6 +443,17 @@ describe("UpstreamProcess", () => { expect(UpstreamProcess.liveInstanceCount).toBe(before); }); + it("keeps a real line when a burst ends with many blank lines", () => { + // The walk budget used to count segments, but `#append` drops empty ones, so + // a run of blank lines could exhaust it before reaching a line that was + // complete in the same chunk. + const stderr = new StderrTail(50); + stderr.push(`real line\n${"\n".repeat(51)}`); + + expect(stderr.lines).toContain("real line"); + expect(stderr.lines.every((line) => line.length > 0)).toBe(true); + }); + it("exposes the child's recent stderr through status()", async () => { const { process } = harness({ ready: false, stderr: "provider config invalid\ntoken missing\n" }); diff --git a/test/upstream-proposals.test.ts b/test/upstream-proposals.test.ts index 99d0f64..1e70420 100644 --- a/test/upstream-proposals.test.ts +++ b/test/upstream-proposals.test.ts @@ -346,6 +346,27 @@ describe("U1 log-file redaction across a chunk boundary", () => { // Nothing before the marker is dropped by bounding the scan window. expect(written).toContain("x".repeat(1_000)); }); + + it("masks a marker whose value follows a whitespace run", async () => { + // The boundary check only inspects a bounded suffix, which has to include the + // whitespace that introduces the value: a run between the marker and the + // credential must not fall outside the window. + const { process, config, dataDir } = harness({ + readyMs: 100, + stderrChunks: [`server password${" ".repeat(20)}leaked-secret\n`], + }); + + await process.resolve(); + // The child's exit flushes the carried tail and closes the log file. + await process.stop(); + + const logFile = path.join(dataDir, "logs", `opencode-${config.upstreamPort}.log`); + const written = await readFileEventually(logFile); + // The mask keeps the marker's own whitespace, so match it rather than the + // single-space spelling. + expect(written).toMatch(/server password\s+\[redacted\]/); + expect(written).not.toContain("leaked-secret"); + }); }); // ------------------------------------------------------------------------ U2 --- From 00255b50d350ab48f1a6675cdc35f2b77b2324bc 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 15:17:52 +0700 Subject: [PATCH 10/10] docs: document the wildcard model route The endpoint table and section 8 still described `{id}` as accepting the unencoded `provider/model` form, which is served by the separate `GET /v1/models/*` route, and neither listed that route. --- docs/API.md | 10 +++++++--- 1 file changed, 7 insertions(+), 3 deletions(-) diff --git a/docs/API.md b/docs/API.md index 4e76442..78eef34 100644 --- a/docs/API.md +++ b/docs/API.md @@ -12,7 +12,8 @@ listen address is `http://127.0.0.1:20123`. | `POST` | `/v1/messages/count_tokens` | Anthropic token counting | | `POST` | `/v1/embeddings` | OpenAI Embeddings (always `501`) | | `GET` | `/v1/models` | OpenAI Models | -| `GET` | `/v1/models/{id}` | OpenAI Models (also accepts `provider/model` unencoded) | +| `GET` | `/v1/models/{id}` | OpenAI Models, by bare id or alias | +| `GET` | `/v1/models/*` | OpenAI Models, by `provider/model` (the slash is a path separator, so this form needs the wildcard route) | Everything else (`/health`, `/ready`, `/healthz`, `/metrics`, `/admin/*`, `/`) is operational; it is summarised at the end of this document and in the README. @@ -906,12 +907,15 @@ curl "http://127.0.0.1:20123/v1/models" -H "Authorization: Bearer $OPENCODE_API_ curl "http://127.0.0.1:20123/v1/models?refresh=true" -H "Authorization: Bearer $OPENCODE_API_KEY" ``` -## 8. `GET /v1/models/{id}` +## 8. `GET /v1/models/{id}` and `GET /v1/models/*` Returns one entry in exactly the same shape as a member of the list. The id may be `provider/model`, a bare model id, an alias, or a `model#variant` -reference. Because model ids contain `/`, both forms work without escaping: +reference. Because model ids contain `/`, the two spellings are registered as +separate routes: `{id}` serves a bare id or an alias, and the wildcard `*` serves +the canonical `provider/model` form, which would otherwise be split into two path +segments. Both work without escaping: ```bash curl http://127.0.0.1:20123/v1/models/opencode/deepseek-v4.1-flash-free \