# AGENTS.md Guidance for OpenCode sessions working in this repo. ## Project `opencode-mcp` — an MCP server (stdio transport) that lets an MCP host drive an [OpenCode](https://opencode.ai) instance and delegate work to its subagents. Built on `@modelcontextprotocol/sdk` + Zod, with real OpenCode integration via `@opencode-ai/sdk` (`createOpencodeServer` / `createOpencodeClient`). Task delegation is **asynchronous**: `opencode_start_task` creates a session and fires `promptAsync` (fire-and-forget), returning a `task_id` immediately. Status/result are polled separately via `opencode_get_task_status` / `opencode_get_task_result`, or long-polled via `opencode_wait_for_task` (`mode: "all"` / `"any"`). ## Commands Runtime requires **Node.js 18+**; development and native TypeScript smoke tests require **Node.js 22.18+**. CI checks the development suite on Node.js 22 and 24. Package manager is **pnpm** (only `pnpm-lock.yaml` exists). Scripts call `npx`/`pnpx` internally, which works regardless of how you invoke them. - `pnpm dev` — launch the MCP Inspector against the server via `tsx` (runs TS directly, no build needed). Use this to test tool wiring interactively. - `pnpm test` — `vitest run` (full suite). - `pnpm test:coverage` — `vitest run --coverage`. Coverage thresholds are **100%** for lines, branches, functions, and statements (see `vitest.config.ts`) — any uncovered line fails the run. - Single test file: `pnpm vitest run tests/modules/tasks/presentation/wait-for-tasks.test.ts`. Single test by name: add `-t "test name"`. - `pnpm build` — clean build: `rm -rf build && tsc && chmod +x build/src/index.js`. **This is also the source typecheck** (no separate `typecheck` script). Tests under `tests/` are outside the build; Vitest transpiles them without typechecking. - `pnpm smoke --message-id-only` — real, non-billable OpenCode message-ID contract probe. `pnpm smoke` runs the full paid smoke; `OPENCODE_MCP_SMOKE_MODEL` overrides its default model. - `pnpm lint` — `biome check .` (read-only). - `pnpm lint:write` — biome check + autofix (lint + format). - `pnpm lint:format` — biome format only. ## Testing Every module has a `.test.ts` Vitest suite under the parallel `tests/` tree mirroring `src/` (e.g. `src/modules/tasks/presentation/mcp/get-task-status.ts` → `tests/modules/tasks/presentation/get-task-status.test.ts`; see `vitest.config.ts` `include`). `src/test-utils/fake-mcp-server.ts` provides a fake `McpServer` for testing tool registration without a real transport (note: its `getHandler()` returns the **last** registered handler — capture a specific tool through `registerTool.mock.calls`). Tests run in a `node` environment; `src/test-utils/` is excluded from coverage. When adding or changing a module, keep its test file at 100% coverage or `pnpm test:coverage` fails. The architecture guardrail lives in `tests/architecture/`: `module-boundaries.test.ts` pins the real repository, `module-boundaries-engine.test.ts` unit-tests the engine (`src/test-utils/module-boundaries-engine.ts`). Rules: `domain`/`application` layers import no frameworks and no infrastructure/presentation (own or other); cross-module imports hit only the other module's facade or its `domain`/`application` contracts; the module import graph stays acyclic (type-only imports included). Platform is exempt as a cycle *source*: its schema references other modules' domain types via `import type` only, so no runtime cycle can close through it. There is **no legacy exemption** — every module under `src/modules/` plays by the same rules. ## Architecture - **Composition root**: `src/index.ts` — awaits `createDelegateTaskInstructions()` (network on cold cache), creates `McpServer` (advertised version must match `package.json`; `tests/index.test.ts` checks this), calls `registerTools(server)`, starts the instance heartbeat, and connects a `StdioServerTransport`. On signals (`SIGHUP`/`SIGINT`/`SIGTERM`) it drains check processes (`stopRunObservers`, from the tasks facade) **before** stamping the instance stopped and calling `killAllServers()`; an `exit` handler is best-effort. A failed check drain keeps everything alive so shutdown can be retried. Hard kills cannot run these handlers. - **Module map** — every module under `src/modules/` is layered (`domain` / `application` / `infrastructure` / `presentation` where applicable), with a root facade `index.ts` as its only public runtime surface: - `platform/` — shared kernel. `infrastructure/persistence/sqlite/` holds the SQLite shared state (`better-sqlite3` + `drizzle-orm`, WAL): auto-bootstrapped schema (`PRAGMA user_version` guard, currently 2), instance registry with heartbeats, short synchronous `BEGIN IMMEDIATE` transactions that never span async I/O. Location: `OPENCODE_MCP_HISTORY_DB` > `$XDG_STATE_HOME` > `~/.local/state/opencode-mcp/history.sqlite`; tests default to `:memory:` via `vitest.config.ts`. Its schema row types reference other modules' domain contracts type-only (JSON column payloads). `infrastructure/config.ts` resolves `MCP_TOOL_TIMEOUT`; `presentation/mcp/mcp-result.ts` holds `jsonResult`/`jsonError`. Consumers (all module infrastructure + presentations) import the platform **facade** (`modules/platform/index.js`), never its internals. - `presentation/mcp/instructions.ts` — `createDelegateTaskInstructions()` builds the MCP server instructions (async: awaits the quota snapshot). It embeds only the *plan and live allowance meters* plus the static tier legend — per-model quotas are deliberately NOT repeated, because `opencode_list_agents` reports them keyed by the real model id. Don't reintroduce a model table: it would be a second, name-keyed copy of data the agent must fetch anyway. - `servers/` — OpenCode server lifecycle. `application/` use cases (`start-server`, `stop-server`, `list-agents`, `list-servers`) are wired in `composition.ts`; `infrastructure/` holds the server registry (live `Map` + durable rows, `killAllServers()` reaps children and stamps `stopped_at`), the SDK launcher, liveness probe, and the permission system (see Permission model below). `presentation/mcp/` registers `opencode_start_server`, `opencode_stop_server` (stop use case + its observer drain are injected by the tool registry wiring — a servers→tasks facade import would close a module cycle), `opencode_list_agents`, `opencode_list_servers`. - `tasks/` — delegation. `domain/` holds persisted contracts (`task.ts`, `task-run.ts`, `cached-task-result.ts`, `status.ts`, `observation.ts`). `application/` holds the `TaskRepository` port, the command use cases (`start-task`, `continue-task`, `cancel-task`), the queries (`get-task-status`, `get-task-result`, `wait-for-tasks`), `derive-status.ts` and the run-observer use case. Everything side-effecting (SDK prompt/session gateway, servers registry, permission scopes, workspaces facade, verification lease/baseline, id generation, observers) arrives through ports bound in `infrastructure/composition.ts` (`taskDispatchPorts` / `taskQueryPorts`). `infrastructure/task-registry.ts` is the full registry (Map hot cache with SQLite hydration, dispatch leases, cancellation, rollback, `AbortController`s, runtime resource extension `baseline`/`workspaceLease`/`controller`); writes go through platform persistence (`BEGIN IMMEDIATE`); `reportReady`/`finalizationStarted`/`finalizedAt` write order and the cancel-wins-over-timestamps rule are frozen. `markTaskCancelled()` stamps `cancelledAt`; `cancel_task` calls it only after a successful **mid-flight** abort — a task whose latest run is already finalized (or already cancelled) is returned as a no-op and never stamped, because `cancelledAt` wins every later status read; aborting alone leaves no trace. `infrastructure/run-observer.ts` finalizes runs in the background and exposes `stopRunObservers` / `stopServerObservers`. `infrastructure/gateway.ts` / `dispatch-gateway.ts` adapt the SDK; `prompt-dispatch.ts` and `message-id.ts` live here too. `presentation/mcp/` registers `opencode_start_task`, `opencode_continue_task`, `opencode_cancel_task`, `opencode_get_task_status`, `opencode_get_task_result`, `opencode_wait_for_task` — schema declarations only, mapping `TaskToolOutcome` onto `jsonResult`/`jsonError`. - `workspaces/` — managed Git worktrees. `infrastructure/git-worktree.ts` / `workspace-registry.ts` own the Git handles and workspace records; `application/` holds create/cleanup/lifecycle use cases; `presentation/mcp/cleanup-workspace.ts` registers `opencode_cleanup_workspace` (cleanup use case injected by the registry wiring). The cleanup task port (`CleanupTaskRegistryPort`) is **bound by the tasks composition** (`bindCleanupTaskPort`, called at import of `tasks/infrastructure/composition.ts`): importing the tasks facade from workspaces would close a tasks↔workspaces cycle, so the dependency flows tasks→workspaces only. - `verification/` — execution verification: workspace snapshots/baselines, leases (`workspace-lease-store.ts`, exclusive overlapping-workspace leases → `workspace_busy` conflicts), the check runner and `relative-path` validation. - `usage/` — OpenCode Go quota and usage accounting (see Usage below). - `tools/index.ts` — **pure registry** (Fase 7): imports each module's MCP presentation and registers every `opencode_*` tool in a fixed order (`start_server`, `stop_server`, `list_agents`, `list_servers`, `start_task`, `get_task_status`, `get_task_result`, `wait_for_task`, `continue_task`, `cancel_task`, `cleanup_workspace`). Its only wiring is the stop-server observer drain (`stopServerObservers` injected from the tasks facade). Registered tool names are prefixed `opencode_`; source filenames are not. - **Cross-module rules**: modules import each other only through facades (root `index.ts`) or `domain`/`application` contracts; infrastructure/presentation internals are off-limits cross-module. The task-registry re-export shim, the run-observer shim, and legacy `src/modules/shared/` are gone. - Task, server, workspace, and usage state persists in the SQLite database and is shared across sibling MCP processes; restarting re-hydrates records and retained worktrees from it (live handles like child processes, SSE connections, and OS timers stay in memory). Verified runs lease directories across processes, so a conflicting run from another instance fails with `workspace_busy`. Worktrees are not security sandboxes; checks run with the MCP process user's privileges. ### Permission model (singletons in `servers/infrastructure/`) A headless `opencode serve` has no interactive approver, so any permission resolved to `ask` blocks the agent **forever**: the session stays genuinely `busy` and the task neither completes nor fails. Three layers instead: 1. `permissions.ts` — `buildServerConfig(policy, { rootDirectory })` is passed to `createOpencodeServer`. Under the default `read-only` policy with a root, `external_directory` becomes the object `{ "/**": "allow" }`, so tasks scoped to any directory below the launch root never get an ask for touching anything inside the server's tree — zero round-trips and zero wedge risk. That object **replaces** lower-level `external_directory` rules for that key (verified live); `read`/`edit`/`bash` keys still survive the deep-merge untouched. Without a root it stays `"ask"`. `startPermissionResponder()` answers every request with two loops: the legacy `/event` SSE subscription (`permission.asked` / `permission.updated`, for 1.18.x servers) and — when `baseUrl` is given — a 1 s REST drain of `GET /api/permission/request?directory=` + `POST /api/session/{id}/permission/{requestID}/reply`, because on 1.19.x the core v2 tool stack publishes asks only on that surface (confirmed live). A FIFO dedupe set (512 ids) prevents double replies; 404s from already-resolved asks are swallowed. `decidePermission()` (in `permission-decision.ts`) grounds shell asks by resource pattern (`groundExternalPatterns`): a bash ask whose patterns sit inside the root is approved `once`; outside the root it is rejected under `read-only` (`allow`/`deny` policies unchanged). **On 1.19.x the real tool path only raises `external_directory` for paths inside the server root but outside the session Location** — an out-of-tree bash workdir runs with no ask at all. External reads are answered `once`, never `always`, because an `always` reply persists keyed by *directory pattern* rather than by operation and would silently let a later write into the same directory through. 2. `permission-scopes.ts` — routes permission responses by server, directory, and registered session, and auto-accepts **subagent (child) sessions**: a delegated task's subagents run as child sessions of the registered parent, their asks carry the child's session id, and (verified live) they inherit the parent's `external_directory` rules. Every scope runs a 3 s children poller (`client.session.children`, `CHILD_POLL_MS`); a v2 ask arriving before acceptance is skipped **without** being marked handled, so the next drain tick answers it once the child is known. 3. `opencode_start_server` accepts an optional `external_directory` input (`read-only` | `allow` | `deny`) that wins over everything: tool param > `OPENCODE_MCP_EXTERNAL_DIR` env var > `OPENCODE_MCP_EXTERNAL_DIR=` CLI arg > `read-only` default. ### Usage module (`usage/`) - `application/usage-limits.ts` — `getUsageLimits()` fetches OpenCode Go quota data from two real endpoints instead of scraping the docs: `https://opencode.ai/console/api/go/status` (live subscription status: plan + shared-allowance meters for the 5h/week/month windows, real used/limit dollars with reset timestamps; requires `Authorization: Bearer ` with the account key from `OPENCODE_GO_API_KEY`, the only auth input) and the public `https://opencode.ai/inference/go/v1/models` catalog (per-model `go.monthly_usage` per plan and real token prices per 1M tokens). `infrastructure/go-credentials.ts` exports `getGoApiKey()` (reads `OPENCODE_GO_API_KEY`, trimmed, falling back to the `opencode-go` credential opencode stores in `~/.local/share/opencode/auth.json` after `/connect`; `XDG_DATA_HOME` respected) and `getAuthFilePath()`. `infrastructure/go-parsers.ts` (`parseStatus`/`parseModels`) are shape-validating parsers; garbage payloads degrade to the cache, never to garbage in. `domain/quota.ts` exports `quotaTier()` (buckets by real **output token price**: ≤ $0.75/1M → high-volume, ≤ $3 → balanced, > $3 → scarce, $0/$0 → free; thresholds live there only) and `quotaByModelId()` (exact-id index — catalog ids are the same ids an OpenCode server reports for `opencode-go`, no slug mangling). `presentation/usage-limits-format.ts` exports `formatUsageLimits()` (plan + meters block for the instructions) and `formatTierGuide()` (static legend keyed by the exact `tier` values `opencode_list_agents` emits). - The meters are live numbers, so the snapshot is cached on disk (`OPENCODE_MCP_CACHE_DIR` > `XDG_CACHE_HOME` > `~/.cache`, under `opencode-mcp/usage-limits.json`) for only 60s by default (`OPENCODE_MCP_LIMITS_TTL_MS` overrides); it also persists to the `quota_snapshots` table as a deeper fallback. The status fetch is skipped entirely when no key is available (the meters then report `allowanceReason: "no OpenCode Go key found (OPENCODE_GO_API_KEY or opencode's auth.json)"`), a failed half is combined with the other fresh half plus the stale cached models, and a total failure falls back to the stale snapshot, then to a quota-agnostic paragraph — startup never depends on the network. DB `user_version` 2 dropped and recreated the v1 `quota_snapshots` shape (it only holds a refetchable cache). - `infrastructure/usage-ledger.ts` aggregates direct-message metrics into the `usage_ledger` table (run-keyed rows). `opencode_list_agents` returns `models.providers[].models` as objects (`{ id, quota }`), **not** plain id strings, plus a sibling `models.quota_snapshot` (`{ source, checked, plan }` or `null`), `models.allowance` (`{ meters, reason }` — the real 5h/week/month meters from the Go status endpoint, with `reason` explaining their absence, or `null` when no snapshot exists at all), and `models.local_usage` (rolling 5h/7d aggregates from the `usage_ledger` table, with `local_usage_reason` when empty/unavailable). `quota` is `{ monthly_usage, input_per_mtok, output_per_mtok, tier }` from the Go model catalog; `monthly_usage` is plan-specific (`null` without a configured key or for free models) and `tier` may be `null` for a catalog entry with no prices. `quota` is `null` for models absent from the Go catalog — verified against a live server: all 31 catalog ids carry prices, the 4 `*-free` models report `$0`/`tier: "free"`, and models on other providers have no row. Models are sorted by output price ascending (cheapest first), with unpriced/un-Go models last. `tasks` progress derivation (`tasks/domain/status.ts` + `application/derive-status.ts`): `deriveTaskStatus()` checks `cancelledAt` first and returns `cancelled` before any session lookup, then returns `empty` — not `completed` — when a finished turn has no text and no tool calls, because a completed timestamp says the turn ended, not that it did work. `buildProgress(latest, whole)` reads `text_snippet` / `current_tool` from the **latest** turn but `tool_calls_completed` / `mutating_tool_calls` / `files_touched` from **all turns in the current run**: an agent's edits land in earlier turns while the final turn is usually just "DONE", so evidence read off the last message alone reports `files_touched: []` for a task that rewrote the workspace. `current_tool_elapsed_ms` is an in-process first-seen floor estimate (the wire carries no tool-start timestamp): 0 on first observation, growing per scope (run or task), cleared when the run finalizes or nothing is in flight; `get_task_status` / `wait_for_task` include `progress` by default for running tasks (`include_progress: false` opts out). ### Adding a tool 1. Create the presentation adapter in the owning module's `presentation/mcp/.ts`, exporting `registerOpencode(server: McpServer, ...)`. Use the module's application use case + ports (e.g. `taskQueryPorts`) — do not construct SDK clients ad hoc; the registries stay the source of truth for server/task identity. 2. Import and call it from `src/modules/tools/index.ts` inside `registerTools`, keeping the fixed registration order and the `opencode_` name prefix. 3. Define `inputSchema` with Zod; serialize results through the platform facade's `jsonResult`/`jsonError`. 4. Add `tests/modules//presentation/.test.ts` (use `src/test-utils/fake-mcp-server.ts`) and extend `tests/modules/tools/index.test.ts` if the tool list changes — coverage thresholds are 100%. ## Gotchas - **MCP processes are spawned per session with cwd = the session Location, not the server root.** Verified live (opencode 1.19.5, 2026-11-08): OpenCode starts an `opencode-mcp` child per session directory, so `process.cwd()` inside a tool equals the session's directory. Consequences: `opencode_start_server` roots its spawned OpenCode server in the *session's* directory (its response therefore reports the effective `directory`, and it walks to the next port when the default 4096 is taken — nested chains spawn two instances both defaulting to 4096); an agent that resolves "directory relative to the server" against its *own* cwd (the session Location) silently double-nests the target (observed: task in `/tmp-mcp-e2e` creating `/tmp-mcp-e2e/tmp-mcp-e2e/nested-buzz` and running fine). The instructions and tool descriptions state the anchor explicitly; `workspace.source_directory` in `start_task` responses is the machine-checkable truth. - **Host MCP request timeouts kill long polls before the tool's own timeout fires.** Both a live host and a delegated agent saw `MCP error -32001: Request timed out` at 290s and 100s waits. That's why the wait clamp defaults to 55s (`MCP_TOOL_TIMEOUT` overrides): returning gracefully at 55s with `timed_out: true` always beats getting the transport error. Agents must loop the wait instead of raising `timeout_ms`. - **OpenCode does not persist prompt-rejection causes.** A prompt with an unknown agent/model id is accepted by `promptAsync` (2xx) yet leaves ZERO messages in the session store (verified live: the failed session has no messages and no error record). The adapter's `status: "failed"` heuristic ("no output; the prompt was likely rejected") is the only diagnostic available; OpenCode-side truth is gone. Unknown-agent prompts cost zero LLM tokens. - **OpenCode version support**: the adapter uses the v1 SDK/API. Validated against OpenCode `1.18.34` originally and re-validated against `1.19.5` (2026-11-08, live: config object syntax, v2 `/api/permission/request` pending list + reply, subagent `Session.parentID`, in-tree bash without asks). On 1.19.x the core v2 tool stack publishes `external_directory` asks only on `/api/permission/request`; they never appear on the legacy `/event` stream, which is why the responder drains REST too. OpenCode 2.x is not yet supported; a real smoke against `2.2.0` times out at server startup. Do not claim compatibility without a real contract/smoke run. - **The generated SDK types lag the running binary.** Verified against opencode `1.18.18` with `@opencode-ai/sdk` `1.17.20`: the live permission event is `permission.asked` (the SDK declares only `permission.updated`), its kind arrives as `properties.permission` (the SDK's `Permission` says `type`), and the call id is nested under `properties.tool.callID` (the SDK puts it at the top level). `servers/infrastructure/permissions.ts` declares its own `PermissionAsk` and reads both spellings. The SDK's `Config.permission` is stale too — it types `edit` as a bare `"ask" | "allow" | "deny"`, but the binary accepts an object of globs. **Verify wire shapes against a live server before trusting a generated type**; a mismatch here fails silently, because a permission that is never answered just hangs. - **SQLite location/schema are frozen.** `OPENCODE_MCP_HISTORY_DB` > `$XDG_STATE_HOME` > `~/.local/state/opencode-mcp/history.sqlite`; `user_version` = 2; the DDL, PRAGMAs (WAL, NORMAL, foreign_keys, busy_timeout), heartbeats and the synchronous `withImmediateTx` live only in `platform/infrastructure/persistence/sqlite/`. Never move the file or change the schema without a migration plan. - **The stop-server drain and shutdown order are frozen.** `stopRunObservers` must complete (or refuse) before `killAllServers()` and instance stamping; the stop tool's drain is injected from the tool registry because a servers→tasks import would close a module cycle. Don't "simplify" by importing the tasks facade from the servers module. - **ESM + NodeNext**: `"type": "module"` with `moduleResolution: NodeNext`. All relative imports in `.ts` files must use `.js` extensions (e.g. `from "./modules/tools/index.js"`), even though the source is `.ts`. - **Build output lives at `build/src/index.js`** (not `build/index.js`) because `rootDir` is `"./"` with sources under `src/`. `package.json` `main`/`bin` correctly point there; keep them in sync if `rootDir` ever changes. `pnpm build` wipes `build/` first and `chmod +x`'s the entrypoint (it has a shebang), and `prepare` runs the build on install. - **Build scope**: `tsconfig.json` includes `src/**/*.ts` and excludes test files and `src/test-utils/**`, so test helpers are not compiled into the published package. - **`files_touched` only attributes write/edit-classified tool calls.** Files created through `bash` (mkdir, tee, redirects, etc.) do not appear in status/progress `files_touched`; execution reports are the source of truth for bash-created evidence. - Biome: 2-space indent, 100 cols, double quotes, organizes imports on write. `build/` is excluded via both `.gitignore` and biome's `!!**/build` negation.