OpenCode — Complete Cheat Sheet

"The reference sheet you print and keep next to your monitor."

SectionInstallation & Setup

Install

MethodCommand
Install scriptcurl -fsSL https://raw.githubusercontent.com/opencode-ai/opencode/main/install | bash
Homebrew (macOS/Linux)brew install opencode-ai/tap/opencode
AUR (Arch)yay -S opencode-bin
Nixnix run nixpkgs#opencode
Gogo install github.com/opencode-ai/opencode@latest
Debian/Ubuntudpkg -i opencode_*.deb
Fedora/RHELrpm -i opencode_*.rpm
Windowsscoop install opencode or winget install OpenCode.OpenCode

First Run

CommandWhat it doesWhen to use itWhy it matters
opencodeOpens the interactive TUIFirst time in a projectMain interface
opencode -p "fix the bug"Runs one prompt and exitsCI/CD or scriptingNo interactive input
opencode -p "explain" -f jsonEmits JSON for pipingAutomation and pipelinesStructured output
opencode -p "explain" -qQuiet output without spinnerCI/CD environmentsClean logs
opencode --yoloRuns tool calls without permission promptsOnly when you trust the agentDangerous if you are not sure
Core CLI Commands
➜ ~ opencode
opens the interactive TUI
➜ ~ opencode -p "fix the null pointer"
⠋ Running agent...
✓ Fixed auth/auth.go line 42
➜ ~ opencode -p "explain" -f json | jq .summary
"This function handles OAuth token refresh."
➜ ~⏎ run · ⌫ clear

SectionCLI Commands

CommandWhat it does exactlyWhen to use itWhy it matters
opencodeOpens the interactive TUI, the main interfaceDaily workUsed most of the time
opencode -p "prompt"Runs one prompt in non-interactive mode and exitsCI/CD, scripts, automationProduces a result without opening the TUI
opencode -f jsonOutputs structured JSONPipelines and parsingEverything is structured and explicit
opencode -qQuiet mode without spinner or decorationsCI/CD environmentsClean log output
opencode -c /pathSets the working directoryRunning from another locationKeeps the agent on the right project
opencode serveStarts a shared workspace serverMulti-client collaborationMultiple TUIs can work together
opencode loginLogs into subscription providersGemini Code Assist, CopilotRequired by authenticated providers
opencode modelsLists available modelsChoosing a modelShows what is available
opencode statsShows usage statisticsCost monitoringShows spend and usage
opencode sessionsLists saved sessionsSession managementShows active and previous work
opencode update-providersUpdates the model database from CatwalkNew model availabilityKeeps provider data current
opencode logsOpens internal logsDebuggingShows what happened inside

SectionAgent System — Types and Roles

Agent Taxonomy & Division of Labor

Agent Swarm Architecture

Primary Agents

AgentRoleTemperaturePermissionsWhen to use it
BuildDefault driver that does everything0.3-0.5Full file ops + system commandsDaily coding, edits, execution
PlanAnalyst that reads and reasons0.0-0.2Ask-first for file edits + bashAnalysis or architecture review
TitleGenerates session titles-Read-onlyAutomatic, not usually invoked manually

Tab key — switch between Build and Plan at any time.

Subagents

SubagentAccessRoleWhen to call it
GeneralFull tools except todoMulti-step task executionTasks with many steps
ExploreRead-only: glob, grep, ls, viewLocal codebase searchFinding something in code
ScoutExternal researcherExternal docs and dependency researchLooking up docs or upstream code

SectionConfiguration — .opencode.json

Full Config

json
{
  "agents": {
    "coder": { "model": "claude-sonnet-4", "maxTokens": 5000 },
    "task": { "model": "claude-sonnet-4", "maxTokens": 5000 },
    "title": { "model": "claude-sonnet-4", "maxTokens": 80 }
  },
  "providers": {
    "anthropic": { "apiKey": "$ANTHROPIC_API_KEY" },
    "openai": { "apiKey": "$OPENAI_API_KEY" },
    "openrouter": { "apiKey": "$OPENROUTER_API_KEY" }
  },
  "permissions": {
    "allowed_tools": ["view", "ls", "grep", "glob", "edit"]
  },
  "mcp": {
    "github": {
      "type": "http",
      "url": "https://api.githubcopilot.com/mcp/",
      "headers": { "Authorization": "Bearer $GH_PAT" }
    }
  },
  "lsp": {
    "go": { "command": "gopls" }
  },
  "hooks": {
    "PreToolUse": [
      { "matcher": "^(view|ls|grep|glob)$", "command": "echo '{\"decision\":\"allow\"}'" }
    ]
  },
  "options": {
    "context_paths": ["AGENTS.md", ".cursorrules"],
    "global_context_paths": ["~/.config/opencode/OPENCODE.md"],
    "tui": { "theme": "catppuccin", "compact_mode": false },
    "initialize_as": "AGENTS.md",
    "data_directory": ".opencode"
  }
}

Config Paths (in order)

