Skip to content

OpenCode Cheat Sheet

This is the quick reference you can keep open while working through the course. It does not replace the lessons. It gives you the commands, file locations, and habits you will use most often.

Start Here

Open the Interactive TUI

opencode

Use this for normal course work. It opens the terminal interface where you can chat with agents, switch modes, run slash commands, and review tool activity.

Run a One-Off Non-Interactive Prompt

opencode -p "Explain what this repository does" -f json

Use this when you want scriptable output or a single response outside the interactive TUI.

Common CLI Flags

Flag Meaning Example
-p Prompt to run non-interactively opencode -p "Summarize this repo"
-f json Format non-interactive output as JSON opencode -p "List risks" -f json
-d Enable debug output opencode -d
-c Set working directory opencode -c ./sample-repo
-q Quiet output opencode -q -p "Summarize"
-h Show help opencode -h
-v Show version opencode -v

Non-Interactive (Headless) Mode

Run OpenCode without the TUI for scripting, CI/CD, or quick one-off tasks:

# Run a prompt and exit
opencode -p "Summarize this repo"

# Output as JSON for programmatic use
opencode -p "List all API endpoints" -f json

# Quiet mode — minimal output
opencode -q -p "What port does this server use?"

Use cases: - CI/CD pipelines: opencode -p "Review this PR diff" -f json - IDE integration: call OpenCode from an editor command - Batch processing: iterate prompts in a shell script - Scheduled checks: cron jobs that audit code quality

The -f json flag makes output machine-parseable. Combine with jq for filtering:

opencode -p "Find security issues in src/" -f json | jq '.findings[]'

The Beginner Workflow

Use this loop for most tasks in the course:

  1. Check where you are: pwd
  2. Check git state: git status
  3. Start OpenCode: opencode
  4. Use plan mode for investigation.
  5. Ask for a short plan with file references.
  6. Switch to build mode only when you want edits.
  7. Review the diff before accepting the result.
  8. Run tests or verification commands.
  9. Commit only when you understand the change.

Plan Mode vs. Build Mode

Use Best Mode Why
Understand a new repo plan Reading is safer than editing.
Investigate a bug plan first Find the likely cause before changing code.
Code review plan Reviews should not modify files.
Security audit plan Keep the agent read-only unless explicitly fixing.
Implement a known change build You are ready for edits.
Write tests build The agent needs to create or edit files.
Refactor code plan, then build Agree on scope before changing behavior.

Built-in Tools

OpenCode agents use these tools. You control access in agent permissions.

Tool What It Does
bash Execute shell commands
read View file contents
write Create and overwrite files
edit Make targeted edits to files
patch Apply diffs to files
glob Find files by name pattern
grep Search file contents for patterns
ls List directory contents
fetch Fetch content from URLs
sourcegraph Search code across public repositories
diagnostics Retrieve LSP diagnostics for files
agent Run sub-tasks with a subagent
webfetch Fetch web pages (permission name)
websearch Search the internet
task Create and manage task lists
todowrite Write todo files directly
lsp Language server protocol integration
skill Discover and load skill files

Most tools are self-explanatory. The ones to note: - fetch: The agent can get web content, like docs or API responses. - sourcegraph: Search across public GitHub repos. - diagnostics: Check for compiler/linter errors in files. - patch: Apply a structured diff instead of rewriting the whole file.

Course habit: when in doubt, start in plan mode.

Useful First Prompts

Understand a Repository

Inspect this repository in plan mode. Explain its purpose, main directories, setup commands, and likely test command. Do not edit files.

Investigate a Bug

Investigate why the failing behavior happens. Start read-only. Give me the likely root cause, the files involved, and a 5-step fix plan before editing anything.

Make a Small Change

Make the smallest safe change to fix this issue. Preserve existing style. After editing, summarize the diff and tell me how to verify it.

Review a Diff

Review the current git diff for bugs, regressions, missing tests, and unclear naming. Findings first, ordered by severity. Do not edit files.

Explain an Error

