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
15 changes: 12 additions & 3 deletions .dockerignore
Original file line number Diff line number Diff line change
@@ -1,11 +1,17 @@
# Keep the build context to what the image actually needs.
# Keep the build context to what the image actually needs: the builder stage compiles `dist/` from `src/` with the
# dev dependencies, and the runtime stage installs the production dependencies - so the context is the source, never
# a local build output or a local dependency tree.
# node_modules is critical: without it `COPY . .` would overwrite the Linux dependencies installed inside the image
# with whatever the host has (a macOS or Windows tree), and a local config.json/.env would be baked into the image.
node_modules
.pnpm-store
.git
.gitignore
.github
# The build output is generated inside the builder stage (`pnpm run build`), never taken from the host: a `dist/` built
# on macOS or Windows can carry the wrong platform's `wreq-js` binding and stale code, and the runtime stage copies the
# compiler's own output only. Excluding it also keeps the context small, because `dist/` holds a full copy of the tree.
dist
# Credentials: the exact names were the only ones kept out, so `.env.local` / `config.local.json` / a private key
# sitting in the working tree were baked into the image layer that `COPY . .` creates. `.env.*` also covers a backup of
# one (`.env.local.bak`), because `*` matches dots.
Expand Down Expand Up @@ -44,11 +50,14 @@ id_ed25519*
.DS_Store
.vscode
.idea
# The smoke suite needs a stub backend and a writable port; it is not part of the runtime image
test
# Documentation is not part of the runtime image either: it was shipped into /app (AGENTS.md alone is tens of KB) and
# nothing in the container reads it. LICENSE stays, because it has to travel with the code.
AGENTS.md
CONTRIBUTING.md
README.md
docker/README.md
# `test/` used to be excluded here as "not part of the runtime image". It still is not - the runtime stage copies
# `dist/`, the manifests and the entrypoint, and nothing else - but the builder stage needs the suites in the context,
# because tsconfig.json compiles `test/**` as well. Excluding the directory made `COPY test ./test` fail with
# `failed to compute cache key: "/test": not found`, so the exclusion lives in the Dockerfile's COPY list instead,
# which is where "not in the image" belongs.
187 changes: 115 additions & 72 deletions .github/workflows/ci.yml

Large diffs are not rendered by default.

10 changes: 10 additions & 0 deletions .gitignore
Original file line number Diff line number Diff line change
@@ -1,4 +1,9 @@
node_modules
# Build output. The project is TypeScript now: `pnpm run build` emits the runnable JavaScript into `dist/`, which is
# generated on every build and never reviewed, so it stays out of the tree. `dist-check-*` is the private outDir the
# migration briefs hand a contributor so two concurrent type-check builds cannot overwrite each other's output.
dist/
dist-check-*/
.DS_Store
*.log
npm-debug.log*
Expand Down Expand Up @@ -44,3 +49,8 @@ id_ed25519*
# Editor and IDE state: not a credential, but it is machine-local and never belongs in a commit
.vscode
.idea
# Local reference material for this project's own work: other repositories and documents consulted while changing this
# one. It is machine-local working material - none of it is part of this project or of its history - so the whole
# directory stays out of the tree, and a `git add -A` cannot sweep a nested checkout's own `.git` directory into this
# repository. The trailing slash ignores the directory itself rather than only a path that happens to be a file.
refers/
816 changes: 322 additions & 494 deletions AGENTS.md

Large diffs are not rendered by default.

124 changes: 73 additions & 51 deletions CONTRIBUTING.md
Original file line number Diff line number Diff line change
Expand Up @@ -21,9 +21,12 @@ purpose is to disable authentication.

| Requirement | Version | Notes |
| --- | --- | --- |
| Node.js | `>=20` (developed on Node 26) | ESM-only project, no build step |
| Node.js | `>=20` (developed on Node 26) | ESM-only TypeScript project; the sources compile to `dist/` with `tsc`, and `dist/index.js` is what runs |
| pnpm | `>=12` (`packageManager: pnpm@12.18.0`) | use pnpm, never npm, for this repository |
| OpenCode CLI | **2.x** release | `npm install -g @opencode/cli` (the newest release), or `curl -fsSL https://opencode.ai/install \| bash` followed by `opencode --version`; authenticate with `opencode auth login` |
| TypeScript | `5.9.3` (dev dependency) | `pnpm run build` compiles `index.ts`, `src/**/*.ts` and `test/**/*.{ts,mjs}` into `dist/` (`rootDir: "."`, so `dist/index.js`, `dist/src/*.js`, `dist/test/*.mjs`); `pnpm run typecheck` is the same compiler with `--noEmit` |