PathPriority
./.opencode.json (local)Highest, project-specific
$XDG_CONFIG_HOME/opencode/.opencode.jsonUser-level
$HOME/.opencode.jsonUser-level fallback

Provider Environment Variables

ProviderVariableNotes
AnthropicANTHROPIC_API_KEYClaude models
OpenAIOPENAI_API_KEYGPT models
Google GeminiGEMINI_API_KEYGemini models
AWS BedrockAWS_ACCESS_KEY_ID + AWS_SECRET_ACCESS_KEY + AWS_REGIONClaude via AWS
Azure OpenAIAZURE_OPENAI_ENDPOINT + AZURE_OPENAI_API_KEYGPT via Azure
OpenRouterOPENROUTER_API_KEYMulti-model access
GitHub CopilotGITHUB_TOKENFree tier available
GroqGROQ_API_KEYFast inference
OllamaLocal endpointSelf-hosted
LM StudioLocal endpointSelf-hosted
LiteLLMLocal endpointProxy for any model

Self-Hosted Models

json
{
  "providers": {
    "ollama": {
      "type": "openai-compat",
      "base_url": "http://localhost:11434/v1",
      "api_key": "ollama",
      "models": [
        { "id": "llama3.1:8b", "name": "Llama 3.1 8B" },
        { "id": "codellama:7b", "name": "CodeLlama 7B" }
      ]
    }
  }
}

SectionPermissions System — Allow/Ask/Deny

The Permission Triad

Permission Triad + Hooks Pipeline

StateMeaningPractical example
ALLOWExecute without askinggit status * — safe
ASKAsk the user firstgrep * — could be risky
DENYCompletely blockedrm -rf / — dangerous

Permission Rules (last rule wins)

json
{
  "permissions": {
    "bash": {
      "rules": [
        { "pattern": "git status *", "decision": "allow" },
        { "pattern": "git diff *", "decision": "allow" },
        { "pattern": "grep *", "decision": "ask" },
        { "pattern": "*", "decision": "deny" }
      ]
    }
  }
}

YOLO Mode

bash
opencode--yolo# everything runs without permission prompts
                # dangerous — use only when fully confident

SectionHooks System — PreToolUse

Hook Config

json
{
  "hooks": {
    "PreToolUse": [
      {
        "name": "no-rm-rf",
        "matcher": "^bash$",
        "command": "./hooks/no-rm-rf.sh",
        "timeout": 10
      }
    ]
  }
}
FieldDescriptionWhen to use it
nameDescriptive name, optionalTo identify the hook
matcherRegex against tool name, optional^bash$ means bash only; omit for all tools
commandShell command, requiredPath to the script
timeoutSeconds, default 30If the hook may take time
Hook in Action
➜ ~ cat .opencode/pre-tool-use.sh
#!/bin/bash
block rm -rf
echo "$OPENCODE_TOOL_INPUT" | grep -q "rm -rf" && exit 1
exit 0
➜ ~ opencode -p "remove all temp files with rm -rf /"
✗ Hook blocked: dangerous rm command detected
➜ ~⏎ run · ⌫ clear

Exit Codes

CodeMeaningWhat happens
0Success; stdout is parsed as JSON envelopeCan allow, deny, or halt
2Block tool; stderr becomes the deny reasonTool call is blocked
49Halt turnThe agent turn stops completely

JSON Envelope

json
{
  "version": 1,
  "decision": "allow",
  "halt": false,
  "reason": "LGTM",
  "context": "Scrubbed secrets",
  "updated_input": { "command": "…" }
}

Practical Examples

1. Block rm -rf on root:

bash
#!/usr/bin/env bash
ifecho"$OPENCODE_TOOL_INPUT_COMMAND"|grep-qE'rm\s+-(rf|fr)\s+/';then
echo"Refusing to run rm -rf against root">&2
exit2
fi

2. Auto-approve read-only tools:

json
{ "matcher": "^(view|ls|grep|glob)$", "command": "echo '{\"decision\":\"allow\"}'" }

3. Inject context for Go files:

bash
#!/usr/bin/env bash
if[["$OPENCODE_TOOL_INPUT_FILE_PATH"==*.go]];then
echo'{"context": "Run gofumpt after editing."}'
else
echo'{}'
fi

4. Halt on drop database:

bash
#!/usr/bin/env bash
ifecho"$OPENCODE_TOOL_INPUT_COMMAND"|grep-qE'drop\s+database';then
echo"Database drop detected — halting turn">&2
exit49
fi

SectionSkills System — SKILL.md

yaml
name: my-skill
description: What this skill does  critical for LLM tool selection.
user-invocable: true
disable-model-invocation: true
# Skill Instructions
Detailed instructions for the skill...
FieldRuleWhy
name1-64 chars, lowercase onlyPrecise matching
description1-1024 charsThe LLM uses it to decide whether to invoke the skill
user-invocabletrue means visible in Ctrl+PUser can call it directly
disable-model-invocationtrue means user-only invocationPrevents autonomous execution

