OpenCode Cheat Sheet: CLI Commands, Shortcuts & Config

Find OpenCode CLI commands, TUI slash commands, shortcuts, sessions, configuration, permissions, agents, MCP servers, Skills, automation, and troubleshooting.

OpenCode is an open-source AI coding agent with a terminal interface, desktop app, and editor extensions.

This cheat sheet covers the CLI commands, TUI slash commands, keyboard shortcuts, configuration options, agents, permissions, MCP servers, Skills, and automation workflows you’ll most likely look up while using OpenCode.

Last updated: September 14, 2026.

OpenCode quick reference

Input syntax

SyntaxAction
Plain textSend a prompt to the current agent.
/commandRun a built-in or custom TUI command.
@path/to/fileFind a project file and include its contents in the prompt.
@alias/pathBrowse a configured reference root.
!commandRun a shell command and attach its output to the conversation.
@agentInvoke a subagent by name.
Tab / Shift+TabCycle primary agents.
ctrl+xStart the default leader-key sequence.

Common tasks

Command or shortcutAction
opencodeStart OpenCode.
opencode /path/to/projectOpen another project.
opencode --continueContinue the latest session.
/connectConnect a provider.
/modelsPick a model.
/initCreate or update AGENTS.md.
/new or ctrl+x nStart a new session.
/sessions or ctrl+x lResume a session.
/compact or ctrl+x cCompact context.
/undo or ctrl+x uUndo the latest turn.
/redo or ctrl+x rRedo an undone turn.
opencode run "Your prompt"Run one prompt from the shell.
opencode run -f file.ts "Review this file"Attach a file to a shell run.
opencode modelsList models.
opencode mcp listList MCP servers.
opencode debug configInspect merged config.
opencode statsShow usage and cost stats.
opencode upgradeUpdate OpenCode.

OpenCode CLI commands

Start the TUI

Syntax or flagPurpose
opencode [project]Start the TUI in the current directory or a project path.
--continue, -cContinue the latest session.
--session, -sContinue a specific session ID.
--forkFork a continued session.
--promptStart with a prompt.
--model, -mSelect a provider/model ID.
--agentSelect a primary agent.
--autoApprove requests that are not explicitly denied.
opencode --continue
opencode --session ses_123 --fork
opencode --model anthropic/claude-sonnet-4-5 --agent plan
opencode --auto

Authentication

CommandPurpose
opencode auth loginAdd credentials for a provider.
opencode auth listList authenticated providers.
opencode auth logoutRemove provider credentials.
opencode auth login --provider <id>Select a provider for login.

Models

Model IDs use the provider/model-id format.

CommandPurpose
opencode modelsList models from configured providers.
opencode models <provider>List models from one provider.
opencode models --refreshRefresh the cached model list.
opencode models --verboseInclude model metadata.

Run a prompt from the shell

opencode run executes a prompt without opening the TUI.

Command or flagPurpose
opencode run [message...]Send a non-interactive prompt.
--continue, -cContinue the latest session.
--session, -sContinue a selected session.
--forkFork a continued session.
--model, -mSelect a model.
--agentSelect an agent.
--file, -fAttach one or more files.
--format jsonEmit JSON events for scripts or CI.
--commandRun a custom command.
--titleSet the session title.
--autoAuto-approve requests that are not denied.
opencode run "Explain the authentication flow"
opencode run -f src/auth.ts "Review this file for security issues"
opencode run --format json "List the failing tests"
opencode run --agent plan "Review the changed files"

Sessions

CommandPurpose
opencode session listList saved sessions.
opencode session list -n 10Show the newest 10 sessions.
opencode session list --format jsonReturn session data as JSON.
opencode session delete <sessionID>Delete a session.

MCP

CommandPurpose
opencode mcp addAdd an MCP server through the wizard.
opencode mcp listList MCP servers and connection status.
opencode mcp auth <name>Start OAuth for a server.
opencode mcp auth listList MCP authentication status.
opencode mcp logout <name>Remove stored OAuth credentials.
opencode mcp debug <name>Test connectivity and OAuth discovery.

Agents

