Documentation
¶
Overview ¶
Package opencode provides a client for the OpenCode CLI. OpenCode is an AI coding assistant that supports 75+ LLM providers with built-in agents for development (build) and analysis (plan).
Index ¶
- Variables
- type Agent
- type CLIResponse
- type CLIToolCall
- type CLIUsage
- type Capabilities
- type CompletionRequest
- type CompletionResponse
- type Config
- type Error
- type MCPServerConfig
- type Message
- type OpenCodeCLI
- func (c *OpenCodeCLI) Capabilities() Capabilities
- func (c *OpenCodeCLI) Close() error
- func (c *OpenCodeCLI) Complete(ctx context.Context, req CompletionRequest) (*CompletionResponse, error)
- func (c *OpenCodeCLI) Provider() string
- func (c *OpenCodeCLI) Stream(ctx context.Context, req CompletionRequest) (<-chan StreamChunk, error)
- type OpenCodeOption
- func WithAgent(agent Agent) OpenCodeOption
- func WithAllowedTools(tools []string) OpenCodeOption
- func WithDebug(debug bool) OpenCodeOption
- func WithDisallowedTools(tools []string) OpenCodeOption
- func WithEnv(env map[string]string) OpenCodeOption
- func WithEnvVar(key, value string) OpenCodeOption
- func WithMCPConfig(path string) OpenCodeOption
- func WithMCPServers(servers map[string]MCPServerConfig) OpenCodeOption
- func WithMaxTurns(n int) OpenCodeOption
- func WithOpenCodePath(path string) OpenCodeOption
- func WithOutputFormat(format OutputFormat) OpenCodeOption
- func WithQuiet(quiet bool) OpenCodeOption
- func WithSystemPrompt(prompt string) OpenCodeOption
- func WithTimeout(d time.Duration) OpenCodeOption
- func WithWorkdir(dir string) OpenCodeOption
- type OutputFormat
- type Role
- type StreamChunk
- type TokenUsage
- type Tool
- type ToolCall
Constants ¶
This section is empty.
Variables ¶
var ( ErrUnavailable = errors.New("LLM service unavailable") // ErrContextTooLong indicates the input exceeds the context window. ErrContextTooLong = errors.New("context exceeds maximum length") // ErrRateLimited indicates the request was rate limited. ErrRateLimited = errors.New("rate limited") // ErrInvalidRequest indicates the request is malformed. ErrInvalidRequest = errors.New("invalid request") // ErrTimeout indicates the request timed out. ErrTimeout = errors.New("request timed out") )
Sentinel errors for OpenCode operations.
Functions ¶
This section is empty.
Types ¶
type CLIResponse ¶
type CLIResponse struct {
Result string `json:"result"`
Error string `json:"error,omitempty"`
IsError bool `json:"is_error,omitempty"`
Usage *CLIUsage `json:"usage,omitempty"`
Model string `json:"model,omitempty"`
Duration int `json:"duration_ms,omitempty"`
ToolCalls []CLIToolCall `json:"tool_calls,omitempty"`
}
CLIResponse represents the JSON response from OpenCode CLI.
type CLIToolCall ¶
type CLIToolCall struct {
ID string `json:"id"`
Name string `json:"name"`
Arguments json.RawMessage `json:"arguments"`
}
CLIToolCall represents a tool call in the response.
type CLIUsage ¶
type CLIUsage struct {
InputTokens int `json:"input_tokens"`
OutputTokens int `json:"output_tokens"`
}
CLIUsage contains token usage from the CLI response.
type Capabilities ¶
type Capabilities struct {
// Streaming indicates if the provider supports streaming responses.
Streaming bool `json:"streaming"`
// Tools indicates if the provider supports tool/function calling.
Tools bool `json:"tools"`
// MCP indicates if the provider supports MCP (Model Context Protocol) servers.
MCP bool `json:"mcp"`
// Sessions indicates if the provider supports multi-turn conversation sessions.
Sessions bool `json:"sessions"`
// Images indicates if the provider supports image inputs.
Images bool `json:"images"`
// NativeTools lists the provider's built-in tools by name.
NativeTools []string `json:"native_tools"`
// ContextFile is the filename for project-specific context.
ContextFile string `json:"context_file,omitempty"`
}
Capabilities describes what a provider natively supports. This type mirrors provider.Capabilities for API compatibility.
func (Capabilities) HasTool ¶
func (c Capabilities) HasTool(name string) bool
HasTool checks if a native tool is available by name.
type CompletionRequest ¶
type CompletionRequest struct {
// SystemPrompt sets the system message that guides the model's behavior.
SystemPrompt string `json:"system_prompt,omitempty"`
// Messages is the conversation history to send to the model.
Messages []Message `json:"messages"`
// Model specifies which model to use (provider-specific).
// OpenCode supports 75+ providers, model names vary by provider.
Model string `json:"model,omitempty"`
// MaxTokens limits the response length.
MaxTokens int `json:"max_tokens,omitempty"`
// Temperature controls response randomness (0.0 = deterministic, 1.0 = creative).
Temperature float64 `json:"temperature,omitempty"`
// Tools lists available tools the model can invoke.
Tools []Tool `json:"tools,omitempty"`
// Options holds provider-specific configuration not covered by standard fields.
Options map[string]any `json:"options,omitempty"`
}
CompletionRequest configures an LLM completion call.
type CompletionResponse ¶
type CompletionResponse struct {
Content string `json:"content"`
ToolCalls []ToolCall `json:"tool_calls,omitempty"`
Usage TokenUsage `json:"usage"`
Model string `json:"model"`
FinishReason string `json:"finish_reason"`
Duration time.Duration `json:"duration"`
}
CompletionResponse is the output of a completion call.
type Config ¶
type Config struct {
// OpenCodePath is the path to the opencode CLI binary.
// Default: "opencode" (found via PATH).
OpenCodePath string `json:"opencode_path" yaml:"opencode_path" mapstructure:"opencode_path"`
// WorkDir is the working directory for file operations.
// Default: current directory.
WorkDir string `json:"work_dir" yaml:"work_dir" mapstructure:"work_dir"`
// Timeout is the maximum duration for a completion request.
// 0 uses the default (5 minutes).
Timeout time.Duration `json:"timeout" yaml:"timeout" mapstructure:"timeout"`
// Agent specifies which OpenCode agent to use.
// Valid values: "build" (default, full access), "plan" (read-only).
Agent Agent `json:"agent" yaml:"agent" mapstructure:"agent"`
// OutputFormat controls CLI output format.
// Default: "json".
OutputFormat OutputFormat `json:"output_format" yaml:"output_format" mapstructure:"output_format"`
// Quiet enables quiet mode for cleaner output.
// Default: true.
Quiet bool `json:"quiet" yaml:"quiet" mapstructure:"quiet"`
// Debug enables debug mode for verbose output.
// Default: false.
Debug bool `json:"debug" yaml:"debug" mapstructure:"debug"`
// SystemPrompt is the system message prepended to all requests.
// Optional.
SystemPrompt string `json:"system_prompt" yaml:"system_prompt" mapstructure:"system_prompt"`
// MaxTurns limits conversation turns (tool calls + responses).
// 0 means no limit.
MaxTurns int `json:"max_turns" yaml:"max_turns" mapstructure:"max_turns"`
// AllowedTools limits which tools OpenCode can use.
// Empty means all tools allowed.
AllowedTools []string `json:"allowed_tools" yaml:"allowed_tools" mapstructure:"allowed_tools"`
// DisallowedTools explicitly blocks certain tools.
// Takes precedence over AllowedTools.
DisallowedTools []string `json:"disallowed_tools" yaml:"disallowed_tools" mapstructure:"disallowed_tools"`
// Env provides additional environment variables.
Env map[string]string `json:"env" yaml:"env" mapstructure:"env"`
}
Config holds configuration for an OpenCode client. Zero values use sensible defaults where noted.
func DefaultConfig ¶
func DefaultConfig() Config
DefaultConfig returns a Config with sensible defaults.
func FromEnv ¶
func FromEnv() Config
FromEnv creates a Config from environment variables with defaults.
func (*Config) LoadFromEnv ¶
func (c *Config) LoadFromEnv()
LoadFromEnv populates config fields from environment variables. Environment variables use OPENCODE_ prefix and take precedence over existing values.
func (*Config) ToOptions ¶
func (c *Config) ToOptions() []OpenCodeOption
ToOptions converts the config to functional options. This enables mixing Config with additional options.
type Error ¶
type Error struct {
Op string // Operation that failed ("complete", "stream")
Err error // Underlying error
Retryable bool // Whether the error is likely transient
}
Error wraps LLM errors with context.
type MCPServerConfig ¶
type MCPServerConfig struct {
// Type specifies the transport type: "stdio", "http", or "sse".
Type string `json:"type,omitempty"`
// Command is the command to run the MCP server (for stdio transport).
Command string `json:"command,omitempty"`
// Args are the arguments to pass to the command (for stdio transport).
Args []string `json:"args,omitempty"`
// Env provides environment variables for the server process.
Env map[string]string `json:"env,omitempty"`
// URL is the server endpoint (for http/sse transport).
URL string `json:"url,omitempty"`
// Headers are HTTP headers (for http/sse transport).
Headers []string `json:"headers,omitempty"`
}
MCPServerConfig defines an MCP server for the OpenCode CLI. Supports stdio, http, and sse transport types.
type Message ¶
type Message struct {
Role Role `json:"role"`
Content string `json:"content"`
Name string `json:"name,omitempty"` // For tool results
}
Message is a conversation turn.
type OpenCodeCLI ¶
type OpenCodeCLI struct {
// contains filtered or unexported fields
}
OpenCodeCLI implements Client using the OpenCode CLI binary.
func NewFromConfig ¶
func NewFromConfig(cfg Config, opts ...OpenCodeOption) *OpenCodeCLI
NewFromConfig creates an OpenCodeCLI from a Config struct. Additional options can be passed to override config values.
func NewFromEnv ¶
func NewFromEnv(opts ...OpenCodeOption) *OpenCodeCLI
NewFromEnv creates an OpenCodeCLI from environment variables. Additional options can be passed to override config values.
func NewOpenCodeCLI ¶
func NewOpenCodeCLI(opts ...OpenCodeOption) *OpenCodeCLI
NewOpenCodeCLI creates a new OpenCode CLI client. Assumes "opencode" is available in PATH unless overridden with WithOpenCodePath. By default uses JSON output format for structured responses.
func (*OpenCodeCLI) Capabilities ¶
func (c *OpenCodeCLI) Capabilities() Capabilities
Capabilities returns OpenCode's native capabilities.
func (*OpenCodeCLI) Close ¶
func (c *OpenCodeCLI) Close() error
Close releases any resources held by the client. For OpenCodeCLI, this is a no-op as each command is independent.
func (*OpenCodeCLI) Complete ¶
func (c *OpenCodeCLI) Complete(ctx context.Context, req CompletionRequest) (*CompletionResponse, error)
Complete implements Client.
func (*OpenCodeCLI) Provider ¶
func (c *OpenCodeCLI) Provider() string
Provider returns the provider name.
func (*OpenCodeCLI) Stream ¶
func (c *OpenCodeCLI) Stream(ctx context.Context, req CompletionRequest) (<-chan StreamChunk, error)
Stream implements Client.
type OpenCodeOption ¶
type OpenCodeOption func(*OpenCodeCLI)
OpenCodeOption configures OpenCodeCLI.
func WithAgent ¶
func WithAgent(agent Agent) OpenCodeOption
WithAgent sets the agent mode (build or plan). Build agent has full access, plan agent is read-only.
func WithAllowedTools ¶
func WithAllowedTools(tools []string) OpenCodeOption
WithAllowedTools sets the allowed tools for opencode (whitelist).
func WithDebug ¶
func WithDebug(debug bool) OpenCodeOption
WithDebug enables debug mode for verbose output.
func WithDisallowedTools ¶
func WithDisallowedTools(tools []string) OpenCodeOption
WithDisallowedTools sets the tools to disallow (blacklist).
func WithEnv ¶
func WithEnv(env map[string]string) OpenCodeOption
WithEnv adds additional environment variables to the CLI process.
func WithEnvVar ¶
func WithEnvVar(key, value string) OpenCodeOption
WithEnvVar adds a single environment variable to the CLI process.
func WithMCPConfig ¶
func WithMCPConfig(path string) OpenCodeOption
WithMCPConfig sets the path to an MCP configuration file.
func WithMCPServers ¶
func WithMCPServers(servers map[string]MCPServerConfig) OpenCodeOption
WithMCPServers sets inline MCP server definitions. The servers are converted to JSON and passed via temp file.
func WithMaxTurns ¶
func WithMaxTurns(n int) OpenCodeOption
WithMaxTurns limits the number of agentic turns in a conversation. A value of 0 means no limit.
func WithOpenCodePath ¶
func WithOpenCodePath(path string) OpenCodeOption
WithOpenCodePath sets the path to the opencode binary.
func WithOutputFormat ¶
func WithOutputFormat(format OutputFormat) OpenCodeOption
WithOutputFormat sets the output format (text, json). Default is json for structured responses.
func WithQuiet ¶
func WithQuiet(quiet bool) OpenCodeOption
WithQuiet enables or disables quiet mode. When enabled (default), suppresses extra output for cleaner responses.
func WithSystemPrompt ¶
func WithSystemPrompt(prompt string) OpenCodeOption
WithSystemPrompt sets a custom system prompt.
func WithTimeout ¶
func WithTimeout(d time.Duration) OpenCodeOption
WithTimeout sets the default timeout for commands.
func WithWorkdir ¶
func WithWorkdir(dir string) OpenCodeOption
WithWorkdir sets the working directory for opencode commands.
type OutputFormat ¶
type OutputFormat string
OutputFormat specifies the CLI output format.
const ( OutputFormatText OutputFormat = "text" OutputFormatJSON OutputFormat = "json" )
Output format constants.
type StreamChunk ¶
type StreamChunk struct {
Content string `json:"content,omitempty"`
ToolCalls []ToolCall `json:"tool_calls,omitempty"`
Usage *TokenUsage `json:"usage,omitempty"` // Only set in final chunk
Done bool `json:"done"`
Error error `json:"-"` // Non-nil if streaming failed
}
StreamChunk is a piece of a streaming response.
type TokenUsage ¶
type TokenUsage struct {
InputTokens int `json:"input_tokens"`
OutputTokens int `json:"output_tokens"`
TotalTokens int `json:"total_tokens"`
}
TokenUsage tracks token consumption.
func (*TokenUsage) Add ¶
func (u *TokenUsage) Add(other TokenUsage)
Add calculates total tokens and adds to existing usage.