Explain this error for a beginner. Identify the immediate cause, the deeper cause, and the next command or file I should inspect.

Slash Commands

Slash commands are reusable prompt shortcuts.

Example use in the TUI:

/review-diff

With arguments:

/explain-file src/auth.ts

Where Commands Live

Commands can be defined either inline in opencode.jsonc or as individual files in .opencode/commands/. Both mechanisms are valid.

Project commands:

<PROJECT>/.opencode/commands/

User commands:

~/.config/opencode/commands/
~/.opencode/commands/

Use project commands for team workflows that should be checked into the repo. Use user commands for personal shortcuts you want across projects.

When to Create a Command

Use the Rule of Three: if you type the same prompt three times, turn it into a command.

Good command candidates:

  • Review the current diff.
  • Explain one file for a beginner.
  • Generate a changelog entry.
  • Run tests and summarize failures.
  • Draft release notes.

Skills

A skill is reusable knowledge the agent can load on demand.

Use a skill when the agent needs specialized instructions, checklists, examples, or domain knowledge.

Commands are for workflows you invoke. Skills are knowledge the agent discovers.

Good skill candidates:

  • Team code review checklist
  • Release notes style guide
  • Security review rubric
  • Course writing style guide
  • Framework-specific migration notes

Agents

An agent is a role with instructions, tools, permissions, and often a model choice.

Common course agents:

Agent Purpose Typical Access
plan Explore, inspect, explain Read-only
build Edit and implement File edits and commands
code-reviewer Review changes Read-only
security-checker Find security risks Read-only
test-impact Run tests and report impact Shell allowed, edits usually denied

When to Create a Custom Agent

Create a custom agent when you need a repeatable role with different permissions, tone, tools, or model choice.

Examples:

  • A docs agent that only edits Markdown.
  • A security agent that cannot write files.
  • A test runner that can use shell but cannot edit source code.

Configuration Areas

OpenCode config can include these areas:

Area What It Controls
providers Which model providers OpenCode can use (Anthropic, OpenAI, Groq, OpenRouter, Copilot).
agents Custom agent definitions — model, prompt, permissions, mode. Includes reasoningEffort.
shell Shell command execution — path and arguments.
mcpServers External MCP tools — local (stdio) or remote (SSE).
lsp Language server integration per language.
plugins OpenCode plugins that extend its behavior.
debug Debugging behavior and verbosity.
debugLSP Debug output for LSP interactions.
autoCompact Conversation/context compaction behavior.

You do not need to master all of these at once. The course introduces them gradually.

Provider Configuration

OpenCode supports multiple providers. Configure them in opencode.jsonc:

{
  "providers": {
    "anthropic": {
      "apiKey": "sk-ant-...",
      "disabled": false
    },
    "openai": {
      "apiKey": "sk-...",
      "disabled": false
    },
    "groq": {
      "apiKey": "gsk-...",
      "disabled": false
    },
    "openrouter": {
      "apiKey": "sk-or-...",
      "disabled": false
    },
    "copilot": {
      "disabled": false
    }
  }
}
  • Anthropic: Best for coding. Fast, reliable, good instruction-following.
  • OpenAI: Widely used. GPT-4o is powerful but more expensive.
  • Groq: Very fast inference, great for lightweight or iterative tasks.
  • OpenRouter: One API key for many models. Route to whichever model suits the task.
  • Copilot: Uses your GitHub Copilot subscription. No extra billing.

You can switch providers per agent. A heavy orchestrator might use Claude while a fast test-runner uses Groq.

Shell Configuration

Control which shell OpenCode uses for bash tool execution:

{
  "shell": {
    "path": "/bin/zsh",
    "args": ["-l"]
  }
}
  • path: The shell binary (bash, zsh, fish, etc.)
  • args: Arguments passed to the shell on startup (-l for login shell)

Set this if your shell has custom PATH or aliases OpenCode needs.

Reasoning Effort

Control how much "thinking" the model does before responding:

