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
9 changes: 7 additions & 2 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -330,7 +330,9 @@ model actually offers.
* OpenAI chat: `reasoning_effort` (or `reasoning.effort`) — `none`, `minimal`,
`low`, `medium`, `high`, `xhigh`, `max`. Common aliases are accepted
(`off`/`disabled` → `none`, `min`/`lowest` → `minimal`,
`default`/`normal`/`mid` → `medium`, `maximum`/`highest` → `max`).
`default`/`normal`/`mid` → `medium`, `maximum`/`highest` → `max`). A value
outside that set is rejected with `400 invalid_request` rather than silently
treated as `medium`.
* OpenAI Responses: `reasoning.effort`.
* Anthropic: `thinking: {type:"enabled", budget_tokens: N}` (bucketed:
`<2k`→minimal, `<6k`→low, `<16k`→medium, `<40k`→high, `<80k`→xhigh, else max)
Expand Down Expand Up @@ -436,13 +438,16 @@ JSON output is bridged through the prompt for the same reason function calling i
| --- | --- | --- |
| `/v1/chat/completions` | `response_format` | `{"type":"json_object"}`, `{"type":"json_schema","json_schema":{name,schema}}` |
| `/v1/responses` | `text.format` | `{"type":"json_object"}`, `{"type":"json_schema",name,schema}` |
| `/v1/messages` | `output_config.format` | `{"type":"json_object"}`, `{"type":"json_schema",schema?}` |

`{"type":"text"}` and an absent field leave the prompt unchanged. The gateway
adds a `# Response format` prompt section asking for a single valid JSON value
and, for a schema, for a value that validates against it. This is a model
contract, not a server-enforced one: nothing validates the reply, so a model that
ignores the instruction can still answer in prose. Validate the result on the
client when it matters.
client when it matters. For the same reason `strict: true` — which promises
server-enforced conformance — is rejected with `400 unsupported_parameter`
instead of accepted and ignored.

## Model naming

Expand Down
54 changes: 38 additions & 16 deletions docs/API.md

Large diffs are not rendered by default.

83 changes: 64 additions & 19 deletions docs/ARCHITECTURE.md
Original file line number Diff line number Diff line change
Expand Up @@ -142,6 +142,18 @@ Event types the gateway consumes:
`finish` is one of `stop | length | tool-calls | content-filter | error | unknown`.
`tokens` is `{ input, output, reasoning, cache: { read, write } }`.

The stream is per **session**, not per turn, so a completion scopes the frames it
consumes: the subscription opens before the prompt is issued, and a turn this
gateway interrupted keeps its record committed for reuse while its terminal
frames are still in flight. `execute()` records the instant it is about to issue
the prompt and drops any frame whose envelope `created` predates it (counted as
`event_frames_dropped_total{reason="stale"}`), because accepting one finalised a
fresh turn with no output — an empty answer reported as a normal `stop`.
`created` is only used for ordering when it is recognisably epoch milliseconds
(`EPOCH_MS_FLOOR`), so a seconds-based or duration-like value can never drop a
turn's frames; an assistant message id cannot scope a turn at all, since one
agent turn spans one assistant message per step.

The stream is documented as volatile: a slow consumer overflows and fails it, and
events during a disconnect are lost. `EventHub` reconnects with backoff and
notifies subscribers through `onReconnect`. In-flight completions do **not**
Expand Down Expand Up @@ -220,6 +232,9 @@ removed; `Surface` gained the `openai.completions` member for the legacy
completions endpoint. `CompletionEvent` `text_end` and `reasoning_end` gained an
optional `messageId` (the upstream assistant message id when known) so streamed
surfaces can use the same identifiers as the buffered aggregate.
`InternalRequest.serviceTier?: string` is the latest additive field: the OpenAI
surfaces accept `service_tier` for client compatibility, record it there and name
it in `x_opencode.unapplied`, because no OpenCode equivalent exists.

`InternalRequest.stop`, `maxTokens`, `temperature` and `topP` were write-only for
a while. `stop` is now consumed by the Anthropic surface and by the OpenAI chat
Expand Down Expand Up @@ -494,10 +509,16 @@ embedded in the upstream `data:` URI only when it matches the RFC 6838
`application/octet-stream`. A value carrying a comma would otherwise turn the
payload into a non-base64 body the receiver never decodes.