opencode agent create opens the agent wizard. opencode agent list shows the available agents.

opencode agent create
opencode agent list

Other useful CLI commands

CommandPurpose
opencode statsShow token usage and cost statistics.
opencode export [sessionID]Export a session as JSON.
opencode export --sanitize [sessionID]Export with sensitive transcript and file data redacted.
opencode import <file-or-url>Import a session.
opencode debug configShow the resolved configuration.
opencode pr <number>Check out a GitHub pull request and start OpenCode.
opencode upgradeUpdate OpenCode.
opencode --helpShow CLI help.
opencode <command> --helpShow help for one command.

TUI slash commands

Type / in the prompt to open command autocomplete.

CommandAlias or shortcutAction
/connectNoneAdd a provider and API key.
/compact/summarize, ctrl+x cCompact the current session.
/detailsNoneToggle tool execution details.
/editorctrl+x eCompose the current message in $EDITOR.
/exit/quit, /q, ctrl+x qExit OpenCode.
/exportctrl+x xExport the conversation to Markdown and open it.
/helpNoneOpen the help dialog.
/initNoneCreate or update AGENTS.md.
/modelsctrl+x mOpen the model picker.
/new/clear, ctrl+x nStart a new session.
/redoctrl+x rRedo an undone message and its file changes.
/sessions/resume, /continue, ctrl+x lList and switch sessions.
/shareNoneShare the current session.
/themesctrl+x tChoose a theme.
/thinkingNoneShow or hide thinking blocks.
/undoctrl+x uRemove the latest user message, responses, and file changes.
/unshareNoneRemove the current session share.

Essential keyboard shortcuts

The default leader key is ctrl+x. Press the leader first, then the second key.

ShortcutAction
ctrl+pOpen the command list.
<leader>nStart a new session.
<leader>lOpen the session list.
<leader>cCompact the current session.
<leader>uUndo the latest turn.
<leader>rRedo an undone turn.
<leader>xExport the session.
<leader>eOpen the external editor.
<leader>mOpen the model list.
<leader>aOpen the agent list.
TabCycle primary agents.
Shift+TabCycle primary agents backward.
ctrl+tCycle the model variant.
F2Cycle recent models.
EscapeInterrupt the current session.
<leader>yCopy the selected message.
ctrl+c, ctrl+d, or <leader>qExit OpenCode.
ReturnSubmit the prompt.
Shift+Return, Ctrl+Return, Alt+Return, or Ctrl+JInsert a new line.

Install and update

CommandMethod
curl -fsSL https://opencode.ai/installbash
npm install -g opencode-ainpm
bun install -g opencode-aiBun
pnpm install -g opencode-aipnpm
brew install anomalyco/tap/opencodeHomebrew tap
scoop install opencodeScoop on Windows
choco install opencodeChocolatey on Windows
docker run -it --rm ghcr.io/anomalyco/opencodeDocker
opencode --version
opencode upgrade
opencode upgrade --method npm

Sessions, files, and context

Session lifecycle

TUI commandCLI commandAction
/newopencodeStart a new session.
/sessionsopencode --continueContinue the latest session.
/sessionsopencode --session <id>Continue a known session.
Session controlsopencode --session <id> --forkFork a session.
Session listopencode session listList sessions.
Session listopencode session delete <id>Delete a session.
/exportopencode export <id>Export a session.
Status viewopencode statsShow usage and cost statistics.

Files and attachments

Use @ to fuzzy-search project files from the TUI.

Explain the error handling in @src/api/index.ts
Compare @package.json with @docs/architecture.md

Attach files to a shell run with repeated --file flags:

opencode run --file src/api/index.ts --file tests/api.test.ts "Review this change"

Undo and redo

/undo removes the latest user message, responses, and associated file changes. /redo restores an undone turn. File rollback uses Git-backed snapshots, so the project must be a Git repository.

Configuration

OpenCode accepts JSON and JSONC. Project configuration normally lives in opencode.json. User-wide configuration lives at ~/.config/opencode/opencode.json. TUI appearance and keybind settings use tui.json.

