How to Install and Use OpenCode: A Complete Guide
How to Install and Use OpenCode: A Complete Guide
OpenCode is an open-source AI coding agent that brings the power of artificial intelligence directly to your terminal. Unlike traditional AI coding tools that live in editors or browsers, OpenCode provides a terminal-based interface, desktop app, and IDE extension—all designed to make you more productive as a developer. This comprehensive guide will walk you through everything you need to know to install, configure, and use OpenCode effectively.
What is OpenCode?
OpenCode is an AI-powered coding assistant that helps you:
- Write code faster with intelligent code generation and completion
- Debug efficiently by analyzing errors and suggesting fixes
- Understand codebases through natural language queries
- Add features with automated planning and implementation
- Review code with AI-powered analysis and suggestions
- Automate workflows using AI agents and custom tools
It supports multiple LLM providers including Anthropic, OpenAI, Google, and others, giving you the flexibility to choose the models that work best for your needs.
System Requirements
Prerequisites
Before installing OpenCode, ensure you have:
Modern Terminal Emulator (for TUI usage):
Node.js (for npm/bun/pnpm/yarn installation):
- Node.js v18 or higher recommended
API Keys for LLM providers:
- Anthropic API key (for Claude models)
- OpenAI API key (for GPT models)
- Or keys from other supported providers
Installation Methods
Method 1: Install Script (Recommended)
The quickest way to install OpenCode is using the official install script:
curl -fsSL https://opencode.ai/install | bashThis method works on macOS, Linux, and Windows (with Git Bash or WSL).
Method 2: Using Node.js Package Managers
Using npm:
npm install -g opencode-aiUsing Bun:
bun install -g opencode-aiUsing pnpm:
pnpm install -g opencode-aiUsing Yarn:
yarn global add opencode-aiMethod 3: Using Homebrew (macOS & Linux)
brew install opencodeMethod 4: Using Paru (Arch Linux)
paru -S opencode-binMethod 5: Windows-Specific Installations
Using Chocolatey:
choco install opencodeUsing Scoop:
scoop bucket add extras
scoop install extras/opencodeUsing Mise:
mise use -g github:sst/opencodeMethod 6: Docker
For containerized usage:
docker run -it --rm ghcr.io/sst/opencodeMethod 7: Download Binary
You can download the pre-compiled binary directly from the GitHub Releases page.
Verify Installation
After installation, verify it's working:
opencode --versionYou should see the version number displayed.
Initial Configuration
Connecting to OpenCode Zen (Recommended for Beginners)
OpenCode Zen is a curated list of models tested and verified by the OpenCode team. It's the easiest way to get started.
- Start OpenCode:
cd /path/to/your/project
opencode- Run the connect command in the TUI:
/connectSelect "opencode" from the provider list
Visit the authentication URL: opencode.ai/auth
Sign in and add billing details (or use free credits if available)
Copy your API key and paste it into the terminal when prompted
Connecting to Other Providers
You can also connect OpenCode to other LLM providers:
Using the /connect Command:
/connectSelect your preferred provider (Anthropic, OpenAI, Google, etc.) and follow the authentication flow.
Using CLI Authentication:
opencode auth loginThis will guide you through configuring API keys for any provider available on Models.dev.
List Configured Providers:
opencode auth listor the short version:
opencode auth lsLogout from a Provider:
opencode auth logoutSetting Up Project Context
After configuring a provider, initialize OpenCode for your project:
- Navigate to your project:
cd /path/to/your/project- Start OpenCode:
opencode- Run the init command:
/initThis analyzes your project structure and creates an AGENTS.md file in the project root. This file helps OpenCode understand your coding patterns, frameworks, and project architecture.
Tip: Commit the AGENTS.md file to Git. This helps maintain consistency across your team and improves OpenCode's understanding of your project over time.
Using the Terminal User Interface (TUI)
OpenCode's TUI provides an interactive experience in your terminal.
Starting the TUI
Simply run:
opencodeOr with optional flags:
# Continue the last session
opencode --continue
# Continue a specific session
opencode --session <session-id>
# Start with a prompt
opencode --prompt "Explain this codebase"
# Use a specific model
opencode --model anthropic/claude-sonnet-4-5
# Use a specific agent
opencode --agent planBasic TUI Navigation
- Scroll: Use mouse wheel or arrow keys
- Switch modes: Press
Tabto toggle between Plan mode and Build mode - Run commands: Type
/to access command palette - Search files: Use
@to fuzzy search for files in your project - Exit: Press
Ctrl+Cor use/exit
Asking Questions
You can ask OpenCode questions about your codebase:
How is authentication handled in @packages/functions/src/api/index.tsUse the @ symbol to reference specific files. OpenCode will analyze those files and provide detailed explanations.
Adding Features
OpenCode excels at adding new features through its two-mode workflow:
Step 1: Plan Mode
- Switch to Plan mode by pressing
Tab - Describe what you want:
When a user deletes a note, we'd like to flag it as deleted in the database.
Then create a screen that shows all the recently deleted notes.
From this screen, the user can undelete a note or permanently delete it.- Review the suggested plan
- Iterate with feedback:
We'd like to design this new screen using a design I've used before.
[Image #1] Take a look at this image and use it as a reference.Tip: You can drag and drop images into the terminal. OpenCode will scan and analyze them.
Step 2: Build Mode
- Switch to Build mode by pressing
Tabagain - Approve the implementation:
Sounds good! Go ahead and make the changes.OpenCode will then implement the feature, creating and modifying files as needed.
Making Direct Changes
For straightforward changes, you can skip the plan phase:
We need to add authentication to the /settings route.
Take a look at how this is handled in the /notes route
in @packages/functions/src/notes.ts and implement the same logic
in @packages/functions/src/settings.tsUndoing and Redoing Changes
Made a mistake? Use the undo command:
/undoThis reverts the last set of changes and lets you refine your prompt.
To redo undone changes:
/redoYou can run /undo multiple times to revert multiple changes.
CLI Commands
OpenCode provides a powerful CLI for programmatic access and automation.
Running Direct Prompts
Execute OpenCode non-interactively:
opencode run "Explain how closures work in JavaScript"Useful for scripting, automation, or quick answers without launching the TUI.
Managing Models
List all available models:
opencode modelsFilter by provider:
opencode models anthropicRefresh the model cache (useful when new models are added):
opencode models --refreshShow verbose model information including costs:
opencode models --verboseStarting a Headless Server
Start an HTTP server for API access:
opencode serveWith custom port:
opencode serve --port 3000This is useful for integrating OpenCode into web applications or for faster response times in scripts (avoiding MCP server cold boot).
Attaching to a Server
In one terminal, start the server:
opencode serveIn another terminal, attach to it for faster execution:
opencode run --attach http://localhost:4096 "Explain async/await in JavaScript"Managing Agents
Create a new custom agent:
opencode agent createThis guides you through creating an agent with custom system prompts and tool configurations.
GitHub Integration
Install the GitHub agent for repository automation:
opencode github installThis sets up GitHub Actions workflows for automated code review and issue handling.
Upgrading OpenCode
Upgrade to the latest version:
opencode upgradeOr to a specific version:
opencode upgrade v0.1.48Specify the installation method if needed:
opencode upgrade --method brewConfiguration
OpenCode supports flexible configuration through JSON config files.
Configuration Locations
Config files are merged together (not replaced), allowing you to have global, project-specific, and custom configs.
Global Config:
~/.config/opencode/opencode.json- Use for themes, providers, keybinds, and general settings
Project Config:
opencode.jsonin project root- Use for project-specific providers, agents, or settings
- Safe to commit to Git
Custom Config Path: Set via
OPENCODE_CONFIGenvironment variableCustom Config Directory: Set via
OPENCODE_CONFIG_DIRenvironment variable
Basic Configuration Example
Create a config file with this structure:
{
"$schema": "https://opencode.ai/config.json",
// Theme selection
"theme": "opencode",
// Main model to use
"model": "anthropic/claude-sonnet-4-5",
// Smaller model for lightweight tasks
"small_model": "anthropic/claude-haiku-4-5",
// Auto-update settings
"autoupdate": true
}Configuring Providers
Configure API keys directly in config:
{
"$schema": "https://opencode.ai/config.json",
"provider": {
"anthropic": {
"options": {
"apiKey": "{env:ANTHROPIC_API_KEY}"
}
},
"openai": {
"options": {
"apiKey": "{env:OPENAI_API_KEY}"
}
}
}
}Using environment variables is recommended for security. Use {env:VARIABLE_NAME} syntax.
Using File References
You can also reference files for sensitive data:
{
"$schema": "https://opencode.ai/config.json",
"provider": {
"openai": {
"options": {
"apiKey": "{file:~/.secrets/openai-key}"
}
}
}
}Custom Commands
Define custom commands for repetitive tasks:
{
"$schema": "https://opencode.ai/config.json",
"command": {
"test": {
"template": "Run full test suite with coverage report and show any failures.\nFocus on failing tests and suggest fixes.",
"description": "Run tests with coverage",
"agent": "build",
"model": "anthropic/claude-haiku-4-5"
},
"component": {
"template": "Create a new React component named $ARGUMENTS with TypeScript support.\nInclude proper typing and basic structure.",
"description": "Create a new component"
}
}
}Use custom commands in TUI by typing /test or /component MyComponent.
Custom Agents
Create specialized agents:
{
"$schema": "https://opencode.ai/config.json",
"agent": {
"code-reviewer": {
"description": "Reviews code for best practices and potential issues",
"model": "anthropic/claude-sonnet-4-5",
"prompt": "You are a code reviewer. Focus on security, performance, and maintainability.",
"tools": {
"write": false,
"edit": false
}
}
}
}Permissions Configuration
Control what OpenCode can do without asking:
{
"$schema": "https://opencode.ai/config.json",
"permission": {
"edit": "ask",
"bash": "ask"
}
}This requires user approval for edit and bash operations.
Code Formatters
Configure formatters to automatically format code:
{
"$schema": "https://opencode.ai/config.json",
"formatter": {
"prettier": {
"disabled": false
},
"custom-prettier": {
"command": ["npx", "prettier", "--write", "$FILE"],
"environment": {
"NODE_ENV": "development"
},
"extensions": [".js", ".ts", ".jsx", ".tsx"]
}
}
}TUI Settings
Customize the terminal interface:
{
"$schema": "https://opencode.ai/config.json",
"tui": {
"scroll_speed": 3,
"scroll_acceleration": {
"enabled": true
}
}
}Advanced Features
Sharing Conversations
Share your conversations with your team:
/shareThis creates a shareable link and copies it to your clipboard. Conversations are not shared by default.
Configure sharing behavior:
{
"share": "manual" // "manual", "auto", or "disabled"
}MCP Servers
Model Context Protocol (MCP) servers extend OpenCode's capabilities:
{
"$schema": "https://opencode.ai/config.json",
"mcp": {
"filesystem": {
"command": "npx",
"args": ["-y", "@modelcontextprotocol/server-filesystem", "/path/to/allowed/files"]
}
}
}Instructions and Rules
Provide project-specific instructions:
{
"$schema": "https://opencode.ai/config.json",
"instructions": [
"CONTRIBUTING.md",
"docs/guidelines.md",
".cursor/rules/*.md"
]
}OpenCode will use these files to understand your project's coding standards and conventions.
Environment Variables
Configure OpenCode using environment variables:
# Automatically share sessions
export OPENCODE_AUTO_SHARE=true
# Path to custom config
export OPENCODE_CONFIG=/path/to/config.json
# Path to config directory
export OPENCODE_CONFIG_DIR=/path/to/config-dir
# Disable auto-update
export OPENCODE_DISABLE_AUTOUPDATE=true
# Disable default plugins
export OPENCODE_DISABLE_DEFAULT_PLUGINS=true
# Enable experimental models
export OPENCODE_ENABLE_EXPERIMENTAL_MODELS=true
# Enable Exa web search
export OPENCODE_ENABLE_EXA=trueExperimental Features
Enable experimental features:
export OPENCODE_EXPERIMENTAL=trueSpecific experimental features:
# Enable icon discovery
export OPENCODE_EXPERIMENTAL_ICON_DISCOVERY=true
# Disable copy on select in TUI
export OPENCODE_EXPERIMENTAL_DISABLE_COPY_ON_SELECT=true
# Set max output length for bash commands
export OPENCODE_EXPERIMENTAL_BASH_MAX_OUTPUT_LENGTH=10000
# Set default timeout for bash commands (ms)
export OPENCODE_EXPERIMENTAL_BASH_DEFAULT_TIMEOUT_MS=30000Best Practices
Effective Prompting
- Be specific: Provide clear, detailed instructions
- Use context: Reference files with
@for better understanding - Provide examples: Show examples of what you want
- Break it down: Complex tasks work better in steps
Working with Large Projects
- Use
/init: Let OpenCode understand your project structure - Reference specific files: Use
@to limit context - Use Plan mode: Review plans before implementation
- Incremental changes: Make small, manageable changes
Cost Optimization
- Use smaller models: Configure
small_modelfor lightweight tasks - Plan before build: Review in Plan mode to reduce iterations
- Custom commands: Define efficient workflows for common tasks
- Monitor usage: Check provider dashboards for usage stats
Security Best Practices
- Never commit API keys: Use environment variables
- Use permissions: Configure
permissionto require approval for sensitive operations - Review changes: Always review OpenCode's suggested changes
- Use separate keys: Create API keys specifically for OpenCode with appropriate limits
Troubleshooting
Installation Issues
Problem: Command not found after installation
Solution:
- Verify installation:
which opencode - Check PATH:
echo $PATH - Try full path:
~/.local/bin/opencode - Reinstall using alternative method
Authentication Issues
Problem: API key not recognized
Solution:
- Verify key is correct:
opencode auth list - Check environment variables:
echo $ANTHROPIC_API_KEY - Re-authenticate:
opencode auth login
Performance Issues
Problem: Slow response times
Solution:
- Use
opencode servefor faster execution - Switch to a faster model
- Use smaller context windows
- Disable unused tools in config
TUI Issues
Problem: Terminal display issues
Solution:
- Use a modern terminal emulator (WezTerm, Alacritty, etc.)
- Check terminal supports 24-bit colors
- Try different theme
- Disable scroll acceleration if experiencing issues
Model Issues
Problem: Model not found
Solution:
- Refresh model list:
opencode models --refresh - Check provider is configured:
opencode auth list - Verify model name format:
provider/model - Check provider has the model available
Integrating OpenCode into Your Workflow
Daily Development
- Morning: Run
/initto sync with latest code changes - Feature work: Use Plan mode to design, then Build mode to implement
- Debugging: Ask questions about errors with file references
- Code review: Use custom code reviewer agent
- Documentation: Generate docs using custom commands
Team Collaboration
- Share configs: Commit
opencode.jsonandAGENTS.mdto Git - Share conversations: Use
/shareto discuss implementations - Custom commands: Define team-specific commands in project config
- Consistent agents: Use shared agent definitions for consistency
CI/CD Integration
- GitHub agent: Install for automated PR reviews
- Testing: Use custom test commands in CI
- Code quality: Configure formatters and permissions
Conclusion
OpenCode represents a new paradigm in AI-assisted development by bringing powerful AI capabilities directly to your terminal. With its flexible configuration options, support for multiple LLM providers, and intuitive TUI interface, it's designed to enhance your productivity without disrupting your existing workflow.
Key Takeaways:
- Install using the install script or your preferred package manager
- Configure API keys through
/connectoropencode auth login - Initialize projects with
/initfor better context understanding - Use Plan mode for complex features, Build mode for direct changes
- Customize with config files, commands, and agents
- Leverage CLI commands for automation and scripting
- Practice good security habits with API keys and permissions
Next Steps:
- Explore OpenCode documentation for advanced features
- Join the OpenCode Discord community
- Customize your setup with themes and keybinds
- Experiment with different LLM providers and models
- Integrate OpenCode into your team's workflow
Ready to supercharge your development workflow?
Check out LightNode's AI-optimized hosting solutions for deploying AI-powered applications with dedicated GPU instances and scalable infrastructure.
OpenCode is open source and constantly evolving. Contribute to the project, report issues, or share your experience to help make it even better for everyone. Happy coding!