Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
7 changes: 7 additions & 0 deletions .dockerignore
Original file line number Diff line number Diff line change
Expand Up @@ -6,3 +6,10 @@ workspace
test
.recon
*.log

# Never upload a real key file into the build context, and never let a future
# `COPY . .` bake it into a layer. `.env.example` carries no secret and is the
# file the docs tell operators to copy, so it stays.
.env
.env.*
!.env.example
11 changes: 11 additions & 0 deletions .github/dependabot.yml
Original file line number Diff line number Diff line change
Expand Up @@ -31,3 +31,14 @@ updates:
open-pull-requests-limit: 10
commit-message:
prefix: "ci(deps)"

# The base images pinned in Dockerfile (`node:22-bookworm-slim`, both stages),
# so a security release of the Node image arrives as a pull request instead of
# ageing silently.
- package-ecosystem: docker
directory: "/"
schedule:
interval: weekly
open-pull-requests-limit: 10
commit-message:
prefix: "build(deps)"
53 changes: 52 additions & 1 deletion .github/workflows/ci.yml
Original file line number Diff line number Diff line change
Expand Up @@ -180,7 +180,9 @@ jobs:
run: pnpm test

# The README documents a Docker deployment; nothing verified the Dockerfile
# until this job existed, so a broken image could merge unnoticed.
# until this job existed, so a broken image could merge unnoticed. Building is
# not enough: the image is started and probed so `pnpm prune --prod`, the
# copied file set and the runtime entry point are exercised too.
docker:
name: Docker image
runs-on: ubuntu-latest
Expand All @@ -201,3 +203,52 @@ jobs:
run: |
cp .env.example .env
docker compose config --quiet

# The image does not contain the OpenCode CLI, so the container is started
# with OPENCODE_AUTOSTART=false: /health must answer without any upstream
# being reachable. `-p 127.0.0.1:0:20123` lets Docker choose a free host
# port, which is then read back with `docker port`, so this never
# conflicts with a gateway already listening on the runner.
- name: Run the image and probe /health
run: |
set -euo pipefail

container_id="$(docker run --detach --rm \
--name opencode-api-ci \
-p 127.0.0.1:0:20123 \
--env OPENCODE_AUTOSTART=false \
--env OPENCODE_API_KEYS=ci-docker-smoke-key \
opencode-api:ci)"

# Always stop and remove the container, also when the probe fails.
cleanup() {
docker stop "$container_id" >/dev/null 2>&1 || true
docker rm --force "$container_id" >/dev/null 2>&1 || true
}
trap cleanup EXIT

probing="$(docker port "$container_id" 20123/tcp)"
port="${probing##*:}"
echo "Probing http://127.0.0.1:${port}/health"

healthy="false"
for _ in $(seq 1 30); do
if [ "$(docker inspect --format '{{.State.Running}}' "$container_id")" != "true" ]; then
echo "::error::the gateway container exited before answering /health"
docker logs "$container_id" || true
exit 1
fi
if curl --fail --silent --show-error --max-time 2 \
"http://127.0.0.1:${port}/health" >/dev/null; then
healthy="true"
break
fi
sleep 1
done

