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## Non-interactive Prompt Mode
253
254You can run OpenCode in non-interactive mode by passing a prompt directly as a command-line argument. This is useful for scripting, automation, or when you want a quick answer without launching the full TUI.
255
256```bash
257# Run a single prompt and print the AI's response to the terminal
258opencode -p "Explain the use of context in Go"
259
260# Get response in JSON format
261opencode -p "Explain the use of context in Go" -f json
262
263# Run without showing the spinner (useful for scripts)
264opencode -p "Explain the use of context in Go" -q
265```
266
267In this mode, OpenCode will process your prompt, print the result to standard output, and then exit. All permissions are auto-approved for the session.
268
269By default, a spinner animation is displayed while the model is processing your query. You can disable this spinner with the `-q` or `--quiet` flag, which is particularly useful when running OpenCode from scripts or automated workflows.
270
271### Output Formats
272
273OpenCode supports the following output formats in non-interactive mode:
274
275| Format | Description                            |
276| ------ | -------------------------------------- |
277| `text` | Plain text output (default)            |
278| `json` | Output wrapped in a JSON object        |
279
280The output format is implemented as a strongly-typed `OutputFormat` in the codebase, ensuring type safety and validation when processing outputs.
281
282## Command-line Flags
283
284| Flag              | Short | Description                                            |
285| ----------------- | ----- | ------------------------------------------------------ |
286| `--help`          | `-h`  | Display help information                               |
287| `--debug`         | `-d`  | Enable debug mode                                      |
288| `--cwd`           | `-c`  | Set current working directory                          |
289| `--prompt`        | `-p`  | Run a single prompt in non-interactive mode            |
290| `--output-format` | `-f`  | Output format for non-interactive mode (text, json)    |
291| `--quiet`         | `-q`  | Hide spinner in non-interactive mode                   |
292
293## Keyboard Shortcuts
294
295### Global Shortcuts
296
297| Shortcut | Action                                                  |
298| -------- | ------------------------------------------------------- |
299| `Ctrl+C` | Quit application                                        |
300| `Ctrl+?` | Toggle help dialog                                      |
301| `?`      | Toggle help dialog (when not in editing mode)           |
302| `Ctrl+L` | View logs                                               |
303| `Ctrl+A` | Switch session                                          |
304| `Ctrl+K` | Command dialog                                          |
305| `Ctrl+O` | Toggle model selection dialog                           |
306| `Esc`    | Close current overlay/dialog or return to previous mode |
307
308### Chat Page Shortcuts
309
310| Shortcut | Action                                  |
311| -------- | --------------------------------------- |
312| `Ctrl+N` | Create new session                      |
313| `Ctrl+X` | Cancel current operation/generation     |
314| `i`      | Focus editor (when not in writing mode) |
315| `Esc`    | Exit writing mode and focus messages    |
316
317### Editor Shortcuts
318
319| Shortcut            | Action                                    |
320| ------------------- | ----------------------------------------- |
321| `Ctrl+S`            | Send message (when editor is focused)     |
322| `Enter` or `Ctrl+S` | Send message (when editor is not focused) |
323| `Ctrl+E`            | Open external editor                      |
324| `Esc`               | Blur editor and focus messages            |
325
326### Session Dialog Shortcuts
327
328| Shortcut   | Action           |
329| ---------- | ---------------- |
330| `↑` or `k` | Previous session |
331| `↓` or `j` | Next session     |
332| `Enter`    | Select session   |
333| `Esc`      | Close dialog     |
334
335### Model Dialog Shortcuts
336
337| Shortcut   | Action            |
338| ---------- | ----------------- |
339| `↑` or `k` | Move up           |
340| `↓` or `j` | Move down         |
341| `←` or `h` | Previous provider |
342| `→` or `l` | Next provider     |
343| `Esc`      | Close dialog      |
344
345### Permission Dialog Shortcuts
346
347| Shortcut                | Action                       |
348| ----------------------- | ---------------------------- |
349| `←` or `left`           | Switch options left          |
350| `→` or `right` or `tab` | Switch options right         |
351| `Enter` or `space`      | Confirm selection            |
352| `a`                     | Allow permission             |
353| `A`                     | Allow permission for session |
354| `d`                     | Deny permission              |
355
356### Logs Page Shortcuts
357
358| Shortcut           | Action              |
359| ------------------ | ------------------- |
360| `Backspace` or `q` | Return to chat page |
361
362## AI Assistant Tools
363
364OpenCode's AI assistant has access to various tools to help with coding tasks:
365
366### File and Code Tools
367
368| Tool          | Description                 | Parameters                                                                               |
369| ------------- | --------------------------- | ---------------------------------------------------------------------------------------- |
370| `glob`        | Find files by pattern       | `pattern` (required), `path` (optional)                                                  |
371| `grep`        | Search file contents        | `pattern` (required), `path` (optional), `include` (optional), `literal_text` (optional) |
372| `ls`          | List directory contents     | `path` (optional), `ignore` (optional array of patterns)                                 |
373| `view`        | View file contents          | `file_path` (required), `offset` (optional), `limit` (optional)                          |
374| `write`       | Write to files              | `file_path` (required), `content` (required)                                             |
375| `edit`        | Edit files                  | Various parameters for file editing                                                      |
376| `patch`       | Apply patches to files      | `file_path` (required), `diff` (required)                                                |
377| `diagnostics` | Get diagnostics information | `file_path` (optional)                                                                   |
378
379### Other Tools
380
381| Tool          | Description                            | Parameters                                                                                |
382| ------------- | -------------------------------------- | ----------------------------------------------------------------------------------------- |
383| `bash`        | Execute shell commands                 | `command` (required), `timeout` (optional)                                                |
384| `fetch`       | Fetch data from URLs                   | `url` (required), `format` (required), `timeout` (optional)                               |
385| `sourcegraph` | Search code across public repositories | `query` (required), `count` (optional), `context_window` (optional), `timeout` (optional) |
386| `agent`       | Run sub-tasks with the AI agent        | `prompt` (required)                                                                       |
387
388## Architecture
389
390OpenCode is built with a modular architecture:
391
392- **cmd**: Command-line interface using Cobra
393- **internal/app**: Core application services
394- **internal/config**: Configuration management
395- **internal/db**: Database operations and migrations
396- **internal/llm**: LLM providers and tools integration
397- **internal/tui**: Terminal UI components and layouts
398- **internal/logging**: Logging infrastructure
399- **internal/message**: Message handling
400- **internal/session**: Session management
401- **internal/lsp**: Language Server Protocol integration
402
403## Custom Commands
404
405OpenCode supports custom commands that can be created by users to quickly send predefined prompts to the AI assistant.
406
407### Creating Custom Commands
408
409Custom commands are predefined prompts stored as Markdown files in one of three locations:
410
4111. **User Commands** (prefixed with `user:`):
412
413   ```
414   $XDG_CONFIG_HOME/opencode/commands/
415   ```
416
417   (typically `~/.config/opencode/commands/` on Linux/macOS)
418
419   or
420
421   ```
422   $HOME/.opencode/commands/
423   ```
424
4252. **Project Commands** (prefixed with `project:`):
426
427   ```
428   <PROJECT DIR>/.opencode/commands/
429   ```
430
431Each `.md` file in these directories becomes a custom command. The file name (without extension) becomes the command ID.
432
433For example, creating a file at `~/.config/opencode/commands/prime-context.md` with content:
434
435```markdown
436RUN git ls-files
437READ README.md
438```
439
440This creates a command called `user:prime-context`.
441
442### Command Arguments
443
444OpenCode 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).
445
446For example:
447
448```markdown
449# Fetch Context for Issue $ISSUE_NUMBER
450
451RUN gh issue view $ISSUE_NUMBER --json title,body,comments
452RUN git grep --author="$AUTHOR_NAME" -n .
453RUN grep -R "$SEARCH_PATTERN" $DIRECTORY
454```
455
456When you run a command with arguments, OpenCode will prompt you to enter values for each unique placeholder. Named arguments provide several benefits:
457
458- Clear identification of what each argument represents
459- Ability to use the same argument multiple times
460- Better organization for commands with multiple inputs
461
462### Organizing Commands
463
464You can organize commands in subdirectories:
465
466```
467~/.config/opencode/commands/git/commit.md
468```
469
470This creates a command with ID `user:git:commit`.
471
472### Using Custom Commands
473
4741. Press `Ctrl+K` to open the command dialog
4752. Select your custom command (prefixed with either `user:` or `project:`)
4763. Press Enter to execute the command
477
478The content of the command file will be sent as a message to the AI assistant.
479
480### Built-in Commands
481
482OpenCode includes several built-in commands:
483
484| Command            | Description                                                                                         |
485| ------------------ | --------------------------------------------------------------------------------------------------- |
486| Initialize Project | Creates or updates the OpenCode.md memory file with project-specific information                    |
487| Compact Session    | Manually triggers the summarization of the current session, creating a new session with the summary |
488
489## MCP (Model Context Protocol)
490
491OpenCode 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.
492
493### MCP Features
494
495- **External Tool Integration**: Connect to external tools and services via a standardized protocol
496- **Tool Discovery**: Automatically discover available tools from MCP servers
497- **Multiple Connection Types**:
498  - **Stdio**: Communicate with tools via standard input/output
499  - **SSE**: Communicate with tools via Server-Sent Events
500- **Security**: Permission system for controlling access to MCP tools
501
502### Configuring MCP Servers
503
504MCP servers are defined in the configuration file under the `mcpServers` section:
505
506```json
507{
508  "mcpServers": {
509    "example": {
510      "type": "stdio",
511      "command": "path/to/mcp-server",
512      "env": [],
513      "args": []
514    },
515    "web-example": {
516      "type": "sse",
517      "url": "https://example.com/mcp",
518      "headers": {
519        "Authorization": "Bearer token"
520      }
521    }
522  }
523}
524```
525
526### MCP Tool Usage
527
528Once 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.
529
530## LSP (Language Server Protocol)
531
532OpenCode integrates with Language Server Protocol to provide code intelligence features across multiple programming languages.
533
534### LSP Features
535
536- **Multi-language Support**: Connect to language servers for different programming languages
537- **Diagnostics**: Receive error checking and linting information
538- **File Watching**: Automatically notify language servers of file changes
539
540### Configuring LSP
541
542Language servers are configured in the configuration file under the `lsp` section:
543
544```json
545{
546  "lsp": {
547    "go": {
548      "disabled": false,
549      "command": "gopls"
550    },
551    "typescript": {
552      "disabled": false,
553      "command": "typescript-language-server",
554      "args": ["--stdio"]
555    }
556  }
557}
558```
559
560### LSP Integration with AI
561
562The AI assistant can access LSP features through the `diagnostics` tool, allowing it to:
563
564- Check for errors in your code
565- Suggest fixes based on diagnostics
566
567While the LSP client implementation supports the full LSP protocol (including completions, hover, definition, etc.), currently only diagnostics are exposed to the AI assistant.
568
569## Development
570
571### Prerequisites
572
573- Go 1.24.0 or higher
574
575### Building from Source
576
577```bash
578# Clone the repository
579git clone https://github.com/opencode-ai/opencode.git
580cd opencode
581
582# Build
583go build -o opencode
584
585# Run
586./opencode
587```
588
589## Acknowledgments
590
591OpenCode gratefully acknowledges the contributions and support from these key individuals:
592
593- [@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
594- [@adamdottv](https://github.com/adamdottv) - For the design direction and UI/UX architecture
595
596Special thanks to the broader open source community whose tools and libraries have made this project possible.
597
598## License
599
600OpenCode is licensed under the MIT License. See the [LICENSE](LICENSE) file for details.
601
602## Contributing
603
604Contributions are welcome! Here's how you can contribute:
605
6061. Fork the repository
6072. Create a feature branch (`git checkout -b feature/amazing-feature`)
6083. Commit your changes (`git commit -m 'Add some amazing feature'`)
6094. Push to the branch (`git push origin feature/amazing-feature`)
6105. Open a Pull Request
611
612Please make sure to update tests as appropriate and follow the existing code style.