README.md

  1# ⌬ OpenCode
  2
  3> **⚠️ Early Development Notice:** This project is in early development and is not yet ready for production use. Features may change, break, or be incomplete. Use at your own risk.
  4
  5A powerful terminal-based AI assistant for developers, providing intelligent coding assistance directly in your terminal.
  6
  7## Overview
  8
  9OpenCode is a Go-based CLI application that brings AI assistance to your terminal. It provides a TUI (Terminal User Interface) for interacting with various AI models to help with coding tasks, debugging, and more.
 10
 11## Features
 12
 13- **Interactive TUI**: Built with [Bubble Tea](https://github.com/charmbracelet/bubbletea) for a smooth terminal experience
 14- **Multiple AI Providers**: Support for OpenAI, Anthropic Claude, Google Gemini, AWS Bedrock, Groq, Azure OpenAI, and OpenRouter
 15- **Session Management**: Save and manage multiple conversation sessions
 16- **Tool Integration**: AI can execute commands, search files, and modify code
 17- **Vim-like Editor**: Integrated editor with text input capabilities
 18- **Persistent Storage**: SQLite database for storing conversations and sessions
 19- **LSP Integration**: Language Server Protocol support for code intelligence
 20- **File Change Tracking**: Track and visualize file changes during sessions
 21- **External Editor Support**: Open your preferred editor for composing messages
 22- **Named Arguments for Custom Commands**: Create powerful custom commands with multiple named placeholders
 23
 24## Installation
 25
 26### Using the Install Script
 27
 28```bash
 29# Install the latest version
 30curl -fsSL https://raw.githubusercontent.com/opencode-ai/opencode/refs/heads/main/install | bash
 31
 32# Install a specific version
 33curl -fsSL https://raw.githubusercontent.com/opencode-ai/opencode/refs/heads/main/install | VERSION=0.1.0 bash
 34```
 35
 36### Using Homebrew (macOS and Linux)
 37
 38```bash
 39brew install opencode-ai/tap/opencode
 40```
 41
 42### Using AUR (Arch Linux)
 43
 44```bash
 45# Using yay
 46yay -S opencode-ai-bin
 47
 48# Using paru
 49paru -S opencode-ai-bin
 50```
 51
 52### Using Go
 53
 54```bash
 55go install github.com/opencode-ai/opencode@latest
 56```
 57
 58## Configuration
 59
 60OpenCode looks for configuration in the following locations:
 61
 62- `$HOME/.opencode.json`
 63- `$XDG_CONFIG_HOME/opencode/.opencode.json`
 64- `./.opencode.json` (local directory)
 65
 66### Auto Compact Feature
 67
 68OpenCode includes an auto compact feature that automatically summarizes your conversation when it approaches the model's context window limit. When enabled (default setting), this feature:
 69
 70- Monitors token usage during your conversation
 71- Automatically triggers summarization when usage reaches 95% of the model's context window
 72- Creates a new session with the summary, allowing you to continue your work without losing context
 73- Helps prevent "out of context" errors that can occur with long conversations
 74
 75You can enable or disable this feature in your configuration file:
 76
 77```json
 78{
 79  "autoCompact": true // default is true
 80}
 81```
 82
 83### Environment Variables
 84
 85You can configure OpenCode using environment variables:
 86
 87| Environment Variable       | Purpose                                                |
 88| -------------------------- | ------------------------------------------------------ |
 89| `ANTHROPIC_API_KEY`        | For Claude models                                      |
 90| `OPENAI_API_KEY`           | For OpenAI models                                      |
 91| `GEMINI_API_KEY`           | For Google Gemini models                               |
 92| `GROQ_API_KEY`             | For Groq models                                        |
 93| `AWS_ACCESS_KEY_ID`        | For AWS Bedrock (Claude)                               |
 94| `AWS_SECRET_ACCESS_KEY`    | For AWS Bedrock (Claude)                               |
 95| `AWS_REGION`               | For AWS Bedrock (Claude)                               |
 96| `AZURE_OPENAI_ENDPOINT`    | For Azure OpenAI models                                |
 97| `AZURE_OPENAI_API_KEY`     | For Azure OpenAI models (optional when using Entra ID) |
 98| `AZURE_OPENAI_API_VERSION` | For Azure OpenAI models                                |
 99| `SHELL`                    | Default shell to use (if not specified in config)      |
100
101### Shell Configuration
102
103OpenCode allows you to configure the shell used by the bash tool. By default, it uses the shell specified in the `SHELL` environment variable, or falls back to `/bin/bash` if not set.
104
105You can override this in your configuration file:
106
107```json
108{
109  "shell": {
110    "path": "/bin/zsh",
111    "args": ["-l"]
112  }
113}
114```
115
116This is useful if you want to use a different shell than your default system shell, or if you need to pass specific arguments to the shell.
117
118### Configuration File Structure
119
120```json
121{
122  "data": {
123    "directory": ".opencode"
124  },
125  "providers": {
126    "openai": {
127      "apiKey": "your-api-key",
128      "disabled": false
129    },
130    "anthropic": {
131      "apiKey": "your-api-key",
132      "disabled": false
133    },
134    "groq": {
135      "apiKey": "your-api-key",
136      "disabled": false
137    },
138    "openrouter": {
139      "apiKey": "your-api-key",
140      "disabled": false
141    }
142  },
143  "agents": {
144    "coder": {
145      "model": "claude-3.7-sonnet",
146      "maxTokens": 5000
147    },
148    "task": {
149      "model": "claude-3.7-sonnet",
150      "maxTokens": 5000
151    },
152    "title": {
153      "model": "claude-3.7-sonnet",
154      "maxTokens": 80
155    }
156  },
157  "shell": {
158    "path": "/bin/bash",
159    "args": ["-l"]
160  },
161  "mcpServers": {
162    "example": {
163      "type": "stdio",
164      "command": "path/to/mcp-server",
165      "env": [],
166      "args": []
167    }
168  },
169  "lsp": {
170    "go": {
171      "disabled": false,
172      "command": "gopls"
173    }
174  },
175  "debug": false,
176  "debugLSP": false,
177  "autoCompact": true
178}
179```
180
181## Supported AI Models
182
183OpenCode supports a variety of AI models from different providers:
184
185### OpenAI
186
187- GPT-4.1 family (gpt-4.1, gpt-4.1-mini, gpt-4.1-nano)
188- GPT-4.5 Preview
189- GPT-4o family (gpt-4o, gpt-4o-mini)
190- O1 family (o1, o1-pro, o1-mini)
191- O3 family (o3, o3-mini)
192- O4 Mini
193
194### Anthropic
195
196- Claude 3.5 Sonnet
197- Claude 3.5 Haiku
198- Claude 3.7 Sonnet
199- Claude 3 Haiku
200- Claude 3 Opus
201
202### Google
203
204- Gemini 2.5
205- Gemini 2.5 Flash
206- Gemini 2.0 Flash
207- Gemini 2.0 Flash Lite
208
209### AWS Bedrock
210
211- Claude 3.7 Sonnet
212
213### Groq
214
215- Llama 4 Maverick (17b-128e-instruct)
216- Llama 4 Scout (17b-16e-instruct)
217- QWEN QWQ-32b
218- Deepseek R1 distill Llama 70b
219- Llama 3.3 70b Versatile
220
221### Azure OpenAI
222
223- GPT-4.1 family (gpt-4.1, gpt-4.1-mini, gpt-4.1-nano)
224- GPT-4.5 Preview
225- GPT-4o family (gpt-4o, gpt-4o-mini)
226- O1 family (o1, o1-mini)
227- O3 family (o3, o3-mini)
228- O4 Mini
229
230## Usage
231
232```bash
233# Start OpenCode
234opencode
235
236# Start with debug logging
237opencode -d
238
239# Start with a specific working directory
240opencode -c /path/to/project
241```
242
243## Command-line Flags
244
245| Flag      | Short | Description                   |
246| --------- | ----- | ----------------------------- |
247| `--help`  | `-h`  | Display help information      |
248| `--debug` | `-d`  | Enable debug mode             |
249| `--cwd`   | `-c`  | Set current working directory |
250
251## Keyboard Shortcuts
252
253### Global Shortcuts
254
255| Shortcut | Action                                                  |
256| -------- | ------------------------------------------------------- |
257| `Ctrl+C` | Quit application                                        |
258| `Ctrl+?` | Toggle help dialog                                      |
259| `?`      | Toggle help dialog (when not in editing mode)           |
260| `Ctrl+L` | View logs                                               |
261| `Ctrl+A` | Switch session                                          |
262| `Ctrl+K` | Command dialog                                          |
263| `Ctrl+O` | Toggle model selection dialog                           |
264| `Esc`    | Close current overlay/dialog or return to previous mode |
265
266### Chat Page Shortcuts
267
268| Shortcut | Action                                  |
269| -------- | --------------------------------------- |
270| `Ctrl+N` | Create new session                      |
271| `Ctrl+X` | Cancel current operation/generation     |
272| `i`      | Focus editor (when not in writing mode) |
273| `Esc`    | Exit writing mode and focus messages    |
274
275### Editor Shortcuts
276
277| Shortcut            | Action                                    |
278| ------------------- | ----------------------------------------- |
279| `Ctrl+S`            | Send message (when editor is focused)     |
280| `Enter` or `Ctrl+S` | Send message (when editor is not focused) |
281| `Ctrl+E`            | Open external editor                      |
282| `Esc`               | Blur editor and focus messages            |
283
284### Session Dialog Shortcuts
285
286| Shortcut   | Action           |
287| ---------- | ---------------- |
288| `↑` or `k` | Previous session |
289| `↓` or `j` | Next session     |
290| `Enter`    | Select session   |
291| `Esc`      | Close dialog     |
292
293### Model Dialog Shortcuts
294
295| Shortcut   | Action            |
296| ---------- | ----------------- |
297| `↑` or `k` | Move up           |
298| `↓` or `j` | Move down         |
299| `←` or `h` | Previous provider |
300| `→` or `l` | Next provider     |
301| `Esc`      | Close dialog      |
302
303### Permission Dialog Shortcuts
304
305| Shortcut                | Action                       |
306| ----------------------- | ---------------------------- |
307| `←` or `left`           | Switch options left          |
308| `→` or `right` or `tab` | Switch options right         |
309| `Enter` or `space`      | Confirm selection            |
310| `a`                     | Allow permission             |
311| `A`                     | Allow permission for session |
312| `d`                     | Deny permission              |
313
314### Logs Page Shortcuts
315
316| Shortcut           | Action              |
317| ------------------ | ------------------- |
318| `Backspace` or `q` | Return to chat page |
319
320## AI Assistant Tools
321
322OpenCode's AI assistant has access to various tools to help with coding tasks:
323
324### File and Code Tools
325
326| Tool          | Description                 | Parameters                                                                               |
327| ------------- | --------------------------- | ---------------------------------------------------------------------------------------- |
328| `glob`        | Find files by pattern       | `pattern` (required), `path` (optional)                                                  |
329| `grep`        | Search file contents        | `pattern` (required), `path` (optional), `include` (optional), `literal_text` (optional) |
330| `ls`          | List directory contents     | `path` (optional), `ignore` (optional array of patterns)                                 |
331| `view`        | View file contents          | `file_path` (required), `offset` (optional), `limit` (optional)                          |
332| `write`       | Write to files              | `file_path` (required), `content` (required)                                             |
333| `edit`        | Edit files                  | Various parameters for file editing                                                      |
334| `patch`       | Apply patches to files      | `file_path` (required), `diff` (required)                                                |
335| `diagnostics` | Get diagnostics information | `file_path` (optional)                                                                   |
336
337### Other Tools
338
339| Tool          | Description                            | Parameters                                                                                |
340| ------------- | -------------------------------------- | ----------------------------------------------------------------------------------------- |
341| `bash`        | Execute shell commands                 | `command` (required), `timeout` (optional)                                                |
342| `fetch`       | Fetch data from URLs                   | `url` (required), `format` (required), `timeout` (optional)                               |
343| `sourcegraph` | Search code across public repositories | `query` (required), `count` (optional), `context_window` (optional), `timeout` (optional) |
344| `agent`       | Run sub-tasks with the AI agent        | `prompt` (required)                                                                       |
345
346## Architecture
347
348OpenCode is built with a modular architecture:
349
350- **cmd**: Command-line interface using Cobra
351- **internal/app**: Core application services
352- **internal/config**: Configuration management
353- **internal/db**: Database operations and migrations
354- **internal/llm**: LLM providers and tools integration
355- **internal/tui**: Terminal UI components and layouts
356- **internal/logging**: Logging infrastructure
357- **internal/message**: Message handling
358- **internal/session**: Session management
359- **internal/lsp**: Language Server Protocol integration
360
361## Custom Commands
362
363OpenCode supports custom commands that can be created by users to quickly send predefined prompts to the AI assistant.
364
365### Creating Custom Commands
366
367Custom commands are predefined prompts stored as Markdown files in one of three locations:
368
3691. **User Commands** (prefixed with `user:`):
370
371   ```
372   $XDG_CONFIG_HOME/opencode/commands/
373   ```
374
375   (typically `~/.config/opencode/commands/` on Linux/macOS)
376
377   or
378
379   ```
380   $HOME/.opencode/commands/
381   ```
382
3832. **Project Commands** (prefixed with `project:`):
384   ```
385   <PROJECT DIR>/.opencode/commands/
386   ```
387
388Each `.md` file in these directories becomes a custom command. The file name (without extension) becomes the command ID.
389
390For example, creating a file at `~/.config/opencode/commands/prime-context.md` with content:
391
392```markdown
393RUN git ls-files
394READ README.md
395```
396
397This creates a command called `user:prime-context`.
398
399### Command Arguments
400
401OpenCode supports named arguments in custom commands using placeholders in the format `$NAME` (where NAME consists of uppercase letters, numbers, and underscores, and must start with a letter).
402
403For example:
404
405```markdown
406# Fetch Context for Issue $ISSUE_NUMBER
407
408RUN gh issue view $ISSUE_NUMBER --json title,body,comments
409RUN git grep --author="$AUTHOR_NAME" -n .
410RUN grep -R "$SEARCH_PATTERN" $DIRECTORY
411```
412
413When you run a command with arguments, OpenCode will prompt you to enter values for each unique placeholder. Named arguments provide several benefits:
414- Clear identification of what each argument represents
415- Ability to use the same argument multiple times
416- Better organization for commands with multiple inputs
417
418### Organizing Commands
419
420You can organize commands in subdirectories:
421
422```
423~/.config/opencode/commands/git/commit.md
424```
425
426This creates a command with ID `user:git:commit`.
427
428### Using Custom Commands
429
4301. Press `Ctrl+K` to open the command dialog
4312. Select your custom command (prefixed with either `user:` or `project:`)
4323. Press Enter to execute the command
433
434The content of the command file will be sent as a message to the AI assistant.
435
436### Built-in Commands
437
438OpenCode includes several built-in commands:
439
440| Command            | Description                                                                                         |
441| ------------------ | --------------------------------------------------------------------------------------------------- |
442| Initialize Project | Creates or updates the OpenCode.md memory file with project-specific information                    |
443| Compact Session    | Manually triggers the summarization of the current session, creating a new session with the summary |
444
445## MCP (Model Context Protocol)
446
447OpenCode implements the Model Context Protocol (MCP) to extend its capabilities through external tools. MCP provides a standardized way for the AI assistant to interact with external services and tools.
448
449### MCP Features
450
451- **External Tool Integration**: Connect to external tools and services via a standardized protocol
452- **Tool Discovery**: Automatically discover available tools from MCP servers
453- **Multiple Connection Types**:
454  - **Stdio**: Communicate with tools via standard input/output
455  - **SSE**: Communicate with tools via Server-Sent Events
456- **Security**: Permission system for controlling access to MCP tools
457
458### Configuring MCP Servers
459
460MCP servers are defined in the configuration file under the `mcpServers` section:
461
462```json
463{
464  "mcpServers": {
465    "example": {
466      "type": "stdio",
467      "command": "path/to/mcp-server",
468      "env": [],
469      "args": []
470    },
471    "web-example": {
472      "type": "sse",
473      "url": "https://example.com/mcp",
474      "headers": {
475        "Authorization": "Bearer token"
476      }
477    }
478  }
479}
480```
481
482### MCP Tool Usage
483
484Once configured, MCP tools are automatically available to the AI assistant alongside built-in tools. They follow the same permission model as other tools, requiring user approval before execution.
485
486## LSP (Language Server Protocol)
487
488OpenCode integrates with Language Server Protocol to provide code intelligence features across multiple programming languages.
489
490### LSP Features
491
492- **Multi-language Support**: Connect to language servers for different programming languages
493- **Diagnostics**: Receive error checking and linting information
494- **File Watching**: Automatically notify language servers of file changes
495
496### Configuring LSP
497
498Language servers are configured in the configuration file under the `lsp` section:
499
500```json
501{
502  "lsp": {
503    "go": {
504      "disabled": false,
505      "command": "gopls"
506    },
507    "typescript": {
508      "disabled": false,
509      "command": "typescript-language-server",
510      "args": ["--stdio"]
511    }
512  }
513}
514```
515
516### LSP Integration with AI
517
518The AI assistant can access LSP features through the `diagnostics` tool, allowing it to:
519
520- Check for errors in your code
521- Suggest fixes based on diagnostics
522
523While the LSP client implementation supports the full LSP protocol (including completions, hover, definition, etc.), currently only diagnostics are exposed to the AI assistant.
524
525## Development
526
527### Prerequisites
528
529- Go 1.24.0 or higher
530
531### Building from Source
532
533```bash
534# Clone the repository
535git clone https://github.com/opencode-ai/opencode.git
536cd opencode
537
538# Build
539go build -o opencode
540
541# Run
542./opencode
543```
544
545## Acknowledgments
546
547OpenCode gratefully acknowledges the contributions and support from these key individuals:
548
549- [@isaacphi](https://github.com/isaacphi) - For the [mcp-language-server](https://github.com/isaacphi/mcp-language-server) project which provided the foundation for our LSP client implementation
550- [@adamdottv](https://github.com/adamdottv) - For the design direction and UI/UX architecture
551
552Special thanks to the broader open source community whose tools and libraries have made this project possible.
553
554## License
555
556OpenCode is licensed under the MIT License. See the [LICENSE](LICENSE) file for details.
557
558## Contributing
559
560Contributions are welcome! Here's how you can contribute:
561
5621. Fork the repository
5632. Create a feature branch (`git checkout -b feature/amazing-feature`)
5643. Commit your changes (`git commit -m 'Add some amazing feature'`)
5654. Push to the branch (`git push origin feature/amazing-feature`)
5665. Open a Pull Request
567
568Please make sure to update tests as appropriate and follow the existing code style.