{
  "$schema": "https://opencode.ai/config.json",
  "model": "anthropic/claude-sonnet-4-5",
  "autoupdate": true
}

Common config locations

LocationUse
~/.config/opencode/opencode.jsonUser-wide configuration.
opencode.jsonProject configuration.
.opencode/agents/Project agents.
.opencode/commands/Project custom commands.
.opencode/skills/Project Skills.
.opencode/plugins/Project plugins.
tui.jsonTUI settings and keybinds.

Common config keys

OptionPurpose
modelDefault provider/model-id.
small_modelLightweight model for small internal tasks.
agentAgent definitions.
default_agentDefault primary agent.
permissionApproval rules.
mcpMCP server definitions.
instructionsAdditional instruction files.
commandCustom commands.
shareSession sharing behavior.
snapshotFile snapshot behavior.
autoupdateUpdate behavior.
providerProvider options and model overrides.

Environment and file substitutions

Use {env:NAME} to load an environment variable and {file:path} to load file contents into config.

{
  "$schema": "https://opencode.ai/config.json",
  "model": "{env:OPENCODE_MODEL}",
  "instructions": ["{file:./instructions.md}"],
  "provider": {
    "openai": {
      "options": {
        "apiKey": "{env:OPENAI_API_KEY}"
      }
    }
  }
}

Models and providers

Use /models in the TUI or opencode models in the shell. Model names use the provider/model-id format.

opencode models
opencode models anthropic
opencode models --refresh
opencode --model openai/gpt-5
opencode run --model openai/gpt-5 "Review the error boundary"

Agents

OpenCode has primary agents for the main conversation and subagents for delegated work.

AgentModeRole
buildPrimaryDevelopment work with file and shell tools.
planPrimaryPlanning and analysis; file edits and shell commands require approval by default.
generalSubagentComplex research and multi-step work.
exploreSubagentFast read-only codebase exploration.
scoutSubagentExternal documentation and dependency research.

Cycle primary agents with Tab and Shift+Tab. Invoke a subagent with @name.

@explore Find every route that writes to the users table
@general Review the migration plan and list unresolved risks

Create a custom agent

Run the wizard:

opencode agent create

Project agents can also live in .opencode/agents/ as Markdown files:

---
description: Review code without edits
mode: subagent
model: anthropic/claude-sonnet-4-5
permission:
  edit: deny
  bash: ask
---
Inspect the code and report defects, edge cases, and missing tests.

Permissions

Permission rules use three values:

ValueBehavior
allowRun without an approval prompt.
askAsk before the action.
denyBlock the action.

Common permission keys include read, edit, bash, task, external_directory, webfetch, websearch, and skill.

{
  "$schema": "https://opencode.ai/config.json",
  "permission": {
    "bash": {
      "*": "ask",
      "git status *": "allow",
      "git push *": "deny"
    },
    "edit": {
      "*": "deny",
      "src/**": "allow"
    }
  }
}

Rules are evaluated in order, and the last matching rule wins. --auto approves actions that would otherwise ask for permission. Explicit deny rules continue to block the action.

Project instructions, custom commands, and Skills

Project instructions

AGENTS.md stores project instructions. Run /init to create or update it.

The instructions config can load additional files:

{
  "$schema": "https://opencode.ai/config.json",
  "instructions": [
    "CONTRIBUTING.md",
    "docs/guidelines.md",
    ".cursor/rules/*.md"
  ]
}

Custom commands

Store project commands in .opencode/commands/ and global commands in ~/.config/opencode/commands/. The filename becomes the slash command name.

---
description: Run tests and explain failures
agent: build
---
Run the test suite. Report each failure with its file, root cause, and a focused fix.

Run this file as /test.

Useful substitutions:

SyntaxResult
$ARGUMENTSAll text after the command name.
$1, $2, $3Positional arguments.
! followed by a backtick commandInsert shell output.
@path/to/fileInsert file contents.

Agent Skills

Project Skills live in .opencode/skills/<name>/SKILL.md. Global Skills live in ~/.config/opencode/skills/<name>/SKILL.md. OpenCode can also discover compatible Skills under .claude/skills/ and .agents/skills/.

