### Start OpenCode with Options (Bash)
Source: https://github.com/opencode-ai/opencode/blob/main/README.md
Demonstrates basic command-line usage for starting OpenCode. Includes options for enabling debug logging and specifying a custom working directory for the project.
```bash
# Start OpenCode
opencode
# Start with debug logging
opencode -d
# Start with a specific working directory
opencode -c /path/to/project
```
--------------------------------
### Install OpenCode using Install Script
Source: https://github.com/opencode-ai/opencode/blob/main/README.md
This script installs the latest or a specific version of OpenCode using curl. It fetches the installation script and pipes it to bash for execution.
```bash
# Install the latest version
curl -fsSL https://raw.githubusercontent.com/opencode-ai/opencode/refs/heads/main/install | bash
# Install a specific version
curl -fsSL https://raw.githubusercontent.com/opencode-ai/opencode/refs/heads/main/install | VERSION=0.1.0 bash
```
--------------------------------
### Install OpenCode using Go
Source: https://github.com/opencode-ai/opencode/blob/main/README.md
Installs the latest version of OpenCode globally using the Go toolchain. Requires Go to be installed and configured on the system.
```bash
go install github.com/opencode-ai/opencode@latest
```
--------------------------------
### Example OpenCode Configuration
Source: https://github.com/opencode-ai/opencode/blob/main/cmd/schema/README.md
An example JSON configuration file for OpenCode. This configuration demonstrates various settings including data directory, debug mode, provider API keys, and agent configurations with model and token limits. It adheres to the generated JSON Schema.
```json
{
"data": {
"directory": ".opencode"
},
"debug": false,
"providers": {
"anthropic": {
"apiKey": "your-api-key"
}
},
"agents": {
"coder": {
"model": "claude-3.7-sonnet",
"maxTokens": 5000,
"reasoningEffort": "medium"
},
"task": {
"model": "claude-3.7-sonnet",
"maxTokens": 5000
},
"title": {
"model": "claude-3.7-sonnet",
"maxTokens": 80
}
}
}
```
--------------------------------
### Example Custom Command Creation
Source: https://github.com/opencode-ai/opencode/blob/main/README.md
This example demonstrates how to create a custom command named `user:prime-context`. By creating a Markdown file at `~/.config/opencode/commands/prime-context.md` with specific content, users can define a new command that executes predefined `RUN` and `READ` operations.
```markdown
For example, creating a file at `~/.config/opencode/commands/prime-context.md` with content:
```markdown
RUN git ls-files
READ README.md
```
This creates a command called `user:prime-context`.
```
--------------------------------
### Install OpenCode using Homebrew
Source: https://github.com/opencode-ai/opencode/blob/main/README.md
Installs OpenCode on macOS and Linux systems using the Homebrew package manager. This command adds the OpenCode tap and installs the package.
```bash
brew install opencode-ai/tap/opencode
```
--------------------------------
### Install OpenCode using AUR
Source: https://github.com/opencode-ai/opencode/blob/main/README.md
Installs OpenCode on Arch Linux systems using an AUR helper like yay or paru. This command uses the AUR to install the pre-compiled binary.
```bash
# Using yay
yay -S opencode-ai-bin
# Using paru
paru -S opencode-ai-bin
```
--------------------------------
### Get Code Diagnostics from Language Servers (Go)
Source: https://context7.com/opencode-ai/opencode/llms.txt
The Diagnostics tool retrieves code analysis results such as errors, warnings, and hints from language servers. It requires configured LSP clients. You can get diagnostics for a specific 'file_path' or for all files by providing an empty string for 'file_path'. The output includes line numbers and diagnostic messages.
```go
package example
import (
"context"
"encoding/json"
"fmt"
"github.com/opencode-ai/opencode/internal/llm/tools"
"github.com/opencode-ai/opencode/internal/lsp"
)
func getCodeDiagnostics(ctx context.Context, lspClients map[string]*lsp.Client) error {
// Create diagnostics tool
diagnosticsTool := tools.NewDiagnosticsTool(lspClients)
// Get diagnostics for specific file
params := map[string]string{
"file_path": "internal/app/app.go",
}
paramsJSON, _ := json.Marshal(params)
result, err := diagnosticsTool.Run(ctx, tools.ToolCall{
ID: "diag-1",
Name: "diagnostics",
Input: string(paramsJSON),
})
if err != nil {
return fmt.Errorf("diagnostics failed: %w", err)
}
fmt.Println(result.Content)
// Output:
// File: internal/app/app.go
// Line 42: Error: undefined: invalidFunc
// Line 58: Warning: unused variable 'result'
// Line 103: Hint: this value is never used
// Get all workspace diagnostics
allParams := map[string]string{
"file_path": "", // empty means all files
}
// Diagnostics include:
// - Syntax errors
// - Type errors
// - Unused variables
// - Import issues
// - Code style suggestions
// - Language-specific hints
// Requires LSP servers configured in .opencode.json:
// {
// "lsp": {
// "go": {
// "command": "gopls",
// "disabled": false
// },
// "typescript": {
// "command": "typescript-language-server",
// "args": ["--stdio"],
// "disabled": false
// }
// }
// }
return nil
}
```
--------------------------------
### Configure MCP Servers in JSON
Source: https://github.com/opencode-ai/opencode/blob/main/README.md
Defines how to configure MCP (Model Context Protocol) servers in the OpenCode configuration file. It shows examples for both 'stdio' and 'sse' connection types, specifying commands, URLs, and headers.
```json
{
"mcpServers": {
"example": {
"type": "stdio",
"command": "path/to/mcp-server",
"env": [],
"args": []
},
"web-example": {
"type": "sse",
"url": "https://example.com/mcp",
"headers": {
"Authorization": "Bearer token"
}
}
}
}
```
--------------------------------
### Custom Command with Named Arguments
Source: https://github.com/opencode-ai/opencode/blob/main/README.md
This example shows how to define custom commands with named arguments using the `$NAME` format. These arguments allow for dynamic input when running a command, improving flexibility and reusability. Placeholders like `$ISSUE_NUMBER`, `$AUTHOR_NAME`, and `$SEARCH_PATTERN` are used here.
```markdown
```markdown
# Fetch Context for Issue $ISSUE_NUMBER
RUN gh issue view $ISSUE_NUMBER --json title,body,comments
RUN git grep --author="$AUTHOR_NAME" -n .
RUN grep -R "$SEARCH_PATTERN" $DIRECTORY
```
```
--------------------------------
### Organizing Custom Commands in Subdirectories
Source: https://github.com/opencode-ai/opencode/blob/main/README.md
This example illustrates how to organize custom commands into subdirectories within the designated command directories. Creating a file like `~/.config/opencode/commands/git/commit.md` results in a command ID `user:git:commit`, allowing for hierarchical organization.
```markdown
You can organize commands in subdirectories:
```
~/.config/opencode/commands/git/commit.md
```
This creates a command with ID `user:git:commit`.
```
--------------------------------
### Initialize OpenCode Application Services (Go)
Source: https://context7.com/opencode-ai/opencode/llms.txt
The setupApplication function demonstrates how to initialize the core services for the OpenCode application. This includes loading configuration, establishing a database connection (which also runs migrations), and creating the main application instance with its various components like session management, message handling, file history, permissions, and the CoderAgent with integrated tools. The function ensures proper shutdown of the application services.
```go
package example
import (
"context"
"database/sql"
"fmt"
"github.com/opencode-ai/opencode/internal/app"
"github.com/opencode-ai/opencode/internal/config"
"github.com/opencode-ai/opencode/internal/db"
)
func setupApplication(ctx context.Context) error {
// Set working directory and load configuration
config.Load("/path/to/project", false)
// Connect to database (runs migrations automatically)
conn, err := db.Connect()
if err != nil {
return fmt.Errorf("database connection failed: %w", err)
}
// Create application with all services initialized
application, err := app.New(ctx, conn)
if err != nil {
return fmt.Errorf("failed to create app: %w", err)
}
defer application.Shutdown()
// Application now has:
// - application.Sessions: session management service
// - application.Messages: message handling service
// - application.History: file change tracking
// - application.Permissions: permission control
// - application.CoderAgent: AI agent with tools
// - application.LSPClients: language server clients
fmt.Println("Application initialized successfully")
return nil
}
```
--------------------------------
### Configure and Load MCP Tools in Go
Source: https://context7.com/opencode-ai/opencode/llms.txt
This Go code snippet demonstrates how to configure and load Model Context Protocol (MCP) tools within OpenCode. It shows how MCP servers, defined in a configuration file (e.g., .opencode.json), can be set up for stdio or SSE connections. The function `agent.GetMcpTools` loads these tools, making them available to the agent alongside built-in tools, each requiring permission approval and supporting arbitrary parameters.
```go
package example
import (
"context"
"fmt"
"github.com/opencode-ai/opencode/internal/config"
"github.com/opencode-ai/opencode/internal/llm/agent"
"github.com/opencode-ai/opencode/internal/permission"
)
func setupMCPTools(ctx context.Context, permService permission.Service) {
// Configure MCP servers in .opencode.json:
cfg := config.Get()
// Stdio MCP server example:
// {
// "mcpServers": {
// "database": {
// "type": "stdio",
// "command": "/usr/local/bin/mcp-database-server",
// "args": ["--db", "postgresql://localhost/mydb"],
// "env": ["DB_USER=admin"]
// }
// }
// }
// SSE MCP server example:
// {
// "mcpServers": {
// "api-gateway": {
// "type": "sse",
// "url": "https://api.example.com/mcp",
// "headers": {
// "Authorization": "Bearer token",
// "X-API-Key": "key123"
// }
// }
// }
// }
// Load MCP tools automatically
mcpTools := agent.GetMcpTools(ctx, permService)
fmt.Printf("Loaded %d MCP tools\n", len(mcpTools))
// MCP tools are then available to the agent alongside built-in tools
// Each MCP tool:
// - Appears in tool list with name and description
// - Requires permission approval like native tools
// - Supports arbitrary parameters defined by the server
// - Returns text or structured responses
// Use case examples:
// - Database query tool
// - API integration tool
// - Custom code analysis tool
// - External service connector
// - Proprietary tool integration
}
```
--------------------------------
### Go: Load and Validate Application Configuration
Source: https://context7.com/opencode-ai/opencode/llms.txt
Loads application settings from environment variables and JSON files (global and local). It validates AI model configurations and manages API keys for multiple providers. Dependencies include the 'github.com/opencode-ai/opencode/internal/config' and 'github.com/opencode-ai/opencode/internal/llm/models' packages. Input is typically a project path and a debug flag, with output being a configuration object or an error.
```go
package example
import (
"fmt"
"os"
"github.com/opencode-ai/opencode/internal/config"
"github.com/opencode-ai/opencode/internal/llm/models"
)
func configureOpenCode() error {
// Set API keys via environment
os.Setenv("ANTHROPIC_API_KEY", "sk-ant-...")
os.Setenv("OPENAI_API_KEY", "sk-...")
// Load configuration from:
// 1. $HOME/.opencode.json
// 2. $XDG_CONFIG_HOME/opencode/.opencode.json
// 3. ./.opencode.json (project-specific)
cfg, err := config.Load("/path/to/project", true) // debug=true
if err != nil {
return fmt.Errorf("config load failed: %w", err)
}
// Configuration structure:
// {
// "data": {"directory": ".opencode"},
// "providers": {
// "anthropic": {"apiKey": "...", "disabled": false},
// "openai": {"apiKey": "...", "disabled": false}
// },
// "agents": {
// "coder": {"model": "claude-4-sonnet", "maxTokens": 5000},
// "title": {"model": "claude-4-sonnet", "maxTokens": 80}
// },
// "lsp": {
// "go": {"command": "gopls", "disabled": false}
// },
// "shell": {"path": "/bin/bash", "args": ["-l"]},
// "autoCompact": true
// }
// Access configuration
fmt.Printf("Data directory: %s\n", cfg.Data.Directory)
fmt.Printf("Working directory: %s\n", config.WorkingDirectory())
// Update agent model programmatically
err = config.UpdateAgentModel(config.AgentCoder, models.GPT41)
if err != nil {
return fmt.Errorf("failed to update model: %w", err)
}
return nil
}
```
--------------------------------
### Build and Run OpenCode from Source (Bash)
Source: https://github.com/opencode-ai/opencode/blob/main/README.md
Provides instructions for building OpenCode from its source code using Go. It includes commands to clone the repository, build the executable, and then run the compiled program.
```bash
# Clone the repository
git clone https://github.com/opencode-ai/opencode.git
cd opencode
# Build
go build -o opencode
# Run
./opencode
```
--------------------------------
### Create or Overwrite Files with Permission Control (Go)
Source: https://context7.com/opencode-ai/opencode/llms.txt
The Write Tool enables agents to create new files or completely replace existing ones, enforcing permission checks before writing. It integrates with permission and history services to manage access and track changes. Session and message context are added for auditing.
```go
package example
import (
"context"
"encoding/json"
"fmt"
"github.com/opencode-ai/opencode/internal/llm/tools"
"github.com/opencode-ai/opencode/internal/permission"
"github.com/opencode-ai/opencode/internal/history"
)
func writeProjectFiles(ctx context.Context,
permService permission.Service,
historyService history.Service) error {
// Create write tool
writeTool := tools.NewWriteTool(permService, historyService)
// Add session context
ctx = context.WithValue(ctx, tools.SessionIDContextKey, "session-123")
ctx = context.WithValue(ctx, tools.MessageIDContextKey, "msg-456")
// Write new file
content := `package main
import "fmt"
func main() {
fmt.Println("Hello, OpenCode!")
}
`
params := map[string]string{
"file_path": "hello.go",
"content": content,
}
paramsJSON, _ := json.Marshal(params)
result, err := writeTool.Run(ctx, tools.ToolCall{
ID: "write-1",
Name: "write",
Input: string(paramsJSON),
})
if err != nil {
// Permission denied error
if err == permission.ErrorPermissionDenied {
fmt.Println("User denied permission to write file")
return nil
}
return fmt.Errorf("write failed: %w", err)
}
if result.IsError {
fmt.Printf("Write error: %s\n", result.Content)
return nil
}
fmt.Println("File written successfully")
// File is tracked in history service for change tracking
return nil
}
```
--------------------------------
### Manage Permissions with Go
Source: https://context7.com/opencode-ai/opencode/llms.txt
The Go code demonstrates how to use the permission service to request authorization for operations, manage session-wide auto-approval, and subscribe to permission events. It handles both file write and bash command execution requests, with clear states for pending, approved, denied, and auto-approved permissions.
```go
package example
import (
"context"
"fmt"
"github.com/opencode-ai/opencode/internal/permission"
)
func managePermissions() {
// Create permission service
permService := permission.NewPermissionService()
// Request permission for file write
approved := permService.Request(permission.CreatePermissionRequest{
SessionID: "session-123",
Path: "/path/to/file.go",
ToolName: "write",
Action: "create",
Description: "Create new API handler",
Params: map[string]interface{}{
"file_path": "handlers/api.go",
"content": "package handlers...",
},
})
if !approved {
fmt.Println("User denied permission")
return
}
// Request permission for bash command
bashApproved := permService.Request(permission.CreatePermissionRequest{
SessionID: "session-123",
Path: "/project/root",
ToolName: "bash",
Action: "execute",
Description: "Execute command: git commit -am 'Add feature'",
Params: map[string]interface{}{
"command": "git commit -am 'Add feature'",
},
})
// Auto-approve all requests for a session
// Used in non-interactive mode
permService.AutoApproveSession("session-456")
// Subscribe to permission events
ctx := context.Background()
eventChan := permService.Subscribe(ctx)
go func() {
for event := range eventChan {
switch event.Type {
case permission.PermissionRequestedEvent:
fmt.Printf("Permission requested: %s\n", event.Data.Description)
case permission.PermissionGrantedEvent:
fmt.Printf("Permission granted: %s\n", event.Data.Description)
case permission.PermissionDeniedEvent:
fmt.Printf("Permission denied: %s\n", event.Data.Description)
}
}
}()
// Permission states:
// - Pending: waiting for user response
// - Approved: user granted permission
// - Denied: user rejected permission
// - Auto: session has auto-approval enabled
}
```
--------------------------------
### Other Tools Overview
Source: https://github.com/opencode-ai/opencode/blob/main/README.md
This section lists additional tools provided by OpenCode, including utilities for executing shell commands, fetching data from URLs, searching code repositories, and interacting with an AI agent. Each tool's description and parameters are provided.
```markdown
| Tool | Description | Parameters |
| ------------- | -------------------------------------- | ----------------------------------------------------------------------------------------- |
| `bash` | Execute shell commands | `command` (required), `timeout` (optional) |
| `fetch` | Fetch data from URLs | `url` (required), `format` (required), `timeout` (optional) |
| `sourcegraph` | Search code across public repositories | `query` (required), `count` (optional), `context_window` (optional), `timeout` (optional) |
| `agent` | Run sub-tasks with the AI agent | `prompt` (required) |
```
--------------------------------
### Execute OpenCode CLI Command (Go)
Source: https://context7.com/opencode-ai/opencode/llms.txt
The main function serves as the entry point for the OpenCode CLI application. It handles command execution, supporting various flags for interactive mode, non-interactive prompts with output formatting, debugging, and specifying the working directory. Errors during execution are caught and reported to standard error.
```go
package main
import (
"fmt"
"os"
"github.com/opencode-ai/opencode/cmd"
)
func main() {
// Execute the root command
// Supports flags: -d (debug), -c
(working directory),
// -p (non-interactive), -f (output format),
// -q (quiet mode), -h (help), -v (version)
if err := cmd.Execute(); err != nil {
fmt.Fprintf(os.Stderr, "Error: %v\n", err)
os.Exit(1)
}
}
// Example: Run in interactive mode
// $ opencode
// Example: Run non-interactive prompt with JSON output
// $ opencode -p "Explain the use of context in Go" -f json
// Example: Run with debug mode in specific directory
// $ opencode -d -c /path/to/project
// Expected output in non-interactive mode:
// {
// "content": "In Go, context is a package that provides...",
// "format": "json"
// }
```
--------------------------------
### Summarize Conversations with Go
Source: https://context7.com/opencode-ai/opencode/llms.txt
This Go code illustrates how to utilize the agent service for summarizing long conversations to prevent token limit issues. It covers manual summarization triggers, listening for summarization events with progress updates, and explains the auto-compact feature's behavior and configuration.
```go
package example
import (
"context"
"fmt"
"github.com/opencode-ai/opencode/internal/llm/agent"
)
func summarizeConversation(ctx context.Context, agentService agent.Service) error {
sessionID := "session-123"
// Manual summarization trigger
err := agentService.Summarize(ctx, sessionID)
if err != nil {
if err == agent.ErrSessionBusy {
return fmt.Errorf("session is busy, cannot summarize now")
}
return fmt.Errorf("summarization failed: %w", err)
}
// Listen for summarization events
eventChan := agentService.Subscribe(ctx)
for event := range eventChan {
if event.Type == agent.AgentEventTypeSummarize {
fmt.Printf("Progress: %s\n", event.Progress)
// Progress updates:
// - "Starting summarization..."
// - "Analyzing conversation..."
// - "Generating summary..."
// - "Creating new session..."
// - "Summary complete"
if event.Done {
fmt.Printf("Summary saved to session: %s\n", event.SessionID)
break
}
}
if event.Type == agent.AgentEventTypeError {
return fmt.Errorf("summarization error: %w", event.Error)
}
}
// Auto-compact feature (enabled by default):
// - Monitors token usage during conversation
// - Triggers at 95% of model's context window
// - Creates summary message in original session
// - Preserves conversation continuity
// - Includes cost tracking
// Configure in .opencode.json:
// {
// "autoCompact": true
// }
return nil
}
```
--------------------------------
### Manage Conversation Sessions with Token Tracking (Go)
Source: https://context7.com/opencode-ai/opencode/llms.txt
Demonstrates how to create, retrieve, update, and delete conversation sessions using the session service. It includes tracking prompt tokens, completion tokens, and cost. This function requires a database querier to interact with the session data.
```go
package example
import (
"context"
"fmt"
"github.com/opencode-ai/opencode/internal/session"
"github.com/opencode-ai/opencode/internal/db"
)
func manageConversationSessions(ctx context.Context, q db.Querier) error {
// Create session service
sessionService := session.NewService(q)
// Create a new session
newSession, err := sessionService.Create(ctx, "Code Review Session")
if err != nil {
return fmt.Errorf("session creation failed: %w", err)
}
fmt.Printf("Created session: %s\n", newSession.ID)
// Get session by ID
retrievedSession, err := sessionService.Get(ctx, newSession.ID)
if err != nil {
return fmt.Errorf("session retrieval failed: %w", err)
}
// Update session with usage data
retrievedSession.Title = "Updated Code Review"
retrievedSession.PromptTokens = 15000
retrievedSession.CompletionTokens = 3000
retrievedSession.Cost = 0.0234
updatedSession, err := sessionService.Save(ctx, retrievedSession)
if err != nil {
return fmt.Errorf("session save failed: %w", err)
}
fmt.Printf("Session cost: $%.4f\n", updatedSession.Cost)
// List all sessions
sessions, err := sessionService.List(ctx)
if err != nil {
return fmt.Errorf("session list failed: %w", err)
}
for _, s := range sessions {
fmt.Printf("Session: %s (tokens: %d in, %d out)\n",
s.Title, s.PromptTokens, s.CompletionTokens)
}
// Delete session
err = sessionService.Delete(ctx, newSession.ID)
if err != nil {
return fmt.Errorf("session deletion failed: %w", err)
}
return nil
}
```
--------------------------------
### Configure LSP Language Servers in JSON
Source: https://github.com/opencode-ai/opencode/blob/main/README.md
Illustrates the configuration of LSP (Language Server Protocol) clients within OpenCode. It demonstrates how to enable or disable specific language servers like Go and TypeScript, and specify their commands and arguments.
```json
{
"lsp": {
"go": {
"disabled": false,
"command": "gopls"
},
"typescript": {
"disabled": false,
"command": "typescript-language-server",
"args": ["--stdio"]
}
}
}
```
--------------------------------
### Go: Run AI Agent with Conversation Context
Source: https://context7.com/opencode-ai/opencode/llms.txt
Manages AI interactions, including message streaming, tool execution, and conversation history. Supports multiple AI providers. Dependencies include 'github.com/opencode-ai/opencode/internal/llm/agent' and 'github.com/opencode-ai/opencode/internal/message'. Takes a context, agent service, and session ID as input, and outputs agent events or an error. Can be used to run agents, process responses, handle errors, and manage summarization progress.
```go
package example
import (
"context"
"fmt"
"github.com/opencode-ai/opencode/internal/llm/agent"
"github.com/opencode-ai/opencode/internal/message"
)
func interactWithAgent(ctx context.Context, agentService agent.Service, sessionID string) error {
// Check if session is busy
if agentService.IsSessionBusy(sessionID) {
return fmt.Errorf("session is currently processing another request")
}
// Run agent with prompt and optional attachments
prompt := "Analyze the main.go file and suggest improvements"
attachments := []message.Attachment{
{
FilePath: "screenshot.png",
MimeType: "image/png",
Content: []byte{/* image data */},
},
}
events, err := agentService.Run(ctx, sessionID, prompt, attachments...)
if err != nil {
return fmt.Errorf("agent run failed: %w", err)
}
// Process agent events
for event := range events {
switch event.Type {
case agent.AgentEventTypeResponse:
// Agent completed successfully
fmt.Printf("Response: %s\n", event.Message.Content())
fmt.Printf("Finish reason: %s\n", event.Message.FinishReason())
case agent.AgentEventTypeError:
// An error occurred
return fmt.Errorf("agent error: %w", event.Error)
case agent.AgentEventTypeSummarize:
// Summarization progress
fmt.Printf("Summary progress: %s\n", event.Progress)
if event.Done {
fmt.Printf("New session created: %s\n", event.SessionID)
}
}
}
// Cancel agent if needed
// agentService.Cancel(sessionID)
return nil
}
```
--------------------------------
### Execute Shell Commands with Bash Tool (Go)
Source: https://context7.com/opencode-ai/opencode/llms.txt
Illustrates how to use the bash tool to execute shell commands, featuring security controls like permission checks and command filtering. It maintains persistent shell state across multiple command executions. This function requires a permission service to enforce access controls.
```go
package example
import (
"context"
"encoding/json"
"fmt"
"github.com/opencode-ai/opencode/internal/llm/tools"
"github.com/opencode-ai/opencode/internal/permission"
)
func executeBashCommands(ctx context.Context, permService permission.Service) error {
// Create bash tool
bashTool := tools.NewBashTool(permService)
// Tool info shows capabilities
info := bashTool.Info()
fmt.Printf("Tool: %s\n", info.Name) // "bash"
// Execute a simple command
params := tools.BashParams{
Command: "ls -la",
Timeout: 30000, // 30 seconds in milliseconds
}
paramsJSON, _ := json.Marshal(params)
// Add session context for permission checking
ctx = context.WithValue(ctx, tools.SessionIDContextKey, "session-123")
ctx = context.WithValue(ctx, tools.MessageIDContextKey, "msg-456")
result, err := bashTool.Run(ctx, tools.ToolCall{
ID: "call-1",
Name: "bash",
Input: string(paramsJSON),
})
if err != nil {
return fmt.Errorf("bash execution failed: %w", err)
}
if result.IsError {
fmt.Printf("Command failed: %s\n", result.Content)
return nil
}
fmt.Printf("Command output:\n%s\n", result.Content)
// Shell state persists across commands
// Environment variables, current directory, etc. remain
gitCommitParams := tools.BashParams{
Command: `git commit -m $(cat <<'EOF'
Add new feature
🤖 Generated with opencode
Co-Authored-By: opencode
EOF
)`,
Timeout: 60000,
}
// Banned commands will be rejected: curl, wget, nc, telnet, etc.
// Safe read-only commands don't require permissions: ls, git status, etc.
return nil
}
```
--------------------------------
### Find Files with Glob Patterns (Go)
Source: https://context7.com/opencode-ai/opencode/llms.txt
The Glob tool allows finding files based on glob patterns across the project. It takes a 'pattern' as input, supporting wildcards like '*', '**', '?', '{}', and '[]'. It can also accept an optional 'path' to limit the search scope. The output is a list of matching file paths.
```go
package example
import (
"context"
"encoding/json"
"fmt"
"github.com/opencode-ai/opencode/internal/llm/tools"
)
func findProjectFiles(ctx context.Context) error {
// Create glob tool
globTool := tools.NewGlobTool()
// Find all Go test files
params := map[string]string{
"pattern": "**/*_test.go",
}
paramsJSON, _ := json.Marshal(params)
result, err := globTool.Run(ctx, tools.ToolCall{
ID: "glob-1",
Name: "glob",
Input: string(paramsJSON),
})
if err != nil {
return fmt.Errorf("glob failed: %w", err)
}
fmt.Println(result.Content)
// Output: List of all test files
// internal/app/app_test.go
// internal/config/config_test.go
// internal/llm/tools/ls_test.go
// Find configuration files
configParams := map[string]string{
"pattern": "**/*.{json,yaml,yml,toml}",
"path": "./config",
}
// Find markdown documentation
docsParams := map[string]string{
"pattern": "**/*.md",
}
// Find source files in specific directory
internalParams := map[string]string{
"pattern": "internal/**/*.go",
}
// Patterns supported:
// - * matches any characters within a path segment
// - ** matches zero or more directories
// - ? matches a single character
// - {a,b,c} matches any of the alternatives
// - [abc] matches any character in the set
return nil
}
```
--------------------------------
### List Directory Contents (Go)
Source: https://context7.com/opencode-ai/opencode/llms.txt
The LS tool provides detailed directory listings, including file name, type, size, and modification time. It supports filtering with ignore patterns and recursive tree views. It can accept a 'path' for the directory to list and an optional 'ignore' list of glob patterns. It respects .gitignore files automatically.
```go
package example
import (
"context"
"encoding/json"
"fmt"
"github.com/opencode-ai/opencode/internal/llm/tools"
)
func listDirectoryContents(ctx context.Context) error {
// Create ls tool
lsTool := tools.NewLSTool()
// List current directory
params := map[string]interface{}{
"path": ".",
}
paramsJSON, _ := json.Marshal(params)
result, err := lsTool.Run(ctx, tools.ToolCall{
ID: "ls-1",
Name: "ls",
Input: string(paramsJSON),
})
if err != nil {
return fmt.Errorf("ls failed: %w", err)
}
fmt.Println(result.Content)
// Output:
// Name Type Size Modified
// cmd/ dir 4096 2024-01-15 10:30:00
// go.mod file 6179 2024-01-15 09:15:00
// main.go file 270 2024-01-15 08:00:00
// README.md file 24456 2024-01-14 16:45:00
// List with ignore patterns
filteredParams := map[string]interface{}{
"path": "./internal",
"ignore": []string{"*_test.go", "*.md"},
}
// List specific directory
dirParams := map[string]interface{}{
"path": "./internal/llm/tools",
}
// Features:
// - Shows file name, type, size, and modification time
// - Respects .gitignore patterns automatically
// - Custom ignore patterns with glob syntax
// - Works with both relative and absolute paths
// - Handles permission errors gracefully
return nil
}
```
--------------------------------
### File and Code Tools Overview
Source: https://github.com/opencode-ai/opencode/blob/main/README.md
This section describes the available tools for interacting with files and code. Each tool has a specific function, such as finding files, searching content, listing directories, viewing, writing, editing, patching files, or retrieving diagnostics. Parameters for each tool are also specified.
```markdown
| Tool | Description | Parameters |
| ------------- | --------------------------- | ---------------------------------------------------------------------------------------- |
| `glob` | Find files by pattern | `pattern` (required), `path` (optional) |
| `grep` | Search file contents | `pattern` (required), `path` (optional), `include` (optional), `literal_text` (optional) |
| `ls` | List directory contents | `path` (optional), `ignore` (optional array of patterns) |
| `view` | View file contents | `file_path` (required), `offset` (optional), `limit` (optional) |
| `write` | Write to files | `file_path` (required), `content` (required) |
| `edit` | Edit files | Various parameters for file editing |
| `patch` | Apply patches to files | `file_path` (required), `diff` (required) |
| `diagnostics` | Get diagnostics information | `file_path` (optional) |
```
--------------------------------
### OpenCode Architecture Overview
Source: https://github.com/opencode-ai/opencode/blob/main/README.md
This section outlines the modular architecture of the OpenCode project. It lists the key internal packages and their responsibilities, such as command-line interface (cmd), core application services (internal/app), configuration management (internal/config), and LLM integration (internal/llm).
```markdown
- **cmd**: Command-line interface using Cobra
- **internal/app**: Core application services
- **internal/config**: Configuration management
- **internal/db**: Database operations and migrations
- **internal/llm**: LLM providers and tools integration
- **internal/tui**: Terminal UI components and layouts
- **internal/logging**: Logging infrastructure
- **internal/message**: Message handling
- **internal/session**: Session management
- **internal/lsp**: Language Server Protocol integration
```
--------------------------------
### Grep Tool: Search Codebase with Ripgrep Performance
Source: https://context7.com/opencode-ai/opencode/llms.txt
The Grep tool enables high-speed code searching across the project using ripgrep. It supports basic text matching, advanced regex patterns, file filtering with glob patterns, and options to display line numbers and context lines before and after matches.
```go
package example
import (
"context"
"encoding/json"
"fmt"
"github.com/opencode-ai/opencode/internal/llm/tools"
)
func searchCodebase(ctx context.Context) error {
// Create grep tool
grepTool := tools.NewGrepTool()
// Basic text search
params := map[string]interface{}{
"pattern": "func main",
}
paramsJSON, _ := json.Marshal(params)
result, err := grepTool.Run(ctx, tools.ToolCall{
ID: "grep-1",
Name: "grep",
Input: string(paramsJSON),
})
if err != nil {
return fmt.Errorf("grep failed: %w", err)
}
fmt.Println(result.Content)
// Output: List of files containing "func main"
// Advanced search with context lines
advancedParams := map[string]interface{}{
"pattern": `error.*handler`,
"path": "./internal",
"include": "*.go",
"case_insensitive": true,
"line_numbers": true,
"context_before": 2,
"context_after": 2,
}
// Regex patterns
regexParams := map[string]interface{}{
"pattern": `^\s*type\s+(\w+)\s+struct`,
"include": "*.go",
}
// Literal string search (no regex)
literalParams := map[string]interface{}{
"pattern": "fmt.Printf(",
"literal_text": true,
}
// Features:
// - Uses ripgrep for fast searching
// - Supports glob patterns for file filtering
// - Can search specific directories or entire project
// - Shows context lines around matches
// - Case-sensitive or case-insensitive search
return nil
}
```
--------------------------------
### Read File Contents with Line Numbers and Diagnostics (Go)
Source: https://context7.com/opencode-ai/opencode/llms.txt
The View Tool reads text files, displaying content with line numbering and optional offset/limit parameters for large files. It integrates with LSP to provide diagnostics, such as identifying code issues. Files over 250KB are rejected, and lines over 2000 characters are truncated.
```go
package example
import (
"context"
"encoding/json"
"fmt"
"github.com/opencode-ai/opencode/internal/llm/tools"
"github.com/opencode-ai/opencode/internal/lsp"
)
func readProjectFiles(ctx context.Context, lspClients map[string]*lsp.Client) error {
// Create view tool with LSP integration
viewTool := tools.NewViewTool(lspClients)
// Read entire file
params := tools.ViewParams{
FilePath: "main.go",
Offset: 0,
Limit: 2000, // default limit
}
paramsJSON, _ := json.Marshal(params)
result, err := viewTool.Run(ctx, tools.ToolCall{
ID: "view-1",
Name: "view",
Input: string(paramsJSON),
})
if err != nil {
return fmt.Errorf("view failed: %w", err)
}
fmt.Println(result.Content)
// Output format:
//
// 1|package main
// 2|
// 3|import (
// 4| "fmt"
// 5|)
// 6|
// 7|func main() {
// 8| fmt.Println("Hello")
// 9|}
//
// Diagnostics: [No LSP issues found]
// Read specific section of large file
partialParams := tools.ViewParams{
FilePath: "large_file.go",
Offset: 500, // Start at line 501
Limit: 100, // Read 100 lines
}
// Features:
// - Files over 250KB are rejected
// - Lines over 2000 chars are truncated
// - Suggests similar filenames if file not found
// - Detects and reports image files
// - Integrates with LSP for diagnostics
return nil
}
```
--------------------------------
### Custom Commands Directory Structure
Source: https://github.com/opencode-ai/opencode/blob/main/README.md
This section details the file structure for creating custom commands in OpenCode. User-specific commands are stored under `$XDG_CONFIG_HOME/opencode/commands/` or `$HOME/.opencode/commands/`, while project-specific commands are located in `/.opencode/commands/`. Markdown files in these directories define the commands.
```markdown
1. **User Commands** (prefixed with `user:`):
```
$XDG_CONFIG_HOME/opencode/commands/
```
(typically `~/.config/opencode/commands/` on Linux/macOS)
or
```
$HOME/.opencode/commands/
```
2. **Project Commands** (prefixed with `project:`):
```
/.opencode/commands/
```
```
--------------------------------
### OpenCode Configuration File Structure (JSON)
Source: https://github.com/opencode-ai/opencode/blob/main/README.md
Defines the overall structure of the OpenCode configuration file, including settings for data directories, AI provider API keys, agent configurations, shell settings, MCP servers, LSP clients, and debugging options.
```json
{
"data": {
"directory": ".opencode"
},
"providers": {
"openai": {
"apiKey": "your-api-key",
"disabled": false
},
"anthropic": {
"apiKey": "your-api-key",
"disabled": false
},
"copilot": {
"disabled": false
},
"groq": {
"apiKey": "your-api-key",
"disabled": false
},
"openrouter": {
"apiKey": "your-api-key",
"disabled": false
}
},
"agents": {
"coder": {
"model": "claude-3.7-sonnet",
"maxTokens": 5000
},
"task": {
"model": "claude-3.7-sonnet",
"maxTokens": 5000
},
"title": {
"model": "claude-3.7-sonnet",
"maxTokens": 80
}
},
"shell": {
"path": "/bin/bash",
"args": ["-l"]
},
"mcpServers": {
"example": {
"type": "stdio",
"command": "path/to/mcp-server",
"env": [],
"args": []
}
},
"lsp": {
"go": {
"disabled": false,
"command": "gopls"
}
},
"debug": false,
"debugLSP": false,
"autoCompact": true
}
```
--------------------------------
### Configure Self-Hosted Model in JSON
Source: https://github.com/opencode-ai/opencode/blob/main/README.md
Shows how to specify a self-hosted model for the 'coder' agent in the OpenCode configuration file. It includes the model name and reasoning effort, allowing customization of the AI's behavior.
```json
{
"agents": {
"coder": {
"model": "local.granite-3.3-2b-instruct@q8_0",
"reasoningEffort": "high"
}
}
}
```
--------------------------------
### Generate OpenCode JSON Schema using Go
Source: https://github.com/opencode-ai/opencode/blob/main/cmd/schema/README.md
This command generates the JSON Schema for OpenCode configuration files using the Go programming language. The output is redirected to a file named 'opencode-schema.json'. This schema can be used for validation and editor autocompletion.
```bash
go run cmd/schema/main.go > opencode-schema.json
```
--------------------------------
### Edit Tool: Modify Files with Search and Replace
Source: https://context7.com/opencode-ai/opencode/llms.txt
The Edit tool allows for precise modifications within files, supporting simple string replacements, regex-based pattern matching, and the ability to insert or delete content at specific locations. It utilizes provided file paths and replacement strings to perform operations, with options for regex and replacing all occurrences.
```go
package example
import (
"context"
"encoding/json"
"fmt"
"github.com/opencode-ai/opencode/internal/llm/tools"
"github.com/opencode-ai/opencode/internal/permission"
"github.com/opencode-ai/opencode/internal/history"
)
func editExistingFiles(ctx context.Context,
permService permission.Service,
historyService history.Service) error {
// Create edit tool
editTool := tools.NewEditTool(permService, historyService)
ctx = context.WithValue(ctx, tools.SessionIDContextKey, "session-123")
ctx = context.WithValue(ctx, tools.MessageIDContextKey, "msg-456")
// Simple string replacement
editParams := map[string]interface{}{
"file_path": "config.go",
"old_string": "defaultPort := 8080",
"new_string": "defaultPort := 3000",
}
paramsJSON, _ := json.Marshal(editParams)
result, err := editTool.Run(ctx, tools.ToolCall{
ID: "edit-1",
Name: "edit",
Input: string(paramsJSON),
})
if err != nil {
return fmt.Errorf("edit failed: %w", err)
}
fmt.Println(result.Content) // Shows diff of changes
// Regex replacement with multiple occurrences
regexParams := map[string]interface{}{
"file_path": "handler.go",
"old_string": `fmt.。.Println\((.*?)\)`,
"new_string": `log.Info($1)`,
"use_regex": true,
"replace_all": true,
}
// Insert at specific position
insertParams := map[string]interface{}{
"file_path": "main.go",
"old_string": "import (",
"new_string": "import (\n\t\"log\"",
}
// Delete lines
deleteParams := map[string]interface{}{
"file_path": "legacy.go",
"old_string": "// TODO: remove this deprecated function\nfunc oldFunc() {}\n",
"new_string": "",
}
return nil
}
```
--------------------------------
### Set Local Endpoint for Self-Hosted Model Provider (Bash)
Source: https://github.com/opencode-ai/opencode/blob/main/README.md
Demonstrates how to set the LOCAL_ENDPOINT environment variable in bash to configure OpenCode to use a self-hosted OpenAI-like model provider. This is useful for local development and experimentation with custom models.
```bash
LOCAL_ENDPOINT=http://localhost:1235/v1
```