{
  "agents": {
    "coder": {
      "model": "anthropic/claude-sonnet-4",
      "maxTokens": 5000,
      "reasoningEffort": "high"
    },
    "task": {
      "model": "anthropic/claude-sonnet-4",
      "maxTokens": 3000,
      "reasoningEffort": "medium"
    }
  }
}

Values: low, medium, high.

  • Low: Fast, cheap. Good for simple mechanical tasks (formatting, boilerplate).
  • Medium: Balanced. Good default for most coding work.
  • High: More thorough. Use for security audits, complex refactors, or ambiguous requirements.

Higher effort costs more tokens and takes longer. Use the lowest setting that gets the job done.

Context Window & Auto-Compact

Every conversation has a limited context window. Once it fills, older messages get summarized or dropped.

OpenCode's autoCompact setting controls this:

{
  "autoCompact": true
}

When autoCompact is on (default), OpenCode automatically summarizes older conversation turns to free space. The agent keeps working but loses granular access to early messages.

When to disable autoCompact: During long investigations where the full history matters — security audits, multi-file refactors, debugging sessions.

When to enable autoCompact: General work. It prevents "forgetting" by keeping only what's recent and summarized.

You can also manually compact by restarting the conversation or starting fresh in a new project.

SSE MCP Servers (Remote)

Besides local (stdio) MCP servers, OpenCode connects to remote MCP servers over SSE (Server-Sent Events):

{
  "mcpServers": {
    "api-gateway": {
      "type": "sse",
      "url": "https://api.example.com/mcp",
      "headers": {
        "Authorization": "Bearer <token>"
      },
      "timeout": 30000
    }
  }
}

Use SSE when: - The MCP server runs on a different machine or in a container - You want a shared team MCP server (one instance, many users) - The server needs to maintain state across connections

Security note: SSE servers receive your config headers. Never hardcode tokens in shared config files. Use environment variables.

AGENTS.md Checklist

Use AGENTS.md to tell agents how to work in a repo.

Include:

  • What the project is.
  • How to install dependencies.
  • How to run tests.
  • How to lint or format.
  • Which directories are off-limits.
  • Which commands are safe.
  • Style and naming conventions.
  • Security warnings, such as never printing secrets.

Beginner example:

# Agent Instructions

This is a small Node.js todo app.

Use `npm test` to run tests.
Use `npm run lint` before final changes.
Do not edit files in `dist/`.
Do not commit `.env` or any credentials.
Prefer small changes and explain verification steps.

Safety Checklist Before Edits

Ask yourself:

  • Am I in the right directory?
  • Is the git working tree already dirty?
  • Do I understand what files the agent plans to edit?
  • Is this a plan-mode task or build-mode task?
  • Are secrets, credentials, or production data involved?
  • Do I have a way to verify the result?

Safety Checklist After Edits

Before you accept or commit:

  • Read the diff.
  • Check that unrelated files were not changed.
  • Run the relevant test or verification command.
  • Ask the agent to explain any change you do not understand.
  • Confirm no secrets or generated junk files were added.

Useful Git Commands While Using OpenCode

Check current changes:

git status

View unstaged changes:

git diff

View staged changes:

git diff --staged

Create a commit:

git add path/to/file
git commit -m "Describe the change"

Do not commit because the agent says so. Commit when you understand and accept the change.

Troubleshooting

The Agent Is Editing Too Much

Stop and narrow the task:

Pause. Do not edit more files. Summarize exactly what changed so far and propose the smallest remaining fix.

The Agent Seems Confused

Reset the context:

Ignore previous assumptions. Re-read the relevant files and list only facts supported by file contents or command output.

The Agent Invents a Command

Ask it to verify:

Before using that command, verify it exists in this repo's package scripts, README, Makefile, or documented setup instructions.

The Task Feels Risky

Move back to plan mode:

Switch to read-only investigation. Do not edit files. Give me risks, options, and your recommended path.

Course Mantra

Use agents for leverage, not autopilot.

The strongest OpenCode users are not the people who delegate everything. They are the people who give clear context, set safe boundaries, verify results, and know when to stay in plan mode.