Guidance for AI coding agents working in this repository. Humans are welcome to read it too — it is the shortest path to a change that fits the codebase.
OpenCode API is a Node.js + Fastify + TypeScript gateway that exposes the AI
models reachable by the OpenCode CLI 2.x runtime through OpenAI-compatible
(/v1/chat/completions, /v1/responses) and Anthropic-compatible
(/v1/messages) endpoints, with SSE streaming, vision/media input, thinking
effort and tool calling. Default port 20123.
The gateway spawns and supervises its own opencode serve child process and
translates between the public wire formats and the OpenCode HTTP API.
docs/ARCHITECTURE.md— the frozen internal contract, the module boundaries and every verified upstream fact.src/upstream/completion.ts— the single orchestrator every surface goes through.src/types/internal.ts— the normalised request/event model.CONTRIBUTING.md— coding standards and the commit message convention.
pnpm install
pnpm setup # .env with the default key sk-dummy-123
pnpm dev # watch mode
pnpm typecheck # must stay clean
pnpm build # tsc emit into dist/
pnpm test # unit tests, no network or CLI needed
pnpm test:integration # needs a running gateway + real upstream quota
pnpm lint:commits # commitlint on your last local commitmain is protected: never commit to it directly. Work on a branch
(feat/..., fix/..., docs/...), push it, and open a pull request — CI
(.github/workflows/ci.yml) must pass before it can be merged.
Never start another server on port 20123 while one is running, and prefer
app.inject() through buildServer(ctx) over real sockets in tests.
- The internal contract is frozen. Changing a signature in
src/types/internal.ts,src/errors.ts,src/upstream/*orsrc/adapter/common/*means updating every call site anddocs/ARCHITECTURE.mdin the same change. - ESM with explicit extensions. Every relative import ends in
.js. - TypeScript strict plus
noUncheckedIndexedAccess. Noany; useunknownand narrow it. - English only — code, comments, JSDoc, logs, errors, tests, docs, commits.
- Two entry points, no direct upstream calls. Adapters use
ctx.completion.run()/ctx.completion.collect(); anything else upstream goes throughctx.client. Neverfetch()the OpenCode server from an adapter, and never call a model provider directly. - Both paths always. Every change to a completion surface must work streamed
and buffered. Streaming handlers open
SseWriterlazily (so pre-stream failures still return a real HTTP status), alwaysclose()it, and balancectx.metrics.activeStreamsin atry/finally. - No new runtime dependency without justification.
fastify,zod,pino,prom-client,dotenvare the whole runtime surface today.
These were verified against opencode serve 2.3.2; re-read
docs/ARCHITECTURE.md §2 for the details.
- Attachments only accept
data:<mime>;base64,…orfile://URIs. Plainhttp(s)URLs are rejected, so remote media must be fetched and inlined. /api/eventis a single global SSE stream; frames aredata: {json}with the discriminator inside the JSON (type), plus: heartbeatcomments. The stream is volatile. A mid-turn reconnect is not reconciled fromGET /api/session/{id}/message:runCompletionkeeps a 5 s grace window for the terminal event and otherwise fails the turn with503 event_stream_lost.time.releasedis in milliseconds; OpenAI'screatedis in seconds.- The free tier answers
429 provider.free-limitwithretryAfterMs. A live test failing with 429 is an environment problem, not a code defect — do not "fix" it by loosening assertions; skip the model call instead. - Function calling cannot be passed natively: the client's tools are rendered
into the prompt and parsed back from
[[OPENCODE_TOOL_CALL]]envelopes. When a request declares tools, the session is created withdenyrules for the agent's built-in actions so the model does not answer with its own shell/web tools instead. - A sticky session record must never stay
busy: trueafter an abort, timeout or failure.execute()releases it infinally; keep it that way.
| Change | Where |
|---|---|
| A new public endpoint | src/adapter/<surface>/…ts + registerXxxRoutes(app, ctx) + call it in src/server.ts + document in docs/API.md |
| A new request field | the surface adapter's zod schema, then InternalRequest if the orchestrator needs it |
| A new environment variable | src/config.ts and .env.example and docs/CONFIGURATION.md |
| Thinking-effort behaviour | src/adapter/common/reasoning.ts |
| Tool envelope or transcript format | src/adapter/common/tools.ts |
| Media source handling (SSRF, size caps, path roots) | src/media/resolve.ts |
| Prompt composition / session reuse | src/upstream/completion.ts, src/upstream/sessions.ts |
| Upstream process lifecycle | src/upstream/process.ts |
| Metrics | src/metrics/registry.ts + increment where the event happens |
- Caller authentication is mandatory (
src/auth.ts); the built-in default keysk-dummy-123exists only so a fresh clone runs. Never log a key or anAuthorizationheader, and never accept a key from the query string. - Remote media resolution must keep: scheme allow-list, manual redirect handling
with per-hop re-validation, DNS/private-address checks when
OPENCODE_ALLOW_PRIVATE_MEDIA_URLS=false, and bounded streaming reads. - Local files stay disabled unless
OPENCODE_ALLOW_LOCAL_FILES=true, and must berealpath-checked againstOPENCODE_ALLOWED_FILE_ROOTS. - Never widen
bodyLimitBytes, attachment caps or request timeouts to make a test pass.
- Unit tests must not need a live OpenCode server or network access. Use
createTestContext({ script })fromtest/helpers/context.tsto script the normalisedCompletionEventstream, then drive the real Fastify app withbuildServer(ctx)andapp.inject(). - Add a regression test for every bug fix; it must fail before the fix.
- Assert on documented behaviour (wire shape, finish/stop reason, SSE ordering, status codes), not on incidental formatting.
pnpm typecheck— clean.pnpm build— clean.pnpm test— green.pnpm smoke:dist— the emitteddist/boots and answers/health.pnpm audit --prod— no advisory in the shipped dependencies (the CI merge gate).- Docs updated when a contract, env var or wire format changed.
- No secrets, no debug logging, no commented-out code, no scratch files
(
.recon/,dist/,.opencode-api/are ignored and should not be committed). - Commit with a Conventional Commit message, as described in
CONTRIBUTING.md(for examplefix(sessions): release the slot after a timeout);pnpm lint:commitschecks it againstcommitlint.config.mjs.