Repository navigation
fix: harden media, streaming, sessions and the tool bridge - #6
Merged
Merged
Conversation
Attachment caps were applied only after every media source had already been fetched and buffered, so one small request could fan out to a million concurrent downloads and retain gigabytes: a 64 MiB body holds more than a million media parts and each one costs up to 20 MiB. Local files were also read through a second path-based syscall after the roots check, and an unreadable or vanished file surfaced as a 500 instead of the documented 400. Enforce one MediaBudget per request, claimed synchronously before the first await, with a bounded download pool, a single abort controller for the request and every refusal reported to the caller instead of being fetched. Read a local file through one O_NOFOLLOW handle so fstat and the bytes on disk cannot disagree, and map the errno values a caller can trigger to the documented 400 codes.
Three fidelity defects reached real clients. A turn the upstream ended with finish "error" was laundered into HTTP 200 plus finish_reason "stop" on /v1/chat/completions and /v1/completions, so an SDK never retried it, while /v1/responses reported the same condition as failed. The Responses stream committed its 200 SSE head before inspecting the first orchestrator event, so a pre-flight failure such as an unavailable event stream became response.failed inside a successful response. And the input union rejected reasoning items, which meant the adapter's own output array could not be fed back as the next input. Convert the errored turn into 502 upstream_error on the buffered paths and into the existing in-band error frame on the streamed ones, check the first Responses event before emitting anything, and accept reasoning items as validated-and-ignored input.
Four defects on the Messages surface. Thinking content_block_start omitted the required signature field that Anthropic sends and the official SDKs type as mandatory. A tool-only turn streamed a synthetic empty text block, so the tool_use landed at index 1 while the buffered payload put it at index 0, and the two paths disagreed. Image and document blocks inside tool_result content were replaced by an information-free placeholder and could never reach the model. And stop_sequences was validated, recorded and then ignored, so stop_reason "stop_sequence" was unreachable. Add the signature field, drop the synthetic text block, resolve tool-result media onto the enclosing user turn with a mime-bearing marker, and filter assistant text through a shared stop-sequence helper that truncates the visible text on both paths and reports the matched entry.
The tool bridge derived both its prompt and its session permissions from one boolean, tools.length > 0 and tool_choice not "none". A request that declared tools with tool_choice "none" therefore created the session with no deny rules, so the OpenCode agent kept bash, webfetch, write, edit and task against the workdir, the opposite of the documented containment. A later turn could reuse that permissive session because the session identity ignored the permission profile and the tool set. Trailing-comma repair also ran a string-unaware regex over malformed envelopes, deleting a comma that the model had placed inside a string value and returning wrong arguments with no error; and the bridge prompt named read, glob and grep, which the deny list does not cover. Decide the deny rules from the declared tools, add the permission profile and tool fingerprint to the session identity and compare them on reuse, reject a tool_choice that requires an undeclared tool, repair commas with a string-aware walk, and align the prompt with what is enforced.
The EventHub published an onReconnect hook that nothing subscribed to, so a mid-turn stream drop silently lost every remaining frame: the turn either returned a truncated answer with finish_reason "stop" or hung until the 600 s request budget and then answered 504. stop() was also not terminal. It never awaited an in-flight start and tracked the child only after readiness, so a spawn racing the process-exit path could outlive the gateway. Record the gap and keep consuming for a bounded grace window so a terminal event that arrives in time still completes the turn, then interrupt the session and fail with 503 event_stream_lost. Add a terminal shutdown() that tracks every spawned child, and narrow the port-retry heuristic, which matched the word "report" in a readiness timeout and retried a hung start ten times.
Three usability defects. forceCloseConnections was true, which makes Fastify call closeAllConnections() in its own onClose hook and destroy requests that are still in flight, so the bounded drain in http/shutdown.ts could never take effect and SIGTERM cut a healthy completion at t=0. The CORS allow-list omitted the headers the official SDKs send (openai-organization, openai-project, x-stainless-*, anthropic-dangerous-direct-browser-access) and never exposed x-request-id, so a browser client's preflight failed. And usingDefaultApiKey was false whenever the published key was configured explicitly, which is exactly what .env.example ships, so the startup warning never fired while the only accepted key was public knowledge. Close idle connections instead of active ones, widen the allow-list and expose the request id, report the published key as soon as it is accepted, and let the process-exit path use the terminal upstream shutdown() while the admin restart route keeps the non-terminal stop().
Cover the behaviour the previous commit changed: the published key is reported as accepted when it is listed explicitly, .env.example may only activate assignments that match a built-in default (the presence-only check could not catch an uncommented line), and the preflight exposes the SDK headers for an allowed origin while a disallowed origin gets no access-control-* header at all. Also pin the activeStreams gauge on all four streaming surfaces instead of only /v1/responses, so a leaking stream cannot hide on the others.
The documented OPENCODE_LOG_PRETTY could never take effect: pino's pino-pretty transport was requested inside a try/catch but the package was not installed, so the gateway always fell back to JSON. Nothing in CI executed dist/ either. pnpm test runs the TypeScript sources through vitest, so a broken emit or a missing runtime extension would only appear in production. Add pino-pretty as a dev dependency, declare packageManager so the workspace, CI and the Dockerfile's corepack all resolve the same pnpm, and run scripts/smoke-dist.mjs plus a production dependency audit in the verify job.
The reference still promised things the code no longer does, or never did: that every listed request field was honoured, that stop_sequence is always null, that a tool-only Anthropic turn streams an empty text block, that the echoed response always reports store false, that metadata is logged, that count_tokens estimates characters / 4, and that forceCloseConnections is true. The media section also described the caps as bounding only the forwarding step. Document the errored-turn status codes and the event_stream_lost error, the reasoning input item, the honoured stop_sequences and tool-result media, the permission-profile part of session identity, the terminal upstream shutdown, the O_NOFOLLOW local-file read with its residual risks, the CORS header set, and the pnpm/logging changes.
The bounded drain now depends on buildServer choosing forceCloseConnections "idle", and the process-exit path calls the terminal upstream shutdown() instead of the non-terminal stop(). Pin both, so a future edit cannot silently reintroduce the immediate teardown.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Add this suggestion to a batch that can be applied as a single commit.This suggestion is invalid because no changes were made to the code.Suggestions cannot be applied while the pull request is closed.Suggestions cannot be applied while viewing a subset of changes.Only one suggestion per line can be applied in a batch.Add this suggestion to a batch that can be applied as a single commit.Applying suggestions on deleted lines is not supported.You must change the existing code in this line in order to create a valid suggestion.Outdated suggestions cannot be applied.This suggestion has been applied or marked resolved.Suggestions cannot be applied from pending reviews.Suggestions cannot be applied on multi-line comments.Suggestions cannot be applied while the pull request is queued to merge.Suggestion cannot be applied right now. Please check back later.
What changed
Hardens the gateway across every surface after a full review pass. The defects
that reached real clients: the Responses stream committed its 200 SSE head before
inspecting the first orchestrator event; a turn the upstream ended with
errorwas laundered into
200plusfinish_reason: "stop"on the chat and legacycompletions surfaces; a mid-turn event-stream reconnect silently truncated the
answer (or hung for the 600 s budget) because nothing consumed the hub's
onReconnecthook; attachment caps were enforced only after every media sourcehad been fetched and buffered;
tool_choice: "none"created sessions without thenative-tool deny rules; and a template repair regex corrupted tool arguments that
contained a comma before a closing brace.
Feature and fidelity work in the same pass: Anthropic
stop_sequencesis nowhonoured on both paths, tool-result image/document blocks reach the prompt,
thinking block starts carry the required empty
signature,/v1/responsesaccepts the
reasoningitems it emits,forceCloseConnections: "idle"makes thebounded drain real,
usingDefaultApiKeyis true whenever the published key isaccepted, and the CORS allow-list covers the official SDK headers.
How it was verified
pnpm typecheck— cleanpnpm build— cleanpnpm test— 391 passed, 4 skipped (POSIX-only assertions on Windows)pnpm smoke:dist—dist/index.jsboots and answers/healthpnpm audit --prod— no known vulnerabilitiespnpm exec commitlint --from 4867f09 --to HEAD— every commit passesEach bug fix ships with a regression test that fails without it; new behaviour is
tested on both the streamed and buffered path, and
docs/,README.mdandAGENTS.mdwere updated wherever a contract, env var or wire format changed.Checklist
pnpm typecheckpasses.pnpm buildpasses.pnpm testpasses.pnpm lint:commits(Conventional Commits).docs/ARCHITECTURE.mdand the relevant reference doc are updated when acontract, an environment variable or a wire format changed.