1. Why OpenCode: One Terminal Harness, Every Frontier & Local Model
Single-vendor coding CLIs tie your workflow, shortcuts, and team habits to one billing account. OpenCode decouples the developer harness—TUI ergonomics, file indexing, LSP diagnostics, session snapshots, and subagents—from the underlying model API so you can assign the sharpest brain to every task.
Quick Navigation
/undo) & SessionsPart 7
3. Annotated OpenCode TUI TourPart 3
9. 5 Copy-Paste Production RecipesPart 8
4. Plan vs. Build Mode MasteryPart 4
10. Sharing, Privacy & Desktop ClientsPart 9
5. Routing & Custom Markdown AgentsPart 5
11. Cross-Tool Synergy PipelinePart 10
6. Troubleshooting & Pre-FlightPart 11
Architecture: Client-Server Core Driving TUI, LSP & 75+ Model Endpoints
plan agent brain, a fast coding flagship for build, and a lightweight small_model in opencode.json for background session titles, summaries, and subagent exploration.
2. Installation, Credential Vault & Provider Strategy Matrix
Install OpenCode via native binary, Homebrew, or npm, link your preferred cloud subscriptions or local Ollama server via /connect, and run /init inside your repository to generate a tailored AGENTS.md.
# Official install script or Homebrew / Bun / npm
curl -fsSL https://opencode.ai/install | bash
brew install anomalyco/tap/opencode
npm install -g opencode-ai@latest
# Launch inside your repo & bootstrap AGENTS.md
cd ~/code/my-app && opencode
# Inside TUI: run /connect then /initopencode auth)Run /connect inside the TUI or opencode auth login in your shell. Credentials live outside Git at ~/.local/share/opencode/auth.json:
opencode auth login # OAuth / API key wizard
opencode auth list # Verify connected providers
opencode models # List all resolved model IDsProvider & Model Strategy Matrix
| Provider Path | Example model String |
Sweet Spot in OpenCode | Billing / Privacy Model |
|---|---|---|---|
| Anthropic / OpenAI | anthropic/claude-sonnet-4-5openai/gpt-5 |
Complex multi-file refactors, architectural Plan blueprints, deep debugging |
Direct API key or supported Pro/Max OAuth flows |
| Google Gemini | google/gemini-2.5-progoogle/gemini-2.5-flash |
1M-token monorepo sweeps, large log analysis, ultra-fast small_model |
AI Studio API key or Vertex AI enterprise IAM |
| OpenCode Zen | opencode/claude-sonnet-4-5 |
Zero-setup curated coding models benchmarked specifically for the OpenCode harness | Single unified pay-as-you-go balance via /connect |
| Local Ollama / vLLM | ollama/qwen3-coder:30b |
Air-gapped codebases, offline flights, unlimited zero-marginal-cost edits | 100% local hardware (set num_ctx ≥ 32768!) |
~/.config/opencode/opencode.json → 3. Env var OPENCODE_CONFIG → 4. Project root opencode.json. Commit project rules and model roles to Git while keeping API keys strictly in auth.json or {env:VAR_NAME} references.
3. Annotated Tour: Navigating the OpenCode TUI Like a Pro
OpenCode’s keyboard-driven TUI keeps diffs, compiler diagnostics, token budgets, and active agent modes visible in one glance—controlled via quick slash commands and the Ctrl+X leader key.
@src/payments/charge.ts and !pnpm test:unit
3
anthropic/claude-sonnet-4-5 • Press Tab for PLAN
typescript-language-server (ready)•
postgres-mcp (4 tools active)
M src/payments/charge.tsM test/charge.spec.tsSnapshot #4 saved •
/undo ready
Control Legend: Essential Zones & Leader Chords
/sessions or Ctrl+X l): Jump between parallel task histories, rename threads, or fork a conversation cleanly.
/compact before hitting 75% capacity.
@ File Fuzzy Search & ! Shell Bar: Type @ to attach exact files/symbols or start a line with ! to run a command and pipe stdout into context.
Tab / Ctrl+X m): Press Tab to toggle PLAN ↔ BUILD, or /models to swap providers mid-thread.
/undo rollback.
4. The Tab Key Habit: Separate Architecture From Mutation
The fastest way to wreck a codebase is letting an eager agent edit ten files before understanding how your auth middleware works. Pressing Tab switches OpenCode into Plan Mode—physically disabling file edits and destructive shell commands while the agent maps out a surgical blueprint.
Tab): Inspect, search, and crystallize edge cases safely inside the read-only Plan frame (left) before flipping to Build mode (right) to execute verified multi-file patches and tests.
PLAN Mode (Read-Only Architect)- Hard Write Lock: File creation, patch edits, and mutating bash tools are denied or gated by permission policy.
- Deep Exploration: Uses
grep,glob, file reads, and@exploresubagents to verify call sites before proposing changes. - Best Model Choice: Route to high-reasoning models (
claude-opus-4-6,gpt-5, orgemini-2.5-pro).
BUILD Mode (Full-Access Implementer)- Full Execution Loop: Applies surgical patches, receives automatic LSP compiler feedback, and runs test suites.
- Follows the Approved Plan: Executes step by step against the blueprint already agreed upon in the same session context.
- Best Model Choice: Fast, high-throughput coding models (
claude-sonnet-4-5or localqwen3-coder).
The 4-Step Plan → Review → Build Rhythm
1. Press [Tab] -> Confirm badge reads PLAN.
2. Prompt: "Trace @src/auth/session.ts and propose a 3-step plan to rotate refresh tokens."
3. Challenge assumptions ("Keep backward compatibility for mobile v2 tokens; skip DB migration").
4. Press [Tab] -> Badge flips to BUILD -> Prompt: "Execute steps 1-3 and run !pnpm test auth"5. Multi-Model Routing & Markdown Specialist Subagents
Instead of paying flagship prices on every grep or code review, assign tailored models, temperatures, and tool boundaries per agent role in opencode.json or drop self-contained Markdown files into .opencode/agents/.
1. Role-Based Routing in opencode.json
{
"$schema": "https://opencode.ai/config.json",
"model": "anthropic/claude-sonnet-4-5",
"small_model": "google/gemini-2.5-flash",
"agent": {
"plan": {
"model": "openai/gpt-5",
"temperature": 0.1
},
"build": {
"model": "anthropic/claude-sonnet-4-5"
}
}
}2. Custom Subagent (.opencode/agents/sec.md)
---
description: Audits diffs for OWASP & auth bugs
mode: subagent
model: google/gemini-2.5-pro
temperature: 0.1
tools:
write: false
edit: false
bash: false
---
Review changed files for SQLi, SSRF, IDOR, and
leaked secrets. Cite file:line and minimal fix.
Invoking Subagents: Mention any subagent directly in chat (for example, @sec audit my staged changes or built-in @explore find where webhook signatures are verified), or let your primary agent delegate automatically based on its description frontmatter. Navigate between parent and child subagent threads anytime using Ctrl+X Right / Left.
Color-Coded Blueprint: High-Signal OpenCode TUI Prompt
6. Native LSP Loops, AGENTS.md & Token Compaction
Most terminal agents waste three turns running full builds just to discover a missing import. OpenCode spawns language servers directly behind the scenes, streaming instant compiler diagnostics into the agent turn the moment a file is written.
OpenCode auto-detects TypeScript, Python, Go, Rust, Elixir, Zig, C#, and Astro language servers. Customize or disable servers in opencode.json:
{
"lsp": {
"pyright": {
"env": { "VIRTUAL_ENV": ".venv" }
},
"eslint": { "disabled": true }
}
}AGENTS.md via /initRunning /init scans your build scripts, lint rules, and folder conventions to write AGENTS.md (also compatible with CLAUDE.md fallback):
- Pin exact single-file test commands (
pnpm vitest run path/to/file). - List architectural boundaries and forbidden directories.
- Load shared team docs via
"instructions": ["docs/arch.md"].
Context Window Hygiene: Staying Fast Past Turn 30
| Command / Shortcut | What It Does Under the Hood | When to Trigger It |
|---|---|---|
/compact (Ctrl+X c) |
Summarizes prior turns, resolved tool logs, and key decisions into a tight handoff block | After finishing one feature slice or whenever token usage crosses ~65–75% |
/new (Ctrl+X n) |
Starts a brand-new clean conversation while preserving AGENTS.md project rules |
Switching to an unrelated bug or subsystem where prior files add noise |
/editor (Ctrl+X e) |
Opens your $EDITOR (Neovim, VS Code, Zed) to compose multi-line specs comfortably |
Drafting detailed acceptance criteria, pasted stack traces, or table schemas |
| Clipboard Image Paste | Drag-and-drop or paste UI screenshots straight into the TUI prompt box | Fixing CSS alignment bugs, mobile overflow, or matching a wireframe |
@explore to Protect Main Context@explore to locate exact symbols first; only its concise file:line summary enters your main session.
7. Fearless Experimentation with /undo & /redo Snapshots
Traditional git reset --hard wipes your manual edits or pollutes commit history. OpenCode maintains a private shadow Git object store behind your repository so every turn is atomically reversible without touching your real Git staging index.
/undo rolls back both the workspace files and the bad conversation turn simultaneously, letting you refine your prompt and replay cleanly from a known-good checkpoint.
/undo Beats Follow-Up NaggingWhen an agent goes down the wrong architectural path, arguing with it in turn 6 leaves five turns of broken code polluting its context window. Instead:
- Run
/undo(Ctrl+X u) once or twice to restore exact pre-turn files; your original prompt pops right back into the input box. - Add the missing constraint or
@filereference and hitEnter. - Changed your mind? Run
/redo(Ctrl+X r) to restore the reverted turn and patches intact.
Benchmark two providers head-to-head on your real repo in under two minutes:
- Let Model A attempt the fix and run
!pnpm test. - Run
/undoto rewind the working tree to its exact starting state. - Switch models with
/models(Ctrl+X m) to Model B and submit the exact same pre-filled prompt.
/undo and /redo engine relies on your folder being initialized with git init. Always initialize Git in scratch prototypes before starting heavy multi-file Build loops.
8. 5 Real-World Copy-Paste Recipes
Copy these five ready-to-use configurations and slash commands into your project to unlock hybrid cloud/local routing, custom slash commands, local Ollama 32K coding, and session continuation.
| Recipe & Goal | Copy-Paste Snippet / Config | Expected Outcome |
|---|---|---|
| 1. Cloud Planner + Local Ollama Coder | {"agent":{"plan":{"model":"anthropic/claude-opus-4-6"},"build":{"model":"ollama/qwen3-coder:30b"}},"provider":{"ollama":{"npm":"@ai-sdk/openai-compatible","options":{"baseURL":"http://localhost:11434/v1"}}}} |
Uses frontier reasoning in PLAN mode and zero-cost local GPU tokens in BUILD mode. |
2. Custom /test-fix Slash Command |
Save .opencode/commands/test-fix.md:---description: Run suite and fix failures---Failure output: !`pnpm test --run` — fix root cause for $ARGUMENTS without weakening assertions. |
Typing /test-fix auth executes tests first, injects stdout, and fixes the failing module. |
| 3. Resume Latest Session From Shell | opencode --continue (or opencode -s ses_01JXYZ...) |
Reopens your exact prior TUI thread, snapshot chain, and active model immediately. |
| 4. Auto-Format Files After Every Edit | In opencode.json:{"formatter":{"biome":{"command":["npx","@biomejs/biome","check","--write","$FILE"],"extensions":[".ts",".tsx",".json"]}}} |
Runs Biome automatically on every touched file so agent diffs always match repo style. |
| 5. Export Full Session JSON Audit Log | opencode export ses_01JXYZ > session-audit.json |
Dumps complete prompts, tool calls, token counts, and diffs for team postmortems or evals. |
.opencode/commands/*.md templates, wrapping a command in exclamation-backtick syntax runs that shell command locally (such as git diff --staged or test runners) and splices its fresh output straight into the prompt before sending it to the LLM.
9. Session Sharing Controls, Privacy Locks & IDE Companions
OpenCode makes code review walkthroughs effortless with one-command share links, while giving enterprise security teams a single config switch to lock sharing off completely across private repositories.
share ModesConfigure "share" in opencode.json to match your repo’s confidentiality level:
"manual"(Default): Nothing leaves your machine unless you explicitly run/share(Ctrl+X s); revoke anytime with/unshare."disabled"(Enterprise Lock): Hard-blocks/sharein proprietary repos so source snippets can never be published to a public URL."auto": Automatically creates shareable links for open-source PR walkthroughs.
- Never Hardcode Keys: Reference environment secrets in
opencode.jsonwith"{env:LITELLM_API_KEY}"or file contents via"{file:~/.secrets/token}". - Block Sensitive Reads: Add
.env*,*.pem, andsecrets/deny rules underpermission.readso prompts never ingest raw credentials. - Zero-Telemetry Local Stack: Pair
"share": "disabled"with local Ollama or VPC Bedrock/Vertex endpoints for full data residency.
Run OpenCode inside your editor’s integrated terminal pane: active file selections, line ranges, and diagnostic problems jump straight into your TUI prompt with a single shortcut while diffs update live in editor buffers.
Run /themes (Ctrl+X t) and pick system or built-in palettes (Catppuccin, Tokyonight, Gruvbox, Rose Pine). Use a TrueColor terminal (Ghostty, Kitty, WezTerm, iTerm2, or Alacritty) for crisp diff highlights.
"share": "disabled" on Day One in Private Client Repos{"share": "disabled"} to your repository’s checked-in opencode.json protects every developer on the team from accidentally running Ctrl+X s during a late-night debugging session.
10. Cross-Tool Synergy: Worktrees + Plan/Build + LSP + PR Review
Combine isolated Git worktrees, multi-provider Plan/Build routing, native LSP verification, and shareable PR walkthroughs into a repeatable high-velocity engineering loop.
Run three independent opencode TUI instances inside three git worktree directories (for example inside tmux or Ghostty splits) so each agent gets isolated shadow snapshots, ports, and LSP caches.
Once your interactive TUI workflow is dialed in, turn to the companion handbook (OpenCode Plugins, Custom Tools, Servers & CI) to wire TypeScript hooks, headless opencode serve, and GitHub Actions automation.
11. Troubleshooting Clinic & 6-Point Pre-Flight Checklist
Fix the seven most frequent TUI, local-model, LSP, and snapshot hiccups in ten seconds flat, then run the 6-point checklist when onboarding any new repository.
| Symptom / Issue | 10-Second Root-Cause Fix |
|---|---|
| 1. Local Ollama model forgets system tools or loops | Ollama defaults to a tiny 4096 token context window! Build a Modelfile with PARAMETER num_ctx 32768 (or 65536) before selecting it in OpenCode. |
| 2. Agent refuses to edit files even when asked | Check the bottom-left mode badge—you are still in read-only PLAN mode! Press Tab once to flip the badge to BUILD. |
3. /undo reports snapshot unavailable |
The directory is not a Git repository. Run git init at the workspace root so OpenCode can initialize its shadow snapshot tree. |
| 4. LSP diagnostics missing for Python or TypeScript | Language server binary isn’t on PATH or wrong venv is active. Install pyright / typescript-language-server or pass VIRTUAL_ENV under lsp in opencode.json. |
5. Newly added API key doesn’t show models in /models |
Run /connect inside the TUI or verify the provider ID via opencode auth list and opencode models --refresh. |
| 6. Diff colors look washed out inside tmux | Enable 24-bit TrueColor in ~/.tmux.conf (set -ga terminal-overrides ",xterm-256color:Tc") and select /themes → system. |
| 7. Responses slow down & cost spikes after 40 turns | Long raw tool outputs are re-sent each turn. Run /compact (Ctrl+X c) to distill history or start a fresh thread with /new. |
AGENTS.md: Ran /init and pinned fast single-file test and lint commands.plan, fast build, and cheap small_model in opencode.json."share": "disabled" in checked-in config for private or client repos.Tab (PLAN) mode with @explore before mutating files./undo on off-track turns and /compact between feature milestones.