Discovery Paths

TypePath
Global~/.config/opencode/skills/
Global~/.agents/skills/
Global~/.claude/skills/
Project.agents/skills/
Project.opencode/skills/
Customoptions.skills_paths in config

SectionContext Files — What the Agent Reads

FileTypeNotes
AGENTS.mdUniversal standardUnderstood by many agents
OPENCODE.mdOpenCode-specificRead by OpenCode
CLAUDE.mdClaude Code-specificRead by Claude Code
GEMINI.mdGemini-specificRead by Gemini
.cursorrulesCursor-specificRead by Cursor
.github/copilot-instructions.mdCopilot-specificRead by GitHub Copilot

Rule: AGENTS.md is the universal standard — write it once and all compatible agents understand it.

SectionBuilt-in Tools — Full Reference

File & Code Tools

ToolWhat it doesWhen to use itWhy it matters
globFinds files by patternLooking for files of a typeFaster than find
grepSearches file contentsLooking for a string in codeRegex search
lsShows directory treeInspecting structureDepth control
viewReads a file with line numbersReading a fileSupports offset and limit
writeCreates or replaces a fileWriting a new fileOverwrites the full file
editFind-and-replace in a fileEditing a sectionRequires exact match
multieditMultiple edits in one fileEditing many placesSequential edits
diagnosticsShows LSP errors/warningsFinding bugsUses language server
referencesFinds symbol referencesUnderstanding usageGo-to-reference

Execution & Search Tools

ToolWhat it doesWhen to use itWhy it matters
bashRuns shell commandsTests and commandsSupports timeout and background jobs
fetchFetches URL contentOnline docs lookuptext/markdown/html formats
downloadDownloads a URL to a fileBinary downloadsBinary-safe streaming
web_searchWeb searchFinding internet infoUses max_results
web_fetchFetches URL as markdownSub-agentsNot for direct use
sourcegraphSearches repos for codeCross-repo implementation lookupCount and context window
agentRuns a sub-agentDeep search by main agentLimited to glob/grep/ls/view
agentic_fetchWeb research sub-agentComplex researchFollows links iteratively

Session & Info Tools

ToolWhat it does
opencode_infoShows runtime state: model, provider, LSP, MCP, skills, hooks
opencode_logsReads internal logs
lsp_restartRestarts the LSP client
job_outputGets background shell output
job_killKills a background process
todosManages structured task lists

SectionKeyboard Shortcuts — Must Know

ShortcutActionWhen to use it
Ctrl+X (Leader)Starts all leader shortcutsLeader key
Leader nNew sessionStarting fresh
Leader lList sessionsReturning to older work
Ctrl+PCommand paletteInvoke a skill or quick action
TabCycle Primary AgentsSwitch Build and Plan
Leader ↓/↑Navigate sessionsParent/child sessions
Ctrl+GScroll to topMove up in chat
Ctrl+Alt+GScroll to bottomMove to latest output
aAllow one tool callPermission dialog
AAllow for the sessionPermission dialog
dDenyPermission dialog

SectionMCP (Model Context Protocol)

TypeWhat it doesExample
stdioRuns as a local processfilesystem, databases
httpConnects to an HTTP endpointGitHub, external APIs
sseServer-Sent Eventsstreaming connections
json
{
  "mcp": {
    "github": {
      "type": "http",
      "url": "https://api.githubcopilot.com/mcp/",
      "headers": { "Authorization": "Bearer $GH_PAT" },
      "disabled_tools": ["create_issue"]
    },
    "filesystem": {
      "type": "stdio",
      "command": "npx",
      "args": ["-y", "@modelcontextprotocol/server-filesystem", "/path"],
      "timeout": 30
    }
  }
}

SectionCrash Recovery — Core Rules

  1. When the server crashes, agents become "ready" but do not restart.
  2. You must restart manually so API credits are not burned overnight.
  3. The compaction agent auto-summarizes at 95% of the context window.
  4. The title agent creates automatic session names.
  5. The summary agent keeps background overviews.

SectionTUI Themes

ThemeLook
opencodeDefault dark
catppuccinWarm pastel
draculaPurple-dark
flexokiInk-inspired
gruvboxRetro warm
monokaiClassic code editor
onedarkAtom-inspired
tokyonightBlue-dark
tronNeon cyan on black

SectionQuick Decision Guide

ScenarioStart here
First time using OpenCodeopencode → TUI opens
Automating somethingopencode -p "..." -f json
Blocking dangerous commandsAdd a hook in .opencode.json
Auto-approving read-only toolspermissions.allowed_tools or a hook
Giving the agent new capabilitiesWrite SKILL.md in .agents/skills/
Helping the agent understand your projectWrite AGENTS.md in the root
Connecting an MCP toolAdd it under mcp in .opencode.json
Adding LSPAdd it under lsp in .opencode.json
Working on another projectopencode -c /path/to/project
Multi-client workopencode serve
Testing a hookopencode_logs or check the exit code