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| `LOCAL_ENDPOINT` | For self-hosted models |
104| `SHELL` | Default shell to use (if not specified in config) |
105
106### Shell Configuration
107
108OpenCode 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.
109
110You can override this in your configuration file:
111
112```json
113{
114 "shell": {
115 "path": "/bin/zsh",
116 "args": ["-l"]
117 }
118}
119```
120
121This 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.
122
123### Configuration File Structure
124
125```json
126{
127 "data": {
128 "directory": ".opencode"
129 },
130 "providers": {
131 "openai": {
132 "apiKey": "your-api-key",
133 "disabled": false
134 },
135 "anthropic": {
136 "apiKey": "your-api-key",
137 "disabled": false
138 },
139 "groq": {
140 "apiKey": "your-api-key",
141 "disabled": false
142 },
143 "openrouter": {
144 "apiKey": "your-api-key",
145 "disabled": false
146 }
147 },
148 "agents": {
149 "coder": {
150 "model": "claude-3.7-sonnet",
151 "maxTokens": 5000
152 },
153 "task": {
154 "model": "claude-3.7-sonnet",
155 "maxTokens": 5000
156 },
157 "title": {
158 "model": "claude-3.7-sonnet",
159 "maxTokens": 80
160 }
161 },
162 "shell": {
163 "path": "/bin/bash",
164 "args": ["-l"]
165 },
166 "mcpServers": {
167 "example": {
168 "type": "stdio",
169 "command": "path/to/mcp-server",
170 "env": [],
171 "args": []
172 }
173 },
174 "lsp": {
175 "go": {
176 "disabled": false,
177 "command": "gopls"
178 }
179 },
180 "debug": false,
181 "debugLSP": false,
182 "autoCompact": true
183}
184```
185
186## Supported AI Models
187
188OpenCode supports a variety of AI models from different providers:
189
190### OpenAI
191
192- GPT-4.1 family (gpt-4.1, gpt-4.1-mini, gpt-4.1-nano)
193- GPT-4.5 Preview
194- GPT-4o family (gpt-4o, gpt-4o-mini)
195- O1 family (o1, o1-pro, o1-mini)
196- O3 family (o3, o3-mini)
197- O4 Mini
198
199### Anthropic
200
201- Claude 3.5 Sonnet
202- Claude 3.5 Haiku
203- Claude 3.7 Sonnet
204- Claude 3 Haiku
205- Claude 3 Opus
206
207### Google
208
209- Gemini 2.5
210- Gemini 2.5 Flash
211- Gemini 2.0 Flash
212- Gemini 2.0 Flash Lite
213
214### AWS Bedrock
215
216- Claude 3.7 Sonnet
217
218### Groq
219
220- Llama 4 Maverick (17b-128e-instruct)
221- Llama 4 Scout (17b-16e-instruct)
222- QWEN QWQ-32b
223- Deepseek R1 distill Llama 70b
224- Llama 3.3 70b Versatile
225
226### Azure OpenAI
227
228- GPT-4.1 family (gpt-4.1, gpt-4.1-mini, gpt-4.1-nano)
229- GPT-4.5 Preview
230- GPT-4o family (gpt-4o, gpt-4o-mini)
231- O1 family (o1, o1-mini)
232- O3 family (o3, o3-mini)
233- O4 Mini
234
235### Google Cloud VertexAI
236
237- Gemini 2.5
238- Gemini 2.5 Flash
239
240## Usage
241
242```bash
243# Start OpenCode
244opencode
245
246# Start with debug logging
247opencode -d
248
249# Start with a specific working directory
250opencode -c /path/to/project
251```
252
253## Non-interactive Prompt Mode
254
255You 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.
256
257```bash
258# Run a single prompt and print the AI's response to the terminal
259opencode -p "Explain the use of context in Go"
260
261# Get response in JSON format
262opencode -p "Explain the use of context in Go" -f json
263
264# Run without showing the spinner (useful for scripts)
265opencode -p "Explain the use of context in Go" -q
266```
267
268In this mode, OpenCode will process your prompt, print the result to standard output, and then exit. All permissions are auto-approved for the session.
269
270By 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.
271
272### Output Formats
273
274OpenCode supports the following output formats in non-interactive mode:
275
276| Format | Description |
277| ------ | -------------------------------------- |
278| `text` | Plain text output (default) |
279| `json` | Output wrapped in a JSON object |
280
281The output format is implemented as a strongly-typed `OutputFormat` in the codebase, ensuring type safety and validation when processing outputs.
282
283## Command-line Flags
284
285| Flag | Short | Description |
286| ----------------- | ----- | ------------------------------------------------------ |
287| `--help` | `-h` | Display help information |
288| `--debug` | `-d` | Enable debug mode |
289| `--cwd` | `-c` | Set current working directory |
290| `--prompt` | `-p` | Run a single prompt in non-interactive mode |
291| `--output-format` | `-f` | Output format for non-interactive mode (text, json) |
292| `--quiet` | `-q` | Hide spinner in non-interactive mode |
293
294## Keyboard Shortcuts
295
296### Global Shortcuts
297
298| Shortcut | Action |
299| -------- | ------------------------------------------------------- |
300| `Ctrl+C` | Quit application |
301| `Ctrl+?` | Toggle help dialog |
302| `?` | Toggle help dialog (when not in editing mode) |
303| `Ctrl+L` | View logs |
304| `Ctrl+A` | Switch session |
305| `Ctrl+K` | Command dialog |
306| `Ctrl+O` | Toggle model selection dialog |
307| `Esc` | Close current overlay/dialog or return to previous mode |
308
309### Chat Page Shortcuts
310
311| Shortcut | Action |
312| -------- | --------------------------------------- |
313| `Ctrl+N` | Create new session |
314| `Ctrl+X` | Cancel current operation/generation |
315| `i` | Focus editor (when not in writing mode) |
316| `Esc` | Exit writing mode and focus messages |
317
318### Editor Shortcuts
319
320| Shortcut | Action |
321| ------------------- | ----------------------------------------- |
322| `Ctrl+S` | Send message (when editor is focused) |
323| `Enter` or `Ctrl+S` | Send message (when editor is not focused) |
324| `Ctrl+E` | Open external editor |
325| `Esc` | Blur editor and focus messages |
326
327### Session Dialog Shortcuts
328
329| Shortcut | Action |
330| ---------- | ---------------- |
331| `↑` or `k` | Previous session |
332| `↓` or `j` | Next session |
333| `Enter` | Select session |
334| `Esc` | Close dialog |
335
336### Model Dialog Shortcuts
337
338| Shortcut | Action |
339| ---------- | ----------------- |
340| `↑` or `k` | Move up |
341| `↓` or `j` | Move down |
342| `←` or `h` | Previous provider |
343| `→` or `l` | Next provider |
344| `Esc` | Close dialog |
345
346### Permission Dialog Shortcuts
347
348| Shortcut | Action |
349| ----------------------- | ---------------------------- |
350| `←` or `left` | Switch options left |
351| `→` or `right` or `tab` | Switch options right |
352| `Enter` or `space` | Confirm selection |
353| `a` | Allow permission |
354| `A` | Allow permission for session |
355| `d` | Deny permission |
356
357### Logs Page Shortcuts
358
359| Shortcut | Action |
360| ------------------ | ------------------- |
361| `Backspace` or `q` | Return to chat page |
362
363## AI Assistant Tools
364
365OpenCode's AI assistant has access to various tools to help with coding tasks:
366
367### File and Code Tools
368
369| Tool | Description | Parameters |
370| ------------- | --------------------------- | ---------------------------------------------------------------------------------------- |
371| `glob` | Find files by pattern | `pattern` (required), `path` (optional) |
372| `grep` | Search file contents | `pattern` (required), `path` (optional), `include` (optional), `literal_text` (optional) |
373| `ls` | List directory contents | `path` (optional), `ignore` (optional array of patterns) |
374| `view` | View file contents | `file_path` (required), `offset` (optional), `limit` (optional) |
375| `write` | Write to files | `file_path` (required), `content` (required) |
376| `edit` | Edit files | Various parameters for file editing |
377| `patch` | Apply patches to files | `file_path` (required), `diff` (required) |
378| `diagnostics` | Get diagnostics information | `file_path` (optional) |
379
380### Other Tools
381
382| Tool | Description | Parameters |
383| ------------- | -------------------------------------- | ----------------------------------------------------------------------------------------- |
384| `bash` | Execute shell commands | `command` (required), `timeout` (optional) |
385| `fetch` | Fetch data from URLs | `url` (required), `format` (required), `timeout` (optional) |
386| `sourcegraph` | Search code across public repositories | `query` (required), `count` (optional), `context_window` (optional), `timeout` (optional) |
387| `agent` | Run sub-tasks with the AI agent | `prompt` (required) |
388
389## Architecture
390
391OpenCode is built with a modular architecture:
392
393- **cmd**: Command-line interface using Cobra
394- **internal/app**: Core application services
395- **internal/config**: Configuration management
396- **internal/db**: Database operations and migrations
397- **internal/llm**: LLM providers and tools integration
398- **internal/tui**: Terminal UI components and layouts
399- **internal/logging**: Logging infrastructure
400- **internal/message**: Message handling
401- **internal/session**: Session management
402- **internal/lsp**: Language Server Protocol integration
403
404## Custom Commands
405
406OpenCode supports custom commands that can be created by users to quickly send predefined prompts to the AI assistant.
407
408### Creating Custom Commands
409
410Custom commands are predefined prompts stored as Markdown files in one of three locations:
411
4121. **User Commands** (prefixed with `user:`):
413
414 ```
415 $XDG_CONFIG_HOME/opencode/commands/
416 ```
417
418 (typically `~/.config/opencode/commands/` on Linux/macOS)
419
420 or
421
422 ```
423 $HOME/.opencode/commands/
424 ```
425
4262. **Project Commands** (prefixed with `project:`):
427
428 ```
429 <PROJECT DIR>/.opencode/commands/
430 ```
431
432Each `.md` file in these directories becomes a custom command. The file name (without extension) becomes the command ID.
433
434For example, creating a file at `~/.config/opencode/commands/prime-context.md` with content:
435
436```markdown
437RUN git ls-files
438READ README.md
439```
440
441This creates a command called `user:prime-context`.
442
443### Command Arguments
444
445OpenCode 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).
446
447For example:
448
449```markdown
450# Fetch Context for Issue $ISSUE_NUMBER
451
452RUN gh issue view $ISSUE_NUMBER --json title,body,comments
453RUN git grep --author="$AUTHOR_NAME" -n .
454RUN grep -R "$SEARCH_PATTERN" $DIRECTORY
455```
456
457When you run a command with arguments, OpenCode will prompt you to enter values for each unique placeholder. Named arguments provide several benefits:
458
459- Clear identification of what each argument represents
460- Ability to use the same argument multiple times
461- Better organization for commands with multiple inputs
462
463### Organizing Commands
464
465You can organize commands in subdirectories:
466
467```
468~/.config/opencode/commands/git/commit.md
469```
470
471This creates a command with ID `user:git:commit`.
472
473### Using Custom Commands
474
4751. Press `Ctrl+K` to open the command dialog
4762. Select your custom command (prefixed with either `user:` or `project:`)
4773. Press Enter to execute the command
478
479The content of the command file will be sent as a message to the AI assistant.
480
481### Built-in Commands
482
483OpenCode includes several built-in commands:
484
485| Command | Description |
486| ------------------ | --------------------------------------------------------------------------------------------------- |
487| Initialize Project | Creates or updates the OpenCode.md memory file with project-specific information |
488| Compact Session | Manually triggers the summarization of the current session, creating a new session with the summary |
489
490## MCP (Model Context Protocol)
491
492OpenCode 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.
493
494### MCP Features
495
496- **External Tool Integration**: Connect to external tools and services via a standardized protocol
497- **Tool Discovery**: Automatically discover available tools from MCP servers
498- **Multiple Connection Types**:
499 - **Stdio**: Communicate with tools via standard input/output
500 - **SSE**: Communicate with tools via Server-Sent Events
501- **Security**: Permission system for controlling access to MCP tools
502
503### Configuring MCP Servers
504
505MCP servers are defined in the configuration file under the `mcpServers` section:
506
507```json
508{
509 "mcpServers": {
510 "example": {
511 "type": "stdio",
512 "command": "path/to/mcp-server",
513 "env": [],
514 "args": []
515 },
516 "web-example": {
517 "type": "sse",
518 "url": "https://example.com/mcp",
519 "headers": {
520 "Authorization": "Bearer token"
521 }
522 }
523 }
524}
525```
526
527### MCP Tool Usage
528
529Once 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.
530
531## LSP (Language Server Protocol)
532
533OpenCode integrates with Language Server Protocol to provide code intelligence features across multiple programming languages.
534
535### LSP Features
536
537- **Multi-language Support**: Connect to language servers for different programming languages
538- **Diagnostics**: Receive error checking and linting information
539- **File Watching**: Automatically notify language servers of file changes
540
541### Configuring LSP
542
543Language servers are configured in the configuration file under the `lsp` section:
544
545```json
546{
547 "lsp": {
548 "go": {
549 "disabled": false,
550 "command": "gopls"
551 },
552 "typescript": {
553 "disabled": false,
554 "command": "typescript-language-server",
555 "args": ["--stdio"]
556 }
557 }
558}
559```
560
561### LSP Integration with AI
562
563The AI assistant can access LSP features through the `diagnostics` tool, allowing it to:
564
565- Check for errors in your code
566- Suggest fixes based on diagnostics
567
568While the LSP client implementation supports the full LSP protocol (including completions, hover, definition, etc.), currently only diagnostics are exposed to the AI assistant.
569
570## Using a self-hosted model provider
571
572OpenCode can also load and use models from a self-hosted (OpenAI-like) provider.
573This is useful for developers who want to experiment with custom models.
574
575### Configuring a self-hosted provider
576
577You can use a self-hosted model by setting the `LOCAL_ENDPOINT` environment variable.
578This will cause OpenCode to load and use the models from the specified endpoint.
579
580```bash
581LOCAL_ENDPOINT=http://localhost:1235/v1
582```
583
584### Configuring a self-hosted model
585
586You can also configure a self-hosted model in the configuration file under the `agents` section:
587
588```json
589{
590 "agents": {
591 "coder": {
592 "model": "local.granite-3.3-2b-instruct@q8_0",
593 "reasoningEffort": "high"
594 }
595 }
596}
597```
598
599## Development
600
601### Prerequisites
602
603- Go 1.24.0 or higher
604
605### Building from Source
606
607```bash
608# Clone the repository
609git clone https://github.com/opencode-ai/opencode.git
610cd opencode
611
612# Build
613go build -o opencode
614
615# Run
616./opencode
617```
618
619## Acknowledgments
620
621OpenCode gratefully acknowledges the contributions and support from these key individuals:
622
623- [@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
624- [@adamdottv](https://github.com/adamdottv) - For the design direction and UI/UX architecture
625
626Special thanks to the broader open source community whose tools and libraries have made this project possible.
627
628## License
629
630OpenCode is licensed under the MIT License. See the [LICENSE](LICENSE) file for details.
631
632## Contributing
633
634Contributions are welcome! Here's how you can contribute:
635
6361. Fork the repository
6372. Create a feature branch (`git checkout -b feature/amazing-feature`)
6383. Commit your changes (`git commit -m 'Add some amazing feature'`)
6394. Push to the branch (`git push origin feature/amazing-feature`)
6405. Open a Pull Request
641
642Please make sure to update tests as appropriate and follow the existing code style.