---
name: git-release
description: Create consistent releases and changelogs
---
Draft release notes from merged pull requests and propose a version bump.

MCP servers

OpenCode can connect to local process MCP servers and remote HTTP MCP servers.

Manage MCP servers

opencode mcp add
opencode mcp list
opencode mcp auth my-server
opencode mcp logout my-server
opencode mcp debug my-server

Local MCP server

{
  "$schema": "https://opencode.ai/config.json",
  "mcp": {
    "local-tools": {
      "type": "local",
      "command": ["npx", "-y", "my-mcp-command"],
      "environment": {
        "MY_API_KEY": "{env:MY_API_KEY}"
      },
      "enabled": true
    }
  }
}

Remote MCP server

{
  "$schema": "https://opencode.ai/config.json",
  "mcp": {
    "remote-tools": {
      "type": "remote",
      "url": "https://mcp.example.com/mcp",
      "enabled": true,
      "headers": {
        "Authorization": "Bearer {env:MY_API_KEY}"
      }
    }
  }
}

Automation and remote use

One-off and CI runs

opencode run "Explain this repository"
opencode run --agent plan --format json "Review the changed files"
opencode run --file src/api.ts "Review this API change"

Persistent backend

Start a backend:

opencode serve --port 4096 --hostname 127.0.0.1

Send a run to it:

opencode run --attach http://127.0.0.1:4096 "Run the focused test suite"

Attach a TUI:

opencode attach http://127.0.0.1:4096

Set OPENCODE_SERVER_PASSWORD when the backend needs HTTP basic authentication.

Common environment variables

VariablePurpose
OPENCODE_CONFIGCustom config file path.
OPENCODE_TUI_CONFIGCustom TUI config file path.
OPENCODE_CONFIG_DIRCustom .opencode-style config directory.
OPENCODE_CONFIG_CONTENTInline JSON config.
OPENCODE_SERVER_PASSWORDServer basic-auth password.
OPENCODE_SERVER_USERNAMEServer basic-auth username.
OPENCODE_DISABLE_AUTOUPDATEDisable update checks.
OPENCODE_DISABLE_AUTOCOMPACTDisable automatic context compaction.
OPENCODE_GIT_BASH_PATHGit Bash executable on Windows.

Troubleshooting

opencode is not recognized

Open a new shell and run opencode --version. Check that the installation directory is on PATH.

Provider or model is missing

Run:

opencode auth list
opencode models --refresh

Check the exact provider/model-id spelling and review enabled_providers or disabled_providers if the provider is absent.

A TUI command fails in a shell

Slash commands run inside the TUI. Use their CLI equivalents from the shell. For example, use opencode models in place of /models and opencode session list in place of /sessions.

A permission prompt blocks a tool

Run:

opencode debug config

Check the global permission rule, agent-specific rules, and later matching patterns. The last matching rule wins.

Undo does not restore files

Confirm that the project is a Git repository and snapshots are enabled.

An MCP server is disconnected

Run:

opencode mcp list
opencode mcp debug <name>

Check the command or URL, environment variables, timeout, and authentication status.

The context becomes too large

Use /compact or ctrl+x c. Disable MCP servers that are not needed for the current task and avoid attaching large unrelated files.

FAQs

What is the difference between Build and Plan?

Build is the primary development agent. Plan focuses on analysis and planning, with file edits and shell commands requiring approval by default.

Does --auto override denied permissions?

No. --auto approves permission requests that would normally ask. Explicit deny rules continue to block the action.

What is the difference between a custom command and an Agent Skill?

A custom command creates a slash command for a repeatable prompt. An Agent Skill stores reusable instructions that an agent can load through the native Skill system.

What does /thinking do?

It shows or hides thinking blocks from models that provide them. It does not change the model’s reasoning capability. Use ctrl+t to cycle provider-specific model variants.

Official OpenCode resources

Related resources

Leave a Reply

Your email address will not be published. Required fields are marked *

Get the latest & top AI tools sent directly to your email.

Subscribe now to explore the latest & top AI tools and resources, all in one convenient newsletter. No spam, we promise!