Skip to content

Latest commit

 

History

History
140 lines (117 loc) · 7.14 KB

AGENTS.md

File metadata and controls

140 lines (117 loc) · 7.14 KB

AGENTS.md

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.

What this project is

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.

Read before changing anything

  1. docs/ARCHITECTURE.md — the frozen internal contract, the module boundaries and every verified upstream fact.
  2. src/upstream/completion.ts — the single orchestrator every surface goes through.
  3. src/types/internal.ts — the normalised request/event model.
  4. CONTRIBUTING.md — coding standards and the commit message convention.

Commands

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 commit

main 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.

Non-negotiable invariants

  • The internal contract is frozen. Changing a signature in src/types/internal.ts, src/errors.ts, src/upstream/* or src/adapter/common/* means updating every call site and docs/ARCHITECTURE.md in the same change.
  • ESM with explicit extensions. Every relative import ends in .js.
  • TypeScript strict plus noUncheckedIndexedAccess. No any; use unknown and 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 through ctx.client. Never fetch() 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 SseWriter lazily (so pre-stream failures still return a real HTTP status), always close() it, and balance ctx.metrics.activeStreams in a try/finally.
  • No new runtime dependency without justification. fastify, zod, pino, prom-client, dotenv are the whole runtime surface today.

Upstream facts that cause bugs when forgotten

These were verified against opencode serve 2.3.2; re-read docs/ARCHITECTURE.md §2 for the details.

  • Attachments only accept data:<mime>;base64,… or file:// URIs. Plain http(s) URLs are rejected, so remote media must be fetched and inlined.
  • /api/event is a single global SSE stream; frames are data: {json} with the discriminator inside the JSON (type), plus : heartbeat comments. The stream is volatile. A mid-turn reconnect is not reconciled from GET /api/session/{id}/message: runCompletion keeps a 5 s grace window for the terminal event and otherwise fails the turn with 503 event_stream_lost.
  • time.released is in milliseconds; OpenAI's created is in seconds.
  • The free tier answers 429 provider.free-limit with retryAfterMs. 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 with deny rules 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: true after an abort, timeout or failure. execute() releases it in finally; keep it that way.

Where to change what

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

Security constraints

  • Caller authentication is mandatory (src/auth.ts); the built-in default key sk-dummy-123 exists only so a fresh clone runs. Never log a key or an Authorization header, 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 be realpath-checked against OPENCODE_ALLOWED_FILE_ROOTS.
  • Never widen bodyLimitBytes, attachment caps or request timeouts to make a test pass.

Testing rules

  • Unit tests must not need a live OpenCode server or network access. Use createTestContext({ script }) from test/helpers/context.ts to script the normalised CompletionEvent stream, then drive the real Fastify app with buildServer(ctx) and app.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.

Before you finish

  1. pnpm typecheck — clean.
  2. pnpm build — clean.
  3. pnpm test — green.
  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).
  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.