`isPrivateHost()` normalises the address itself before classifying it: any IPv6
`isPrivateHost()` normalises the address itself before classifying it: an IPv6
zone identifier (`%en0`, `%25en0`) is stripped, any IPv6
spelling (full, compressed, IPv4-mapped, IPv4-compatible, dotted tail) is expanded
first, then IPv4 is canonicalised, then loopback, RFC1918, link-local, unique-local,
multicast, `0.0.0.0`, `100.64/10` and the cloud-metadata ranges are matched.
multicast, `0.0.0.0`, `100.64/10` and the cloud-metadata ranges are matched. A
colon-containing host that `net.isIP` rejects, and an otherwise unrecognised IPv6
literal whose last 32 bits decode to a private IPv4, are treated as private; a
single trailing dot is stripped before the hostname table is consulted, so
`localhost.` is loopback. A remote attachment stores `${host}${pathname}` in
`origin` — never a credential or a query string.
`isWithinRoots()` compares resolved real paths, so a caller must `realpath` the
candidate first. Both are exported for the media path and for tests; the media
code never relies on `new URL()` having canonicalised the hostname.
Expand Down Expand Up @@ -598,6 +619,13 @@ tests can substitute a scripted runner (`test/helpers/context.ts`).
* All code, comments, JSDoc, log messages, error messages, tests and docs are in **English**.
* Validation uses `zod` (`z.object({...}).safeParse(body)`), and on failure throw
`ApiError.badRequest(message, { code: "invalid_request", param })`.
* Route classification — public paths, `/admin/*` versus `/metrics`, the
rate-limit bucket and the Anthropic error envelope — goes through
`classifyPath()` (`src/auth.ts`), which prefers the matched route pattern over
`request.url`. The router matches on the percent-decoded path while the raw URL
keeps the caller's bytes, so comparing `request.url` against a route literal
let `/%61dmin/config` reach an admin route as a general request; never classify
on the raw URL again.
* Never call `fetch` to the OpenCode server directly; use `ctx.client`.
* Never call the model provider directly; use `runCompletion`/`collectCompletion`.
* Streaming handlers must:
Expand Down Expand Up @@ -631,11 +659,16 @@ tests can substitute a scripted runner (`test/helpers/context.ts`).
`OPENCODE_REASONING_FIELD=both` (read from `Config.reasoningField`).
* Anthropic: `/v1/messages` accepts `thinking: { type, budget_tokens }` — the
documented Anthropic shape — and additionally tolerates a non-standard
`thinking.effort` / top-level `reasoning_effort` as a convenience. Reasoning
becomes a `thinking` content block with a deterministic `signature`; the
streamed form emits the same signature as `signature_delta` before the block
stops, using the upstream assistant message id carried by `reasoning_end` /
`text_end`, so streamed and buffered signatures agree.
`thinking.effort` / top-level `reasoning_effort` / `output_config.effort` as a
convenience (`output_config.format` maps onto `InternalRequest.responseFormat`
when `text(format)` is absent; `thinking` wins over `output_config.effort`).
Reasoning becomes a `thinking` content block with a deterministic `signature`
keyed on the **gateway** message id: the streamed form emits it as
`signature_delta` before the block stops and the buffered form signs with the
same value, while the upstream assistant id is not available when the streamed
block closes (it only arrives with `reasoning_end` / `text_end`). Keying on the
upstream id made the two paths disagree, because the buffered aggregate always
has it and the streamed path usually does not.
* Anthropic `stop_sequences` is honoured by an adapter-local filter over assistant
text only, shared by both paths (`truncateAtStopSequence`): the visible text is
truncated at the first match, `stop_reason` becomes `stop_sequence` and
Expand All @@ -646,15 +679,24 @@ tests can substitute a scripted runner (`test/helpers/context.ts`).
adapters honour `stop` the same way and keep their documented `finish_reason`.
* Fields the gateway cannot honour are never silently ignored: the OpenAI surfaces
accept the generation knobs (`temperature`, `top_p`, `max_tokens`,
`max_completion_tokens`, `max_output_tokens`, `presence_penalty`,
`frequency_penalty`, `seed`, `logit_bias`) for client compatibility and list
them in `x_opencode.unapplied` on the final payload, and they reject every field
that would change the shape of the response (`logprobs`/`top_logprobs` when
requested, non-text `modalities`, `audio`, `prediction`, `store: true`,
`web_search_options`, legacy `functions`/`function_call`,
`previous_response_id`, non-empty `include`, `best_of`, `suffix`, and any
`detail` other than `"auto"`) with `400 unsupported_parameter` naming the field
in `param`.
`max_completion_tokens`, `max_output_tokens`, `service_tier`,
`presence_penalty`, `frequency_penalty`, `seed`, `logit_bias`) for client
compatibility and list them in `x_opencode.unapplied` on the final payload, and
they reject every field that would change the shape of the response
(`logprobs`/`top_logprobs` when requested, non-text `modalities`, `audio`,
`prediction`, `store: true`, `web_search_options`, legacy
`functions`/`function_call`, `previous_response_id`, non-empty `include`,
`best_of`, `suffix`, `json_schema`/`text.format` with `strict: true`, media parts
on a role that cannot carry them, and any `detail` other than `"auto"`) with
`400 unsupported_parameter` naming the field in `param`. An invalid
`reasoning_effort` is `400 invalid_request` (`param: "reasoning_effort"`) rather
than a silent fold into `medium`.
* Token accounting is per surface: the upstream reports cached input separately
(`input` is the non-cached count), so the OpenAI `prompt_tokens` /
`input_tokens` fold `cache_read` and `cache_write` into the prompt and expose
them as the `cached_tokens` subset, while `/v1/messages` keeps Anthropic's
convention where `input_tokens` excludes them. Thinking tokens are a subset of
the completion/output count on every surface.
* `/v1/responses` reports a filtered turn as `status: "incomplete"` with
`incomplete_details.reason: "content_filter"`, keeps `created_at` constant for
the whole response, echoes `instructions`, announces the reasoning item with
Expand Down Expand Up @@ -694,15 +736,18 @@ tests can substitute a scripted runner (`test/helpers/context.ts`).
* JSON output is bridged through the prompt, exactly like tool calling:
`response_format` (chat) and `text.format` (responses) become a
`# Response format` prompt section (`InternalRequest.responseFormat`). Nothing
validates the reply server-side.
validates the reply server-side, so `strict: true` is rejected rather than
accepted-and-ignored, and `/v1/responses` echoes the effective `text.format`
(`{"type":"text"}` by default) on the response object.
* Client disconnects are detected from the response connection
(`src/http/disconnect.ts`); an in-flight turn is interrupted, the sticky slot
is released and a pending media download is aborted.
* `POST /v1/completions` maps a legacy `prompt` (a string, or a single-element
array with `n: 1`) onto one user turn and re-frames the same normalised events
array) onto one user turn and re-frames the same normalised events
as `text_completion` objects or `text_completion` SSE chunks; `echo: true` is
rejected with `400 unsupported_parameter` because the prompt is not replayed
verbatim by the agent.
verbatim by the agent, and so is a `prompt` array with more than one element —
silently joining them returned a completion that matched none of the prompts.
* `parallel_tool_calls: false` on the OpenAI surfaces reaches the tool bridge and
caps the model at one bridged call per turn; the default wording is unchanged.
* `/v1/responses` reports `status: "failed"` with an `error` object when the turn
Expand Down
3 changes: 3 additions & 0 deletions docs/CONFIGURATION.md
Original file line number Diff line number Diff line change
Expand Up @@ -145,6 +145,9 @@ way: the default (`on-request`, `info`) is kept and a warning naming the variabl
is logged. The warning never echoes the value, because an operator can paste a
secret into the wrong variable.

