Salta ai contenuti

OpenCode Cheat Sheet

Overview

OpenCode is an open-source, terminal-based AI coding agent designed for developers who prefer working in the terminal. It connects to various LLM providers (Anthropic, OpenAI, Google, local models) and provides an interactive TUI (terminal user interface) for having conversations about your codebase, generating code, running commands, editing files, and debugging issues without leaving your terminal.

OpenCode reads your project context, understands file structures, and can perform multi-step coding tasks autonomously. It supports tool use for file operations, shell commands, and web searches. The agent runs locally, keeps your code on your machine, and integrates with your existing terminal workflow. It is built with Go for fast startup and low resource usage.

Installation

# Install via Go
go install github.com/opencode-ai/opencode@latest

# Install via Homebrew
brew install opencode

# Install via npm
npm install -g opencode

# Install via curl (Linux/macOS)
curl -fsSL https://opencode.ai/install.sh | bash

# Verify installation
opencode --version

Configuration Setup

# Initialize configuration in current project
opencode init

# Or create config manually
mkdir -p ~/.config/opencode
cat > ~/.config/opencode/config.toml << 'EOF'
[provider]
default = "anthropic"

[provider.anthropic]
api_key = "sk-ant-..."
model = "claude-sonnet-4-20250514"

[provider.openai]
api_key = "sk-..."
model = "gpt-4o"

[provider.local]
base_url = "http://localhost:11434/v1"
model = "deepseek-coder-v2"
EOF

Core Commands

CommandDescription
opencodeStart interactive TUI session
opencode initInitialize config in current directory
opencode chat "prompt"One-shot prompt without TUI
opencode --provider openaiUse a specific provider
opencode --model claude-sonnet-4-20250514Use a specific model
opencode --context file.pyInclude specific files as context
opencode --no-toolsDisable tool use (chat only)
opencode --verboseShow debug output
opencode configOpen configuration
opencode providersList configured providers

Interactive TUI

# Start the TUI
opencode

# TUI Layout:
┌─────────────────────────────────────┐
│ Chat History                         │
│                                      │
│ User: Fix the bug in auth.py         │
│                                      │
│ Agent: I'll look at auth.py and...   │
│ [Reading file: src/auth.py]          │
│ [Editing file: src/auth.py]          │
│                                      │
├─────────────────────────────────────┤
│ > Type your message...               │
└─────────────────────────────────────┘

TUI Keybindings

KeyAction
EnterSend message
Shift+EnterNew line in input
Ctrl+CCancel current operation
Ctrl+DExit
Ctrl+LClear screen
Ctrl+RRetry last message
TabAutocomplete file paths
Up/DownScroll through history
Ctrl+OOpen file picker
/helpShow available commands
/clearClear conversation
/modelSwitch model
/contextManage context files
/toolsToggle tools on/off
/costShow session cost

Tool Capabilities

Available Tools

ToolDescription
read_fileRead contents of a file
write_fileCreate or overwrite a file
edit_fileMake targeted edits to a file
list_directoryList files in a directory
search_filesSearch for text patterns in files
run_commandExecute shell commands
web_searchSearch the web for information
web_fetchFetch content from a URL

Example Prompts

# Code generation
> Create a REST API in Python with Flask that has CRUD endpoints for a blog

# Debugging
> I'm getting a TypeError on line 42 of server.js. Help me fix it.

# Refactoring
> Refactor the database module to use connection pooling and add proper error handling

# Testing
> Write comprehensive unit tests for src/utils/validation.ts using Vitest

# Understanding
> Explain the architecture of this project and how the authentication flow works

# Shell operations
> Find all TODO comments in the codebase and list them with file names

# Multi-step tasks
> Set up a CI/CD pipeline with GitHub Actions that runs tests, lints, and deploys to Render

Configuration

Project Configuration (.opencode.toml)

# .opencode.toml — project-level configuration

[project]
name = "my-app"
description = "A Node.js web application"
language = "typescript"

[context]
# Files and directories to always include as context
include = [
  "src/",
  "package.json",
  "tsconfig.json",
]
# Files to never include
exclude = [
  "node_modules/",
  "dist/",
  ".env",
  "*.lock",
]
max_file_size = "100KB"

[tools]
# Enable or disable specific tools
read_file = true
write_file = true
edit_file = true
run_command = true
web_search = true

[tools.run_command]
# Allowed and blocked commands
allowed_patterns = ["npm *", "node *", "git *", "pytest *"]
blocked_patterns = ["rm -rf /", "sudo *"]
timeout = 30

[provider]
default = "anthropic"
model = "claude-sonnet-4-20250514"
max_tokens = 8192
temperature = 0.1

Global Configuration

# ~/.config/opencode/config.toml

[general]
theme = "dark"        # dark, light, auto
editor = "vim"        # External editor for large edits
pager = "less"        # Pager for long outputs
auto_approve = false  # Auto-approve file changes
show_cost = true      # Show token costs

[provider.anthropic]
api_key = "sk-ant-..."
model = "claude-sonnet-4-20250514"
max_tokens = 8192

[provider.openai]
api_key = "sk-..."
model = "gpt-4o"
max_tokens = 4096

[provider.google]
api_key = "..."
model = "gemini-2.0-flash"

[provider.ollama]
base_url = "http://localhost:11434/v1"
model = "codestral"
api_key = "ollama"

[keybindings]
send = "enter"
newline = "shift+enter"
cancel = "ctrl+c"
exit = "ctrl+d"
clear = "ctrl+l"

Advanced Usage

One-Shot Mode

# Execute a single prompt and get output
opencode chat "Explain what this function does" --context src/parser.py

# Pipe content as context
cat error.log | opencode chat "What is causing this error?"

# Generate code to stdout
opencode chat "Write a Python function to parse CSV with type inference" --no-tui

# Chain with other commands
opencode chat "Generate a .gitignore for a Node.js project" --no-tui > .gitignore

Context Management

# Add files to context during session
/context add src/models/*.py
/context add README.md

# Remove files from context
/context remove README.md

# List current context
/context list

# Clear context
/context clear

# Add directory tree as context
/context add-tree src/

Custom System Prompts

# .opencode.toml
[system_prompt]
content = """
You are a senior TypeScript developer working on a Next.js 14 application.
Follow these conventions:
- Use server components by default
- Prefer Zod for validation
- Use Drizzle ORM for database queries
- Write tests with Vitest
- Follow the existing code style in the project
"""

Session Management

# Save a session
/save my-refactoring-session

# Load a previous session
opencode --session my-refactoring-session

# List saved sessions
opencode sessions list

# Delete a session
opencode sessions delete my-refactoring-session

# Export session as markdown
opencode sessions export my-session > session.md

Git Integration

# OpenCode can work with git context:
> Review the changes in my last commit and suggest improvements
> Generate a commit message for the staged changes
> What files changed between main and this branch?
> Create a PR description summarizing all changes on this branch

Troubleshooting

IssueSolution
API key not foundSet in config file or environment variable: ANTHROPIC_API_KEY, OPENAI_API_KEY
Model not availableCheck provider supports the model; verify API plan includes model access
File edits not applyingApprove changes when prompted; check file permissions
Context too largeExclude large directories in .opencode.toml; use specific file references
TUI rendering issuesTry a different terminal emulator; check terminal supports 256 colors
Command execution blockedAdd command pattern to allowed_patterns in config
Slow responsesSwitch to a faster model; reduce context size; check internet connection
Local model errorsVerify Ollama/LM Studio is running; check base_url in config
High token costsUse smaller models for simple tasks; monitor with /cost command