Nothing else is installed: there is no OpenCode CLI to fetch and no upstream account to authenticate. The gateway talks to
`https://opencode.ai`'s own inference API, and the suites talk to an in-repository stub of it.

## Local setup

Expand All @@ -32,11 +35,13 @@ git clone https://github.com/dinhdev666/opencode-api.git
cd opencode-api
pnpm install --frozen-lockfile # use plain `pnpm install` when you intentionally change dependencies
cp config.json.example config.json # optional: file-based configuration
pnpm test # five suites (stub backend, no OpenCode CLI needed)
pnpm start # gateway on http://127.0.0.1:8083, backend on :4097
pnpm run build # tsc -> dist/; nothing runs from source, so build before you run anything
pnpm run typecheck # tsc --noEmit; this is the repository's linter, there is no separate one
pnpm test # every suite, against the free-upstream stub: no network and no CLI
pnpm start # build, then serve on http://127.0.0.1:8083
```

Smoke test:
Quick check:

```bash
curl -s http://127.0.0.1:8083/health
Expand All @@ -51,24 +56,37 @@ in development.

## Coding conventions

- **ES modules only** (`import`/`export`, `"type": "module"`); no CommonJS, no transpiler.
- **No new dependencies without an issue.** Fastify and `@opencode/client` are the only runtime dependencies; logging,
CORS, routing helpers and body handling are in-tree on purpose.
- **TypeScript, strict.** The sources are `.ts` and `tsconfig.json` turns on `strict`, `noImplicitOverride`,
`noFallthroughCasesInSwitch`, `forceConsistentCasingInFileNames` and `useUnknownInCatchVariables`; `pnpm run
typecheck` must be clean. Prefer `unknown` to `any` — `any` switches the guarantee off at exactly the boundary that
needs it, so narrow with a type guard or a small `asRecord()`-style helper instead. Comments explain **why** a
behaviour is what it is, not what the next line does; the free-tier values and the transport rule in
`src/opencode-free/constants.ts` and `src/opencode-free/transport.ts` are the load-bearing examples.
- **ES modules only** (`import`/`export`, `"type": "module"`); no CommonJS, no bundled transpiler, no second build
tool. Import specifiers stay `.js` even from a `.ts` file (`./proxy.js`), because that is the file the compiler
emits.
- **No new dependencies without an issue.** `fastify` and `wreq-js` are the only runtime dependencies; logging,
CORS, routing helpers and body handling are in-tree on purpose. `wreq-js` is pinned to an exact version rather than
a range because its native binding ships per platform, so "the newest minor" is not necessarily a binding this
project has.
- **Style** — 4-space indentation and semicolons throughout; prefer `const`, prefer `async`/`await` over raw promise
chains in handlers, and quote strings the way the surrounding file already does. No formatter or linter is
configured, so consistency with the file you are editing is reviewed by hand.
- **Logging** — always through `src/logger.js`; never `console.log` in `src/` or `index.js`; never log an unmasked
- **Logging** — always through `src/logger.ts`; never `console.log` in `src/` or `index.ts`; never log an unmasked
`authorization` header; expensive debug payloads go behind `logger.isEnabled('debug')`.
- **Errors** — user-facing failures use the OpenAI envelope `{"error":{"message":"…","type":"…"}}`; internal errors
are logged with context, not swallowed.
- **Configuration** — new settings follow env > `config.json` > default precedence and must also be added to
`config.json.example`, the README configuration table, and `docker/docker-entrypoint.sh` when containers need them.
The entrypoint persists only the keys it writes into the generated `/app/config.json` (its header lists them); the
advanced tuning keys are read from the environment or from a mounted file and are not copied into that file.
- **Backend lifecycle and streaming code** — read the comments in `src/proxy.js` before touching `collectFromEvents`,
`pollForAssistantResponse`, `ensureBackend` or the SSE branch; those blocks encode fixes for real OpenCode protocol
quirks. The completion queue lives in `src/queue.js`, the readiness probe in `src/backend-health.js` and the three
request normalizers/SSE writers in `src/chat.js`, `src/responses.js` and `src/anthropic.js`.
- **The free lane and streaming code** — read the comments in `src/opencode-free/` and the SSE branch of
`src/proxy.ts` before touching them; those blocks encode what the upstream gate compares and which failures are
transient. The upstream conversation lives in `src/opencode-free/driver.ts`, the request shape and its fingerprint in
`request.ts`/`fingerprint.ts`, the transport in `transport.ts`, the session ids in `session.ts`, the model list in
`catalog.ts`, and the three request normalizers/SSE writers in `src/chat.ts`, `src/responses.ts` and
`src/anthropic.ts`. Do not "tidy" a fingerprint constant, a header or a session-id shape: each one is there because a
request without it is refused upstream.