if [ "$healthy" != "true" ]; then
echo "::error::/health did not answer within 30 s"
docker logs "$container_id" || true
exit 1
fi
echo "The image answers /health."
6 changes: 4 additions & 2 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -515,8 +515,10 @@ Every variable, with types, defaults and security notes:
`opencode_api_`: `http_requests_total`, `http_request_duration_seconds`,
`upstream_requests_total`, `upstream_request_duration_seconds`,
`tokens_total`, `completions_total`, `active_streams`, `upstream_restarts_total`,
`session_cache_entries`, `event_stream_connected`, plus process defaults. Requires a key unless
`OPENCODE_METRICS_PUBLIC=true`.
`session_cache_entries`, `event_stream_connected`, `event_stream_reconnects_total`,
`event_frames_dropped_total`, `rate_limit_rejections_total`, plus process
defaults. Requires a key unless `OPENCODE_METRICS_PUBLIC=true`. `/metrics` is
never rate limited, so a local scraper cannot be throttled by its own traffic.
* **`/admin/*`** — `/admin/status` (config, upstream binary and URL, catalog
counts, session count), `/admin/config` (effective configuration with API keys
and the upstream password redacted), `/admin/models/refresh`, `/admin/sessions`
Expand Down
16 changes: 12 additions & 4 deletions docs/API.md
Original file line number Diff line number Diff line change
Expand Up @@ -896,19 +896,26 @@ Unknown ids return `404`:
"service": "opencode-api",
"version": "1.0.0",
"endpoints": [
"GET /",
"POST /v1/chat/completions",
"POST /v1/responses",
"POST /v1/completions",
"POST /v1/messages",
"POST /v1/messages/count_tokens",
"GET /v1/models",
"GET /v1/models/{id}",
"GET /v1/models/*",
"POST /v1/embeddings",
"GET /health",
"GET /ready",
"GET /healthz",
"GET /metrics",
"GET /admin/status",
"GET /admin/config"
"GET /admin/config",
"POST /admin/models/refresh",
"GET /admin/sessions",
"DELETE /admin/sessions",
"POST /admin/upstream/restart"
]
}
```
Expand All @@ -933,8 +940,8 @@ These are not model surfaces; they report or control gateway state.
When `OPENCODE_RATE_LIMIT_RPM` is non-zero every authenticated request is charged
against a per-key token bucket (with a separate bucket for `/admin/*`). A
rejected request answers `429` with `error.code: "rate_limit_exceeded"` and a
`retry-after` header in seconds. `/health`, `/ready`, `/healthz` and `/` are never
rate limited.
`retry-after` header in seconds. `/health`, `/ready`, `/healthz`, `/metrics` and `/`
are never rate limited.

### Metrics

Expand All @@ -944,7 +951,8 @@ rate limited.
| Series | Type | Labels |
| --- | --- | --- |
| `http_requests_total`, `http_request_duration_seconds` | counter, histogram | `method`, `route`, `status` |
| `upstream_requests_total`, `upstream_request_duration_seconds` | counter, histogram | `operation`, `outcome` |
| `upstream_requests_total` | counter | `operation`, `outcome` |
| `upstream_request_duration_seconds` | histogram | `operation` |
| `tokens_total` | counter | `model`, `direction` |
| `completions_total` | counter | `surface`, `model`, `stream`, `finish_reason`, `error_code` |
| `active_streams` | gauge | `surface` |
Expand Down
37 changes: 32 additions & 5 deletions docs/ARCHITECTURE.md
Original file line number Diff line number Diff line change
Expand Up @@ -147,12 +147,22 @@ interrupts the session and fails the turn with `503 event_stream_lost` instead o
returning a silently truncated answer. A half-open socket
never rejects `read()`, so every read is bounded by an idle watchdog (three
documented heartbeats, overridable through `EventHubOptions.idleTimeoutMs` in
tests); the connection attempt itself is bounded by the same watchdog, so an
upstream that accepts the socket and never writes a response head cannot park the
hub indefinitely. Expiry fails the connection so the loop reconnects. `stop()` and
tests); the connect phase alone is bounded by the same watchdog, so an upstream
that accepts the socket and never writes a response head cannot park the hub
indefinitely. That connect timer is cleared as soon as the response head arrives:
the deadline must never fire against a stream that is actively sending
heartbeats. Expiry fails the connection so the loop reconnects. Half-received
frame text is assembled in a buffer capped at 1 MiB; a chunk that crosses the cap
without a blank line drops the partial frame (unusable either way), increments
`event_frames_dropped_total{reason="malformed"}` and starts the next frame from a
clean buffer, so a re-framing proxy or a dialect mismatch cannot grow the buffer
without bound or turn every chunk into an O(buffer) scan. `stop()` and
every other exit cancel the response body reader and zero the
`event_stream_connected` gauge, and `#controller` is cleared when a connection
attempt returns. The reconnect delay is reset only after a connection has actually
attempt returns. Each loop is stamped with a generation that `stop()` retires, so
a `start()` racing an old loop that is still parked in `read()` cannot leave two
loops consuming the same upstream stream. The reconnect delay is reset only after
a connection has actually
delivered `server.connected`, so an accept-then-close upstream backs off instead of
being polled four times a second.

Expand Down Expand Up @@ -271,6 +281,15 @@ timeout (`OpencodeClientOptions.catalogueTimeoutMs`, default 10 s) rather than t
candidates while keeping the conversation key, so a stale-session replay caches
its replacement where the next turn of that conversation will find it.

`execute()`'s `finally` settles the sticky record on every exit. When the turn did
not complete it releases the record; a session that was **created for that turn**
(`!prepared.reused`) has no record yet, so the release finds nothing and the
eviction hook never fires — the upstream session would then outlive the failed
turn for the life of `opencode serve`. In that case the same `finally` also issues
a best-effort `deleteSession()`, so a first turn that fails (429, timeout,
disconnect, `event_stream_lost`) leaves no orphan. Reused sessions keep being
deleted by the session-store eviction hook.

`stop()` is deliberately **non-terminal**: `POST /admin/upstream/restart` and the
retry paths call `stop()`/`invalidate()` and then `resolve()` again, and
`test/process.test.ts` pins that. `shutdown()` is the terminal variant, used only
Expand Down Expand Up @@ -302,7 +321,15 @@ answer. The streamed surfaces apply the same rule independently.
`finish_reason` stays within the documented `FinishReason` values and a failure
adds a bounded `error_code` label (the gateway's own `ApiError.code`), so a lost
event stream is counted as `finish_reason="error", error_code="event_stream_lost"`
rather than as its own finish reason. `upstream_restarts_total{reason}` is
rather than as its own finish reason. The label is filtered through a closed
allow-list built from the gateway's own codes, the provider codes documented in
§2 and `http_<status>`, with `"other"` as the fallback — several paths copy the
code verbatim from an upstream `record.type` / `_tag`, and prom-client never
evicts a label set, so an unfiltered value would become a permanent time series.
Pre-flight exits count too: model resolution, modality validation and session
creation fail before `execute()` can report its own outcome, so they are recorded
in the same counter with the model label that is actually known (`"unknown"` when
resolution itself failed). `upstream_restarts_total{reason}` is
classified once per published server (`initial`, `stale`, `invalidated`,
`restart`).

Expand Down
71 changes: 68 additions & 3 deletions docs/VERIFICATION.md
Original file line number Diff line number Diff line change
Expand Up @@ -126,16 +126,16 @@ leak with operational impact) / **minor** (incorrect behaviour in an edge case o

### Not reported (checked and found correct)

* Auth: every non-public route is behind the global `preHandler`; `/health`, `/ready`, `/healthz` are the only public paths; `/metrics` is public only with `OPENCODE_METRICS_PUBLIC=true`; unknown paths return 404 through the (unauthenticated) not-found handler without exposing data; OPTIONS preflight returns 204 before auth and never touches data. A disallowed origin receives the same 204 without any `access-control-*` header, so the browser blocks the response and never sends the real request. An allowed origin additionally receives `access-control-allow-headers` covering the official OpenAI and Anthropic SDK headers and `access-control-expose-headers: x-request-id`.
* Auth: every non-public route is behind the global `onRequest` hook (so an anonymous caller is rejected before Fastify buffers or parses the body); `/health`, `/ready`, `/healthz` are the only public paths; `/metrics` is public only with `OPENCODE_METRICS_PUBLIC=true`; unknown paths return 404 through the (unauthenticated) not-found handler without exposing data; OPTIONS preflight returns 204 before auth and never touches data. A disallowed origin receives the same 204 without any `access-control-*` header, so the browser blocks the response and never sends the real request. An allowed origin additionally receives `access-control-allow-headers` covering the official OpenAI and Anthropic SDK headers and `access-control-expose-headers: x-request-id`.
* Constant-time comparison is used for keys (`timingSafeEqual` with a length guard).
* Local paths: `realpath` is applied **before** the `allowedFileRoots` check, and only the OpenAI `document` part exposes a path field — symlink escape and traversal are correctly blocked. The file is now read through one handle (`fsp.open` with `O_NOFOLLOW` where the platform has it, then `fstat` and `read`), so a final-component swap after the check cannot redirect the read, and an unreadable or vanished file returns 400 `invalid_attachment` / `attachment_not_found` instead of a 500. Residual risks, not closed by `realpath` + `O_NOFOLLOW`: hard links created inside an allowed root, a swapped parent directory, and Windows reparse points (Node exposes no `openat2`/`RESOLVE_BENEATH`).
* Attachment caps: `OPENCODE_MAX_ATTACHMENTS` and `OPENCODE_MAX_ATTACHMENT_BYTES` are enforced while media is resolved, not only when it is forwarded. One budget per request covers every message and every nested `tool_result` block, the count slot is claimed before the first `await`, downloads run in a bounded pool, and the first hard failure aborts the in-flight siblings instead of letting them run to the fetch timeout.
* Remote downloads are streamed with a hard `maxAttachmentBytes` cap and a fetch timeout, and an oversized `content-length` is rejected before reading.
* SSE framing: `[DONE]` is emitted only by `/v1/chat/completions`; Anthropic block indexes are contiguous `0,1,2…` with matching `content_block_start/stop`; Responses `sequence_number` is strictly increasing and unique (verified: `[0..15]`, strictly increasing `true`); in-stream error frames were observed on all three surfaces.
* `content: null` is emitted by the chat adapter exactly when a tool call exists and no text was produced; `finish_reason`/`stop_reason` mapping matches the documented tables (`length`→`max_tokens`, `content_filter`→`refusal`, bridged calls→`tool_calls`/`tool_use`).
* `OPENCODE_AGENT_PERMISSIONS` / `OPENCODE_TOOL_BRIDGE_DENY_NATIVE_TOOLS` deny rules are merged correctly (`bash, webfetch, websearch, edit, write, patch, task, skill`).
* Every environment variable in `src/config.ts` (46) appears in `.env.example` (46) and in `docs/CONFIGURATION.md` (46) — exact match, no extras either way.
* No `TODO`/`FIXME`/`XXX`/stub markers anywhere in `src/`; no `any` annotations (three widening casts exist: `as never` twice in `src/upstream/completion.ts:229,433` and `as unknown as FastifyInstance` in `src/server.ts:34`, all narrowing-free and none of which was observed to hide a runtime defect); all sources, tests, comments and docs are English (CJK/Cyrillic scan: none).
* Every environment variable in `src/config.ts` (49) appears in `.env.example` (49) and in `docs/CONFIGURATION.md` (49) — exact match, no extras either way.
* No `TODO`/`FIXME`/`XXX`/stub markers anywhere in `src/`; no `any` annotations (three widening casts exist: `as never` twice in `src/upstream/completion.ts:382,685` and `as unknown as FastifyInstance` in `src/server.ts:65`, all narrowing-free and none of which was observed to hide a runtime defect); all sources, tests, comments and docs are English (CJK/Cyrillic scan: none).
* Requirements 1–9 are all implemented; `src/` contains TypeScript only (`scripts/smoke.mjs` is an operator script, not a source module).

## 4. Docker review
Expand Down Expand Up @@ -257,3 +257,68 @@ is in the git history; the entries that touch the findings above are:
* `stop` is now honoured on `/v1/chat/completions` and `/v1/completions`, and the
generation knobs the gateway cannot apply are named in `x_opencode.unapplied`
instead of being silently dropped (`docs/API.md`).

### Addendum — remediation pass of 2026-12-03 (P-01 … P-25)

Recorded so the counts and line references above are read against the current
tree. **The revision these statements describe is the `87d10db` base plus the
remediation changes carried by the accompanying commit on the review branch**
(the pass was verified in the working tree before it was committed, and the
branch carries the same `docs/API.md`, `docs/ARCHITECTURE.md` and `src/` state).

What changed in the numbers this document quotes:

* `src/config.ts` now reads **49** environment variables, all 49 documented in
`.env.example` and `docs/CONFIGURATION.md` (§3, second-to-last bullet).
* the widening casts moved: `as never` is at `src/upstream/completion.ts:382,685`
and the Fastify cast at `src/server.ts:65` (both refreshed above).
* `test/docs-consistency.test.ts` now enforces three lists that had already
drifted once: the environment variables (unchanged), the `GET /` endpoint index
in `docs/API.md` against the routes `src/` registers (19 entries, including
`GET /`, `GET /healthz`, `GET /v1/models/*` and the four `/admin/*` routes the
index had omitted), and every metric series declared in
`src/metrics/registry.ts` against `docs/API.md` and `README.md`.

What the pass changed, beyond the pre-remediation findings above:

* **Authentication and rate limiting run `onRequest`** (`src/server.ts`), before
Fastify buffers and parses the body; an unauthenticated caller can no longer
spend `bodyLimitBytes` per connection. The limiter buckets credential-less
callers by `request.ip` and its bucket map is bounded, the public-path check is
canonicalised, and the `GET /` index now matches the registered routes.
* **The upstream event hub** clears its connect-phase watchdog once the response
head arrives, caps the frame-assembly buffer at 1 MiB, and stamps each loop
with a generation `stop()` retires, so a healthy stream is no longer aborted
every 45 s and a `stop()`/`start()` race cannot run two consumers.
* **The model catalogue survives an empty refresh**, `completions_total` counts
pre-flight failures with a closed `error_code` label, a failed first turn
deletes the upstream session it created, `reusedCount` is incremented, the
partial stderr line is bounded, and each message is serialised once per turn.
* **The streamed OpenAI surfaces adopt a consolidated `text_end`** like
`/v1/responses` and the buffered path already did; `/v1/responses` fixes its
`output_index` at announcement time and adopts a step-level `reasoning_end`
only when it is longer; `/v1/messages` keeps every tool call the buffered route
returns and its stop-sequence filter is O(1) instead of O(n²). The Anthropic
stream announces blocks in arrival order rather than withholding text until a
possible thinking block is known — withholding was prototyped and rejected
because it turned a text-only streamed answer into a single burst.
* **`/v1/messages` stop-sequence scanning** and the tool-envelope fence parsing
are now linear (a 64 KiB near-match dropped from ~5 s to under 2 ms).

What was re-verified for the pass:

| Command | Result |
| --- | --- |
| `pnpm typecheck` | **PASS** — `$ tsc -p tsconfig.json --noEmit`, exit 0 |
| `pnpm build` | **PASS** — `tsc -p tsconfig.build.json`, exit 0 |
| `pnpm test` | **PASS** — 24 files, **542 passed**, 4 skipped |
| `pnpm smoke:dist` | **PASS** — `dist/index.js answered /health with version 1.0.0` |
| `pnpm exec vitest run test/docs-consistency.test.ts` | **PASS** — `Test Files 1 passed (1)`, `Tests 11 passed (11)` |
| `docker build --tag opencode-api:ci .` | **PASS** — image built from the current tree |
| `docker run --detach … -e OPENCODE_AUTOSTART=false -e OPENCODE_API_KEYS=… opencode-api:ci` + `GET /health` | **PASS** — `200 {"status":"ok",…,"upstream":{"ready":false,"source":null}}` after ~2 s, container still `running`; the same sequence is the new `Docker image` CI step |
| `cp .env.example .env && docker compose config --quiet` | **PASS** — exit 0 after the `.dockerignore` change (temporary `.env` removed afterwards) |

Still unresolved at the time of writing: none of the P-01 … P-25 items were left
open; the P-14/P-15/P-16/P-17/P-19 documentation, Docker and CI items and the
P-18 image smoke test are covered above, and the remaining source-level items are
covered by the regression tests named in the proposals file.
Loading
Loading