Skip to content
Back to search

opencode-primer

Master OpenCode, the open-source AI coding agent — setup, agents, skills, plugins, MCP, Zen & headless CI.

Safety scan

A static text scan, not a guarantee. Select the badge to see what was scanned and every finding.

Checked today
Badge for your README
findsafeskills safety rating

Markdown

[![findsafeskills safety rating](/api/listings/wesammustafa--opencode-primer/badge.svg)](/listings/wesammustafa--opencode-primer)

HTML

<a href="/listings/wesammustafa--opencode-primer"><img src="/api/listings/wesammustafa--opencode-primer/badge.svg" alt="findsafeskills safety rating" /></a>

Install

i

Install instructions from the README

As written by the repo's author. findsafeskills has not verified these steps.

What is OpenCode?

OpenCode is an open-source AI coding agent — a terminal app (TUI), desktop app, and IDE extension that reads your repo, runs commands, edits files, and talks to any LLM you point it at. Maintained by [Anomaly](https://github.com/anomalyco), MIT-licensed — and as of July 2026 the [most-starred coding agent on GitHub](https://github.com/anomalyco/opencode) (182K+ stars), with [8M monthly users by the founder's count](https://betakit.com/qa-opencodes-founder-on-how-the-ai-agent-went-from-zero-to-8-million-users-in-a-year/).

**Three things it does that a chat UI can't:**

- **Reads your actual repo** — not pasted snippets. Greps your files, follows imports, grounds answers in real context using built-in `read`/`grep`/`glob` tools. - **Edits in place and runs your stack** — diff-aware `edit`/`write`/`apply_patch`, then `bash` to run your tests, linter, or build on the spot. - **Composes with the rest of your toolchain** — multi-provider models, custom slash commands, agent skills, JS/TS plugins, MCP servers, LSP, formatters, and an HTTP server for CI use.

**Three interfaces:**

| Surface | Command | When | |---|---|---| | **TUI** (default) | `opencode` | Interactive day-to-day work in your terminal | | **CLI / headless** | `opencode run "<prompt>"` | Scripts, CI jobs, one-shot prompts | | **Server** | `opencode serve` or `opencode web` | Headless API, web UI, or remote attach |

opencode                                       # start TUI in the current repo
opencode run "fix the failing test in src/api.test.ts"
opencode serve --port 4096                     # headless server

> OpenCode sits in the same space as Claude Code, Codex CLI, and Cursor — same problem, different trade-offs. None is universally better; pick the one whose model, surface, and ecosystem fit your workflow. (The field consolidated hard in 2026: Gemini CLI was [retired in June](https://developers.googleblog.com/an-important-update-transitioning-gemini-cli-to-antigravity-cli/) in favor of the closed-source Antigravity CLI, and Roo Code shut down in May.)

> ⚠️ **AI-coding caveat:** OpenCode (like every coding agent) can produce wrong code, miss edge cases, hallucinate APIs, and over-apply patterns. **You're still the reviewer.** Read diffs before accepting, run tests, and don't auto-approve destructive operations on code you care about.

---

When OpenCode isn't the right tool

| Limitation | Detail | |---|---| | **No inline editor completion** | OpenCode is a conversational agent, not Copilot-style autocomplete. For ghost-text-while-you-type, reach for [Copilot](https://github.com/features/copilot), [Cursor Tab](https://cursor.com/), [Windsurf (formerly Codeium)](https://windsurf.com/), or [Supermaven](https://supermaven.com/) — or alongside. | | **Quality depends on the underlying model** | OpenCode doesn't replace the LLM's reasoning. If your task fails on Sonnet, switching to OpenCode won't fix it. | | **Provider-agnostic ≠ provider-equivalent** | Some models tool-call better than others. A slug swap isn't free. | | **TUI on slow SSH / minimal terminals** | The TUI uses truecolor and complex layouts. Degrades over slow connections. `opencode serve` + `attach` or `opencode run` are better for those cases. | | **Plugins run arbitrary code** | Any plugin — local or npm — has full user permissions. Audit before installing. | | **Free Zen models are time-limited** | The [Zen docs](https://opencode.ai/docs/zen) call them "available for a limited time." Don't build production on them. | | **Docs lag shipping** | OpenCode moves fast. This guide and even the official docs occasionally trail the actual binary. | | **Not a substitute for code review** | Diff-aware edits + passing tests don't guarantee correct, secure, or maintainable code. Treat AI output as a junior teammate's PR. |

**When something else fits better:**

- Want a polished single-vendor product → **Claude Code** or **Codex CLI**.

What was scanned

The files the safety scan read, as written by the repository's author and shown as plain text. Lines with a finding are marked.

README.md · README · 732 lines · 2 findings marked

View this file on GitHub (read at the repository's current version: the scan did not record which commit it read)

  1. <img src="Images/banner.svg" alt="OpenCode Primer — everything you need to know about the open-source AI coding agent" width="100%">
  2. # OpenCode Primer
  3. Everything you need to know about [OpenCode](https://opencode.ai) — from your first prompt to custom agents, skills, plugins, and MCP integrations. Clear mental models, real examples, every fact verified against the current release.
  4. [![License: MIT](https://img.shields.io/badge/license-MIT-blue.svg?style=flat-square)](LICENSE)
  5. [![OpenCode v1.17.13](https://img.shields.io/badge/OpenCode-v1.17.13-7C3AED?style=flat-square)](https://github.com/anomalyco/opencode/releases)
  6. [![Last reviewed](https://img.shields.io/badge/last%20reviewed-July%202026-22c55e?style=flat-square)](#updates--deprecations)
  7. [![PRs welcome](https://img.shields.io/badge/PRs-welcome-ff69b4?style=flat-square)](CONTRIBUTING.md)
  8. [![GitHub stars](https://img.shields.io/github/stars/wesammustafa/opencode-primer?style=flat-square&color=eab308)](https://github.com/wesammustafa/opencode-primer/stargazers)
  9. ```bash
  10. curl -fsSL https://opencode.ai/install | bash
    • Note: Pipes a downloaded script directly into a shell (curl | sh / wget | bash)
    • Line 14 on GitHub
  11. ```
  12. **Who this is for:** Developers using (or about to use) [OpenCode](https://opencode.ai). Beginners get a guided path; power users get depth on Custom Commands, Skills, Plugins, MCP, and Agents.
  13. > ⚖️ **Not affiliated with the OpenCode team.** This is a community-maintained guide. For canonical sources, check [opencode.ai/docs](https://opencode.ai/docs/) and [github.com/anomalyco/opencode](https://github.com/anomalyco/opencode).
  14. > 💡 **Pro Tip:** If this guide saves you an afternoon, a ⭐ helps other developers find it.
  15. ---
  16. ## 🧭 Choose your path
  17. | You are… | Start with | Time |
  18. |---|---|---|
  19. | 🚀 **New to OpenCode** | [What is it](#what-is-opencode) → [Setup](#setup) → [Prompt Engineering](#prompt-engineering) | ~15 min |
  20. | ⚡ **Already using it** | [Custom Commands](#custom-commands) · [Skills](#agent-skills) · [Plugins](#plugins) · [MCP](#mcp-servers) | ~20 min each |
  21. | 🧠 **Configuring or headless** | [Agents](#agents) · [Headless & CI](#headless--ci) · [Models & Providers](#models--providers) | varies |
  22. <!-- Compatibility anchors for old internal links (auto-generated heading anchors
  23. handle: setup, opencode-zen, themes, agents, plugins, custom-commands,
  24. agent-skills, mcp-servers, prompt-engineering, tui--themes, headless--ci) -->
  25. <a id="opencode-setup"></a>
  26. <a id="configuring-providers"></a>
  27. <a id="prompt-engineering-deep-dive"></a>
  28. <a id="tui-mastery"></a>
  29. <a id="subagents"></a>
  30. <a id="custom-agents"></a>
  31. <a id="model-context-protocol-mcp"></a>
  32. <a id="when-to-use-what"></a>
  33. <a id="whats-inside"></a>
  34. ---
  35. ## Getting started
  36. ### What is OpenCode?
  37. OpenCode is an open-source AI coding agent — a terminal app (TUI), desktop app, and IDE extension that reads your repo, runs commands, edits files, and talks to any LLM you point it at. Maintained by [Anomaly](https://github.com/anomalyco), MIT-licensed — and as of July 2026 the [most-starred coding agent on GitHub](https://github.com/anomalyco/opencode) (182K+ stars), with [8M monthly users by the founder's count](https://betakit.com/qa-opencodes-founder-on-how-the-ai-agent-went-from-zero-to-8-million-users-in-a-year/).
  38. **Three things it does that a chat UI can't:**
  39. - **Reads your actual repo** — not pasted snippets. Greps your files, follows imports, grounds answers in real context using built-in `read`/`grep`/`glob` tools.
  40. - **Edits in place and runs your stack** — diff-aware `edit`/`write`/`apply_patch`, then `bash` to run your tests, linter, or build on the spot.
  41. - **Composes with the rest of your toolchain** — multi-provider models, custom slash commands, agent skills, JS/TS plugins, MCP servers, LSP, formatters, and an HTTP server for CI use.
  42. **Three interfaces:**
  43. | Surface | Command | When |
  44. |---|---|---|
  45. | **TUI** (default) | `opencode` | Interactive day-to-day work in your terminal |
  46. | **CLI / headless** | `opencode run "<prompt>"` | Scripts, CI jobs, one-shot prompts |
  47. | **Server** | `opencode serve` or `opencode web` | Headless API, web UI, or remote attach |
  48. ```bash
  49. opencode # start TUI in the current repo
  50. opencode run "fix the failing test in src/api.test.ts"
  51. opencode serve --port 4096 # headless server
  52. ```
  53. > OpenCode sits in the same space as Claude Code, Codex CLI, and Cursor — same problem, different trade-offs. None is universally better; pick the one whose model, surface, and ecosystem fit your workflow. (The field consolidated hard in 2026: Gemini CLI was [retired in June](https://developers.googleblog.com/an-important-update-transitioning-gemini-cli-to-antigravity-cli/) in favor of the closed-source Antigravity CLI, and Roo Code shut down in May.)
  54. > ⚠️ **AI-coding caveat:** OpenCode (like every coding agent) can produce wrong code, miss edge cases, hallucinate APIs, and over-apply patterns. **You're still the reviewer.** Read diffs before accepting, run tests, and don't auto-approve destructive operations on code you care about.
  55. ---
  56. ### When OpenCode isn't the right tool
  57. | Limitation | Detail |
  58. |---|---|
  59. | **No inline editor completion** | OpenCode is a conversational agent, not Copilot-style autocomplete. For ghost-text-while-you-type, reach for [Copilot](https://github.com/features/copilot), [Cursor Tab](https://cursor.com/), [Windsurf (formerly Codeium)](https://windsurf.com/), or [Supermaven](https://supermaven.com/) — or alongside. |
  60. | **Quality depends on the underlying model** | OpenCode doesn't replace the LLM's reasoning. If your task fails on Sonnet, switching to OpenCode won't fix it. |
  61. | **Provider-agnostic ≠ provider-equivalent** | Some models tool-call better than others. A slug swap isn't free. |
  62. | **TUI on slow SSH / minimal terminals** | The TUI uses truecolor and complex layouts. Degrades over slow connections. `opencode serve` + `attach` or `opencode run` are better for those cases. |
  63. | **Plugins run arbitrary code** | Any plugin — local or npm — has full user permissions. Audit before installing. |
  64. | **Free Zen models are time-limited** | The [Zen docs](https://opencode.ai/docs/zen) call them "available for a limited time." Don't build production on them. |
  65. | **Docs lag shipping** | OpenCode moves fast. This guide and even the official docs occasionally trail the actual binary. |
  66. | **Not a substitute for code review** | Diff-aware edits + passing tests don't guarantee correct, secure, or maintainable code. Treat AI output as a junior teammate's PR. |
  67. **When something else fits better:**
  68. - Want a polished single-vendor product → **Claude Code** or **Codex CLI**.
  69. - Deeply embedded in VS Code workflow → **Cursor** or **GitHub Copilot**.
  70. - Want a small Python tool you can read end-to-end → **[Aider](https://aider.chat/)** (note: development has slowed markedly in 2026).
  71. - Don't want to manage provider keys → a managed hosted product, or [OpenCode Go](#opencode-go).
  72. > OpenCode's trade-off: flexibility and openness over polish and single-vendor integration. Worth it for many use cases; not all.
  73. ---
  74. ### Setup
  75. > ⏱️ **5 minutes** from zero to first AI-assisted commit.
  76. #### 1. Install
  77. ```bash
  78. curl -fsSL https://opencode.ai/install | bash
    • Note: Pipes a downloaded script directly into a shell (curl | sh / wget | bash)
    • Line 111 on GitHub
  79. ```
  80. Other supported installers (pick whichever you already use):
  81. ```bash
  82. npm i -g opencode-ai@latest # npm / pnpm / yarn / bun all work
  83. brew install anomalyco/tap/opencode # macOS / Linux
  84. scoop install opencode # Windows
  85. choco install opencode # Windows
  86. sudo pacman -S opencode # Arch
  87. paru -S opencode-bin # Arch (AUR)
  88. mise use -g github:anomalyco/opencode # mise users
  89. docker run -it --rm ghcr.io/anomalyco/opencode # Docker
  90. ```
  91. A desktop app for macOS / Windows / Linux is in beta at [opencode.ai/download](https://opencode.ai/download).
  92. #### 2. Authenticate
  93. ```bash
  94. opencode auth login # interactive provider picker
  95. opencode auth list # see who you're signed in to
  96. ```
  97. Or from inside the TUI: `/connect`. Provider options covered in the next section.
  98. #### 3. First prompt
  99. ```bash
  100. cd ~/your-project
  101. opencode
  102. ```
  103. Try one of these:
  104. - `explain what this codebase does`
  105. - `add a README section about installation`
  106. - `find and fix the failing test in src/api.test.ts`
  107. #### 4. Generate an `AGENTS.md`
  108. ```
  109. /init
  110. ```
  111. `/init` generates an `AGENTS.md` — your project's "house rules" that OpenCode reads every session. Commit it. More in [Prompt Engineering](#prompt-engineering).
  112. > 📝 **Coming from Claude Code?** OpenCode reads `CLAUDE.md` as a fallback if no `AGENTS.md` exists. Disable with `OPENCODE_DISABLE_CLAUDE_CODE=1` once migrated.
  113. #### 5. (Bonus) See a real configured project
  114. This repo's own [`.opencode/`](.opencode/) directory is a working example:
  115. | Path | What it does |
  116. |---|---|
  117. | [`.opencode/agents/`](.opencode/agents) | Custom agent definitions (markdown + YAML) |
  118. | [`.opencode/commands/`](.opencode/commands) | Custom slash commands |
  119. | [`.opencode/plugins/`](.opencode/plugins) | Working JS plugins (audit log, secret blocker) |
  120. | [`.opencode/skills/`](.opencode/skills) | Agent skills with `SKILL.md` files |
  121. | [`AGENTS.md`](AGENTS.md) | Project instructions OpenCode reads every session |
  122. | [`opencode.json`](opencode.json) | Project config with safe defaults |
  123. ---
  124. ### Models & Providers
  125. OpenCode is **provider-agnostic**. Four ways to plug in a model — pick whichever fits your accounts, budget, and privacy posture:
  126. | | Best for | Trade-off |
  127. |---|---|---|
  128. | **Direct providers** (Anthropic, OpenAI, Google, Groq, OpenRouter, AWS Bedrock, Azure) | You already have credits with a provider | Manage one key per provider |
  129. | **[OpenCode Zen](#opencode-zen)** — pay-as-you-go gateway | One key, curated lineup, no commitment | Pricier per token than going direct in some cases |
  130. | **[OpenCode Go](#opencode-go)** — flat-rate subscription | Predictable $10/month, zero key management | Curated open models only, usage limits |
  131. | **Local models** (Ollama, LM Studio, llama.cpp) | Offline, strict data-residency, hobbyist | Quality varies hugely with model and hardware |
  132. There's no universally right answer — pick what fits.
  133. > ⚠️ **Warning:** You can no longer sign in with a Claude Pro/Max subscription. OpenCode removed its built-in Anthropic OAuth login in March 2026 at Anthropic's legal request ([PR #18186](https://github.com/anomalyco/opencode/pull/18186)). Anthropic models still work fine — via an **API key** in the provider config below, or via **Zen**.
  134. #### Direct provider config
  135. ```json
  136. {
  137. "$schema": "https://opencode.ai/config.json",
  138. "model": "anthropic/claude-sonnet-5",
  139. "provider": {
  140. "anthropic": { "options": { "apiKey": "{env:ANTHROPIC_API_KEY}" } },
  141. "openai": { "options": { "apiKey": "{file:~/.secrets/openai-key}" } }
  142. }
  143. }
  144. ```
  145. Variable substitution: `{env:NAME}` (environment) or `{file:./path}` (file content, absolute or relative).
  146. Per-agent model override:
  147. ```json
  148. {
  149. "agent": {
  150. "plan": { "model": "anthropic/claude-haiku-4-5" },
  151. "deep-thinker": { "model": "openai/gpt-5.5", "options": { "reasoningEffort": "high" } }
  152. }
  153. }
  154. ```
  155. #### OpenCode Zen
  156. A curated, pay-as-you-go AI gateway. The OpenCode team tests and tunes models for coding-agent workloads; you get one key and a benchmarked lineup. Reference Zen models with the `opencode/<model-id>` namespace.
  157. ```bash
  158. # 1. Sign up at https://opencode.ai/auth, add billing, copy API key
  159. # 2. In OpenCode:
  160. /connect # pick "OpenCode Zen", paste key
  161. /models # browse the lineup
  162. ```
  163. **Pricing snapshot** *(verified 2026-07-05; check [opencode.ai/docs/zen](https://opencode.ai/docs/zen) for current)*
  164. | Model ID | Input / Output (per MTok) | Reach for it when… |
  165. |---|---|---|
  166. | `opencode/claude-fable-5` | $10 / $50 | Absolute frontier — the hardest reasoning problems |
  167. | `opencode/claude-opus-4-8` | $5 / $25 | Flagship reasoning — complex refactors, large multi-file work |
  168. | `opencode/claude-sonnet-5` | $2 / $10 | Balanced everyday coding — newer *and* cheaper than Sonnet 4.6 |
  169. | `opencode/claude-haiku-4-5` | $1 / $5 | Fast, lightweight tasks |
  170. | `opencode/gpt-5.5` *(≤272K)* | $5 / $30 | Long-context, OpenAI ecosystem |
  171. | `opencode/gpt-5.4-mini` | $0.75 / $4.50 | Cost-efficient frontier |
  172. | `opencode/gemini-3.1-pro` *(≤200K)* | $2 / $12 | Multimodal, Google ecosystem |
  173. | `opencode/qwen3.7-plus` | $0.40 / $1.60 | Budget-friendly heavy lifting |
  174. **Free tier** *(rotating, time-limited, for community feedback):* `big-pickle` *(stealth)*, `deepseek-v4-flash-free`, `mimo-v2.5-free`, `north-mini-code-free`, `nemotron-3-ultra-free`.
  175. > 📚 Full lineup, cached-read/write rates, GPT-5 Codex variants, Gemini, GLM, Kimi, MiniMax, DeepSeek, Grok, and the Claude Opus 4.8/4.7/4.6/4.5 line: [opencode.ai/docs/zen](https://opencode.ai/docs/zen) · Deeper guide (incl. deprecation sunset dates): [`docs/zen.md`](docs/zen.md).
  176. > 💡 **Pattern: cheap explorer / strong executor.** Use a cheap model (`qwen3.7-plus`, `gpt-5.4-mini`) for `explore` and `scout` subagents that read a lot, and a stronger one (`claude-sonnet-5` or `claude-opus-4-8`) for the main `build` agent that does the editing.
  177. #### OpenCode Go
  178. The flat-rate alternative to Zen: **$10/month ($5 your first month)** for a curated set of hosted open coding models — no API keys, no per-token math. Usage limits apply (roughly $12 per 5 hours / $30 per week / $60 per month of equivalent usage); past them, Go can fall back to a Zen balance.
  179. **Zen vs. Go in one line:** Zen bills per token across the full lineup; Go is a fixed subscription to open models. Reach for Go to learn and hack on a predictable budget; reach for Zen (or direct keys) when you want frontier models. Details: [opencode.ai/docs/go](https://opencode.ai/docs/go/) · [`docs/zen.md`](docs/zen.md).
  180. ---
  181. ## Using OpenCode
  182. ### Prompt Engineering
  183. > **📖 Project Initialization.** Run `/init` to auto-generate an `AGENTS.md`. Treat it like any frequently-used prompt — iterate on it. Don't just dump 500 lines and forget.
  184. #### Plan → Build cycle
  185. Two primary agents you toggle with **Tab**:
  186. | Agent | What changes | Use it for |
  187. |---|---|---|
  188. | **`plan`** | `edit` and `bash` default to `ask` — analysis without surprise writes | Reading code, designing approaches, reviewing diffs |
  189. | **`build`** | Full tool access (default) | Implementation, refactors, running tests |
  190. Natural workflow:
  191. ```text
  192. [plan] > how would you implement OAuth for this app?
  193. (reads, plans, proposes — no writes)
  194. [plan] > <Tab>
  195. [build] > do it
  196. (implements, edits, runs tests)
  197. ```
  198. > 💡 Prompts like `think hard`, `think more`, or `ultrathink` nudge reasoning depth on supported models — the same pattern in the [Anthropic prompt engineering guide](https://platform.claude.com/docs/en/docs/build-with-claude/prompt-engineering/overview).
  199. #### File references and shell
  200. | Syntax | Effect | Example |
  201. |---|---|---|
  202. | `@<path>` | Attach file content (fuzzy resolved) | `look at @src/api/auth.ts` |
  203. | `!<cmd>` | Run shell, inject output | `!git diff` then ask about it |
  204. ```text
  205. > review @packages/api/src/handlers/auth.ts for missing input validation
  206. > !pnpm test --reporter=verbose
  207. > based on those failures, fix the auth handler
  208. ```
  209. #### `AGENTS.md` for project rules
  210. ```markdown
  211. # AGENTS.md
  212. ## Commands
  213. - build: `pnpm build`
  214. - test: `pnpm test`
  215. - lint: `pnpm lint && pnpm typecheck`
  216. ## Conventions
  217. - TypeScript strict mode, no `any`
  218. - Prefer named exports; default exports only for React components
  219. ## Don't
  220. - Edit anything under `vendor/`
  221. - Run migrations without confirmation
  222. - Push to `main` directly
  223. ```
  224. Reads on every session. Add extra files via `instructions: ["..."]` in `opencode.json`.
  225. ---
  226. ### TUI & Themes
  227. #### Leader key
  228. OpenCode's TUI uses a **leader key** (default `ctrl+x`) followed by a single letter. Keeps single-keystroke editing keys free for the input box.
  229. | Binding | Action |
  230. |---|---|
  231. | `ctrl+x n` | New session |
  232. | `ctrl+x l` | List sessions |
  233. | `ctrl+x c` | Compact session |
  234. | `ctrl+x e` | Open external editor |
  235. | `ctrl+x m` | Browse models |
  236. | `ctrl+x t` | Switch theme |
  237. | `ctrl+x u` / `ctrl+x r` | Undo / Redo |
  238. | `ctrl+x q` | Quit |
  239. | `ctrl+p` | Command palette |
  240. | `Tab` | Cycle primary agents |
  241. | `Esc` | Cancel / dismiss |
  242. Readline shortcuts also work inside the prompt box (`ctrl+a`, `ctrl+e`, `ctrl+k`, `ctrl+u`).
  243. #### Themes
  244. Built-in: `system` · `tokyonight` · `everforest` · `ayu` · `catppuccin` · `catppuccin-macchiato` · `gruvbox` · `kanagawa` · `nord` · `matrix` · `one-dark`. Set via `/themes` or `tui.json`.
  245. ```json
  246. {
  247. "$schema": "https://opencode.ai/tui.json",
  248. "theme": "tokyonight",
  249. "leader_timeout": 2000,
  250. "keybinds": { "command_list": "ctrl+p" }
  251. }
  252. ```
  253. Custom themes: `.opencode/themes/<name>.json` (project) or `~/.config/opencode/themes/<name>.json` (global). Truecolor terminals required.
  254. > 📚 Deep dive: [`docs/tui.md`](docs/tui.md) · [opencode.ai/docs/keybinds](https://opencode.ai/docs/keybinds) · [opencode.ai/docs/themes](https://opencode.ai/docs/themes).
  255. ---
  256. ### Headless & CI
  257. Three ways to run OpenCode unattended:
  258. ```bash
  259. # 1. One-shot prompts
  260. opencode run "summarize the last 5 commits"
  261. opencode run --format json "list every TODO with file and line" > todos.json
  262. opencode run --agent plan --model anthropic/claude-haiku-4-5 \
  263. "audit src/ for missing input validation"
  264. # 2. Headless server / web UI
  265. opencode serve --port 4096 --hostname 0.0.0.0
  266. opencode web --port 4096
  267. # 3. GitHub agent
  268. opencode github install # add a workflow file to your repo
  269. opencode pr 123 # check out PR #123 and start a session
  270. ```
  271. Useful `run` flags: `--continue` / `--session <id>` (resume), `--fork` (branch a session), `--share` (publish), `--format json` (machine-readable), `--file <path>` (attach), `--replay` (interactive replay, v1.16+), `--auto` (auto-approve everything not `deny` — **CI only**). There's also a lightweight `--mini` mode (v1.17.10+).
  272. Sessions, stats, sharing:
  273. ```bash
  274. opencode session list # past sessions
  275. opencode stats --days 30 --models # token & cost by model
  276. opencode export <id> --sanitize # JSON dump (with redaction)
  277. opencode import session.json # restore from JSON or share URL
  278. ```
  279. > 📚 Full CLI reference: [`docs/reference/cli.md`](docs/reference/cli.md). CI recipes (GitHub Actions, GitLab CI): [`docs/workflows.md`](docs/workflows.md).
  280. ---
  281. ### Sharing
  282. `/share` generates a public link to the current session (`opncd.ai/s/<id>`). Three modes via `opencode.json`:
  283. ```json
  284. { "share": "manual" } // default — only when you ask
  285. { "share": "auto" } // every new session is shared
  286. { "share": "disabled" } // forbid sharing entirely
  287. ```
  288. `/unshare` revokes the link. Enterprise builds can enforce `"disabled"` via managed config.
  289. > ⚠️ **Privacy:** Shared conversations live on OpenCode's servers until you unshare. Don't share sessions with secrets, proprietary code, or confidential data.
  290. ---
  291. ## Extending OpenCode
  292. OpenCode has **five extension points**. Pick by trigger and surface:
  293. ```mermaid
  294. flowchart TD
  295. Start([Repeatable task you want<br/>OpenCode to do]) --> Q1{How does it trigger?}
  296. Q1 -->|User types /name| Q2{Just a prompt template,<br/>or a full role<br/>with permissions?}
  297. Q1 -->|Model auto-discovers<br/>from a description| AS[Agent Skill<br/>.opencode/skills/NAME/SKILL.md]
  298. Q1 -->|Event in OpenCode<br/>itself| Q3{Local code or<br/>external system?}
  299. Q2 -->|Prompt template| CC[Custom Command<br/>.opencode/commands/NAME.md]
  300. Q2 -->|Full role| CA[Custom Agent<br/>.opencode/agents/NAME.md]
  301. Q3 -->|Local JS/TS| PL[Plugin<br/>.opencode/plugins/NAME.js]
  302. Q3 -->|External tool| MCP[MCP Server<br/>opencode.json → mcp]
  303. ```
  304. | Extension | Triggered by | Lives in |
  305. |---|---|---|
  306. | [Custom Commands](#custom-commands) | User typing `/<name>` | `.opencode/commands/*.md` |
  307. | [Agent Skills](#agent-skills) | Model auto-discovery (description match) | `.opencode/skills/<name>/SKILL.md` |
  308. | [Plugins](#plugins) | Lifecycle events (tool calls, file edits, sessions) | `.opencode/plugins/*.{js,ts}` |
  309. | [Agents](#agents) | Tab key or `@<name>` mention | `.opencode/agents/<name>.md` |
  310. | [MCP Servers](#mcp-servers) | Prompt-driven external tool use | `opencode.json` → `mcp` |
  311. > 💡 These five compose. Most polished workflows combine 2–3.
  312. ---
  313. ### Slash Commands
  314. OpenCode ships a set of built-in slash commands plus everything you write yourself.
  315. | Command | What it does |
  316. |---|---|
  317. | `/init` | Guided generation of `AGENTS.md` |
  318. | `/help` | Show the help dialog |
  319. | `/new` *(`/clear`)* | New session |
  320. | `/sessions` *(`/resume`, `/continue`)* | List and switch sessions |
  321. | `/models` | Browse models |
  322. | `/connect` | Add a provider |
  323. | `/themes` | Switch theme |
  324. | `/compact` *(`/summarize`)* | Compact session to save tokens |
  325. | `/share` · `/unshare` | Public link control |
  326. | `/export` | Export to markdown |
  327. | `/undo` · `/redo` | Walk edit history |
  328. | `/editor` | Open `$EDITOR` |
  329. | `/details` · `/thinking` | Toggle visibility of tool / reasoning blocks |
  330. | `/exit` *(`/quit`, `/q`)* | Exit |
  331. Custom commands can override built-ins with the same name.
  332. > 📚 Full reference: [`docs/reference/slash-commands.md`](docs/reference/slash-commands.md).
  333. ---
  334. ### Custom Commands
  335. > **Mental model:** A custom command is a prompt template you've named. Save as `.opencode/commands/<name>.md`, invoke as `/<name>` in the TUI — with `$ARGUMENTS`, `@file`, and `!shell` interpolated at invocation time.
  336. Minimal example:
  337. ```markdown
  338. ---
  339. description: Run tests and triage failures
  340. agent: build
  341. ---
  342. !`pnpm test --reporter=verbose`
  343. If any tests failed above, open the failing files and propose precise fixes.
  344. Otherwise, summarize the coverage.
  345. ```
  346. Save as `.opencode/commands/test.md` → invoke with `/test`.
  347. | Frontmatter key | Purpose |
  348. |---|---|
  349. | `description` (required) | Shown in the slash-command palette |
  350. | `agent` | Which agent runs it (`build`, `plan`, or custom) |
  351. | `model` | Override the model just for this command |
  352. | `subtask` | `true` runs as a subagent (isolated child session) |
  353. | Body placeholder | Substitutes |
  354. |---|---|
  355. | `$ARGUMENTS` / `$1` / `$2` | Text after the command name |
  356. | `@<path>` | File content (fuzzy resolved) |
  357. | ``!`<cmd>` `` | Shell stdout (backticks required in templates) |
  358. This repo ships four examples in [`.opencode/commands/`](.opencode/commands/): `/review`, `/pr`, `/test`, `/optimize`.
  359. > 📚 Deep dive: [`docs/commands.md`](docs/commands.md) · [opencode.ai/docs/commands](https://opencode.ai/docs/commands).
  360. ---
  361. ### Agent Skills
  362. > **Mental model:** A skill is a **discoverable** workflow. The agent sees the skill's `name` and `description` and decides on its own to load it when the task matches. You don't have to remember to invoke — the model does.
  363. OpenCode uses Claude Code-compatible Agent Skill folders. Lookup paths (project → global → Claude-compat → Agent-compat):
  364. ```
  365. .opencode/skills/<name>/SKILL.md
  366. ~/.config/opencode/skills/<name>/SKILL.md
  367. .claude/skills/<name>/SKILL.md
  368. .agents/skills/<name>/SKILL.md
  369. ```
  370. Each `SKILL.md` needs YAML frontmatter with a `name` (lowercase-kebab, ≤64 chars) and a `description` (1–1024 chars). **The description is the discovery signal** — write it like a trigger sentence the agent will recognize.
  371. **Command vs. skill, in one line:** commands are user-invoked (`/<name>`), skills are model-invoked (description match). Write both for the same workflow if you want both surfaces.
  372. This repo ships one example: [`.opencode/skills/git-release/SKILL.md`](.opencode/skills/git-release/SKILL.md).
  373. > 📚 Deep dive: [`docs/skills.md`](docs/skills.md) · [opencode.ai/docs/skills](https://opencode.ai/docs/skills).
  374. ---
  375. ### Plugins
  376. > **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. `husky` for your AI session.
  377. Two locations:
  378. ```
  379. .opencode/plugins/<name>.{js,ts} # project
  380. ~/.config/opencode/plugins/<name>.{js,ts} # global
  381. ```
  382. Plus npm packages via the `plugin` array in `opencode.json`:
  383. ```json
  384. { "plugin": ["opencode-helicone-session", "@my-org/custom-plugin"] }
  385. ```
  386. Auto-installed via Bun, cached under `~/.cache/opencode/node_modules/`.
  387. Plugins receive `{ project, directory, worktree, client, $ }` and return hooks. `$` is the Bun shell. Two shapes: typed hooks like `tool.execute.before`/`shell.env` that get `(input, output)`, and a generic `event` handler for the lifecycle stream (files, sessions, messages, permissions, LSP, TUI — ~26 events).
  388. This repo ships two working examples in [`.opencode/plugins/`](.opencode/plugins/):
  389. | File | What it does |
  390. |---|---|
  391. | [`protect-secrets.js`](.opencode/plugins/protect-secrets.js) | Blocks any tool call touching `.env*`, `secrets/`, SSH keys |
  392. | [`audit-log.js`](.opencode/plugins/audit-log.js) | Appends every successful tool call to `.opencode/audit.jsonl` |
  393. > ⚠️ **Security:** Plugins run arbitrary code with your user permissions. Read every third-party plugin before installing — exactly like reviewing a shell script before sourcing.
  394. > 📚 Deep dive: [`docs/plugins.md`](docs/plugins.md) · [opencode.ai/docs/plugins](https://opencode.ai/docs/plugins).
  395. ---
  396. ### Agents
  397. OpenCode ships five built-in agents, and you can define your own as markdown files.
  398. #### Built-in
  399. | Agent | Mode | Tools | Reach for it when… |
  400. |---|---|---|---|
  401. | `build` | primary (default) | All | Default daily-driver — implementation, refactors |
  402. | `plan` | primary | `edit` and `bash` default to `ask` | Read-only-ish analysis, exploration |
  403. | `general` | subagent | All minus `todowrite` | Multi-step tasks isolated from main session |
  404. | `explore` | subagent | `read`, `grep`, `glob`, `list` | "Where is X?" code search |
  405. | `scout` | subagent | `webfetch`, `websearch`, + read tools | External docs and dependency research |
  406. `Tab` cycles primaries. `@<name>` invokes a subagent.
  407. #### Custom
  408. Drop a markdown file in `.opencode/agents/`:
  409. ```markdown
  410. ---
  411. description: Senior frontend engineer — Tailwind + React + TypeScript
  412. mode: all
  413. model: anthropic/claude-sonnet-5
  414. permission:
  415. edit: allow
  416. bash:
  417. "*": "ask"
  418. "pnpm test*": "allow"
  419. "git status*": "allow"
  420. ---
  421. You're a senior frontend engineer working on a React/Tailwind codebase…
  422. ```
  423. Filename → agent name. `frontend-engineer.md` → `@frontend-engineer` (subagent) or in the Tab cycle (primary). The `mode` value picks the surface:
  424. | `mode` | Where it appears |
  425. |---|---|
  426. | `primary` | Tab cycle alongside `build` / `plan` |
  427. | `subagent` | `@<name>` mentions only (runs in a child session) |
  428. | `all` | Both |
  429. Bash permissions accept a **glob-pattern map** (`{"*": "ask", "git status*": "allow", "rm -rf*": "deny"}`) — rules match in order and the **last matching rule wins**, so list the catch-all `*` first.
  430. > 📐 This repo ships **drop-in specialist prompts** in [`specialized-agents/`](specialized-agents/) — backend, frontend, code reviewer, security reviewer, tech lead, database, UX. Copy any of them into `.opencode/agents/<name>.md` to use.
  431. > 📚 Deep dive — full frontmatter key list, all 15 permission keys, JSON-form alternative: [`docs/agents.md`](docs/agents.md) · [`docs/reference/permissions.md`](docs/reference/permissions.md).
  432. ---
  433. ### MCP Servers
  434. > MCP is the universal connector that lets OpenCode talk to **external tools** — browsers, databases, search engines, ticketing systems — through one open protocol. USB-C for AI integrations.
  435. Declare servers in the `mcp` section of `opencode.json`. Local servers spawn a subprocess; remote servers hit an HTTPS endpoint with automatic OAuth via Dynamic Client Registration (RFC 7591).
  436. ```json
  437. {
  438. "$schema": "https://opencode.ai/config.json",
  439. "mcp": {
  440. "playwright": {
  441. "type": "local",
  442. "command": ["npx", "-y", "@playwright/mcp@latest"]
  443. },
  444. "context7": {
  445. "type": "remote",
  446. "url": "https://mcp.context7.com/mcp",
  447. "headers": { "CONTEXT7_API_KEY": "{env:CONTEXT7_API_KEY}" }
  448. },
  449. "sentry": {
  450. "type": "remote",
  451. "url": "https://mcp.sentry.dev/mcp",
  452. "oauth": {}
  453. }
  454. }
  455. }
  456. ```
  457. Manage from the CLI: `opencode mcp add | list | auth <name> | logout <name> | debug <name>`. Reference a server's tools in a prompt with `use <server-name>`.
  458. Featured walkthroughs in [`mcp-servers/`](./mcp-servers/):
  459. | Server | What it adds |
  460. |---|---|
  461. | [Playwright](./mcp-servers/playwright.md) | Browser automation — DOM, network, screenshots, accessibility |
  462. | [Context7](./mcp-servers/context7.md) | Live, version-pinned library docs piped into the prompt |
  463. | [Sentry](./mcp-servers/sentry.md) | Errors, traces, releases |
  464. | [Grep by Vercel](./mcp-servers/grep.md) | Code search across GitHub |
  465. > ⚠️ **Token budget:** MCP tools land in the model's tool surface every turn — heavy servers can easily eat 10K+ tokens of context. Disable noisy tools with the `tools` map (e.g. `"github_*": false`).
  466. > 📚 Deep dive: [`docs/mcp.md`](docs/mcp.md) · [opencode.ai/docs/mcp-servers](https://opencode.ai/docs/mcp-servers) · [Registry](https://registry.modelcontextprotocol.io/).
  467. ---
  468. ## Reference
  469. ### FAQ
  470. *[→ Full FAQ in `docs/reference/faq.md`](docs/reference/faq.md)*
  471. **Is OpenCode free?**
  472. The software is open source (MIT). You pay for whichever LLM provider you use. [OpenCode Zen](#opencode-zen) is pay-as-you-go per token; [OpenCode Go](#opencode-go) is a flat $10/month for hosted open models; BYOK works for direct providers.
  473. **Does OpenCode work without an internet connection?**
  474. Yes, with a local model (Ollama, LM Studio, llama.cpp). Network is needed for hosted providers, remote MCP servers, sharing, and updates.
  475. **Can I migrate from Claude Code?**
  476. Most concepts map cleanly but a few fields and file paths differ. OpenCode reads `CLAUDE.md` and `.claude/skills/` as fallbacks. Slash commands move from `.claude/commands/` → `.opencode/commands/`; Python hooks become JS/TS plugins; agent frontmatter uses different keys (`name` gone, `mode` new, `tools` becomes `permission`). See [the full migration guide](docs/migration.md).
  477. **Custom commands vs. skills — which should I write?**
  478. Both. Commands are **explicit** (user types `/<name>`); skills are **discoverable** (model picks them up). Use commands for workflows the user owns, skills for expertise the agent should reach for. Comparison in [`docs/commands.md`](docs/commands.md#when-to-use-a-command-vs-a-skill-vs-an-agent).
  479. **How do I keep OpenCode from running risky shell commands?**
  480. Set `bash` permission to `"ask"` at the project level, or use the glob form to whitelist only safe patterns. Full mechanism in [`docs/reference/permissions.md`](docs/reference/permissions.md).
  481. **Where do I see my token usage?**
  482. `opencode stats` for a multi-day breakdown by model and project. The TUI also surfaces per-session totals in the footer.
  483. ---
  484. ### Updates & Deprecations
  485. *[→ Full changelog in `docs/reference/changelog.md`](docs/reference/changelog.md)*
  486. **Current release:** **v1.17.13** *(2026-07-01)*. Run `opencode upgrade` to get it.
  487. **New in v1.17:**
  488. - 🆕 **Session snapshots & revert** *(v1.17.11)* — roll a session back to an earlier message, including the file changes it made.
  489. - 🆕 **TUI yolo mode** *(v1.17.12)* — auto-approve permission prompts from inside the TUI; plus adaptive thinking for Claude Sonnet 5.
  490. - 🆕 **MCP resources** *(v1.17.10)* — resource template listing and resource-read tools, and MCP server instructions now land in session context. Local servers also gained a `cwd` option *(v1.17.4)*.
  491. - 🆕 **`--mini` CLI mode & V2 plugin API** *(v1.17.10)* — a lightweight CLI surface, namespaced plugin hooks, and Effect/Promise plugin support.
  492. - ⚡ **Faster file search** (new `fff`-backed tools), WSL-backed desktop on Windows, and a desktop v2 refresh (Chrome-style tabs, searchable model picker) *(v1.17.0–v1.17.13)*.
  493. - ⚠️ **Deprecation:** the `reference` config key is now `references` *(v1.17.1; old entries still load)*.
  494. **Still recent (v1.16):**
  495. - **File-based agents & skill discovery** — drop-in agent markdown files and `SKILL.md` discovery are GA; scaffold an agent with `opencode agent create`.
  496. - **Workspace cloning & session mobility** — managed workspace clones keep dirty/untracked files; move sessions between workspaces and directories.
  497. - **`opencode run --replay`** — interactively replay a run as it streams.
  498. - **~38% faster startup**, OpenAI models via AWS Bedrock, GitHub Copilot usage tracking.
  499. - 📝 **AGENTS.md** is canonical; `CLAUDE.md` is a fallback only.
  500. > 💡 Source of truth: [GitHub releases](https://github.com/anomalyco/opencode/releases).
  501. ---
  502. ### References
  503. *[→ Full reading list in `docs/reference/further-reading.md`](docs/reference/further-reading.md)*
  504. **Most-clicked starting points:**
  505. - [OpenCode docs (official)](https://opencode.ai/docs/)
  506. - [OpenCode on GitHub](https://github.com/anomalyco/opencode)
  507. - [OpenCode Zen](https://opencode.ai/docs/zen)
  508. - [Config schema](https://opencode.ai/config.json) · [TUI schema](https://opencode.ai/tui.json)
  509. - [Official MCP registry](https://registry.modelcontextprotocol.io/) · [Protocol spec](https://modelcontextprotocol.io/)
  510. ---
  511. **Reading tips:** Anchor links work natively on GitHub — tap the table-of-contents button at the top of the file view. On a phone, stick to [Choose your path](#-choose-your-path); wider tables read best on desktop.
  512. > Features, pricing, and availability change frequently. Always check the [official OpenCode documentation](https://opencode.ai/docs/) for the most current information.
  513. *Last reviewed 2026-07-05 · OpenCode v1.17.13 · Spotted something stale? [Open an issue](https://github.com/wesammustafa/opencode-primer/issues) or send a PR — see [`CONTRIBUTING.md`](CONTRIBUTING.md).*
  514. **Found this useful? [Give it a ⭐](https://github.com/wesammustafa/opencode-primer) — it's how other developers discover the guide.**

Ratings and comments

Sign in to rate this skill.

Sign in

Free to use. If it’s helped, pass it on.