`OPENCODE_REASONING_FIELD` follows the same rule: an unrecognised value falls back
to `reasoning_content` and logs the same warning naming the variable.

## Environment variables read by other libraries

`dotenv` loads `.env` from the project root and then the working directory. The
Expand Down
56 changes: 56 additions & 0 deletions docs/VERIFICATION.md
Original file line number Diff line number Diff line change
@@ -1,5 +1,11 @@
# OpenCode API — independent verification report

> **This document is a layered record.** Sections 1–5 and the first two addenda
> below describe the 2026-12-02 audit and the remediation passes that followed, in
> their own numbers. The **last addendum** ("current state after the
> audit-and-fix pass of 2026-12-05") is the authoritative current state: where any
> earlier count or line reference disagrees with it, the last addendum is correct.

* **Date of audit:** 2026-12-02 (Asia/Saigon, UTC+07:00)
* **Auditor:** independent adversarial verifier (did not write the code)
* **Version audited:** `opencode-api` 0.1.0 (`package.json` at audit time; the released package is `1.0.0`), working tree as of 16:05 local time
Expand Down Expand Up @@ -323,3 +329,53 @@ Still unresolved at the time of writing: none of the P-01 … P-25 items were le
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.

### Addendum — current state after the audit-and-fix pass of 2026-12-05

The body and the two earlier addenda above are the historical record of the
2026-12-02 audit and the remediation passes that followed. This addendum is the
authoritative **current** state; where a number above disagrees with this table,
this one is correct.

| Command | Result |
| --- | --- |
| `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 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 |

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`.
* 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`.
Loading
Loading