README.md

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