## Commit messages

Expand Down Expand Up @@ -127,20 +145,19 @@ Defaults to 1 so existing behaviour is unchanged.
```

```
fix(stream): stop waiting four seconds when the event stream is silent
fix(stream): answer the queue-full refusal in the route's own envelope

opencode >= 1.19 intermittently delivers no message.part.updated events.
Once the prompt call returns, the answer is already pollable, so the
first-delta wait is shortened to ~50 ms. Stream p50 under load drops from
4014 ms to 484 ms with a stub backend.
The onRequest short-circuit answered /v1/messages with a chat-shaped
queue_full. An Anthropic SDK switching on error.type read a value its own
vocabulary does not have; the refusal now goes through earlyErrorBody().
```

```
perf(backend): cache successful health probes for two seconds
perf(proxy): serve an expired model listing while the refresh runs

Each chat completion opened a fresh TCP probe. Bursts now share one probe
over a keep-alive socket; non-stream throughput rises from ~1900 to
~3900 req/s.
The request that crossed the cache TTL awaited a full upstream round trip.
An expired-but-known listing now answers it while the refresh runs behind
it: 5.0 ms to 0.6 ms on a loopback stub.
```

```
Expand Down Expand Up @@ -213,8 +230,9 @@ Example: `fix/stream-first-delta-fallback`.

### PR checklist

- [ ] `pnpm run check` passes (syntax check for every JavaScript file).
- [ ] `pnpm test` passes; new assertable behaviour is covered in `test/smoke.mjs`.
- [ ] `pnpm run check` passes (it is `pnpm run typecheck`, i.e. `tsc --noEmit` over the whole project).
- [ ] `pnpm test` passes; new assertable behaviour is covered in the suite that owns it (`test/stream.ts` for upstream
behaviour, `test/contract.ts` for the HTTP surface, `test/protocols.ts` for the Responses and Messages wires).
- [ ] The gateway boots and `GET /health` returns `200`.
- [ ] `/v1/models` returns `401` without a key and `200` with it.
- [ ] Chat completions were exercised both with and without `stream: true`.
Expand All @@ -228,43 +246,47 @@ Example: `fix/stream-first-delta-fallback`.

## Testing

`pnpm test` runs five suites in order, and none of them needs an OpenCode CLI or network access:
`test/smoke.mjs` (the chat/SSE contract), `test/protocols-smoke.mjs` (`/v1/responses` and `/v1/messages` end to end)
and the three codec unit tests (`test/protocol-responses.mjs`, `test/protocol-anthropic.mjs`, `test/protocol-chat.mjs`),
which need no ports at all. The two end-to-end suites boot `test/lib/stub-opencode.mjs` (a minimal `opencode serve`
stand-in) plus the gateway through the shared scaffolding in `test/lib/harness.mjs` - a library, not a suite, used by
both.

