OpenCode.ai CLI Cheatsheet

    Quick reference for OpenCode CLI commands and flags.

    Tob

    Tob

    Backend Developer

    5 min readTools

    OpenCode is an open-source AI coding agent that runs in your terminal. It supports multiple LLM providers, file editing, bash execution, and session management. Here's the commands you need to be productive.

    TL;DR: OpenCode CLI accelerates development with AI. Navigate to a project, run opencode, and start asking questions or making changes.

    Installation & Setup

    Install OpenCode via the official script or your preferred package manager.

    bash
    # Official install script
    curl -fsSL https://opencode.ai/install | bash
    
    # npm
    npm install -g opencode-ai
    
    # Homebrew (macOS/Linux)
    brew install anomalyco/tap/opencode
    
    # Arch Linux
    sudo pacman -S opencode
    
    # Windows (Chocolatey)
    choco install opencode

    After installation, authenticate with your preferred LLM provider.

    bash
    opencode auth login

    This stores credentials in ~/.local/share/opencode/auth.json. You can also use environment variables or a .env file in your project.

    Initialize OpenCode for a project by running /init inside the TUI. This creates an AGENTS.md file that helps OpenCode understand your codebase structure and coding patterns.

    Core Commands

    The opencode command starts the interactive TUI. Without arguments, it uses the current directory.

    bash
    opencode                                    # Start TUI in current directory
    opencode /path/to/project                   # Start TUI in specific directory
    opencode run "Explain closures in JavaScript"   # Non-interactive mode

    Agent Management

    bash
    opencode agent list                          # List all available agents
    opencode agent create                        # Create a custom agent

    Authentication

    bash
    opencode auth login                          # Login to a provider
    opencode auth list                           # List authenticated providers
    opencode auth logout                         # Logout from a provider

    Session Management

    bash
    opencode session list                        # List all sessions
    opencode session list -n 10                  # Limit to 10 most recent
    opencode export [sessionID]                  # Export session as JSON
    opencode import session.json                 # Import from local file
    opencode import https://opncd.ai/s/abc123    # Import from share URL

    Models

    bash
    opencode models                              # List all available models
    opencode models anthropic                    # Filter by provider
    opencode models --refresh                    # Refresh model cache
    opencode models --verbose                    # Include cost metadata

    MCP Servers

    bash
    opencode mcp add                             # Add an MCP server
    opencode mcp list                            # List configured servers
    opencode mcp auth <name>                     # Authenticate with OAuth
    opencode mcp debug <name>                    # Debug connection issues

    Server & Web

    bash
    opencode serve --port 4096                   # Start headless API server
    opencode web --port 4096                     # Start web interface
    opencode attach http://localhost:4096        # Attach TUI to remote server

    Stats & Usage

    bash
    opencode stats                               # Show token usage & costs
    opencode stats --days 7                      # Last 7 days
    opencode stats --models                      # Show model breakdown
    opencode stats --project "myapp"             # Filter by project

    Upgrade

    bash
    opencode upgrade                             # Upgrade to latest
    opencode upgrade v0.1.48                    # Upgrade to specific version

    Essential Flags

    Global flags work with any command.

    bash
    opencode --help                              # Show help
    opencode --version                           # Show version
    opencode --print-logs                        # Print logs to stderr
    opencode --log-level DEBUG                   # Set log level

    TUI Flags

    bash
    opencode --continue                          # Continue last session
    opencode --session <id>                      # Continue specific session
    opencode --fork                              # Fork session when continuing
    opencode --prompt "message"                  # Pre-fill prompt
    opencode --model anthropic/claude-sonnet-4-5 # Specify model
    opencode --agent plan                        # Use specific agent

    Run Command Flags

    bash
    opencode run --continue                      # Continue last session
    opencode run --session <id>                  # Continue specific session
    opencode run --fork                          # Fork session when continuing
    opencode run --share                         # Share session automatically
    opencode run --model <model>                 # Specify model
    opencode run --agent <agent>                 # Use specific agent
    opencode run --file path/to/file             # Attach file(s) to message
    opencode run --format json                    # Output as raw JSON events
    opencode run --title "Session name"           # Set session title
    opencode run --attach http://localhost:4096  # Attach to running server
    opencode run --port 4096                     # Local server port

    GitHub Integration

    bash
    opencode github install                      # Install GitHub agent
    opencode github run --event pull_request     # Run for GitHub event
    opencode github run --token <pat>            # Provide GitHub token

    Common Workflows

    Starting a New Project Session

    bash
    cd /path/to/project
    opencode
    # Inside TUI: run /init to create AGENTS.md
    # Then start asking questions or making changes

    Code Review with Plan Mode

    bash
    opencode
    # Press Tab to switch to Plan mode
    # Describe what you want reviewed
    # Iterate on feedback
    # Switch back to Build mode when ready

    Running Non-Interactive Tasks

    bash
    opencode run "Run the test suite and fix any failures"
    opencode run "Add authentication to the /api/users route"
    opencode run --file broken.js "Fix the syntax error in this file"

    Attaching to a Running Server

    bash
    # Terminal 1: Start server
    opencode serve --port 4096
    
    # Terminal 2: Attach TUI
    opencode attach http://localhost:4096
    
    # Or run commands directly
    opencode run --attach http://localhost:4096 "Explain this codebase"

    Sharing and Collaborating

    bash
    # Inside TUI
    /share
    
    # This copies a link to the conversation to your clipboard

    Using File References

    Inside the TUI, use @ to reference files:

    bash
    How does auth work in @packages/functions/src/api/index.ts?

    The file content is automatically included in the context.

    Running Shell Commands in TUI

    Prefix with ! to run bash commands:

    bash
    !ls -la
    !git log --oneline -5

    The output becomes part of the conversation context.

    Custom Commands

    Create reusable commands in your config or .opencode/commands/ directory.

    .opencode/commands/test.md:

    markdown
    ---
    description: Run tests with coverage
    agent: build
    ---
    
    Run the full test suite with coverage report and show any failures.
    Focus on the failing tests and suggest fixes.

    Use it inside TUI with /test.

    Configuration Tips

    OpenCode config is JSON or JSONC, loaded in this order (later overrides earlier):

    1. Remote config (.well-known/opencode) - organizational defaults
    2. Global config (~/.config/opencode/opencode.json) - user preferences
    3. Custom config (OPENCODE_CONFIG env var)
    4. Project config (opencode.json in project root)
    5. Inline config (OPENCODE_CONFIG_CONTENT env var)

    Basic Config Example

    json
    {
      "$schema": "https://opencode.ai/config.json",
      "model": "anthropic/claude-sonnet-4-5",
      "autoupdate": true,
      "provider": {
        "anthropic": {
          "options": {
            "timeout": 600000,
            "chunkTimeout": 30000
          }
        }
      }
    }

    Permission Control

    Require approval for destructive operations:

    json
    {
      "permission": {
        "edit": "ask",
        "bash": "ask"
      }
    }

    Custom Commands in Config

    json
    {
      "command": {
        "test": {
          "template": "Run the full test suite with coverage report",
          "description": "Run tests with coverage",
          "agent": "build"
        }
      }
    }

    TUI-Specific Settings

    Use tui.json for TUI-only settings:

    json
    {
      "$schema": "https://opencode.ai/tui.json",
      "theme": "tokyonight",
      "scroll_speed": 3,
      "diff_style": "auto"
    }

    Environment Variables

    bash
    export OPENCODE_CONFIG=/path/to/config.json
    export OPENCODE_TUI_CONFIG=/path/to/tui.json
    export OPENCODE_CONFIG_DIR=/path/to/config-directory
    export OPENCODE_SERVER_PASSWORD=mypassword
    export OPENCODE_DISABLE_AUTOUPDATE=true
    export OPENCODE_DISABLE_AUTOCOMPACT=true

    Troubleshooting

    "Command not found" after install

    bash
    # Verify installation
    npm list -g opencode-ai
    # Or
    which opencode
    
    # Reinstall if needed
    curl -fsSL https://opencode.ai/install | bash

    API key not recognized

    bash
    # Check authenticated providers
    opencode auth list
    
    # Re-authenticate
    opencode auth login
    
    # Or set in environment
    export ANTHROPIC_API_KEY=sk-...
    export OPENAI_API_KEY=sk-...

    Slow model responses

    json
    {
      "provider": {
        "anthropic": {
          "options": {
            "timeout": 600000,
            "chunkTimeout": 30000
          }
        }
      }
    }

    Context running out

    Inside TUI, use /compact or /summarize to compact the session. You can also enable auto-compaction:

    json
    {
      "compaction": {
        "auto": true,
        "prune": true,
        "reserved": 10000
      }
    }

    Undo not working

    The /undo command requires your project to be a Git repository. Initialize one if needed:

    bash
    git init
    git add .
    git commit -m "Initial commit"

    File changes not persisting

    Check that you have write permissions and the project directory is not on a read-only mount.

    MCP server connection issues

    bash
    opencode mcp list                            # Check connection status
    opencode mcp debug <server-name>            # Debug OAuth flow

    Session not resuming

    bash
    # List sessions
    opencode session list
    
    # Resume specific session
    opencode --session <session-id>
    
    # Or inside TUI
    /sessions

    Sources: OpenCode.ai Documentation

    Related Blog

    OpenCode.ai CLI Cheatsheet | Tob