diff --git a/docs/agents.md b/docs/agents.md new file mode 100644 index 0000000..cf932d2 --- /dev/null +++ b/docs/agents.md @@ -0,0 +1,228 @@ +# Agents — Custom Agents & Subagents + +> Custom agents let you bake a role, model choice, and permission profile into a markdown file. They show up in the Tab cycle (primary) or as `@mentions` (subagent). + +## The agent zoo + +Five OpenCode-built-in agents you should know: + +| Name | Mode | Tools | Reach for it when… | +|---|---|---|---| +| `build` | primary (default) | All | Default daily-driver — implementation, refactors | +| `plan` | primary | `edit` & `bash` set to `"ask"` | Read-only-ish analysis — exploration, design | +| `general` | subagent | All minus `todowrite` | Big sub-tasks you want isolated from main context | +| `explore` | subagent | `read`, `grep`, `glob`, `list` | "Where is X?" code search | +| `scout` | subagent | `webfetch`, `websearch`, + read tools | External docs and dependency research | + +Hit **Tab** to cycle primaries. Use `@` in your prompt to invoke a subagent. + +## Custom agents — file format + +Two locations, same format: + +| Scope | Path | +|---|---| +| Project | `.opencode/agents/.md` | +| Global | `~/.config/opencode/agents/.md` | + +```markdown +--- +description: Senior frontend engineer — Tailwind + React + TypeScript expert +mode: all +model: anthropic/claude-sonnet-4-5 +temperature: 0.2 +permission: + edit: allow + bash: + "*": "ask" + "pnpm test*": "allow" + "pnpm lint*": "allow" + "git status*": "allow" + webfetch: deny +tools: + websearch: false +--- + +You are a senior frontend engineer. Specifics: +- Use Tailwind for styling. Reach for CSS modules only when Tailwind can't express it. +- Components are TypeScript with named exports and explicit Props types. +- Tests use Vitest + @testing-library/react. +- Match existing patterns in `src/components/Button/` for new components. +``` + +### Frontmatter keys + +Verified against the [config JSON schema's `AgentConfig`](https://opencode.ai/config.json): + +| Key | Type | Purpose | +|---|---|---| +| `description` | string | Shown in `/agents` and surfaced to the LLM | +| `mode` | `primary` \| `subagent` \| `all` | How the agent can be invoked | +| `model` | `provider/model-id` | Per-agent model override | +| `temperature` · `top_p` | number | Sampling controls | +| `permission` | object | Per-tool `allow`/`ask`/`deny` (see below) | +| `tools` | object | Boolean per tool — `{"websearch": false}` | +| `prompt` *(JSON form only)* | string | System prompt; alternative to markdown body | +| `maxSteps` | number | Hard cap on agent steps in one invocation | +| `steps` | array | Scripted step sequence (advanced) | +| `disable` | boolean | Disable an agent entirely | +| `hidden` | boolean | Hide from the UI but keep available | +| `color` | string | UI accent color | +| `variant` · `options` | string · object | Model variant + per-provider options | + +Only `description` and `mode` are required. + +### Filename → agent name + +The filename (minus `.md`) becomes the agent name. `security-auditor.md` → `@security-auditor`. + +Naming rules: lowercase, alphanumeric, hyphens. No spaces, no underscores. + +## Mode reference + +| `mode` | Where it appears | Use when | +|---|---|---| +| `primary` | Tab cycle alongside `build`/`plan` | A persistent role you'll inhabit for hours | +| `subagent` | `@` mentions, `task` tool | A focused helper for a specific sub-task | +| `all` | Both | You want flexibility (most custom agents) | + +## Permission model + +Permission keys (verified against `PermissionConfig` in the [config JSON schema](https://opencode.ai/config.json)): + +| Key | Tools / behavior gated | +|---|---| +| `read` | `read` tool | +| `edit` | `write`, `edit`, `apply_patch` | +| `bash` | shell — supports glob-pattern overrides | +| `glob` · `grep` · `list` | search and listing | +| `task` | spawning subagents | +| `todowrite` | the in-session todo list | +| `question` | the `question` tool | +| `external_directory` | files outside the project root | +| `repo_clone` · `repo_overview` | repo-level operations | +| `webfetch` · `websearch` | network access | +| `lsp` | language server tools | +| `skill` | agent skill loading | +| `doom_loop` | runaway-loop safeguards | + +Three values everywhere: `"allow"` (no prompt) · `"ask"` (prompt user) · `"deny"` (block). + +### Glob-pattern bash + +The `bash` key can be a single value or a glob-map. **Order matters**: most specific patterns first. + +```json +{ + "permission": { + "bash": { + "rm -rf*": "deny", + "git push --force*": "deny", + "git status*": "allow", + "git diff*": "allow", + "pnpm test*": "allow", + "*": "ask" + } + } +} +``` + +Use this to keep an agent productive (no constant prompting for safe reads) while still gating destructive commands. + +## Choosing a model per agent + +```json +{ + "agent": { + "explore": { "model": "opencode/qwen3.6-plus" }, + "scout": { "model": "opencode/qwen3.6-plus" }, + "plan": { "model": "opencode/claude-opus-4-7" }, + "build": { "model": "opencode/claude-sonnet-4-6" }, + "deep-thinker": { "model": "openai/gpt-5", "reasoningEffort": "high" } + } +} +``` + +If unspecified: +- Primary agents inherit the global `model`. +- Subagents inherit the model from whatever agent invoked them. + +## Tools per agent + +The `tools` map enables/disables individual tools by name, including MCP tools (use glob patterns): + +```json +{ + "agent": { + "doc-writer": { + "tools": { + "bash": false, + "edit": true, + "websearch": false, + "github_*": false + } + } + } +} +``` + +Note: `tools` is independent from `permission`. A tool can be enabled but still require `"ask"` per the permission map. + +## Patterns + +### Read-only reviewer + +A subagent that reviews diffs but never writes. See [`specialized-agents/system-prompts/code-reviewer-prompt.md`](../specialized-agents/system-prompts/code-reviewer-prompt.md) for the full prompt. + +```markdown +--- +description: Reviews code without modifying files +mode: subagent +permission: + edit: deny + bash: + "*": "ask" + "git diff*": "allow" +--- +``` + +### Specialist primary + +A daily-driver agent with a baked-in role. Different model, different prompt, different defaults. + +```markdown +--- +description: Backend engineer — TypeScript, Postgres, REST +mode: primary +model: anthropic/claude-sonnet-4-5 +permission: + bash: + "*": "ask" + "pnpm test*": "allow" + "pnpm typecheck*": "allow" + "psql*": "deny" +--- + +You're a backend engineer working on this monorepo's API… +``` + +### Cheap research subagent + +Read-only, cheap model — `@scout`-replacement scoped to a specific knowledge area. + +```markdown +--- +description: Looks up React Router v7 patterns and idioms +mode: subagent +model: opencode/qwen3.6-plus +permission: + edit: deny + bash: deny +--- +``` + +## Drop-in specialists + +This repo ships 10 production-ready prompts in [`specialized-agents/`](../specialized-agents/). Copy any of them to `.opencode/agents/.md` to use as a starting point. + +> 📚 Full agent reference: [opencode.ai/docs/agents](https://opencode.ai/docs/agents). diff --git a/docs/commands.md b/docs/commands.md new file mode 100644 index 0000000..7f9f389 --- /dev/null +++ b/docs/commands.md @@ -0,0 +1,170 @@ +# Custom Commands + +> A custom command is a prompt template you've named. Drop a markdown file in `.opencode/commands/.md` and it becomes `/` in the TUI — with arguments, file refs, and shell output stitched in. + +## When to use a command vs. a skill vs. an agent + +| | Custom Command | Agent Skill | Custom Agent | +|---|---|---|---| +| Invocation | **Manual** — user types `/` | **Auto** — model loads when description matches | Mode-dependent (Tab or `@`) | +| Best for | Repeatable user-driven prompts | Domain expertise the model should discover | A persistent role / tool surface | +| File | `.opencode/commands/.md` | `.opencode/skills//SKILL.md` *(folder)* | `.opencode/agents/.md` | + +A good rule of thumb: **commands run a workflow; skills teach the agent how to handle a class of task; agents are the role doing the work.** + +## File format + +```markdown +--- +description: Run tests with coverage and triage failures +agent: build +model: anthropic/claude-sonnet-4-5 +subtask: false +--- + +Run the full test suite with coverage and surface failures. +Focus on the failing tests and suggest precise fixes. + +Arguments: $ARGUMENTS +``` + +### Frontmatter + +| Key | Type | Required | Purpose | +|---|---|---|---| +| `description` | string | yes | One-liner shown in the slash-command palette | +| `agent` | string | no | Which agent runs the command (`build`, `plan`, or custom) | +| `model` | `provider/model-id` | no | Override model just for this command | +| `subtask` | bool | no | If `true`, runs as a subagent (fresh, isolated context) | + +### Body placeholders + +| Syntax | Substitutes | +|---|---| +| `$ARGUMENTS` | Everything after the command name | +| `$1`, `$2`, … | Positional args (whitespace-split) | +| `@` | File content (fuzzy resolved) | +| `` `!` `` | Shell stdout | + +Placeholders are resolved **at invocation time**, so each run picks up fresh file content and shell output. + +## Where commands live + +| Scope | Path | +|---|---| +| Project (committed) | `.opencode/commands/` | +| Global | `~/.config/opencode/commands/` | + +Project commands override globals; both override built-in commands of the same name. + +## Examples + +### Test runner + +```markdown +--- +description: Run tests, triage failures +agent: build +--- + +!pnpm test --reporter=verbose + +If any tests failed above, open the relevant source files and propose a fix. +Otherwise, summarize coverage and any flaky-looking tests. +``` + +### Targeted code review + +```markdown +--- +description: Review changed files for the current branch +agent: plan +--- + +!git diff --name-only main...HEAD + +Review each changed file above for security, perf, and style. Suggest fixes +with code snippets — but do not edit files. Prioritize anything under +`src/auth/` or `src/api/`. +``` + +### Scaffolding with positional args + +```markdown +--- +description: Scaffold a new React component +agent: build +--- + +Create a new React component named `$1` under `src/components/$1/`: + +- `index.tsx` — named export, Props type, default boilerplate +- `$1.test.tsx` — render test using @testing-library/react +- `$1.module.css` — only if styling is needed + +Match the patterns in `src/components/Button/`. TypeScript strict mode. +``` + +Invoke with: `/scaffold-component UserAvatar` + +### Subtask isolation + +```markdown +--- +description: Deep architectural review (isolated context) +agent: build +subtask: true +model: opencode/claude-opus-4-7 +--- + +You are reviewing the architectural integrity of $ARGUMENTS. + +Spend your context on: +- Coupling and cohesion +- Layer violations +- Missing abstractions / premature abstractions +- Long-term maintainability + +Produce a report with findings and recommendations. Run as a subagent — +your work won't pollute the main session's context. +``` + +`subtask: true` runs the prompt as a `general` subagent in a child session, so the heavy reading and analysis stays separate from your main conversation. + +## Patterns + +### Chain commands + +A command can reference outputs from previous commands via the conversation context: + +```text +/test +# (failures observed) +/review src/api/auth.ts +``` + +The `/review` invocation sees the test output in the conversation history and can use it. + +### Capture team-wide workflows + +Commit `.opencode/commands/` to your repo. Every contributor's `opencode` now has the same `/test`, `/review`, `/pr` commands with the same exact behavior — like committed git hooks for prompts. + +### Pre-baked arguments via frontmatter + +If a command always runs with a particular model or agent, put it in the frontmatter so the user can't forget: + +```markdown +--- +description: Long, deep refactor planning (Opus only) +agent: plan +model: opencode/claude-opus-4-7 +--- +``` + +## Built-in commands and overriding + +OpenCode's built-in commands (`/init`, `/help`, `/share`, etc. — see [`reference/slash-commands.md`](reference/slash-commands.md)) can be overridden by a same-named file in your `.opencode/commands/`. + +> ⚠️ Override sparingly. If you replace `/help`, users in your repo lose access to the real help dialog. Pick a unique name like `/repo-help` instead. + +> 📚 Full Commands guide: [opencode.ai/docs/commands](https://opencode.ai/docs/commands). diff --git a/docs/mcp.md b/docs/mcp.md new file mode 100644 index 0000000..e9e4dfa --- /dev/null +++ b/docs/mcp.md @@ -0,0 +1,198 @@ +# Model Context Protocol (MCP) + +> **Mental model:** MCP is the universal connector — one open protocol that lets OpenCode talk to **external tools** (browsers, databases, search engines, ticket systems) without writing custom integrations for each. Think USB-C for AI integrations. + +## Why MCP exists + +Before MCP, every AI app needed a custom integration for every tool — `N × M` brittle one-off connections: + +```mermaid +flowchart LR + subgraph Before[Before MCP - N x M integrations] + direction LR + A1[App 1] --- T1[Postgres] + A1 --- T2[GitHub] + A1 --- T3[Slack] + A2[App 2] --- T1 + A2 --- T2 + A2 --- T3 + A3[App N] --- T1 + A3 --- T2 + A3 --- T3 + end +``` + +MCP collapses this to `N + M`: each app implements MCP once, each tool exposes MCP once. + +```mermaid +flowchart LR + subgraph After[With MCP - N + M integrations] + direction LR + B1[App 1] --> MCP{{MCP Protocol}} + B2[App 2] --> MCP + B3[App N] --> MCP + MCP --> S1[Postgres] + MCP --> S2[GitHub] + MCP --> S3[Slack] + end +``` + +For OpenCode that means you get a Playwright MCP server, a Sentry MCP server, a Postgres MCP server, etc. — and any of them works without OpenCode-specific glue code. + +## Local vs. remote servers + +OpenCode supports both, declared in `opencode.json` under `mcp`. + +### Local servers — spawned subprocess + +```json +{ + "$schema": "https://opencode.ai/config.json", + "mcp": { + "playwright": { + "type": "local", + "command": ["npx", "-y", "@playwright/mcp@latest"], + "enabled": true, + "environment": { "BROWSER_TYPE": "chromium" }, + "timeout": 5000 + } + } +} +``` + +| Key | Required | Notes | +|---|---|---| +| `type` | yes | `"local"` | +| `command` | yes | Array form — argv-style | +| `enabled` | no | Default `true`; set `false` to keep the entry but disable it | +| `environment` | no | Extra env vars for the subprocess | +| `timeout` | no | Tool-call timeout (ms). Default 5000. | + +### Remote servers — HTTP + +```json +{ + "mcp": { + "context7": { + "type": "remote", + "url": "https://mcp.context7.com/mcp", + "headers": { "CONTEXT7_API_KEY": "{env:CONTEXT7_API_KEY}" } + } + } +} +``` + +| Key | Required | Notes | +|---|---|---| +| `type` | yes | `"remote"` | +| `url` | yes | HTTPS endpoint | +| `headers` | no | Custom HTTP headers (supports `{env:NAME}`) | +| `oauth` | no | Pre-registered OAuth client credentials | + +## OAuth + +OpenCode handles OAuth automatically for remote servers that support it. When a server returns 401, OpenCode initiates Dynamic Client Registration (RFC 7591), pops a browser to complete auth, and stores the credentials locally. + +```json +{ + "mcp": { + "sentry": { + "type": "remote", + "url": "https://mcp.sentry.dev/mcp", + "oauth": {} + } + } +} +``` + +For servers that require pre-registered credentials: + +```json +{ + "mcp": { + "my-corp-api": { + "type": "remote", + "url": "https://mcp.example.com/mcp", + "oauth": { + "clientId": "{env:CLIENT_ID}", + "clientSecret": "{env:CLIENT_SECRET}", + "scope": "tools:read tools:execute" + } + } + } +} +``` + +### Managing OAuth from the CLI + +```bash +opencode mcp auth sentry # complete or refresh OAuth flow +opencode mcp logout sentry # forget stored credentials +opencode mcp debug sentry # diagnose connection issues +opencode mcp list # show servers and auth status +``` + +## Token budget warning + +MCP tools land in the model's tool surface every turn. Heavy servers (e.g., a full GitHub MCP with dozens of tools) can easily eat 10K+ tokens of context — purely for tool *descriptions* the model may never actually call. + +Disable noisy tools at the project level and re-enable them only for agents that need them: + +```json +{ + "tools": { + "github_*": false, + "slack_*": false + }, + "agent": { + "issue-triager": { + "tools": { + "github_get_issue": true, + "github_list_issues": true, + "github_add_comment": true + } + } + } +} +``` + +## Featured servers + +This repo has walkthroughs for several MCP servers in [`../mcp-servers/`](../mcp-servers/). + +| Server | Adds | Type | Source | +|---|---|---|---| +| **Playwright** | Browser automation (DOM, network, screenshots, accessibility) | local | [`@playwright/mcp`](https://github.com/microsoft/playwright-mcp) | +| **Context7** | Live, version-pinned library docs | remote | [`upstash/context7`](https://github.com/upstash/context7) | +| **Sentry** | Errors, traces, releases | remote (OAuth) | [`mcp.sentry.dev`](https://mcp.sentry.dev/) | +| **Grep by Vercel** | Code search across GitHub | remote | [`mcp.grep.app`](https://mcp.grep.app/) | +| **Chrome DevTools** | Drive a real Chrome instance | local | [`ChromeDevTools/chrome-devtools-mcp`](https://github.com/ChromeDevTools/chrome-devtools-mcp) | +| **Memory / mem0** | Long-term cross-session memory | local/remote | [`mem0ai/mem0`](https://github.com/mem0ai/mem0) | +| **Tavily** | Web search + extraction for agents | remote | [`tavily-ai/tavily-mcp`](https://github.com/tavily-ai/tavily-mcp) | +| **Sequential Thinking** | Step-by-step reasoning helper | local | [`modelcontextprotocol/servers`](https://github.com/modelcontextprotocol/servers) | + +## Invocation from a prompt + +Reference an MCP server's tools naturally — OpenCode surfaces them as additional tools: + +```text +use playwright to open https://example.com and screenshot the navbar +look up the React Router v7 changelog (use context7) +search the codebase for `parseToken` calls with grep +``` + +## Discovery — the MCP Registry + +The [Official MCP Registry](https://registry.modelcontextprotocol.io/) (live since 2025) catalogues vetted servers. Browse via the website or look for `opencode mcp` discovery features in newer versions. + +## Troubleshooting + +| Problem | Fix | +|---|---| +| Server fails to connect | `opencode mcp debug ` | +| OAuth flow stuck | `opencode mcp logout ` then `opencode mcp auth ` | +| Server eats too many tokens | Disable tools you don't use via the `tools` map | +| `command not found` for local server | Make sure the binary is on `$PATH` or use a fully-qualified `npx` invocation | +| Connection times out | Bump `timeout` (default 5000ms) | + +> 📚 Full MCP guide: [opencode.ai/docs/mcp-servers](https://opencode.ai/docs/mcp-servers) · Registry: [registry.modelcontextprotocol.io](https://registry.modelcontextprotocol.io/) · Protocol spec: [modelcontextprotocol.io](https://modelcontextprotocol.io/). diff --git a/docs/migration.md b/docs/migration.md new file mode 100644 index 0000000..20a865e --- /dev/null +++ b/docs/migration.md @@ -0,0 +1,228 @@ +# Migration Guide + +> Switching from another AI coding tool to OpenCode. Concrete mappings, no marketing. + +> Before reading this, a fair note: **none of the tools below is universally better.** This guide is about migrating *to* OpenCode, which makes sense if its trade-offs (open source, multi-provider, terminal-first, configurable) line up with what you want. If you're happy on Claude Code, Cursor, Copilot, or Aider, those are good tools — keep using them. + +## From Claude Code + +OpenCode has **shape compatibility** with Claude Code — similar concepts, similar file layouts, fallback support for `CLAUDE.md` and `.claude/skills/` — but it isn't a literal drop-in. Frontmatter keys differ on agents, hooks become JS/TS plugins, and the CLI surface is its own. Plan to spend ~30 minutes adapting a non-trivial Claude Code project. + +### What Claude Code does better + +- **Tighter Anthropic integration.** First-party support for Claude-specific features (extended thinking, prompt caching tuning, etc.) lands in Claude Code first and is more battle-tested there. +- **Single-vendor polish.** One company owns the model, the CLI, and the docs — fewer rough edges where layers meet. +- **Subscription pricing** can be more predictable than pay-as-you-go if you're a heavy user. + +If those matter more to you than multi-provider flexibility or full open source, staying on Claude Code is reasonable. + +### What's the same + +- Terminal-first interaction model +- `@` for file references +- `!` for shell injection +- Slash commands (`/init`, `/help`, `/share`, `/export`, etc.) +- Custom commands as markdown files +- Agent Skills (`SKILL.md` folders) +- MCP server support (same protocol) + +### What's different + +| Claude Code | OpenCode | +|---|---| +| Anthropic models only | Any provider (Anthropic, OpenAI, Google, Groq, Bedrock, local…) via Zen or direct config | +| Subscription pricing (Pro/Max) | Pay-as-you-go via Zen, or your own provider's billing | +| `CLAUDE.md` for project rules | `AGENTS.md` (falls back to `CLAUDE.md` for compatibility) | +| `.claude/commands/.md` | `.opencode/commands/.md` | +| `.claude/skills//SKILL.md` | `.opencode/skills//SKILL.md` *(but also reads from `.claude/skills/`)* | +| `.claude/settings.json` hooks (Python scripts on lifecycle events) | `.opencode/plugins/.{js,ts}` (JS/TS modules on events) | +| `.claude/agents/.md` | `.opencode/agents/.md` (similar markdown+YAML format, different fields) | +| `claude` CLI | `opencode` CLI | +| `/auth login` | `opencode auth login` or `/connect` | + +### Migration steps + +```bash +# 1. Install +curl -fsSL https://opencode.ai/install | bash + +# 2. Authenticate +opencode auth login # pick a provider (Anthropic, Zen, OpenAI, etc.) + +# 3. Move project config +git mv .claude/commands .opencode/commands # if you had commands +git mv .claude/skills .opencode/skills # if you had skills +git mv .claude/agents .opencode/agents # but see agent format note below +mv CLAUDE.md AGENTS.md # rename — OpenCode prefers AGENTS.md + +# 4. Disable the Claude fallback once migrated +export OPENCODE_DISABLE_CLAUDE_CODE=1 +# Or, if you only want to disable one half of the fallback: +export OPENCODE_DISABLE_CLAUDE_CODE_PROMPT=1 # ignore CLAUDE.md +export OPENCODE_DISABLE_CLAUDE_CODE_SKILLS=1 # ignore .claude/skills/ +``` + +### Agent format differences + +Claude Code subagents and OpenCode agents are conceptually the same but use different frontmatter keys. Claude Code uses: + +```yaml +--- +name: code-reviewer +description: ... +tools: Read, Grep, Glob, Bash +model: sonnet +--- +``` + +OpenCode uses: + +```yaml +--- +description: ... +mode: subagent +model: anthropic/claude-sonnet-4-5 +permission: + edit: deny + bash: ask +--- +``` + +Key changes: +- No `name` field — filename is the name. +- `tools` becomes either the `tools` map (`{"bash": true}`) or the `permission` map (`{"bash": "allow"}`). +- `model` is `provider/model-id`, not a shorthand. +- Add `mode: subagent` (or `primary` / `all`). + +### Hooks → Plugins + +Claude Code uses Python scripts triggered by `.claude/settings.json`. OpenCode uses JS/TS modules in `.opencode/plugins/`. Behaviorally similar, syntactically different. + +Claude Code `pre_tool_use.py`: + +```python +import json, sys +event = json.load(sys.stdin) +if event["tool_name"] == "Write" and ".env" in event["tool_input"]["path"]: + print("Blocked: cannot write .env", file=sys.stderr) + sys.exit(2) +``` + +OpenCode equivalent (`.opencode/plugins/protect-env.js`): + +```javascript +export const ProtectEnv = async () => { + return { + event: async ({ event }) => { + if (event.type === "tool.execute.before" && event.tool === "edit") { + if ((event.input?.path ?? "").includes(".env")) { + throw new Error("Plugin blocked: cannot write .env"); + } + } + }, + }; +}; +``` + +## From Cursor + +Cursor and OpenCode have different surfaces (IDE-embedded vs. terminal-first) but similar AI capabilities. + +### What's the same + +- AI-assisted edits with project context +- File-mention syntax (`@`) +- Custom rules / project conventions + +### What's different + +| | Cursor | OpenCode | +|---|---|---| +| **Surface** | VS Code fork (full IDE) | TUI, desktop, or IDE extension — bring your own editor | +| **Rules** | `.cursor/rules/*.md` | `AGENTS.md` + `instructions: ["..."]` in `opencode.json` | +| **Workflow** | Cursor Composer / Cursor Tab inline | TUI + custom commands | +| **Pricing** | Subscription | Pay-as-you-go or BYOK | +| **Source** | Proprietary | MIT open source | + +### What Cursor does better + +- **Inline tab-completion** is Cursor's bread and butter and is genuinely excellent — OpenCode doesn't have an equivalent. +- **Native IDE integration** — diff views, refactor previews, multi-file edits live in your editor, no terminal context-switch. +- **Onboarding** is faster — install the app, sign in, you're productive. + +If you write code primarily in a GUI editor and want the AI right there, Cursor is hard to beat. + +### Importing Cursor rules + +You can keep your `.cursor/rules/` and reference them from OpenCode: + +```json +{ + "$schema": "https://opencode.ai/config.json", + "instructions": [".cursor/rules/*.md", "AGENTS.md"] +} +``` + +OpenCode glob-expands the patterns and concatenates the content into the system prompt. + +## From GitHub Copilot + +Copilot is autocompletion-first; OpenCode is conversation-first. They serve different (overlapping) jobs. + +### Mental model shift + +| Copilot | OpenCode | +|---|---| +| Inline ghost-text completion in your editor | Full conversation in the terminal | +| Single-file scope by default | Whole-repo grounding by default | +| Code generation | Code generation + reading + editing + running tests + git ops | +| Subscription, IDE-locked | Provider-agnostic, terminal/desktop/IDE | + +OpenCode replaces Copilot's *kind* of help only partially. For inline completion you'd still want Copilot, Cursor Tab, Codeium, or Supermaven. OpenCode is better suited to multi-file edits, refactors, and "do the thing" prompts where the agent runs the loop — but Copilot covers a high-frequency use case (every keystroke) that OpenCode doesn't try to. + +Most teams that adopt agent tools run them **alongside** an autocomplete tool, not instead. + +### Migration + +There's no config to migrate. Install OpenCode alongside Copilot — they don't conflict. + +```bash +curl -fsSL https://opencode.ai/install | bash +opencode auth login +cd ~/your-project && opencode +``` + +## From Aider + +[Aider](https://aider.chat/) was an early terminal-AI tool and is still actively maintained. The two tools target the same space with different priorities. + +### What Aider does better + +- **Smaller surface area.** Aider is a focused Python tool you can read end-to-end. OpenCode has substantially more moving parts. +- **Strong git integration.** Aider's automatic commit-per-change and git-aware editing workflow is mature. +- **Lower setup overhead** for users who just want "edit my files with an LLM." + +OpenCode adds skills, plugins, MCP, subagents, themes, a desktop app, and a headless server. Whether that's an upgrade or scope creep depends on what you actually need. + +### Mapping + +| Aider | OpenCode | +|---|---| +| `.aider.conf.yml` | `opencode.json` | +| `.aider.chat.history.md` | OpenCode session persistence (`/sessions`) | +| Aider's `/run` | OpenCode's `!cmd` prefix or `bash` tool | +| Aider's `--edit-format` modes | OpenCode's `edit` / `write` / `apply_patch` tools | +| Aider's `--read` files | OpenCode's `@` references | + +Migration is mostly muscle-memory adjustment, not config porting. + +## After migration + +1. Run `/init` to refresh your `AGENTS.md` — OpenCode reads it slightly differently and `/init` will populate the canonical sections (commands, conventions, repo layout). +2. Browse this repo's [`.opencode/`](../.opencode/) for example agent, command, and skill formats. +3. Audit your old hooks/scripts for things that should become **plugins** versus things that should become **agent permission rules** (a lot of "block X" hooks are simpler as `bash: { "X*": "deny" }`). +4. Set `OPENCODE_DISABLE_CLAUDE_CODE=1` to stop the `CLAUDE.md` fallback once you've fully renamed to `AGENTS.md`. + +--- + +*Last reviewed: 2026-05-18 · Canonical source: [opencode.ai/docs](https://opencode.ai/docs/).* diff --git a/docs/plugins.md b/docs/plugins.md new file mode 100644 index 0000000..1c9a965 --- /dev/null +++ b/docs/plugins.md @@ -0,0 +1,225 @@ +# Plugins + +> **Mental model:** Plugins are OpenCode's **event-driven extension surface** — small JavaScript or TypeScript modules that subscribe to lifecycle events (tool calls, file edits, session state) and run code automatically. Think `husky` for your AI session. + +## When to write a plugin + +| Reach for a plugin when… | Skip plugins and use a command/skill if… | +|---|---| +| You want code to run **automatically** (no user prompt) | The trigger is "user types /something" | +| You're connecting to an external system (notifications, logging, telemetry) | You're shaping the prompt or output | +| You want to enforce policy (block writes to certain paths) | You want the agent to decide what to do | + +## Where plugins live + +Three locations: + +| Location | Scope | +|---|---| +| `.opencode/plugins/.{js,ts}` | Project | +| `~/.config/opencode/plugins/.{js,ts}` | Global | +| `plugin: [...]` in `opencode.json` | NPM packages | + +NPM-installed plugins: + +```json +{ + "$schema": "https://opencode.ai/config.json", + "plugin": [ + "opencode-helicone-session", + "opencode-wakatime", + "@my-org/custom-plugin" + ] +} +``` + +These install on first run via Bun and cache under `~/.cache/opencode/node_modules/`. + +### Dependencies for local plugins + +Local plugins can use npm packages. Drop a `package.json` next to them: + +```json +{ + "dependencies": { + "shescape": "^2.1.0", + "node-notifier": "^10.0.1" + } +} +``` + +Run `opencode plugin ` (or `opencode plug`) to add a plugin and let OpenCode update your config: + +```bash +opencode plugin opencode-helicone-session +opencode plugin --global opencode-wakatime +``` + +## Plugin API + +A plugin is a default-export async function returning an object of event handlers: + +```javascript +// .opencode/plugins/notify-on-idle.js +export const NotifyOnIdle = async ({ project, client, $, directory, worktree }) => { + return { + event: async ({ event }) => { + if (event.type === "session.idle") { + await $`osascript -e 'display notification "Session done!" with title "opencode"'`; + } + }, + }; +}; +``` + +### Arguments + +| Argument | What you get | +|---|---| +| `project` | Project metadata — name, root, language hints | +| `directory` | Current working directory string | +| `worktree` | Git worktree path (when applicable) | +| `client` | OpenCode SDK client — call back into OpenCode from inside the plugin | +| `$` | Bun shell — run commands; supports tagged-template syntax | + +### Available events + +Verified against the [Plugins doc](https://opencode.ai/docs/plugins): + +| Category | Events | +|---|---| +| **Tools** | `tool.execute.before`, `tool.execute.after` | +| **Files** | `file.edited`, `file.watcher.updated` | +| **Sessions** | `session.created`, `session.updated`, `session.compacted`, `session.idle`, `session.status`, `session.error`, `session.diff`, `session.deleted` | +| **Messages** | `message.updated`, `message.removed`, `message.part.updated`, `message.part.removed` | +| **Commands** | `command.executed` | +| **Permissions** | `permission.asked`, `permission.replied` | +| **LSP** | `lsp.client.diagnostics`, `lsp.updated` | +| **Server / installation** | `server.connected`, `installation.updated` | +| **Shell** | `shell.env` | +| **Todo** | `todo.updated` | +| **TUI** | `tui.prompt.append`, `tui.command.execute`, `tui.toast.show` | + +> 📚 Each event carries event-specific payload. Full reference: [opencode.ai/docs/plugins](https://opencode.ai/docs/plugins). + +## Common patterns + +### 1. Auto-format on save + +Every time the agent edits a file, run the project formatter: + +```javascript +// .opencode/plugins/autoformat.js +export const Autoformat = async ({ $ }) => { + return { + event: async ({ event }) => { + if (event.type === "file.edited") { + const path = event.path; + if (/\.(ts|tsx|js|jsx|json|md)$/.test(path)) { + await $`pnpm prettier --write ${path}`.quiet(); + } else if (/\.py$/.test(path)) { + await $`ruff format ${path}`.quiet(); + } else if (/\.go$/.test(path)) { + await $`gofmt -w ${path}`.quiet(); + } + } + }, + }; +}; +``` + +### 2. Action audit log + +Append every tool call to a JSONL log — paper trail for what the agent did. + +```javascript +// .opencode/plugins/audit-log.js +import { appendFile } from "node:fs/promises"; + +export const AuditLog = async ({ directory }) => { + const logPath = `${directory}/.opencode/audit.jsonl`; + + return { + event: async ({ event }) => { + if (event.type === "tool.execute.after") { + await appendFile( + logPath, + JSON.stringify({ + ts: new Date().toISOString(), + tool: event.tool, + input: event.input, + success: !event.error, + }) + "\n" + ); + } + }, + }; +}; +``` + +### 3. Notify on long-running task completion + +macOS notification when a session goes idle: + +```javascript +export const NotifyOnIdle = async ({ $ }) => { + return { + event: async ({ event }) => { + if (event.type === "session.idle") { + await $`osascript -e 'display notification "OpenCode is idle" with title "opencode" sound name "Glass"'`.quiet(); + } + }, + }; +}; +``` + +### 4. Block sensitive paths + +Prevent any edits to `.env` files or `secrets/` directories: + +```javascript +export const ProtectSecrets = async ({ client }) => { + return { + event: async ({ event }) => { + if (event.type === "tool.execute.before" && event.tool === "edit") { + const path = event.input?.path ?? ""; + if (/\.env|secrets\//i.test(path)) { + throw new Error(`Plugin blocked: ${path} is a protected path`); + } + } + }, + }; +}; +``` + +## Loading order + +Plugins load in this order (later ones can override earlier behavior): + +1. NPM packages in the **global** `plugin` array +2. NPM packages in the **project** `plugin` array +3. **Global plugins** in `~/.config/opencode/plugins/` +4. **Project plugins** in `.opencode/plugins/` + +## Security + +> ⚠️ **Plugins run with your user permissions.** They can read, modify, delete any file you can, plus make network calls. Treat installation like running an unaudited shell script — read every third-party plugin before adding it. + +Best practices: + +- Pin plugin versions in `opencode.json` (`"opencode-foo@1.2.3"`). +- Audit `package.json` for transitive dependencies. +- Sandboxed plugins: run OpenCode in a container if you can't audit a plugin you need. +- Don't `eval` user-controlled strings in plugin code. +- Use absolute paths for shell commands so PATH manipulation can't redirect them. + +## Debugging + +```bash +opencode --log-level DEBUG --print-logs # see plugin loading +opencode debug # debug subcommands +``` + +Plugin errors show up in the TUI; full traces appear in OpenCode's log (default at `~/.local/share/opencode/log/`, or stderr with `--print-logs`). + +> 📚 Full Plugins guide and event reference: [opencode.ai/docs/plugins](https://opencode.ai/docs/plugins). diff --git a/docs/quickstart.md b/docs/quickstart.md index d4201f8..21f4974 100644 --- a/docs/quickstart.md +++ b/docs/quickstart.md @@ -1,242 +1,112 @@ -# OpenCode Quick Start Guide +# Quickstart -## 📋 Overview -This guide helps you install OpenCode and get started in under 5 minutes. +> Five minutes from `curl` to your first AI-assisted commit. -## 🚀 Installation Methods +## 1. Install + +Pick one: -### Method 1: Install Script (Recommended) ```bash +# Recommended: install script (auto-detects OS) curl -fsSL https://opencode.ai/install | bash -``` -### Method 2: Package Managers - -**Homebrew (macOS/Linux):** -```bash +# Or via a package manager you already use: +npm i -g opencode-ai@latest brew install anomalyco/tap/opencode -``` - -**npm:** -```bash -npm install -g opencode-ai -``` - -**Bun:** -```bash -bun install -g opencode-ai -``` - -**pnpm:** -```bash -pnpm install -g opencode-ai -``` - -**Yarn:** -```bash -yarn global add opencode-ai -``` - -### Method 3: System Package Managers - -**Arch Linux:** -```bash +scoop install opencode sudo pacman -S opencode -``` - -**Arch Linux AUR (latest):** -```bash paru -S opencode-bin +mise use -g opencode +nix run nixpkgs#opencode ``` -**Chocolatey (Windows):** -```bash -choco install opencode -``` +A desktop app (beta) for macOS / Windows / Linux is at [opencode.ai/download](https://opencode.ai/download). -**Scoop (Windows):** -```bash -scoop install opencode -``` - -### Method 4: Binary Download -1. Visit: https://github.com/anomalyco/opencode/releases -2. Download appropriate binary for your OS -3. Extract and add to PATH - -## 🖥️ Windows Installation - -### Recommended: Use WSL2 (Windows Subsystem for Linux) -```bash -# Enable WSL2 -wsl --install - -# Install Ubuntu or preferred distro -wsl --install -d Ubuntu - -# Then use Linux installation methods above -``` - -### Native Windows Options: -```bash -# Using Chocolatey -choco install opencode - -# Using Scoop -scoop install opencode - -# Using npm -npm install -g opencode-ai - -# Using Docker -docker run -it --rm ghcr.io/anomalyco/opencode -``` - -## ✅ Verification - -After installation, verify OpenCode is working: +Verify: ```bash -# Check version opencode --version +``` -# Start OpenCode TUI +## 2. Sign in to a provider + +You need an LLM provider. The fastest path is **OpenCode Zen** — one key, dozens of curated models, pay-as-you-go. + +```bash +# Visit https://opencode.ai/auth, sign up, add billing, copy your API key. +# Then: +opencode auth login +# Choose "OpenCode Zen" and paste the key. +``` + +Or sign in directly to Anthropic, OpenAI, Google, Groq, OpenRouter, AWS Bedrock, Azure, Ollama, LM Studio, etc. See [opencode.ai/docs/providers](https://opencode.ai/docs/providers) for the full list. + +## 3. Open OpenCode in a real project + +```bash +cd ~/your-project opencode - -# Or run a quick test -opencode run "Hello, what version of OpenCode am I running?" ``` -## 🔧 Post-Installation Setup +The TUI launches. Try one of these: -### 1. First Run Configuration -```bash -# Start OpenCode -opencode +| Prompt | What happens | +|---|---| +| `explain what this codebase does` | Reads the repo, summarizes | +| `find every TODO comment` | Greps and lists them | +| `find and fix the failing test in src/api.test.ts` | Diagnoses, edits, runs tests | + +## 4. Generate `AGENTS.md` -# You'll see the welcome screen -# Press Enter to continue ``` - -### 2. Configure Your First Provider -```bash -# In the TUI, run: -/connect - -# Follow the prompts to add: -# 1. OpenCode Zen (recommended for beginners) -# 2. Or another provider (OpenAI, Anthropic, etc.) -``` - -### 3. Initialize a Project -```bash -# Navigate to your project -cd /path/to/your/project - -# Start OpenCode in project context -opencode . - -# Initialize project analysis /init ``` -## 🛠️ Troubleshooting Installation +This walks you through generating a project-level instructions file (build/test commands, conventions, architecture). Commit it — it's read every session. -### Common Issues: +## 5. Learn the two essential shortcuts + +| Key | Purpose | +|---|---| +| `Tab` | Cycle primary agents (default: `build` ↔ `plan`) | +| `Esc` | Cancel / dismiss | + +Two character prefixes that change how you talk to OpenCode in prompts: + +| Prefix | Purpose | Example | +|---|---|---| +| `@` | Attach a file's content (fuzzy resolved) | `look at @src/api/auth.ts` | +| `!` | Run shell, inject output | `!git diff` then ask Claude about it | + +## What next? + +- **[Custom Commands](commands.md)** — turn prompts into `/` shortcuts (~3 min) +- **[OpenCode Zen](zen.md)** — model picks, pricing, and BYOK +- **[Agents](agents.md)** — custom build/plan variants and subagents +- **[MCP](mcp.md)** — plug in external tools (browsers, DBs, search) + +## Common first-day issues + +**`opencode: command not found`** + +Add the install path to your shell config: -**1. "Command not found: opencode"** ```bash -# Check installation path -which opencode - -# Add to PATH if needed -echo 'export PATH="$HOME/.local/bin:$PATH"' >> ~/.bashrc -source ~/.bashrc +echo 'export PATH="$HOME/.local/bin:$PATH"' >> ~/.zshrc # or ~/.bashrc +source ~/.zshrc ``` -**2. Permission Errors** +**Auth fails with "no provider configured"** + +Run `opencode auth login` and pick a provider. Re-run `/connect` from inside the TUI if you want to add another. + +**Want to upgrade later?** + ```bash -# Fix permissions for global install -sudo chown -R $(whoami) /usr/local/lib/node_modules +opencode upgrade # latest +opencode upgrade v1.15.0 # specific version ``` -**3. Node.js Version Issues** -```bash -# Check Node.js version -node --version - -# Update if needed (using nvm) -nvm install 18 -nvm use 18 -``` - -**4. Windows WSL Setup** -```bash -# Enable WSL2 -wsl --install - -# Install Ubuntu or preferred distro -wsl --install -d Ubuntu - -# Then use Linux installation methods -``` - -## 🔄 Updating OpenCode - -### Update Methods: -```bash -# Using install script (re-run) -curl -fsSL https://opencode.ai/install | bash - -# Using npm -npm update -g opencode-ai - -# Using Homebrew -brew update -brew upgrade opencode - -# Check for updates -opencode --version -# Compare with latest: https://github.com/anomalyco/opencode/releases -``` - -## 🗑️ Uninstallation - -### Remove OpenCode: -```bash -# npm -npm uninstall -g opencode-ai - -# Homebrew -brew uninstall opencode - -# Remove config files (optional) -rm -rf ~/.config/opencode -rm -rf ~/.opencode -``` - -> **💡 Pro Tip**: Keep your config files (`~/.config/opencode/`) if you plan to reinstall, as they contain your provider configurations and customizations. - -## 🎯 Next Steps - -After successful installation: - -1. **Configure Zen** (recommended for beginners) or your preferred provider -2. **Initialize a test project** to explore features -3. **Try basic commands** like `/help` and `/models` -4. **Explore the TUI** with Tab key for agent switching - -You're now ready to dive into OpenCode's powerful features! - --- -## 📚 What's Next? - -- [Core Concepts](../README.md#-core-concepts-30-minutes) - Learn Zen, TUI, and Agents -- [Zen Model Router Guide](ZEN-GUIDE.md) - Deep dive into Zen -- [TUI Mastery Guide](TUI-MASTERY.md) - Master the terminal interface -- [Agents Guide](AGENTS-GUIDE.md) - Work with AI agents - ---- - -*Last updated: February 2026* \ No newline at end of file +*Last reviewed: 2026-05-18 · Canonical source: [opencode.ai/docs](https://opencode.ai/docs/).* diff --git a/docs/skills.md b/docs/skills.md new file mode 100644 index 0000000..77cfb0f --- /dev/null +++ b/docs/skills.md @@ -0,0 +1,180 @@ +# Agent Skills + +> **Mental model:** A skill is a **discoverable workflow**. The agent sees the skill's `name` and `description` in its tool surface and decides on its own to load the full content when the task matches. You don't have to remember to invoke it — the model does. + +## Skill vs. Command — when to use which + +| | Agent Skill | Custom Command | +|---|---|---| +| Trigger | Agent decides (description match) | User types `/` | +| File | `.opencode/skills//SKILL.md` *(folder)* | `.opencode/commands/.md` *(file)* | +| Best for | "When you're doing X, here's how" expertise | Repeatable user-driven actions | +| Discoverable | Yes — surfaces as a tool | Yes — in slash palette | + +A great heuristic: **write a skill when the workflow has a natural trigger** ("when preparing a release", "when reviewing a payment-related change"). Write a command when the user is the one who knows it's time. + +## File format + +A skill is a **folder** named after the skill, containing a `SKILL.md`: + +``` +.opencode/skills/ +└── git-release/ + ├── SKILL.md # required + └── ... # optional resources the skill references +``` + +`SKILL.md`: + +```markdown +--- +name: git-release +description: Draft release notes from merged PRs, propose a semver bump, and emit a copy-pasteable `gh release create` command. Use when preparing a tagged GitHub release. +license: MIT +compatibility: opencode +metadata: + audience: maintainers + workflow: github +--- + +## What I do +- Read merged PRs since the last tag +- Group by feat/fix/other +- Propose a semver bump (major / minor / patch) +- Emit Keep-a-Changelog-style notes +- Print a ready-to-run `gh release create` command + +## When to use me +Use this when preparing a tagged release. Ask the user to confirm the +version bump before doing anything destructive. + +## What I won't do +- Push tags or publish releases without confirmation +- Edit files +- Hallucinate changelog entries +``` + +### Frontmatter rules + +| Key | Required | Constraints | +|---|---|---| +| `name` | yes | `^[a-z0-9]+(-[a-z0-9]+)*$`, 1–64 chars — lowercase alphanumeric with single hyphens | +| `description` | yes | 1–1024 chars. **This is the discovery signal** — write it carefully. | +| `license` | no | SPDX identifier ideal | +| `compatibility` | no | `opencode`, `claude-code`, or both | +| `metadata` | no | Arbitrary structured metadata | + +### Why the `description` matters + +The description is what the model reads when deciding whether to load the skill. Bad descriptions don't get loaded: + +```yaml +# 👎 Vague +description: Helps with releases + +# 👍 Specific, trigger-shaped +description: Draft release notes from merged PRs, propose a semver bump, and emit a `gh release create` command. Use when preparing a tagged GitHub release. +``` + +Anatomy of a good description: +- **What it does** (verb-first) +- **What it produces** (concrete output) +- **When to use it** (trigger phrase) + +## Where skills live + +OpenCode searches multiple locations: + +| Location | Scope | +|---|---| +| `.opencode/skills//SKILL.md` | Project | +| `~/.config/opencode/skills//SKILL.md` | Global | +| `.claude/skills//SKILL.md` | Claude Code compatibility | +| `.agents/skills//SKILL.md` | Agent-format compatibility | + +Project skills take precedence over global. Same-named skills in different locations: project wins. + +## Permissions + +Skills are gated by the `skill` permission. Three values plus glob patterns: + +```json +{ + "permission": { + "skill": { + "*": "allow", + "pr-review": "allow", + "internal-*": "deny", + "experimental-*": "ask" + } + } +} +``` + +| Value | Behavior | +|---|---| +| `"allow"` | Skill loads silently when the agent decides to | +| `"ask"` | User must approve each load | +| `"deny"` | Skill is hidden from the agent's surface | + +To disable skills entirely for an agent: + +```json +{ + "agent": { + "build": { + "tools": { "skill": false } + } + } +} +``` + +## Writing skills the model will actually use + +The hardest part is getting the agent to **find** your skill. Tips: + +1. **Trigger phrases in the description.** "Use when preparing a release", "Use for any payment-related change", "Use when generating release notes". +2. **Be concrete about output.** Models load skills more readily when the description names a specific artifact they can produce. +3. **One skill, one job.** Don't bundle "release notes + version bump + deploy" — the description gets vague and load decisions get muddled. +4. **Test discovery.** Ask your agent something the skill should handle without naming the skill. If it doesn't pull it in, refine the description. + +## Patterns + +### Procedure skill + +The skill carries the exact procedure for a recurring task. + +```yaml +name: bump-dependency +description: Safely upgrade a single dependency — runs typecheck, tests, and changelog scan to surface breaking changes. Use when the user asks to update a specific package. +``` + +Body: step-by-step procedure, including which commands to run and how to interpret output. + +### Convention skill + +The skill encodes domain conventions for a specific area of the codebase. + +```yaml +name: payment-handler +description: How to safely modify payment-handler code. Use when editing anything under packages/payments/. Encodes our idempotency, refund, and webhook conventions. +``` + +Body: conventions and rules — what to do, what not to do, with code examples. + +### Tool-bridge skill + +The skill explains how to use an external CLI or service the agent should discover. + +```yaml +name: argo-rollout +description: Use Argo CD to roll out staging deployments. Use when the user wants to deploy a branch to staging. Wraps the `argocd` CLI. +``` + +Body: CLI invocation, common flags, what success and failure look like. + +## Compatibility with Claude Code + +Skills using `compatibility: claude-code` work in both tools — OpenCode reads from `.claude/skills/`, Claude Code reads from there natively. Useful for teams running both. + +> 📚 Full Skills guide: [opencode.ai/docs/skills](https://opencode.ai/docs/skills). diff --git a/docs/tui.md b/docs/tui.md new file mode 100644 index 0000000..e8be6da --- /dev/null +++ b/docs/tui.md @@ -0,0 +1,185 @@ +# TUI Mastery + +> The terminal UI is where you'll spend most of your time. This page goes deeper than the README's TUI section. + +## Layout + +``` +┌─────────────────────────────────────────────────────────────┐ +│ [agent: build] session: "fix-auth-bug" tokens │ ← top bar +├─────────────────────────────────────────────────────────────┤ +│ │ +│ Conversation (scrollable) │ +│ │ +│ │ +├─────────────────────────────────────────────────────────────┤ +│ > prompt input │ ← input box +└─────────────────────────────────────────────────────────────┘ +``` + +Use the **leader key** (default `ctrl+x`) for session-level actions, and readline shortcuts inside the input box. + +## Full keybind reference + +### Leader chords (default leader: `ctrl+x`) + +| Binding | Action | +|---|---| +| `ctrl+x n` | New session | +| `ctrl+x l` | List sessions | +| `ctrl+x g` | Timeline view | +| `ctrl+x c` | Compact (summarize) session | +| `ctrl+x e` | Open `$EDITOR` to compose a long prompt | +| `ctrl+x m` | Browse models | +| `ctrl+x t` | Switch theme | +| `ctrl+x u` / `ctrl+x r` | Undo / Redo | +| `ctrl+x b` | Toggle sidebar | +| `ctrl+x y` | Copy messages | +| `ctrl+x q` | Quit | +| `ctrl+p` | Command palette | + +### Top-level + +| Key | Action | +|---|---| +| `Tab` | Cycle primary agents (`build` ↔ `plan` ↔ custom primaries) | +| `Esc` | Cancel / dismiss | +| `ctrl+c` / `ctrl+d` | Exit | + +### Inside the prompt box (readline / emacs-style) + +| Key | Action | +|---|---| +| `ctrl+a` / `ctrl+e` | Beginning / end of line | +| `ctrl+k` | Delete to end of line | +| `ctrl+u` | Delete to beginning of line | +| `ctrl+r` | Rename current session | +| `ctrl+d` | Delete current session *(when prompt is empty)* | + +## Prompt prefixes + +### `@` — attach files + +Fuzzy-search the project and attach matched file content to the prompt. Multiple `@`s work in one message. + +```text +review @src/api/auth.ts and @src/api/auth.test.ts for missing edge cases +``` + +### `!` — run shell, attach output + +```text +!git diff main...HEAD +based on this diff, write a PR description +``` + +The command runs in the project's working directory. + +### `use ` — invoke an MCP tool + +```text +use playwright open https://example.com and take a screenshot +``` + +## Slash commands (built-in) + +Reference table — full list also lives in [`reference/slash-commands.md`](reference/slash-commands.md). + +| Command | Purpose | +|---|---| +| `/init` | Generate or update `AGENTS.md` | +| `/help` | Show help dialog | +| `/new` *(alias `/clear`)* | New session | +| `/sessions` *(aliases `/resume`, `/continue`)* | List & switch sessions | +| `/models` | Browse models | +| `/connect` | Add a provider | +| `/themes` | Switch theme | +| `/compact` *(alias `/summarize`)* | Compact session | +| `/share` · `/unshare` | Public link control | +| `/export` | Export to markdown | +| `/undo` · `/redo` | Walk edit history | +| `/editor` | Open `$EDITOR` | +| `/details` | Toggle tool execution detail visibility | +| `/thinking` | Toggle thinking/reasoning blocks | +| `/exit` *(aliases `/quit`, `/q`)* | Exit | + +## Customizing keybinds + +Drop a `tui.json` next to your `opencode.json`: + +```json +{ + "$schema": "https://opencode.ai/tui.json", + "theme": "tokyonight", + "leader_timeout": 2000, + "scroll_speed": 3, + "keybinds": { + "command_list": "ctrl+p", + "messages_copy": ["y", "ctrl+shift+c"], + "input_paste": { "key": "ctrl+v", "preventDefault": false } + }, + "attention": { + "enabled": true, + "notifications": true, + "sound": true, + "volume": 0.4 + } +} +``` + +Set a binding to `"none"` or `false` to disable. Arrays bind multiple shortcuts to the same action. + +## Themes + +Set the theme in `tui.json` or with `/themes` interactively. + +Built-in themes: + +`system` · `tokyonight` · `everforest` · `ayu` · `catppuccin` · `catppuccin-macchiato` · `gruvbox` · `kanagawa` · `nord` · `matrix` · `one-dark` + +Custom themes: + +- Project: `.opencode/themes/.json` +- Global: `~/.config/opencode/themes/.json` + +A custom theme is a JSON file mapping color slots to hex (`"#1a1b26"`), ANSI numbers (0–255), or `"none"` (terminal default). Truecolor terminals required. + +## Sessions + +Sessions are conversation snapshots. They persist across restarts and can be: + +- **listed** — `/sessions` or `ctrl+x l` +- **resumed** — pick from the list, or `opencode --continue` on the CLI +- **shared** — `/share` produces a public `opncd.ai/s/` URL +- **exported** — `/export` writes Markdown; `opencode export ` writes JSON +- **compacted** — `/compact` summarizes the conversation to free up context window + +> 💡 **Pro tip:** Use `/compact` aggressively for long-running sessions. The summary preserves intent while dropping verbose tool output that's no longer needed. + +## Image and file attachment + +You can drag files (including images, for multimodal models) into the TUI. Image limits live under `attachment.image` in `opencode.json`: + +```json +{ + "attachment": { + "image": { + "auto_resize": true, + "max_width": 2048, + "max_height": 2048, + "max_base64_bytes": 5242880 + } + } +} +``` + +## Performance & long sessions + +| Symptom | Fix | +|---|---| +| TUI feels sluggish on a large repo | Add ignore patterns under `watcher.ignore` in config | +| Context window filling fast | `/compact` or pick a model with a bigger context | +| Tools spamming output | `/details` to hide tool execution chrome | +| Costs rising | `opencode stats --days 7 --models` to find the offender | + +> 📚 Full TUI reference: [opencode.ai/docs/tui](https://opencode.ai/docs/tui) · keybinds at [opencode.ai/docs/keybinds](https://opencode.ai/docs/keybinds). diff --git a/docs/workflows.md b/docs/workflows.md index 5de5bc8..7164a53 100644 --- a/docs/workflows.md +++ b/docs/workflows.md @@ -1,582 +1,187 @@ -# Workflow Design Guide +# Workflows — Real-World Recipes -## 🎯 Overview -This guide covers proven workflows for AI-assisted development with OpenCode. Choose the workflow that best fits your task. +> Glue patterns that combine commands, agents, skills, and MCP. Use them as inspiration or copy them whole. -## 🔄 1. Explore → Plan → Code → Commit +## 1. Test-Driven feature development -The most versatile workflow for complex problems: +Goal: implement a feature with tests written first and reviewed in plan mode. -### Explore: -- Read relevant files, images, URLs -- Use subagents for verification -- Do **not** code yet - understand first - -### Plan: -- Ask OpenCode to create a plan -- Review and refine the approach -- Consider alternatives and trade-offs - -### Code: -- Implement the solution -- Verify reasonableness as you go -- Use tests to validate - -### Commit: -- Commit results with clear messages -- Create pull requests if needed -- Update documentation - -### Example: -```bash -# Explore: Understand the codebase -@explore Analyze @src/auth/ for authentication implementation - -# Plan: Design the solution -[Plan] How would you add OAuth2 support to the existing authentication? - -# Code: Implement -[Build] Implement OAuth2 support as planned - -# Commit: Save changes -!git add . -!git commit -m "feat: Add OAuth2 authentication support" +```text +[plan] > write failing tests for a `slugify` function with these specs: + - handles unicode (café → cafe) + - collapses spaces (Hello World → hello-world) + - strips trailing punctuation +[build] > +[build] > run the failing tests to confirm they fail +[build] > implement slugify so the tests pass +[build] > /review @src/util/slugify.ts +[build] > /pr ``` -## 🧪 2. Test-Driven Development (TDD) +What's happening: -Ideal for changes verifiable with unit/integration tests: +- **`plan`** writes tests without touching code (edits default to `ask` in plan agent — easier than expected). +- **`build`** runs the tests and implements. +- **`/review`** custom command surfaces any issues before PR. +- **`/pr`** opens the PR with a generated title and summary. -### Write Tests: -- Create tests based on expected behavior -- Mark as TDD to guide OpenCode -- Ensure tests fail initially (Red) +## 2. Bug investigation with subagents -### Run & Fail Tests: -- Confirm tests fail as expected -- No implementation yet +Goal: isolate context-heavy research from your main session. -### Write Code: -- Implement minimal code to pass tests (Green) -- Iterate with verification +```text +> a user reports the payment webhook is being processed twice +> @explore find every code path that handles the payment webhook +> @scout what does Stripe's docs say about webhook idempotency (latest)? -### Refactor: -- Improve code while keeping tests green -- Maintain test coverage +(based on subagent reports) -### Commit: -- Final commit after all tests pass - -### Example: -```bash -# Start TDD session -/tdd "User registration validation" - -# OpenCode guides through: -# 1. Write failing test -# 2. Implement minimal solution -# 3. Refactor -# 4. Repeat for each requirement - -# Complete and commit -!git add . -!git commit -m "test: Add user registration validation" +[plan] > given the findings, what's the most likely root cause and how should + we fix it? +[build] > implement the fix +[build] > add an integration test that exercises the duplicate-delivery path +[build] > /test +[build] > /pr ``` -## 🎨 3. Visual Iteration +`@explore` and `@scout` run in **child sessions** — separate from your main session. Their long file reads and search output don't bloat the parent conversation. Navigate between parent and children with the session-child keybinds. -Perfect for UI/design work: +## 3. Multi-agent review -### Provide Visual Reference: -- Drag and drop images into terminal -- Provide screenshots or mockups -- Describe desired outcome +Goal: get two perspectives on the same change. -### Implement Code: -- Create code matching visual reference -- Take screenshots of result - -### Iterate: -- Compare result with reference -- Make adjustments -- Repeat until satisfied - -### Commit: -- Commit final implementation - -### Example: -```bash -# Drag dashboard-mockup.png into terminal -[Image #1: dashboard-mockup.png] - -# Implement based on image -Create a React dashboard component matching [Image #1] - -# Iterate based on results -The spacing looks off. Adjust to match the mockup more closely. - -# Finalize -!git add . -!git commit -m "feat: Add dashboard component" +```text +[build] > implement the OAuth token refresh path in src/auth/refresh.ts +[build] > @code-reviewer review the changes in src/auth/refresh.ts +[build] > @security-auditor audit src/auth/refresh.ts for token-handling vulns +[build] > address the high-severity findings, then re-run @code-reviewer to verify ``` -## 🐛 4. Bug Fix Workflow +Two specialized subagents from [`.opencode/agents/`](../.opencode/agents/) give you independent review perspectives. Run them sequentially or in parallel — your call. -Systematic approach to debugging: +## 4. Cross-repo research with MCP -### Reproduce: -- Understand the bug report -- Reproduce the issue -- Identify error conditions +Goal: find how an idiom is used across GitHub before adopting it. -### Diagnose: -- Analyze logs and error messages -- Trace through code execution -- Identify root cause +Configure [`grep`](https://mcp.grep.app/) MCP server in `opencode.json`: -### Fix: -- Implement solution -- Test the fix -- Ensure no regressions - -### Verify: -- Run existing tests -- Add regression tests -- Confirm fix works - -### Example: -```bash -# Reproduce bug -The user reports: "Registration fails with invalid email error" - -# Diagnose -@debugger Analyze @src/auth/registration.ts for email validation issues - -# Fix -[Build] Fix the email validation regex in @src/auth/registration.ts - -# Verify -!npm test -- --testPathPattern=registration -!git add . -!git commit -m "fix: Correct email validation regex" +```json +{ + "mcp": { + "gh_grep": { + "type": "remote", + "url": "https://mcp.grep.app" + } + } +} ``` -## 🚀 5. Feature Development Workflow +Then: -Complete feature implementation: - -### Requirements Analysis: -- Understand feature requirements -- Identify dependencies -- Plan implementation steps - -### Architecture Design: -- Design solution architecture -- Plan database schema (if needed) -- Design API endpoints - -### Implementation: -- Implement backend components -- Implement frontend components -- Connect pieces together - -### Testing: -- Write unit tests -- Write integration tests -- Perform user acceptance testing - -### Deployment: -- Prepare for deployment -- Update documentation -- Deploy to environment - -### Example: -```bash -# Multi-agent feature development -@product-manager Define requirements for user profile feature -@architect Design profile feature architecture -@backend Implement profile API endpoints -@frontend Implement profile UI components -@tester Create comprehensive test suite -@devops Prepare deployment configuration -@documentation Update user and developer docs +```text +use gh_grep to search for "useTransition" usage in React 19 codebases on GitHub +look for the 3 most common patterns and summarize when each is used ``` -## 🧩 Workflow Customization +OpenCode reads the search results through MCP and produces a written summary grounded in real code. -Create your own workflows by combining: +## 5. Long-running migration plan -### Agent Chains: -```bash -# Custom workflow using agent chain -@explore → @plan → @implement → @test → @review → @deploy +Goal: walk a multi-step migration from a fresh plan to a tracked rollout. + +```text +[plan] > Read AGENTS.md and the architecture doc. + Then propose a migration plan to move from REST to GraphQL. + Break the plan into atomic, independently-mergeable PRs. + Output a checklist. +[plan] > save the plan as docs/migration-graphql.md +[build] > +[build] > start on phase 1 of docs/migration-graphql.md — add the GraphQL server + skeleton. Use the /tdd workflow for each new resolver. ``` -### Skill Sequences: -```bash -# Custom workflow using skills -/analyze → /plan → /implement → /test → /review → /deploy +Combine that with the [`git-release`](../.opencode/skills/git-release/SKILL.md) skill so each phase ends with a clean tagged release: + +```text +> we're about to merge phase 1 — draft release notes ``` -### Hybrid Approaches: -```bash -# Mix agents and skills -@explore Analyze requirements -/plan Create implementation plan -@implement Write code -/test Run tests -/review Code review -/deploy Deploy changes -``` +The agent picks up the `git-release` skill from the description match and walks through release prep without explicit invocation. -## 🤖 The BMAD Method (AI Agent Framework) +## 6. CI integration — headless OpenCode in a workflow -BMAD (Brainstorm, Model, Act, Deliver) is a systematic framework for AI-assisted development. +Goal: run OpenCode on every PR to audit changes. The example below uses GitHub Actions, but the same pattern works on GitLab CI, Buildkite, CircleCI, Jenkins, or anything else that can run a shell — OpenCode is just a CLI you `curl | bash` and then invoke. -### Phase 1: Brainstorm -**Purpose:** Explore the problem space without constraints +`.github/workflows/opencode-review.yml`: -**Activities:** -- Research existing solutions -- Generate multiple approaches -- Consider edge cases and constraints -- Gather requirements and context - -**OpenCode Commands:** -```bash -# Explore the codebase -@explore Analyze @src/ for related functionality - -# Research requirements -What are the requirements for user authentication? - -# Generate ideas -Brainstorm 3 different approaches to implement OAuth2 - -# Consider constraints -What are the security considerations for this feature? -``` - -**Output:** -- Problem understanding -- Multiple solution approaches -- Requirements list -- Constraints and considerations - -### Phase 2: Model -**Purpose:** Create detailed, actionable plans - -**Activities:** -- Select best approach from brainstorming -- Create detailed implementation plan -- Design architecture and components -- Plan testing and validation - -**OpenCode Commands:** -```bash -# Create implementation plan -[Plan] Create detailed plan for OAuth2 implementation - -# Design architecture -Design the authentication system architecture - -# Plan testing strategy -What tests are needed for this feature? - -# Create timeline -Estimate effort and create implementation timeline -``` - -**Output:** -- Detailed implementation plan -- Architecture diagrams -- Test plan -- Timeline and milestones - -### Phase 3: Act -**Purpose:** Execute the plan with precision - -**Activities:** -- Implement code according to plan -- Follow best practices and patterns -- Validate implementation continuously -- Adapt based on findings - -**OpenCode Commands:** -```bash -# Switch to Build mode -[Build] Implement the authentication system as planned - -# Follow implementation steps -1. Create OAuth2 configuration -2. Implement callback handler -3. Add user session management -4. Update frontend components - -# Validate as you go -Test each component as it's implemented -``` - -**Output:** -- Working implementation -- Passing tests -- Documentation updates -- Code review feedback addressed - -### Phase 4: Deliver -**Purpose:** Complete and deploy the solution - -**Activities:** -- Final testing and validation -- Performance optimization -- Documentation completion -- Deployment and monitoring - -**OpenCode Commands:** -```bash -# Final testing -/test --all - -# Performance optimization -/analyze --focus performance - -# Documentation -/docs update - -# Deployment preparation -/deploy prepare -``` - -**Output:** -- Production-ready feature -- Comprehensive documentation -- Deployment artifacts -- Monitoring setup - -### Complete BMAD Workflow Example: -```bash -# Brainstorm: Explore authentication options -@explore Analyze current authentication in @src/auth/ -What OAuth2 providers should we support? -Brainstorm implementation approaches - -# Model: Create detailed plan -[Plan] Create OAuth2 implementation plan including: -1. Google OAuth2 integration -2. GitHub OAuth2 integration -3. Session management -4. Frontend components -5. Testing strategy - -# Act: Implement -[Build] Implement Google OAuth2 first -[Build] Implement GitHub OAuth2 -[Build] Create session management -[Build] Update frontend login components -/test each component - -# Deliver: Complete and deploy -/test --integration -/analyze --security -/docs --api -/deploy --staging -/monitor --setup -``` - -### BMAD Variations: - -**Lightweight BMAD:** For small changes -```bash -# Brainstorm: Quick analysis -What's the best way to fix this null pointer? - -# Model: Simple plan -[Plan] Fix by adding null check on line 45 - -# Act: Implement -[Build] Add null check: if (user) { ... } - -# Deliver: Test and commit -/test --unit -!git commit -m "fix: Add null check for user object" -``` - -**Extended BMAD:** For complex projects -```bash -# Multi-phase BMAD with multiple agents -@product-manager Brainstorm feature requirements -@architect Model system architecture -@team-lead Model implementation timeline -@developers Act: Implement in parallel -@qa-engineers Act: Test implementation -@devops Deliver: Deploy and monitor -@documentation Deliver: Update all docs -``` - -### BMAD Benefits: -- **Consistency:** Structured approach for all tasks -- **Quality:** Each phase validates previous work -- **Efficiency:** Reduces rework and mistakes -- **Documentation:** Natural documentation through process -- **Collaboration:** Clear handoffs between phases - -## ⚡ Workflow Automation - -### Scheduled Tasks: -```bash -# Daily code review -0 9 * * * opencode run "/review changed --since yesterday" - -# Weekly dependency audit -0 10 * * 1 opencode run "/audit dependencies" - -# Monthly performance analysis -0 11 1 * * opencode run "/analyze @src/ --focus performance" -``` - -### Event-Triggered Workflows: -```bash -# On git push -git push && opencode run "/test && /review" - -# On file change -inotifywait -m -e modify @src/ | while read; do - opencode run "/analyze $REPLY" -done -``` - -### CI/CD Integration: ```yaml -# GitHub Actions workflow -name: OpenCode Review -on: [pull_request] +name: OpenCode review +on: + pull_request: + types: [opened, synchronize] + jobs: review: runs-on: ubuntu-latest steps: - - uses: actions/checkout@v3 - - uses: anomalyco/opencode-action@v1 + - uses: actions/checkout@v5 with: - command: "/review changed" - token: ${{ secrets.OPENCODE_TOKEN }} + fetch-depth: 0 + - run: curl -fsSL https://opencode.ai/install | bash + - run: | + opencode run --agent plan --format json \ + "Review the diff between origin/main and HEAD. Surface security and + correctness issues only. Output JSON with {severity,file,line,issue,fix}." \ + > review.json + env: + OPENCODE_API_KEY: ${{ secrets.OPENCODE_API_KEY }} + - run: gh pr comment ${{ github.event.pull_request.number }} --body-file review.json + env: + GH_TOKEN: ${{ secrets.GITHUB_TOKEN }} ``` -## 📊 Workflow Optimization +Equivalent shape on **GitLab CI**: -### Metrics to Track: -- Time from idea to implementation -- Bug rate per feature -- Test coverage changes -- Code review feedback quality -- Deployment frequency - -### Optimization Strategies: -1. **Identify bottlenecks**: Which steps take longest? -2. **Parallelize**: Can steps run concurrently? -3. **Automate**: Which manual steps can be automated? -4. **Simplify**: Can workflows be made simpler? -5. **Standardize**: Create templates for common workflows - -### Continuous Improvement: -```bash -# Regular workflow review -@analyzer Analyze our development workflow for improvements - -# Implement improvements -[Build] Create workflow automation for repetitive tasks - -# Measure impact -!opencode stats --workflow-metrics +```yaml +opencode-review: + rules: + - if: $CI_PIPELINE_SOURCE == "merge_request_event" + script: + - curl -fsSL https://opencode.ai/install | bash + - export PATH="$HOME/.local/bin:$PATH" + - opencode run --agent plan --format json "Review the diff..." > review.json + - 'curl -X POST -H "PRIVATE-TOKEN: $CI_TOKEN" --data-urlencode "body=$(cat review.json)" "$CI_API_V4_URL/projects/$CI_PROJECT_ID/merge_requests/$CI_MERGE_REQUEST_IID/notes"' + variables: + OPENCODE_API_KEY: $OPENCODE_API_KEY ``` -## 🎯 Choosing the Right Workflow +Same idea on Buildkite, CircleCI, Jenkins — install the CLI, set the env var, run a prompt, post the result wherever you post things. -### For New Features: -- **Complex features**: Explore → Plan → Code → Commit -- **Simple features**: Lightweight BMAD -- **Team projects**: Extended BMAD with multiple agents +`--dangerously-skip-permissions` is available for fully unattended runs — use it with care. -### For Bug Fixes: -- **Complex bugs**: Bug Fix Workflow -- **Simple bugs**: Lightweight BMAD +## 7. Visual iteration -### For UI/Design: -- **Visual changes**: Visual Iteration -- **Component updates**: TDD or Explore → Plan → Code → Commit +Goal: implement UI to match a mock. -### For Refactoring: -- **Major refactoring**: Explore → Plan → Code → Commit -- **Minor improvements**: TDD - -## 📋 Workflow Templates - -### BMAD Template: -```markdown -# BMAD: [Feature Name] - -## Brainstorm -- Requirements: -- Approaches: -- Constraints: - -## Model -- Architecture: -- Implementation Plan: -- Testing Strategy: -- Timeline: - -## Act -- Implementation Steps: -- Validation: -- Adjustments: - -## Deliver -- Final Testing: -- Documentation: -- Deployment: -- Monitoring: +```text +[plan] > [drag screenshot of the mock into the TUI] + > what HTML/CSS structure best matches this layout? +[build] > +[build] > implement it under src/components/Dashboard/. + > take a screenshot of the result with the playwright MCP server + > compare the new screenshot to the mock and refine ``` -### Workflow Automation Template: -```bash -# .opencode/workflows/feature-development.sh -#!/bin/bash -# Feature Development Workflow +Two-three iteration rounds usually produces a close visual match. Multimodal models (`opencode/gemini-3.1-pro`, `opencode/claude-sonnet-4-6`) handle the comparison well. -FEATURE_NAME=$1 +## Cross-cutting tips -echo "Starting feature development: $FEATURE_NAME" - -# 1. Explore -@explore Analyze related code for $FEATURE_NAME - -# 2. Plan -[Plan] Create implementation plan for $FEATURE_NAME - -# 3. Implement -[Build] Implement $FEATURE_NAME as planned - -# 4. Test -/test --feature $FEATURE_NAME - -# 5. Review -/review changed - -# 6. Deploy -/deploy --feature $FEATURE_NAME - -echo "Feature development complete: $FEATURE_NAME" -``` - -By designing and optimizing your workflows, you can maximize OpenCode's potential and achieve consistent, high-quality results. +- **Always commit `.opencode/` and `AGENTS.md`.** Your workflows become reproducible across teammates. +- **Use `/compact` aggressively** for long sessions — the summary preserves intent at a fraction of the tokens. +- **Use subagents for read-heavy work.** Your main session shouldn't carry 50KB of grep output it'll never reference again. +- **Pick a cheap model for `explore` and `scout` subagents.** They do dumb (but voluminous) work. +- **Audit `opencode stats` weekly.** Surprises in cost almost always trace to one overactive agent or MCP server. --- -## 📚 What's Next? - -- [FAQ & Troubleshooting](FAQ-TROUBLESHOOTING.md) - Common issues and solutions -- [Back to Main Guide](../README.md) - ---- - -*Last updated: February 2026* \ No newline at end of file +*Last reviewed: 2026-05-18 · Canonical source: [opencode.ai/docs](https://opencode.ai/docs/).* diff --git a/docs/zen.md b/docs/zen.md new file mode 100644 index 0000000..56304ed --- /dev/null +++ b/docs/zen.md @@ -0,0 +1,183 @@ +# OpenCode Zen + +> **Mental model:** Zen is OpenCode's curated, pay-as-you-go AI gateway. The OpenCode team tests and benchmarks models for coding-agent workloads and ships a focused lineup with consistent pricing. +> +> *(Beta — verified against [opencode.ai/docs/zen](https://opencode.ai/docs/zen) on 2026-05-18. Pricing and model availability change frequently; check the docs before quoting numbers.)* + +## When to reach for Zen vs. direct providers + +| Reach for Zen when… | Reach for direct providers when… | +|---|---| +| You want to try many models without juggling N API keys | You already pay for Anthropic/OpenAI/etc. and want to use existing credits | +| You want curated, benchmark-vetted models | You need a model Zen doesn't carry | +| You want billing in one place for a team | You're running fully local (Ollama, LM Studio) | +| You want a free tier to learn on | You want zero third-party intermediation | + +Zen is **opt-in**. OpenCode itself is provider-agnostic; you can mix Zen models with direct-provider models in the same config. + +## Setup + +```bash +# 1. Create a Zen account +# https://opencode.ai/auth + +# 2. Add billing details (auto-reload: $20 top-up when balance falls below $5) +# 3. Copy your API key + +# 4. Sign in from OpenCode +opencode auth login # pick "OpenCode Zen", paste key + +# Or from inside the TUI: +/connect # → OpenCode Zen → paste + +# 5. Browse the lineup +/models +``` + +In `opencode.json`, reference a Zen model with the `opencode/` prefix: + +```json +{ + "$schema": "https://opencode.ai/config.json", + "model": "opencode/claude-sonnet-4-6" +} +``` + +> Slug format: keep the dots in the upstream model name where they exist (`gpt-5.5`, `gemini-3.1-pro`, `qwen3.6-plus`, `minimax-m2.5`); Anthropic IDs use hyphens (`claude-opus-4-7`, `claude-sonnet-4-6`). + +## Available models + +Selected lineup below. **For the full list (40+ entries, latest pricing, cached-read/write rates, and endpoint URLs), see [opencode.ai/docs/zen](https://opencode.ai/docs/zen).** + +### Anthropic family + +| Model ID | Input / Output (per MTok) | Notes | +|---|---|---| +| `opencode/claude-opus-4-7` | $5 / $25 | Flagship reasoning — complex refactors, multi-file work | +| `opencode/claude-sonnet-4-6` | $3 / $15 | Workhorse — most coding work lives here | +| `opencode/claude-haiku-4-5` | $1 / $5 | Cheap, fast — title generation, simple Q&A | + +Older versions (`claude-opus-4-6`, `claude-opus-4-5`, `claude-sonnet-4-5`, `claude-sonnet-4`, `claude-3-5-haiku`) are also available — see the full list. + +### OpenAI family + +| Model ID | Input / Output (per MTok) | Notes | +|---|---|---| +| `opencode/gpt-5.5` *(≤272K)* | $5 / $30 | Long-context flagship | +| `opencode/gpt-5.5` *(>272K)* | $10 / $45 | Same model, beyond-window pricing | +| `opencode/gpt-5.5-pro` | $30 / $180 | Pro variant | +| `opencode/gpt-5.4-mini` | $0.75 / $4.50 | Cost-efficient frontier | +| `opencode/gpt-5.4-nano` | $0.20 / $1.25 | Cheap, fast, narrow tasks | +| `opencode/gpt-5.3-codex` · `opencode/gpt-5.2-codex` | $1.75 / $14 | Codex-tuned variants | + +GPT 5.1 / 5 / 5-codex / 5-nano are also available with their own pricing. + +### Other + +| Model ID | Input / Output (per MTok) | Notes | +|---|---|---| +| `opencode/gemini-3.1-pro` *(≤200K)* | $2 / $12 | Multimodal flagship | +| `opencode/gemini-3-flash` | $0.50 / $3 | Fast Gemini variant | +| `opencode/qwen3.6-plus` | $0.50 / $3 | Budget-friendly heavy lifting | +| `opencode/qwen3.5-plus` | $0.20 / $1.20 | Even cheaper | +| `opencode/kimi-k2.6` | $0.95 / $4 | Moonshot lineup | +| `opencode/glm-5.1` | $1.40 / $4.40 | Zhipu lineup | +| `opencode/minimax-m2.7` | $0.30 / $1.20 | MiniMax current | + +### Free tier (rotating, time-limited) + +For community feedback during model rollout: + +- `opencode/deepseek-v4-flash-free` +- `opencode/minimax-m2.5-free` +- `opencode/nemotron-3-super-free` +- `opencode/big-pickle` *(stealth model)* + +Great for learning OpenCode without burning a budget. + +## Billing + +- **Auto-reload:** default $20 top-up when balance falls under $5. Configurable on the dashboard; can be disabled. +- **Workspace limits:** monthly cap for a team and per-member spending limits. +- **BYOK:** bring your own Anthropic / OpenAI keys and Zen routes those provider calls through your credentials while still letting you use other Zen-hosted models. +- **Transaction fees:** credit card fees pass through at cost (per docs: 4.4% + $0.30 per transaction). +- **Title model:** sessions show `claude-haiku-3-5` charges — that's the low-cost model OpenCode uses to generate session titles automatically. + +## Patterns + +### Cheap explorer / strong executor + +Different agents, different models. A cheap model handles read-heavy subagents; a strong model does the editing. + +```json +{ + "model": "opencode/claude-sonnet-4-6", + "agent": { + "explore": { "model": "opencode/qwen3.6-plus" }, + "scout": { "model": "opencode/qwen3.6-plus" }, + "plan": { "model": "opencode/claude-haiku-4-5" }, + "build": { "model": "opencode/claude-sonnet-4-6" } + } +} +``` + +### Plan-with-Opus / execute-with-Sonnet + +For complex tasks, plan with the smartest model, then hand the atomic plan to a cheaper executor. + +```json +{ + "agent": { + "plan": { "model": "opencode/claude-opus-4-7" }, + "build": { "model": "opencode/claude-sonnet-4-6" } + } +} +``` + +### BYOK + Zen extras + +Reuse Anthropic credits while still having one-key access to GPT and Gemini. + +```json +{ + "model": "anthropic/claude-sonnet-4-5", + "provider": { + "anthropic": { "options": { "apiKey": "{env:ANTHROPIC_API_KEY}" } } + }, + "agent": { + "vision-helper": { "model": "opencode/gemini-3.1-pro" } + } +} +``` + +## API access + +You can also call Zen models directly via OpenCode's HTTP endpoints — handy if you're building scripts outside OpenCode itself: + +| Family | Endpoint pattern | +|---|---| +| OpenAI | `https://opencode.ai/zen/v1/responses` | +| Anthropic | `https://opencode.ai/zen/v1/messages` | +| Google | `https://opencode.ai/zen/v1/models/` | +| OpenAI-compatible (Qwen, Kimi, GLM, etc.) | `https://opencode.ai/zen/v1/chat/completions` | +| Full models list | `https://opencode.ai/zen/v1/models` | + +Use the matching AI SDK package (`@ai-sdk/openai`, `@ai-sdk/anthropic`, `@ai-sdk/google`, `@ai-sdk/openai-compatible`). + +## FAQ + +**Is my code sent anywhere I don't control?** +Zen is a gateway between OpenCode and the upstream provider. The privacy posture depends on the underlying provider plus Zen's own policy for billing/routing. The Zen docs page has the current statement. + +**Are free models reliable for production?** +No — the docs call them "available for a limited time" while the team collects feedback. Build with the assumption that any given free model could disappear, become paid, or be replaced. They're for learning, experimentation, and feedback. + +**Can I cancel auto-reload?** +Yes — turn it off in the dashboard, or set a monthly hard cap. + +**How does Zen compare to OpenRouter?** +Both are gateways. Zen is **curated** — the OpenCode team picks and tunes models for coding-agent loops. OpenRouter is broader but unopinionated. OpenCode supports both. + +--- + +*Last reviewed: 2026-05-18 · Canonical source: [opencode.ai/docs](https://opencode.ai/docs/).*