OpenCode is a command-line AI coding assistant that provides an interactive terminal-based interface for AI-powered software development. It supports multiple AI providers, offers extensive customization options, and includes advanced features like language server integration, file monitoring, and session sharing.
Source: packages/opencode/src/installation/index.ts
- curl: One-line installation script that downloads appropriate binary
- Package Managers: npm, pnpm, bun, yarn
- Homebrew: For macOS users
- Platform Detection: Automatically detects OS (darwin/linux/windows) and architecture (x64/arm64)
Source: scripts/install (shell script)
- Creates directories:
~/.config/opencode
,~/.local/share/opencode
,~/.cache/opencode
- Modifies shell configuration to add OpenCode to PATH
- Supports fish, zsh, bash, ash, and sh shells
- GitHub Actions: Special handling with
$GITHUB_PATH
- Idempotent: Checks if PATH entry already exists before adding
- Pre-push Git Hook: Installation script available at
scripts/hooks
Source: packages/opencode/src/cli/cmd/tui.ts:99-111
- Automatically prompts for authentication if no providers configured
- Shows ASCII art logo during setup
- For Git repositories: Prompts to initialize AGENTS.md file
Source: packages/opencode/src/cli/cmd/tui.ts:13-114 Launches the interactive terminal UI with full chat interface.
Options:
[project]
: Optional path to start OpenCode in a specific directory--print-logs
: Print logs to stderr for debugging (Source: packages/opencode/src/index.ts:37-40)
Behavior:
- Changes to specified directory if provided
- Checks for configured providers, prompts for auth if none found
- Launches Go-based TUI with embedded binary or development mode
- Auto-update check runs in background (can be disabled) (Source: packages/opencode/src/cli/cmd/tui.ts:76-91)
- Embedded Binary Support: Detects and uses embedded TUI binaries (Source: packages/opencode/src/cli/cmd/tui.ts:46-59)
Source: packages/opencode/src/cli/cmd/run.ts:25-163 Execute OpenCode with a single message and get a response.
Options:
--continue
/-c
: Continue the last session--session
/-s
: Session ID to continue--share
: Share the session--model
/-m
: Model to use (format: provider/model)
Special Behavior:
- Piped Output: When output is piped (
!process.stdout.isTTY
), only outputs the final text response without UI elements (Source: packages/opencode/src/cli/cmd/run.ts:76,156-159) - Shows tool invocations as they execute with color coding (Source: packages/opencode/src/cli/cmd/run.ts:15-23)
- Displays session share URL if enabled
Source: packages/opencode/src/cli/cmd/auth.ts:14-264 Manage authentication credentials.
Subcommands:
auth login
: Interactive provider authentication- Claude Pro/Max: OAuth flow with browser (Source: packages/opencode/src/cli/cmd/auth.ts:152-181)
- GitHub Copilot: Device flow authentication (Source: packages/opencode/src/cli/cmd/auth.ts:184-220)
- API Keys: Direct input for other providers
- Amazon Bedrock: Uses AWS environment variables (Source: packages/opencode/src/cli/cmd/auth.ts:128-134)
auth logout
: Remove stored credentialsauth list
/auth ls
: Show all configured credentials and active environment variables (Source: packages/opencode/src/cli/cmd/auth.ts:49-72)
Storage:
- Credentials stored in
~/.local/share/opencode/auth.json
- File permissions set to 0600 for security (Source: packages/opencode/src/auth/index.ts)
Source: packages/opencode/src/cli/cmd/upgrade.ts:6-53 Upgrade OpenCode to latest or specific version.
Options:
[target]
: Version to upgrade to (e.g., '0.1.48' or 'v0.1.48')--method
/-m
: Installation method (curl, npm, pnpm, bun, brew) (Source: packages/opencode/src/cli/cmd/upgrade.ts:19)
Behavior:
- Auto-detects installation method if not specified
- Prevents upgrades for snapshot/dev versions
- Shows progress spinner during upgrade
- Homebrew: Sets
HOMEBREW_NO_AUTO_UPDATE=1
to skip auto-updates (Source: packages/opencode/src/installation/index.ts)
Source: packages/opencode/src/cli/cmd/models.ts:5-19 List all available models from configured providers.
Output Format: provider/model
(one per line)
Source: packages/opencode/src/cli/cmd/serve.ts:7-50 Start a headless OpenCode server for API access.
Options:
--port
/-p
: Port to listen on (default: 4096)--hostname
/-h
: Hostname to bind to (default: 127.0.0.1)
Features:
- RESTful API with OpenAPI documentation at
/doc
- Server-sent events at
/event
- Full session and message management
Source: packages/opencode/src/cli/cmd/generate.ts Generate OpenAPI specification file.
Output: Creates gen/openapi.json
with full API documentation
Source: packages/opencode/src/cli/cmd/scrap.ts Diagnostic command for testing LSP integration.
Behavior: Touches the specified file and returns LSP diagnostics
Source: packages/opencode/src/index.ts:32-66
--help
: Show help for any command--version
/-v
: Show version number--print-logs
: Enable log output to stderr
Source: packages/tui/internal/tui/tui.go
- BubbleTea Framework: Elm-inspired terminal UI architecture
- Flex Layout: Vertical split between message history and input editor (Source: packages/tui/internal/layout/)
- Container System: Max width 80 characters, center-aligned (Source: packages/tui/internal/layout/container.go)
- Responsive: Adapts to terminal resize events
Source: packages/tui/internal/components/chat/messages.go
- Markdown Rendering: Full markdown support in messages
- Syntax Highlighting: Code blocks with language-specific highlighting
- Tool Invocations: Collapsible tool execution details
- User/Assistant Distinction: Visual differentiation between message types
- Auto-scroll: Maintains position or follows new messages
- Message Caching: Performance optimization for long conversations (Source: packages/tui/internal/components/chat/cache.go)
- Optimistic Updates: Shows user messages immediately before server confirmation (Source: packages/tui/internal/tui/tui.go:314-323)
Source: packages/tui/internal/components/chat/editor.go
- Multi-line Support: Full text editor with line wrapping
- Command History: Navigate with up/down arrows
- Syntax Highlighting: Real-time highlighting as you type
- Line Continuation: Backslash for multi-line commands
- Submit Hints: Shows current keybind for submission
- Status Indicators: Spinner during processing, model/provider display
Source: packages/tui/internal/image/
- Clipboard Paste: Ctrl+V to paste images from clipboard
- Platform Support: Unix (xclip/wl-paste) and Windows (Source: packages/tui/internal/image/clipboard_unix.go, clipboard_windows.go)
- Preview: ANSI color representation in terminal
- Validation: Size and format checking
Source: packages/tui/internal/components/dialog/models.go
- Provider Selection: Horizontal scrolling through providers
- Model List: Vertical navigation with live preview
- Escape Behavior: Cancel without applying changes
Source: packages/tui/internal/components/dialog/session.go
- Session List: All sessions with search functionality
- Delete Confirmation: Press 'd' twice to delete
- Session Switching: Instant switch between sessions
- Title Display: Shows session titles
Source: packages/tui/internal/components/dialog/theme.go
- 20+ Built-in Themes: Catppuccin, Dracula, Gruvbox, Nord, etc. (Source: packages/tui/internal/theme/themes/.json*)
- Live Preview: Theme changes as you navigate
- System Detection: Adapts to system theme (Source: packages/tui/internal/theme/system.go)
- Custom Themes: Load from config directories
Source: packages/tui/internal/components/dialog/help.go
- Command Reference: All available commands and keybindings
- Scrollable: Navigate long help text
- Context-sensitive: Shows relevant commands
Source: packages/tui/internal/components/dialog/permission.go
- Tool Permissions: Allow/Deny for specific tools
- Session Scope: Permissions per session
- Keyboard Navigation: Quick approve/deny
Source: packages/tui/internal/components/dialog/complete.go
- Trigger: '/' key activates completions
- Command Completion: Available commands (Source: packages/tui/internal/completions/commands.go)
- File/Folder Completion: Path-based suggestions (Source: packages/tui/internal/completions/files-folders.go)
- Tab/Enter: Complete selection
- Escape: Cancel completion
Source: packages/tui/internal/components/dialog/init.go
- Git Detection: Shows when Git repo detected without AGENTS.md
- Yes/No Selection: Quick keyboard shortcuts (y/n)
Source: packages/tui/internal/components/status/status.go
- Version Display: OpenCode version
- Working Directory: Current path (relative display)
- Token Usage: Current session token count and cost (Source: packages/tui/internal/components/status/status.go:98-116)
- Context Window: Percentage of context used
- Real-time Updates: Live status changes
Source: packages/tui/internal/config/config.go
- Leader Key:
Ctrl+X
(customizable)
<leader>h
: Show help<leader>q
orCtrl+C
: Exit application<leader>e
: Open external editor
<leader>n
: New session<leader>l
: List sessions<leader>s
: Share session<leader>c
: Toggle compact modeEsc
: Interrupt (double-press within 1 second when busy) (Source: packages/tui/internal/tui/tui.go:41,214-227)
<leader>m
: List models<leader>t
: List themes<leader>d
: Toggle tool details<leader>i
: Initialize project (AGENTS.md)
Enter
: Submit messageShift+Enter
orCtrl+J
: Insert newlineCtrl+C
: Clear inputCtrl+V
: Paste (supports images)/
: Open completions
PgUp/PgDn
: Page up/down in messagesCtrl+Alt+U/D
: Half page up/downCtrl+G
: Go to first messageCtrl+Alt+G
: Go to last messageCtrl+Alt+K
: Previous messageCtrl+Alt+J
: Next message
Source: packages/tui/internal/components/toast/toast.go
- Types: Success, Error, Warning, Info
- Auto-dismiss: 5-second default timeout
- Position: Top-right corner
- Stacking: Multiple toasts stack vertically
- Color-coded: Border colors indicate type
- Interrupt Debouncing: Double Esc within 1 second to confirm interrupt
- Scroll Bug Workaround: Ignores certain keys for 100ms after scroll (Source: packages/tui/internal/tui/tui.go)
- WSL Detection: Disables background color request on WSL (Source: packages/tui/internal/tui/tui.go:66)
- Optimistic Updates: Shows user messages immediately
- Modal Behavior: Esc/Ctrl+C closes any modal, captures all input
Source: packages/opencode/src/tool/read.ts
- Line Numbers: Shows content with line numbers (cat -n format)
- Large Files: Supports offset and limit for pagination
- Image Detection: Recognizes and handles image files
- Size Limit: 250KB maximum file size
- Line Truncation: Lines longer than 2000 characters are truncated
- Tracking: Records when files were last read (Source: packages/opencode/src/file/time.ts)
Source: packages/opencode/src/tool/write.ts
- Create/Overwrite: Full file creation or replacement
- Permission Required: Asks for user permission (currently auto-approved after 1 second) (Source: packages/opencode/src/permission/index.ts:67)
- Read Verification: Must read existing files before overwriting
- LSP Integration: Triggers diagnostics after write
Source: packages/opencode/src/tool/edit.ts
- Multiple Strategies:
- Simple string replacement
- Line-trimmed matching
- Block anchor matching
- Whitespace normalized
- Indentation flexible
- Escape sequence normalized
- Context-aware replacement
- Diff Generation: Shows changes before applying
- Validation: Ensures file hasn't changed since last read
Source: packages/opencode/src/tool/multiedit.ts
- Sequential Edits: Apply multiple edits to one file
- Order Matters: Edits applied in sequence
- Atomic Operation: All succeed or all fail
Source: packages/opencode/src/tool/patch.ts
- Multi-file Changes: Apply patches across multiple files
- Context Validation: Verifies surrounding context
- Diff Format: Standard patch format support
Source: packages/opencode/src/tool/glob.ts
- Ripgrep Backend: Fast pattern matching (Source: packages/opencode/src/external/ripgrep.ts)
- Sort Order: Results sorted by modification time
- Result Limit: Configurable maximum results
Source: packages/opencode/src/tool/grep.ts
- Regex Support: Full regular expression patterns
- File Filtering: Include/exclude patterns
- Performance: Ripgrep for speed
Source: packages/opencode/src/tool/ls.ts
- Directory Listing: With ignore patterns
- Tree Structure: Hierarchical display
- Absolute Paths: Requires absolute path input
Source: packages/opencode/src/tool/bash.ts
- Command Execution: Run shell commands
- Security: Banned commands list (curl, wget, browsers) (Source: packages/opencode/src/tool/bash.ts:BANNED_COMMANDS)
- Output Limit: 30KB maximum output (truncated if exceeded)
- Timeout: Default 1 minute, max 10 minutes
- Environment: Sets
BUN_BE_BUN=1
for OpenCode detection
Source: packages/opencode/src/tool/webfetch.ts
- HTTP Requests: Fetch web content
- HTML→Markdown: Automatic conversion
- Timeout Support: Configurable request timeout
- Size Limits: Content size restrictions
Source: packages/opencode/src/tool/websearch.txt
- Search Integration: Web search capabilities
- Result Processing: Structured search results
Source: packages/opencode/src/tool/todo.ts
- Session-scoped: Todo lists per session
- Priority Levels: High, medium, low
- Status Tracking: Pending, in-progress, completed
- Persistence: Survives session restarts
Source: packages/opencode/src/tool/task.ts
- Sub-sessions: Create child sessions for complex tasks
- Progress Monitoring: Track task completion
- Hierarchical: Parent-child session relationships
Source: packages/opencode/src/lsp/
- Multi-language: Automatic language detection (Source: packages/opencode/src/lsp/language.ts)
- Server Management: Spawns LSP servers as needed (Source: packages/opencode/src/lsp/server.ts)
- Client Pool: Maintains active connections (Source: packages/opencode/src/lsp/client.ts)
- Initialize Timeout: 5-second timeout for server initialization
- Diagnostics: Get errors/warnings for files (Source: packages/opencode/src/tool/lsp-diagnostics.ts)
- Hover: Get type information and documentation (Source: packages/opencode/src/tool/lsp-hover.ts)
- Real-time Updates: Live diagnostic notifications
Source: packages/opencode/src/mcp/index.ts
- Local Servers: stdio-based process communication
- Remote Servers: SSE-based network communication
- Tool Namespacing: Tools prefixed with server name
- Environment Variables: Custom env for each server
- Enable/Disable: Per-server configuration
- Authentication Note: MCP authentication not yet supported (Source: packages/opencode/src/mcp/index.ts)
Source: packages/opencode/src/config/config.ts
- Search Order:
opencode.jsonc
, thenopencode.json
(Source: packages/opencode/src/config/config.ts:18-19) - Directory Traversal: Searches from current directory to root
- Deep Merge: Configurations merged from root to current (Source: packages/opencode/src/config/config.ts:21)
- JSON with Comments: JSONC format supported
- Global:
~/.config/opencode/config.json
- Project:
./opencode.json
or./opencode.jsonc
- Schema:
$schema: "https://opencode.ai/config.json"
Source: packages/opencode/src/config/config.ts:137-209
theme
: UI theme namemodel
: Default model (format: provider/model)autoshare
: Automatically share new sessionsautoupdate
: Enable automatic updates (default: true)disabled_providers
: Array of provider IDs to disable
Source: packages/opencode/src/config/config.ts:67-132 Complete customization of all keyboard shortcuts:
leader
: Leader key for combinationshelp
,editor_open
,session_*
,tool_*
,model_*
,theme_*
input_*
,history_*
,messages_*
,app_exit
{
"provider": {
"provider-id": {
"api": "https://custom-endpoint",
"models": {
"model-id": {
"name": "Display Name",
"cost": { "input": 0.01, "output": 0.02 },
"limit": { "context": 100000, "output": 4096 }
}
}
}
}
}
Source: packages/opencode/src/config/config.ts:29-65
{
"mcp": {
"server-name": {
"type": "local",
"command": ["node", "server.js"],
"environment": { "KEY": "value" },
"enabled": true
}
}
}
Source: packages/opencode/src/config/config.ts:179-204, packages/opencode/src/config/hooks.ts
{
"experimental": {
"hook": {
"file_edited": {
"*.py": [{
"command": ["black", "$FILE"],
"environment": {}
}]
},
"session_completed": [{
"command": ["notify-send", "Session complete"],
"environment": {}
}]
}
}
}
Source: packages/opencode/src/session/index.ts
- Creation: New sessions with optional parent
- Updates: Real-time message streaming
- Completion: Idle detection and cleanup
- Deletion: Manual deletion with confirmation
- Auto-summarization: When approaching token limits (Source: packages/opencode/src/session/index.ts)
- Parent-child: Hierarchical session relationships
- Sharing: Generate public URLs with secrets
- Interruption: Graceful cancellation of operations
- Compact Mode: Condensed view option
- Version Tracking: Each session stores the opencode version (Source: packages/opencode/src/session/index.ts)
Source: packages/opencode/src/share/share.ts
- URL Format:
https://opencode.ai/s/{sessionID}
- Secret-based: Secure synchronization
- Selective Sync: Only session data, not system files
- Auto-share: Optional automatic sharing
- Sync Queue: Batched sync operations (Source: packages/opencode/src/share/share.ts)
Source: packages/opencode/src/provider/
- Anthropic (Claude)
- OpenAI
- Google (Gemini)
- Amazon Bedrock
- Azure OpenAI
- GitHub Copilot
- Custom providers via configuration
Source: packages/opencode/src/auth/
- OAuth: Claude Pro/Max, GitHub Copilot
- API Keys: Most providers
- Environment Variables: AWS credentials, custom keys
Source: packages/opencode/src/provider/models.ts
- Automatic Detection: Provider-specific model lists
- Cost Calculation: Per-token pricing
- Capability Flags: Attachments, reasoning, tools
- Context Limits: Input/output token limits
Source: packages/opencode/src/lsp/
- Automatic Spawning: Based on file extensions
- Multiple Servers: Concurrent language support
- Diagnostics: Real-time error detection
- Code Intelligence: Hover information
- Waiting for Diagnostics: Option when opening files
Source: packages/opencode/src/file/time.ts
- Modification Tracking: Detects external changes
- Conflict Prevention: Validates before editing
- Hook System: Trigger commands on file changes
- Ripgrep Integration: Fast file searching (Source: packages/opencode/src/external/ripgrep.ts)
- FZF Integration: Fuzzy finding support (Source: packages/opencode/src/external/fzf.ts)
- Binary Management: Auto-download if not found
- Platform-specific: Correct binary for OS/arch
Source: packages/opencode/src/util/log.ts
- Location:
~/.local/share/opencode/logs
- Rotation: Keeps last 10 log files
- Debug Output:
--print-logs
flag - Error Details: Log path shown on errors
OPENCODE_AUTO_SHARE
: Set to "true" or "1" for auto-sharing (Source: packages/opencode/src/flag/flag.ts:2)OPENCODE_API
: Override API endpoint (Source: packages/opencode/src/share/share.ts:55)OPENCODE_BIN_PATH
: Override binary location (Source: packages/opencode/bin/opencode)OPENCODE_SERVER
: Internal variable for TUI-server communication (Source: packages/opencode/src/cli/cmd/tui.ts:68)OPENCODE_APP_INFO
: Internal app metadata for TUI (Source: packages/opencode/src/cli/cmd/tui.ts:69)BUN_BE_BUN
: Set by bash tool for detection (Source: packages/opencode/src/mcp/index.ts:66)- Provider-specific variables (shown in
auth list
)
Source: packages/opencode/bin/opencode
- Naming:
opencode-{platform}-{arch}
- Platforms: darwin, linux, win32
- Architectures: x64, arm64, arm
- Windows:
.exe
extension handling (Source: packages/opencode/src/cli/cmd/tui.ts:48-49)
Source: install script
- Fish: Adds to
~/.config/fish/config.fish
- Zsh: Adds to
~/.zshrc
- Bash: Adds to
~/.bashrc
or~/.bash_profile
- Generic: Falls back to
~/.profile
- Binary extension:
.exe
- Clipboard: Windows-specific implementation (Source: packages/tui/internal/image/clipboard_windows.go)
- Path handling: Proper escaping
Source: packages/opencode/src/tool/bash.ts:BANNED_COMMANDS Bash tool blocks dangerous commands:
- Network tools: curl, wget
- Browsers: chrome, firefox, safari, edge
- Forces use of WebFetch for HTTP requests
- Auth file: 0600 (user read/write only) (Source: packages/opencode/src/auth/index.ts)
- Binary files: 0755 (executable)
Source: packages/opencode/src/permission/index.ts
- Per-session tool permissions
- Currently auto-approves after 1 second (Source: packages/opencode/src/permission/index.ts:67)
- Framework for future UI integration
Source: packages/opencode/src/util/error.ts
- Structured error types with data
- Consistent error reporting
- User-friendly messages
Source: packages/opencode/src/provider/provider.ts
ProviderAuthError
: Authentication failuresProviderNoDefaultError
: No default model configured- MCP-specific error handling with notes
- Graceful degradation
- Automatic retries where appropriate
- Clear error explanations
Source: packages/tui/internal/components/chat/cache.go
- Rendered message cache
- Cache invalidation on changes
- Key-based tool result caching
Source: packages/opencode/src/util/lazy.ts
- On-demand provider initialization
- Deferred model discovery
- Incremental configuration loading
- Proper cleanup on shutdown
- Connection pooling for LSP
- Controlled subprocess spawning
Source: packages/opencode/src/server/server.ts
GET /doc
: OpenAPI documentationGET /event
: Server-sent events stream- Session management endpoints
- Message streaming endpoints
- File search integration
Source: packages/opencode/src/bus/index.ts
- Real-time event broadcasting
- Session state changes
- Tool execution events
- Error propagation
The product includes infrastructure for several features that are not yet fully implemented:
- Complete permission UI (currently auto-approves)
- MCP authentication support
- Extended hook system capabilities
- Plugin architecture preparations
Source: scripts/hooks
- Pre-push hook installation
- Automatic Git detection for AGENTS.md prompt
- OpenAPI spec generation (Source: packages/opencode/src/cli/cmd/generate.ts)
- Embedded binary support for distribution
- Platform-specific build configurations
This comprehensive specification captures the complete user-facing behavior of OpenCode, including all the detailed edge cases and behaviors that make it a sophisticated AI coding assistant, with direct references to the source code implementation.