`test/smoke.mjs` asserts the chat contract end to end: the root index and health, auth (401 with a missing or wrong
key, with a `type` and `code`), CORS and preflight, the request-id header, model listing and by-id answers (including
ids with several slashes and ids that are not models), 400 validation, the 404 envelope, non-streaming completions,
SSE frames (valid JSON, streamed content and reasoning, the stop and usage frames, `[DONE]`), the failure and
fallback paths (a rejected session, prompt, message poll or event stream), tool-call filtering across delta
boundaries, the queue (a full queue answers `503 queue_full`; an abandoned or stalled stream frees its slot; a
request abandoned while queued never reaches the backend), session cleanup on every path, and clean `SIGINT`
shutdown. `test/protocols-smoke.mjs` covers the other two protocols the same way, their own frame vocabularies and
error envelopes included, and boots a second short-lived gateway (`PROTOCOLS_SMOKE_PORT + 1`, concurrency 2, a 1.5 s
request budget) to check that concurrent Responses streams keep their own sequence numbers and terminal frames. Each
end-to-end suite owns its own port pair, so both can run at once: `test/smoke.mjs` listens on stub port 4199 and
gateway port 8199, overridden with `SMOKE_STUB_PORT` / `SMOKE_PORT`, and `test/protocols-smoke.mjs` on stub port 4299
and gateway port 8299, overridden with `PROTOCOLS_SMOKE_STUB_PORT` / `PROTOCOLS_SMOKE_PORT` (it refuses to start when
either is busy rather than sharing the chat suite's ports). `AGENTS.md` lists the stub's test markers, which is where to
look before adding a case for a new behaviour.
`pnpm test` builds first and then runs every suite from `dist/`. None of them needs network access and none needs an
OpenCode CLI - that is what `test/lib/stub-free-upstream.ts` is for: it stands in for the upstream and enforces the
free tier's own gates, so a request the lane gets wrong is refused the way the real host refuses it.

| Suite | What it protects |
| --- | --- |
| `test/contract.ts` | The gateway's own HTTP contract: the authentication variants, CORS and preflight, request ids, the 404 sentence, the body policy, each protocol's error envelope, the queue-full `503`, `DISABLE_TOOLS`, malformed and oversized bodies |
| `test/protocols.ts` | `/v1/responses` and `/v1/messages` end to end: each frame vocabulary, the non-streaming shapes, the Anthropic `max_tokens`/thinking mapping, the `anthropic-version` echo, and each route's own queue-full code |
| `test/stream.ts` | The upstream-facing half: delta ordering, reasoning and usage, a mid-stream upstream failure, an upstream refusal surfacing its status, masking in an echoed upstream message, the overload retry, session reuse, and the fingerprint the stub enforces |
| `test/effort.ts` | The thinking-level table and its one downgrade (`max`/`ultra` to the strongest level the model serves), the spelling each wire then carries, and the level the upstream really received |
| `test/vision.ts` | Images in each wire's own shape (chat `image_url`, Responses `input_image`, Messages `image` block), a remote image forwarded by reference, and a `file`/`document` part refused by name on every route |
| `test/protocol-chat.ts`, `test/protocol-responses.ts`, `test/protocol-anthropic.ts` | The three codecs in isolation - request normalizer, body builder, SSE writer - with no ports and no stub |

`test/lib/free-harness.ts` is the shared scaffolding every end-to-end suite loads (boot the stub, boot the gateway
in-process, count failures instead of throwing, read every assertion off the wire) and `test/lib/codec-checks.ts` holds
the assertions the three codec suites share. Both are libraries, not suites. Each end-to-end suite owns its own port
pair, so they can run at once: contract 4700/8700, protocols 4710/8710, stream 4720/8720, effort 4740/8740, vision
4750/8750. Every suite prints the exact number of checks it executed, so quote that number rather than this table.

`test/live-free.ts` is the one opt-in check, and it is deliberately **not** part of `pnpm test`, because it is the only
thing that can prove what the stub by construction cannot: that the upstream's TLS gate accepts this process.
`OPENCODE_FREE_LIVE=1 node dist/test/live-free.js` spends one catalog read, one short completion and one session id
from the free tier's own quota, and also asserts that a plain `fetch` to the same endpoint is *refused* - which is the
evidence that the completion passed because of the impersonating transport and not because the gate is absent. A failure
there is not automatically a bug in this repository: the upstream owns the gate and can change it at any time.

CI (`.github/workflows/ci.yml`) runs `pnpm run check`, the container entrypoint shell check and `pnpm test` on Node
20, 22 and 24, then builds the Docker image, checks that the container answers `/health`, and checks that the image
enforces authentication (`/` open, `/v1/models` 401 without a key and 200 with the built-in key).

When adding behaviour worth protecting, extend `test/lib/stub-opencode.mjs` and `test/smoke.mjs` instead of writing a
one-off script. For exploratory checks a throwaway stub in `/tmp` is fine.
When adding behaviour worth protecting, extend `test/lib/stub-free-upstream.ts` and the suite that owns that behaviour
instead of writing a one-off script. `AGENTS.md` lists the stub's markers, which is where to look before adding a case.

Additional manual checks that CI cannot cover:

- Use a real `opencode serve` for end-to-end verification, since model latency and provider behaviour vary widely.
- Run the opt-in live check when you touch the fingerprint, the transport or the session shape: every other suite runs
against a stub that enforces the gates by construction, so it cannot tell you the real gate still accepts us.
- When touching streaming, inspect the raw bytes: `data: {…}` frames, a final `finish_reason:"stop"` frame, then
`data: [DONE]`, with reasoning deltas arriving as `reasoning_content`.
- When touching the backend lifecycle, run with the CLI missing (`OPENCODE_PATH` pointing nowhere): requests must
fail in milliseconds, not after a multi-minute startup wait.
- When touching the transport, confirm the missing-binding path on a platform without it: the request must fail with
the named `wreq-js` sentence, not with a stack trace from inside the binding.

## Releasing

Expand Down
Loading
Loading