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 @@ -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
8 changes: 5 additions & 3 deletions AGENTS.md
Original file line number Diff line number Diff line change
Expand Up @@ -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`.
4 changes: 4 additions & 0 deletions CONTRIBUTING.md
Original file line number Diff line number Diff line change
Expand Up @@ -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
```

Expand Down Expand Up @@ -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.
Expand Down
11 changes: 8 additions & 3 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -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). |
Expand Down Expand Up @@ -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. |
Expand Down Expand Up @@ -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
Expand Down
27 changes: 19 additions & 8 deletions docs/API.md
Original file line number Diff line number Diff line change
Expand Up @@ -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.
Expand Down Expand Up @@ -457,6 +458,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
Expand Down Expand Up @@ -899,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 \
Expand Down Expand Up @@ -970,11 +981,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
Expand Down
10 changes: 8 additions & 2 deletions docs/ARCHITECTURE.md
Original file line number Diff line number Diff line change
Expand Up @@ -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`.

Expand Down Expand Up @@ -435,6 +435,10 @@ renderToolResult(message): string, class ToolCallFilter(allowedNames?: Iterable<
// declared, so the check runs once for every surface.

// usage.ts
// 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)
```

Expand Down Expand Up @@ -481,6 +485,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
Expand Down Expand Up @@ -569,7 +575,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
Expand Down
12 changes: 10 additions & 2 deletions docs/CONFIGURATION.md
Original file line number Diff line number Diff line change
Expand Up @@ -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 <key>`, `x-api-key: <key>`,
Expand Down Expand Up @@ -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:<password>`). | 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. |
Expand Down Expand Up @@ -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
Expand Down
Loading
Loading