Documentation
¶
Overview ¶
Package claude provides interfaces and implementations for the Claude Code CLI.
This package can be used directly via NewClaudeCLI, or through the unified provider interface via provider.New("claude", cfg).
Direct Usage ¶
client := claude.NewClaudeCLI(
claude.WithModel("claude-sonnet-4-20250514"),
claude.WithWorkdir("/path/to/project"),
)
resp, err := client.Complete(ctx, claude.CompletionRequest{
Messages: []claude.Message{{Role: claude.RoleUser, Content: "Hello"}},
})
Provider Interface Usage ¶
import _ "github.com/randalmurphal/llmkit/claude" // Register provider
client, err := provider.New("claude", provider.Config{
Provider: "claude",
Model: "claude-sonnet-4-20250514",
})
resp, err := client.Complete(ctx, provider.Request{
Messages: []provider.Message{{Role: provider.RoleUser, Content: "Hello"}},
})
Package claude provides a Go wrapper for the Claude CLI.
This package enables programmatic interaction with Claude through the official CLI binary. It supports both synchronous completions and streaming responses.
Basic Usage ¶
client := claude.NewCLI()
resp, err := client.Complete(ctx, claude.CompletionRequest{
Messages: []claude.Message{
{Role: claude.RoleUser, Content: "Hello!"},
},
})
Streaming ¶
stream, err := client.Stream(ctx, req)
for chunk := range stream {
fmt.Print(chunk.Content)
}
Container Support ¶
For containerized environments, credentials can be loaded from a mounted directory:
client := claude.NewCLI(
claude.WithHomeDir("/home/worker"),
claude.WithDangerouslySkipPermissions(),
)
Testing ¶
Use MockClient for testing without the actual CLI:
mock := &claude.MockClient{
CompleteFunc: func(ctx context.Context, req CompletionRequest) (*CompletionResponse, error) {
return &CompletionResponse{Content: "test"}, nil
},
}
Index ¶
- Constants
- Variables
- func ContextWithClient(ctx context.Context, c Client) context.Context
- func DefaultCredentialPath() string
- func ResetDefaultClient()
- func SetDefaultClient(c Client)
- func SetDefaultConfig(cfg Config)
- func WriteCredentials(path string, creds *Credentials) error
- func WriteCredentialsToDir(dir string, creds *Credentials) error
- type AssistantMessage
- type CLIModelUsage
- type CLIResponse
- type CLIUsage
- type Capabilities
- type ClaudeCLI
- func (c *ClaudeCLI) Capabilities() Capabilities
- func (c *ClaudeCLI) Close() error
- func (c *ClaudeCLI) Complete(ctx context.Context, req CompletionRequest) (*CompletionResponse, error)
- func (c *ClaudeCLI) Provider() string
- func (c *ClaudeCLI) Stream(ctx context.Context, req CompletionRequest) (<-chan StreamChunk, error)
- type ClaudeOption
- func WithAddDirs(dirs []string) ClaudeOption
- func WithAllowedTools(tools []string) ClaudeOption
- func WithAppendSystemPrompt(prompt string) ClaudeOption
- func WithClaudePath(path string) ClaudeOption
- func WithConfigDir(dir string) ClaudeOption
- func WithContinue() ClaudeOption
- func WithDangerouslySkipPermissions() ClaudeOption
- func WithDisallowedTools(tools []string) ClaudeOption
- func WithEnv(env map[string]string) ClaudeOption
- func WithEnvVar(key, value string) ClaudeOption
- func WithFallbackModel(model string) ClaudeOption
- func WithHomeDir(dir string) ClaudeOption
- func WithJSONSchema(schema string) ClaudeOption
- func WithMCPConfig(pathOrJSON string) ClaudeOption
- func WithMCPServers(servers map[string]MCPServerConfig) ClaudeOption
- func WithMaxBudgetUSD(amount float64) ClaudeOption
- func WithMaxTurns(n int) ClaudeOption
- func WithModel(model string) ClaudeOption
- func WithNoSessionPersistence() ClaudeOption
- func WithOutputFormat(format OutputFormat) ClaudeOption
- func WithPermissionMode(mode PermissionMode) ClaudeOption
- func WithResume(sessionID string) ClaudeOption
- func WithSessionID(id string) ClaudeOption
- func WithSettingSources(sources []string) ClaudeOption
- func WithStrictMCPConfig() ClaudeOption
- func WithSystemPrompt(prompt string) ClaudeOption
- func WithTimeout(d time.Duration) ClaudeOption
- func WithTools(tools []string) ClaudeOption
- func WithWorkdir(dir string) ClaudeOption
- type Client
- type CompletionRequest
- type CompletionResponse
- type Config
- type CredentialFile
- type Credentials
- type Error
- type InitMessage
- type MCPServerConfig
- type ManagerOption
- type Message
- type MockClient
- func (m *MockClient) CallCount() int
- func (m *MockClient) Complete(ctx context.Context, req CompletionRequest) (*CompletionResponse, error)
- func (m *MockClient) LastCall() *CompletionRequest
- func (m *MockClient) Reset()
- func (m *MockClient) Stream(ctx context.Context, req CompletionRequest) (<-chan StreamChunk, error)
- func (m *MockClient) WithCompleteFunc(...) *MockClient
- func (m *MockClient) WithError(err error) *MockClient
- func (m *MockClient) WithResponses(responses ...string) *MockClient
- func (m *MockClient) WithStreamFunc(...) *MockClient
- type OutputFormat
- type OutputMessage
- type PermissionMode
- type ResultMessage
- type Role
- type Session
- type SessionClient
- func (c *SessionClient) Close() error
- func (c *SessionClient) Complete(ctx context.Context, req CompletionRequest) (*CompletionResponse, error)
- func (c *SessionClient) Info() session.SessionInfo
- func (c *SessionClient) Session() session.Session
- func (c *SessionClient) SessionID() string
- func (c *SessionClient) Status() session.SessionStatus
- func (c *SessionClient) Stream(ctx context.Context, req CompletionRequest) (<-chan StreamChunk, error)
- type SessionInfo
- type SessionManager
- type SessionOption
- type SessionStatus
- type StreamAccumulator
- func (a *StreamAccumulator) AllMarkers() []parser.Marker
- func (a *StreamAccumulator) Append(chunk StreamChunk)
- func (a *StreamAccumulator) ConsumeStream(stream <-chan StreamChunk) error
- func (a *StreamAccumulator) ConsumeStreamWithCallback(stream <-chan StreamChunk, callback func(StreamChunk) bool) error
- func (a *StreamAccumulator) Content() string
- func (a *StreamAccumulator) Done() bool
- func (a *StreamAccumulator) Error() error
- func (a *StreamAccumulator) GetBlockedReason() string
- func (a *StreamAccumulator) GetMarker(tag string) (parser.Marker, bool)
- func (a *StreamAccumulator) GetMarkerValue(tag string) string
- func (a *StreamAccumulator) HasMarker(tag string) bool
- func (a *StreamAccumulator) HasMarkerValue(tag, value string) bool
- func (a *StreamAccumulator) IsPhaseBlocked() bool
- func (a *StreamAccumulator) IsPhaseComplete() bool
- func (a *StreamAccumulator) Len() int
- func (a *StreamAccumulator) Reset()
- func (a *StreamAccumulator) ToResponse() *CompletionResponse
- func (a *StreamAccumulator) Usage() *TokenUsage
- type StreamChunk
- type TokenUsage
- type Tool
- type ToolCall
- type UserMessage
Constants ¶
const ( SessionStatusCreating = session.StatusCreating SessionStatusActive = session.StatusActive SessionStatusClosing = session.StatusClosing SessionStatusClosed = session.StatusClosed SessionStatusError = session.StatusError SessionStatusTerminating = session.StatusTerminating )
Session status constants.
Variables ¶
var ( // ErrCredentialsNotFound indicates no credentials file was found. ErrCredentialsNotFound = errors.New("credentials file not found") // ErrCredentialsInvalid indicates the credentials file is malformed. ErrCredentialsInvalid = errors.New("invalid credentials format") // ErrCredentialsExpired indicates the access token has expired. ErrCredentialsExpired = errors.New("credentials expired") // ErrNoOAuthCredentials indicates OAuth credentials are not present. ErrNoOAuthCredentials = errors.New("no OAuth credentials in file") )
Credential errors.
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 LLM operations.
var ( // SessionWithID sets a specific session ID. SessionWithID = session.WithSessionID // SessionWithResume enables resuming a persisted session. SessionWithResume = session.WithResume // SessionWithModel sets the model for the session. SessionWithModel = session.WithModel // SessionWithWorkdir sets the working directory for the session. SessionWithWorkdir = session.WithWorkdir // SessionWithSystemPrompt sets a custom system prompt. SessionWithSystemPrompt = session.WithSystemPrompt // SessionWithAppendSystemPrompt appends to the system prompt. SessionWithAppendSystemPrompt = session.WithAppendSystemPrompt // SessionWithAllowedTools sets the allowed tools whitelist. SessionWithAllowedTools = session.WithAllowedTools // SessionWithDisallowedTools sets the disallowed tools blacklist. SessionWithDisallowedTools = session.WithDisallowedTools // SessionWithPermissions configures permission handling. // If skip is true, all permission prompts are bypassed. SessionWithPermissions = session.WithPermissions // SessionWithMaxBudgetUSD sets a maximum spending limit. SessionWithMaxBudgetUSD = session.WithMaxBudgetUSD // SessionWithMaxTurns limits the number of turns. SessionWithMaxTurns = session.WithMaxTurns // SessionWithNoPersistence disables session persistence. SessionWithNoPersistence = session.WithNoSessionPersistence // SessionWithIncludeHookOutput includes hook output in the output channel. SessionWithIncludeHookOutput = session.WithIncludeHookOutput )
Session options re-exported for convenience. Note: These are prefixed with "Session" to avoid conflicts with ClaudeCLI options.
var ( // WithMaxSessions sets the maximum number of concurrent sessions. WithMaxSessions = session.WithMaxSessions // WithSessionTTL sets the time-to-live for idle sessions. WithSessionTTL = session.WithSessionTTL // WithCleanupInterval sets how often to check for expired sessions. WithCleanupInterval = session.WithCleanupInterval // WithDefaultSessionOptions sets default options for all sessions. WithDefaultSessionOptions = session.WithDefaultSessionOptions )
Manager options re-exported for convenience.
var NewSessionManager = session.NewManager
NewSessionManager creates a new session manager. Use this to manage multiple concurrent sessions with automatic cleanup.
Example:
mgr := claude.NewSessionManager(
claude.WithMaxSessions(10),
claude.WithSessionTTL(30*time.Minute),
)
defer mgr.CloseAll()
var NewUserMessage = session.NewUserMessage
NewUserMessage creates a new user message for sending to Claude.
Functions ¶
func ContextWithClient ¶ added in v1.1.0
ContextWithClient adds a Client to a context. Use ClientFromContext to retrieve it.
Example:
client := claude.NewFromConfig(cfg) ctx := claude.ContextWithClient(context.Background(), client) // Pass ctx to functions that need the client
func DefaultCredentialPath ¶
func DefaultCredentialPath() string
DefaultCredentialPath returns the default path to Claude credentials. This is ~/.claude/.credentials.json on Unix-like systems.
func ResetDefaultClient ¶ added in v1.1.0
func ResetDefaultClient()
ResetDefaultClient clears the singleton client. Useful for testing to ensure clean state between tests. After reset, GetDefaultClient will create a new client.
Example:
func TestSomething(t *testing.T) {
mock := claude.NewMockClient("response")
claude.SetDefaultClient(mock)
defer claude.ResetDefaultClient()
// Test code that uses GetDefaultClient()
}
func SetDefaultClient ¶ added in v1.1.0
func SetDefaultClient(c Client)
SetDefaultClient sets the singleton client directly. Useful for testing or when you want to manage the client lifecycle. Note: If GetDefaultClient was already called, call ResetDefaultClient first.
Example:
// In tests
mock := claude.NewMockClient("test response")
claude.SetDefaultClient(mock)
defer claude.ResetDefaultClient()
func SetDefaultConfig ¶ added in v1.1.0
func SetDefaultConfig(cfg Config)
SetDefaultConfig sets the configuration for the default client. Must be called before GetDefaultClient is first called. Not thread-safe with concurrent GetDefaultClient calls during initialization.
Example:
// In main.go or init
claude.SetDefaultConfig(claude.Config{
Model: "claude-opus-4-5-20251101",
MaxTurns: 10,
})
// Anywhere else in the application
client := claude.GetDefaultClient()
func WriteCredentials ¶
func WriteCredentials(path string, creds *Credentials) error
WriteCredentials writes credentials to the specified path. This is useful for containers that need to receive credentials.
func WriteCredentialsToDir ¶
func WriteCredentialsToDir(dir string, creds *Credentials) error
WriteCredentialsToDir writes credentials to .credentials.json in the specified directory.
Types ¶
type AssistantMessage ¶ added in v1.1.0
type AssistantMessage = session.AssistantMessage
AssistantMessage contains Claude's response.
type CLIModelUsage ¶
type CLIModelUsage struct {
InputTokens int `json:"inputTokens"`
OutputTokens int `json:"outputTokens"`
CacheReadInputTokens int `json:"cacheReadInputTokens"`
CacheCreationInputTokens int `json:"cacheCreationInputTokens"`
CostUSD float64 `json:"costUSD"`
}
CLIModelUsage contains per-model token usage and cost.
type CLIResponse ¶
type CLIResponse struct {
Type string `json:"type"`
Subtype string `json:"subtype"`
IsError bool `json:"is_error"`
Result string `json:"result"`
SessionID string `json:"session_id"`
DurationMS int `json:"duration_ms"`
DurationAPI int `json:"duration_api_ms"`
NumTurns int `json:"num_turns"`
TotalCostUSD float64 `json:"total_cost_usd"`
Usage CLIUsage `json:"usage"`
ModelUsage map[string]CLIModelUsage `json:"modelUsage"`
}
CLIResponse represents the full JSON response from Claude CLI.
type CLIUsage ¶
type CLIUsage struct {
InputTokens int `json:"input_tokens"`
OutputTokens int `json:"output_tokens"`
CacheCreationInputTokens int `json:"cache_creation_input_tokens"`
CacheReadInputTokens int `json:"cache_read_input_tokens"`
}
CLIUsage contains aggregate token usage from the CLI response.
type Capabilities ¶ added in v1.2.0
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 (e.g., "CLAUDE.md").
ContextFile string `json:"context_file,omitempty"`
}
Capabilities describes what a provider natively supports. This type mirrors provider.Capabilities for API compatibility.
func (Capabilities) HasTool ¶ added in v1.2.0
func (c Capabilities) HasTool(name string) bool
HasTool checks if a native tool is available by name.
type ClaudeCLI ¶
type ClaudeCLI struct {
// contains filtered or unexported fields
}
ClaudeCLI implements Client using the Claude CLI binary.
func NewClaudeCLI ¶
func NewClaudeCLI(opts ...ClaudeOption) *ClaudeCLI
NewClaudeCLI creates a new Claude CLI client. Assumes "claude" is available in PATH unless overridden with WithClaudePath. By default uses JSON output format for structured responses with token tracking.
func (*ClaudeCLI) Capabilities ¶ added in v1.2.0
func (c *ClaudeCLI) Capabilities() Capabilities
Capabilities returns Claude Code's native capabilities. Implements provider.Client.
func (*ClaudeCLI) Close ¶ added in v1.2.0
Close releases any resources held by the client. For ClaudeCLI, this is a no-op as each command is independent. Implements provider.Client.
func (*ClaudeCLI) Complete ¶
func (c *ClaudeCLI) Complete(ctx context.Context, req CompletionRequest) (*CompletionResponse, error)
Complete implements Client.
func (*ClaudeCLI) Provider ¶ added in v1.2.0
Provider returns the provider name. Implements provider.Client.
func (*ClaudeCLI) Stream ¶
func (c *ClaudeCLI) Stream(ctx context.Context, req CompletionRequest) (<-chan StreamChunk, error)
Stream implements Client.
type ClaudeOption ¶
type ClaudeOption func(*ClaudeCLI)
ClaudeOption configures ClaudeCLI.
func WithAddDirs ¶
func WithAddDirs(dirs []string) ClaudeOption
WithAddDirs adds directories to Claude's file access scope.
func WithAllowedTools ¶
func WithAllowedTools(tools []string) ClaudeOption
WithAllowedTools sets the allowed tools for claude (whitelist).
func WithAppendSystemPrompt ¶
func WithAppendSystemPrompt(prompt string) ClaudeOption
WithAppendSystemPrompt appends to the system prompt without replacing it.
func WithClaudePath ¶
func WithClaudePath(path string) ClaudeOption
WithClaudePath sets the path to the claude binary.
func WithConfigDir ¶
func WithConfigDir(dir string) ClaudeOption
WithConfigDir sets the Claude config directory path. If set, this overrides the default ~/.claude location. Note: This sets CLAUDE_CONFIG_DIR environment variable if supported by the CLI.
func WithContinue ¶
func WithContinue() ClaudeOption
WithContinue continues the most recent session.
func WithDangerouslySkipPermissions ¶
func WithDangerouslySkipPermissions() ClaudeOption
WithDangerouslySkipPermissions skips all permission prompts. Use this for non-interactive execution in trusted environments. WARNING: This allows Claude to execute any tools without confirmation.
func WithDisallowedTools ¶
func WithDisallowedTools(tools []string) ClaudeOption
WithDisallowedTools sets the tools to disallow (blacklist).
func WithEnv ¶
func WithEnv(env map[string]string) ClaudeOption
WithEnv adds additional environment variables to the CLI process. These are merged with the parent environment and any other configured env vars.
func WithEnvVar ¶
func WithEnvVar(key, value string) ClaudeOption
WithEnvVar adds a single environment variable to the CLI process.
func WithFallbackModel ¶
func WithFallbackModel(model string) ClaudeOption
WithFallbackModel sets a fallback model to use if the primary is overloaded.
func WithHomeDir ¶
func WithHomeDir(dir string) ClaudeOption
WithHomeDir sets the HOME environment variable for the CLI process. This is useful in containers where credentials are mounted to a non-standard location. The Claude CLI will look for credentials in $HOME/.claude/.credentials.json.
func WithJSONSchema ¶
func WithJSONSchema(schema string) ClaudeOption
WithJSONSchema forces structured output matching the given JSON schema.
func WithMCPConfig ¶ added in v1.1.0
func WithMCPConfig(pathOrJSON string) ClaudeOption
WithMCPConfig adds an MCP configuration file path or JSON string. Can be called multiple times to load multiple configs. The path can be a file path to a JSON config, or a raw JSON string.
func WithMCPServers ¶ added in v1.1.0
func WithMCPServers(servers map[string]MCPServerConfig) ClaudeOption
WithMCPServers sets inline MCP server definitions. The servers are converted to JSON and passed via --mcp-config. This is an alternative to WithMCPConfig for programmatic configuration.
func WithMaxBudgetUSD ¶
func WithMaxBudgetUSD(amount float64) ClaudeOption
WithMaxBudgetUSD sets a maximum spending limit for the session.
func WithMaxTurns ¶
func WithMaxTurns(n int) ClaudeOption
WithMaxTurns limits the number of agentic turns in a conversation. A value of 0 means no limit.
func WithNoSessionPersistence ¶
func WithNoSessionPersistence() ClaudeOption
WithNoSessionPersistence disables saving session data.
func WithOutputFormat ¶
func WithOutputFormat(format OutputFormat) ClaudeOption
WithOutputFormat sets the output format (text, json, stream-json). Default is json for structured responses with token tracking.
func WithPermissionMode ¶
func WithPermissionMode(mode PermissionMode) ClaudeOption
WithPermissionMode sets the permission handling mode.
func WithResume ¶
func WithResume(sessionID string) ClaudeOption
WithResume resumes a specific session by ID.
func WithSessionID ¶
func WithSessionID(id string) ClaudeOption
WithSessionID sets a specific session ID for conversation tracking.
func WithSettingSources ¶
func WithSettingSources(sources []string) ClaudeOption
WithSettingSources specifies which setting sources to use. Valid values: "project", "local", "user"
func WithStrictMCPConfig ¶ added in v1.1.0
func WithStrictMCPConfig() ClaudeOption
WithStrictMCPConfig enables strict MCP configuration mode. When enabled, only MCP servers specified via WithMCPConfig or WithMCPServers are used, ignoring any other configured MCP servers.
func WithSystemPrompt ¶
func WithSystemPrompt(prompt string) ClaudeOption
WithSystemPrompt sets a custom system prompt, replacing the default.
func WithTimeout ¶
func WithTimeout(d time.Duration) ClaudeOption
WithTimeout sets the default timeout for commands.
func WithTools ¶
func WithTools(tools []string) ClaudeOption
WithTools specifies the exact list of available tools from the built-in set. Use an empty slice to disable all tools, or specify tool names like "Bash", "Edit", "Read". This is different from WithAllowedTools which is a whitelist filter.
func WithWorkdir ¶
func WithWorkdir(dir string) ClaudeOption
WithWorkdir sets the working directory for claude commands.
type Client ¶
type Client interface {
// Complete sends a request and returns the full response.
// The context controls cancellation and timeouts.
Complete(ctx context.Context, req CompletionRequest) (*CompletionResponse, error)
// Stream sends a request and returns a channel of response chunks.
// The channel is closed when streaming completes (check chunk.Done).
// Errors during streaming are returned via chunk.Error.
Stream(ctx context.Context, req CompletionRequest) (<-chan StreamChunk, error)
}
Client is the interface for LLM providers. Implementations must be safe for concurrent use.
func ClientFromContext ¶ added in v1.1.0
ClientFromContext retrieves a Client from a context. Returns nil if no Client is present.
Example:
func processRequest(ctx context.Context, prompt string) (string, error) {
client := claude.ClientFromContext(ctx)
if client == nil {
return "", errors.New("claude client not found in context")
}
resp, err := client.Complete(ctx, claude.CompletionRequest{
Messages: []claude.Message{{Role: claude.RoleUser, Content: prompt}},
})
if err != nil {
return "", err
}
return resp.Content, nil
}
func GetDefaultClient ¶ added in v1.1.0
func GetDefaultClient() Client
GetDefaultClient returns a singleton default client. Creates the client lazily on first call using the default config. Thread-safe for concurrent access after initialization.
Example:
client := claude.GetDefaultClient() resp, err := client.Complete(ctx, req)
func MustClientFromContext ¶ added in v1.1.0
MustClientFromContext retrieves a Client or panics. Use when client is required and missing is a programming error.
Example:
func handler(ctx context.Context) {
client := claude.MustClientFromContext(ctx)
// Use client - will panic if not present
}
func NewFromConfig ¶ added in v1.1.0
func NewFromConfig(cfg Config, opts ...ClaudeOption) Client
NewFromConfig creates a Client from a Config struct. Additional options can be provided to override config values.
Example:
cfg := claude.Config{
Model: "claude-opus-4-5-20251101",
SystemPrompt: "You are a code reviewer.",
MaxTurns: 5,
}
client := claude.NewFromConfig(cfg)
func NewFromEnv ¶ added in v1.1.0
func NewFromEnv(opts ...ClaudeOption) Client
NewFromEnv creates a Client configured from environment variables. Additional options can be provided to override env values.
Environment variables checked (CLAUDE_ prefix):
- CLAUDE_MODEL: Model name
- CLAUDE_FALLBACK_MODEL: Fallback model
- CLAUDE_SYSTEM_PROMPT: System prompt
- CLAUDE_MAX_TURNS: Max conversation turns
- CLAUDE_TIMEOUT: Request timeout (e.g., "5m")
- CLAUDE_MAX_BUDGET_USD: Budget limit
- CLAUDE_WORK_DIR: Working directory
- CLAUDE_PATH: Path to claude binary
- CLAUDE_HOME_DIR: Override HOME (for containers)
- CLAUDE_CONFIG_DIR: Override .claude directory
- CLAUDE_OUTPUT_FORMAT: Output format (json, text, stream-json)
- CLAUDE_SKIP_PERMISSIONS: Skip permission prompts (true/1)
- CLAUDE_PERMISSION_MODE: Permission mode
- CLAUDE_SESSION_ID: Session ID
- CLAUDE_NO_SESSION_PERSISTENCE: Disable session saving (true/1)
Example:
// Set environment: // CLAUDE_MODEL=claude-opus-4-5-20251101 // CLAUDE_MAX_TURNS=20 client := claude.NewFromEnv()
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 (e.g., "claude-sonnet-4-20250514").
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"`
// Claude CLI specific fields (populated when using JSON output)
SessionID string `json:"session_id,omitempty"`
CostUSD float64 `json:"cost_usd,omitempty"`
NumTurns int `json:"num_turns,omitempty"`
}
CompletionResponse is the output of a completion call.
type Config ¶ added in v1.1.0
type Config struct {
// Model is the primary model to use.
// Default: "claude-sonnet-4-20250514"
Model string `json:"model" yaml:"model" mapstructure:"model"`
// FallbackModel is used when primary model is unavailable.
// Optional.
FallbackModel string `json:"fallback_model" yaml:"fallback_model" mapstructure:"fallback_model"`
// SystemPrompt is the system message prepended to all requests.
// Optional.
SystemPrompt string `json:"system_prompt" yaml:"system_prompt" mapstructure:"system_prompt"`
// AppendSystemPrompt is appended to the existing system prompt.
// Use when you want to add to defaults rather than replace.
AppendSystemPrompt string `json:"append_system_prompt" yaml:"append_system_prompt" mapstructure:"append_system_prompt"`
// MaxTurns limits conversation turns (tool calls + responses).
// 0 means no limit. Default: 10.
MaxTurns int `json:"max_turns" yaml:"max_turns" mapstructure:"max_turns"`
// Timeout is the maximum duration for a completion request.
// 0 uses the default (5 minutes).
Timeout time.Duration `json:"timeout" yaml:"timeout" mapstructure:"timeout"`
// MaxBudgetUSD limits spending per request.
// 0 means no limit.
MaxBudgetUSD float64 `json:"max_budget_usd" yaml:"max_budget_usd" mapstructure:"max_budget_usd"`
// WorkDir is the working directory for file operations.
// Default: current directory.
WorkDir string `json:"work_dir" yaml:"work_dir" mapstructure:"work_dir"`
// AllowedTools limits which tools Claude 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"`
// Tools specifies the exact list of available tools.
// Different from AllowedTools which is a whitelist filter.
Tools []string `json:"tools" yaml:"tools" mapstructure:"tools"`
// DangerouslySkipPermissions bypasses permission prompts.
// Use with extreme caution, only in trusted environments.
DangerouslySkipPermissions bool `json:"dangerously_skip_permissions" yaml:"dangerously_skip_permissions" mapstructure:"dangerously_skip_permissions"`
// PermissionMode sets the permission handling mode.
// Valid values: "", "acceptEdits", "bypassPermissions"
PermissionMode PermissionMode `json:"permission_mode" yaml:"permission_mode" mapstructure:"permission_mode"`
// SessionID enables session persistence with this ID.
// Optional.
SessionID string `json:"session_id" yaml:"session_id" mapstructure:"session_id"`
// Continue resumes the last session.
Continue bool `json:"continue" yaml:"continue" mapstructure:"continue"`
// Resume resumes a specific session by ID.
Resume string `json:"resume" yaml:"resume" mapstructure:"resume"`
// NoSessionPersistence disables session saving.
NoSessionPersistence bool `json:"no_session_persistence" yaml:"no_session_persistence" mapstructure:"no_session_persistence"`
// HomeDir overrides the home directory (for containers).
HomeDir string `json:"home_dir" yaml:"home_dir" mapstructure:"home_dir"`
// ConfigDir overrides the .claude config directory.
ConfigDir string `json:"config_dir" yaml:"config_dir" mapstructure:"config_dir"`
// Env provides additional environment variables.
Env map[string]string `json:"env" yaml:"env" mapstructure:"env"`
// OutputFormat controls CLI output format.
// Default: "json".
OutputFormat OutputFormat `json:"output_format" yaml:"output_format" mapstructure:"output_format"`
// JSONSchema forces structured output matching the given schema.
JSONSchema string `json:"json_schema" yaml:"json_schema" mapstructure:"json_schema"`
// AddDirs adds directories to Claude's file access scope.
AddDirs []string `json:"add_dirs" yaml:"add_dirs" mapstructure:"add_dirs"`
// SettingSources specifies which setting sources to use.
// Valid values: "project", "local", "user"
SettingSources []string `json:"setting_sources" yaml:"setting_sources" mapstructure:"setting_sources"`
// MCPConfigPath is the path to an MCP configuration JSON file.
// Maps to the --mcp-config CLI flag.
MCPConfigPath string `json:"mcp_config_path" yaml:"mcp_config_path" mapstructure:"mcp_config_path"`
// MCPServers defines MCP servers inline (alternative to config file).
// Keys are server names, values are server configurations.
MCPServers map[string]MCPServerConfig `json:"mcp_servers" yaml:"mcp_servers" mapstructure:"mcp_servers"`
// StrictMCPConfig ignores all MCP configurations except those specified.
// Maps to the --strict-mcp-config CLI flag.
StrictMCPConfig bool `json:"strict_mcp_config" yaml:"strict_mcp_config" mapstructure:"strict_mcp_config"`
// ClaudePath is the path to the claude CLI binary.
// Default: "claude" (found via PATH).
ClaudePath string `json:"claude_path" yaml:"claude_path" mapstructure:"claude_path"`
}
Config holds configuration for a Claude client. Zero values use sensible defaults where noted.
func DefaultConfig ¶ added in v1.1.0
func DefaultConfig() Config
DefaultConfig returns a Config with sensible defaults.
func FromEnv ¶ added in v1.1.0
func FromEnv() Config
FromEnv creates a Config from environment variables with defaults.
func (*Config) LoadFromEnv ¶ added in v1.1.0
func (c *Config) LoadFromEnv()
LoadFromEnv populates config fields from environment variables. Environment variables use CLAUDE_ prefix and take precedence over existing values.
func (*Config) ToOptions ¶ added in v1.1.0
func (c *Config) ToOptions() []ClaudeOption
ToOptions converts the config to functional options. This enables mixing Config with additional options.
type CredentialFile ¶
type CredentialFile struct {
ClaudeAiOauth *Credentials `json:"claudeAiOauth"`
}
CredentialFile represents the ~/.claude/.credentials.json file structure.
type Credentials ¶
type Credentials struct {
// AccessToken is the OAuth access token for API authentication.
AccessToken string `json:"accessToken"`
// RefreshToken is used to obtain new access tokens.
RefreshToken string `json:"refreshToken"`
// ExpiresAt is the Unix timestamp (milliseconds) when the access token expires.
ExpiresAt int64 `json:"expiresAt"`
// Scopes are the OAuth scopes granted to this token.
Scopes []string `json:"scopes"`
// SubscriptionType indicates the Claude subscription tier (e.g., "max").
SubscriptionType string `json:"subscriptionType"`
// RateLimitTier indicates the rate limit tier for this subscription.
RateLimitTier string `json:"rateLimitTier"`
}
Credentials represents Claude OAuth authentication tokens.
func LoadCredentials ¶
func LoadCredentials(path string) (*Credentials, error)
LoadCredentials loads Claude OAuth credentials from the specified path. If path is empty, uses DefaultCredentialPath().
func LoadCredentialsFromDir ¶
func LoadCredentialsFromDir(dir string) (*Credentials, error)
LoadCredentialsFromDir loads credentials from a .credentials.json file in the specified directory. This is useful for container environments where the Claude config directory is mounted to a custom location.
func (*Credentials) ExpirationTime ¶
func (c *Credentials) ExpirationTime() time.Time
ExpirationTime returns the expiration time as a time.Time value.
func (*Credentials) ExpiresIn ¶
func (c *Credentials) ExpiresIn() time.Duration
ExpiresIn returns the duration until the access token expires. Returns a negative duration if already expired.
func (*Credentials) HasScope ¶
func (c *Credentials) HasScope(scope string) bool
HasScope returns true if the credentials include the specified scope.
func (*Credentials) IsExpired ¶
func (c *Credentials) IsExpired() bool
IsExpired returns true if the access token has expired.
func (*Credentials) IsExpiringSoon ¶
func (c *Credentials) IsExpiringSoon(within time.Duration) bool
IsExpiringSoon returns true if the token expires within the given duration. This is useful for proactive refresh or warning users.
func (*Credentials) Validate ¶
func (c *Credentials) Validate() error
Validate checks that the credentials have required fields.
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 InitMessage ¶ added in v1.1.0
type InitMessage = session.InitMessage
InitMessage contains session initialization data.
type MCPServerConfig ¶ added in v1.1.0
type MCPServerConfig struct {
// Type specifies the transport type: "stdio", "http", or "sse".
// If empty, defaults to "stdio" for servers with Command set.
Type string `json:"type,omitempty" yaml:"type,omitempty" mapstructure:"type"`
// Command is the command to run the MCP server (for stdio transport).
Command string `json:"command,omitempty" yaml:"command,omitempty" mapstructure:"command"`
// Args are the arguments to pass to the command (for stdio transport).
Args []string `json:"args,omitempty" yaml:"args,omitempty" mapstructure:"args"`
// Env provides environment variables for the server process.
Env map[string]string `json:"env,omitempty" yaml:"env,omitempty" mapstructure:"env"`
// URL is the server endpoint (for http/sse transport).
URL string `json:"url,omitempty" yaml:"url,omitempty" mapstructure:"url"`
// Headers are HTTP headers (for http/sse transport).
Headers []string `json:"headers,omitempty" yaml:"headers,omitempty" mapstructure:"headers"`
}
MCPServerConfig defines an MCP server for the Claude CLI. Supports stdio, http, and sse transport types.
type ManagerOption ¶ added in v1.1.0
type ManagerOption = session.ManagerOption
ManagerOption configures session manager creation.
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 MockClient ¶
type MockClient struct {
// Calls tracks all requests for assertions.
Calls []CompletionRequest
// contains filtered or unexported fields
}
MockClient is a test double for Client. It supports fixed responses, sequential responses, and custom handlers.
func NewMockClient ¶
func NewMockClient(response string) *MockClient
NewMockClient creates a mock that returns a fixed response.
func (*MockClient) CallCount ¶
func (m *MockClient) CallCount() int
CallCount returns the number of times Complete or Stream was called.
func (*MockClient) Complete ¶
func (m *MockClient) Complete(ctx context.Context, req CompletionRequest) (*CompletionResponse, error)
Complete implements Client.
func (*MockClient) LastCall ¶
func (m *MockClient) LastCall() *CompletionRequest
LastCall returns the most recent request, or nil if no calls made.
func (*MockClient) Reset ¶
func (m *MockClient) Reset()
Reset clears the call history and response index.
func (*MockClient) Stream ¶
func (m *MockClient) Stream(ctx context.Context, req CompletionRequest) (<-chan StreamChunk, error)
Stream implements Client.
func (*MockClient) WithCompleteFunc ¶
func (m *MockClient) WithCompleteFunc(fn func(ctx context.Context, req CompletionRequest) (*CompletionResponse, error)) *MockClient
WithCompleteFunc sets a custom handler for Complete calls. This takes precedence over fixed responses.
func (*MockClient) WithError ¶
func (m *MockClient) WithError(err error) *MockClient
WithError configures the mock to always return an error.
func (*MockClient) WithResponses ¶
func (m *MockClient) WithResponses(responses ...string) *MockClient
WithResponses configures sequential responses. Each call to Complete returns the next response in the list. Cycles back to the beginning after exhausting all responses.
func (*MockClient) WithStreamFunc ¶
func (m *MockClient) WithStreamFunc(fn func(ctx context.Context, req CompletionRequest) (<-chan StreamChunk, error)) *MockClient
WithStreamFunc sets a custom handler for Stream calls.
type OutputFormat ¶
type OutputFormat string
OutputFormat specifies the CLI output format.
const ( OutputFormatText OutputFormat = "text" OutputFormatJSON OutputFormat = "json" OutputFormatStreamJSON OutputFormat = "stream-json" )
Output format constants.
type OutputMessage ¶ added in v1.1.0
type OutputMessage = session.OutputMessage
OutputMessage represents any message received from Claude CLI stdout.
type PermissionMode ¶
type PermissionMode string
PermissionMode specifies how Claude handles tool permissions.
const ( PermissionModeDefault PermissionMode = "" PermissionModeAcceptEdits PermissionMode = "acceptEdits" PermissionModeBypassPermissions PermissionMode = "bypassPermissions" )
Permission mode constants.
type ResultMessage ¶ added in v1.1.0
type ResultMessage = session.ResultMessage
ResultMessage contains the final result of a session turn.
type Session ¶ added in v1.1.0
Session manages a long-running Claude CLI process with stream-json I/O.
type SessionClient ¶ added in v1.1.0
type SessionClient struct {
// contains filtered or unexported fields
}
SessionClient wraps a session.Session to implement the Client interface. This allows using session-based execution (with multi-turn context retention) with code that expects the simpler Client interface.
Unlike ClaudeCLI which spawns a new process per request, SessionClient maintains a long-running Claude CLI process with full conversation history.
func NewSessionClient ¶ added in v1.1.0
func NewSessionClient(s session.Session) *SessionClient
NewSessionClient creates a client from an existing session. The caller is responsible for closing the session when done.
func NewSessionClientWithManager ¶ added in v1.1.0
func NewSessionClientWithManager(ctx context.Context, mgr session.SessionManager, sessionID string, opts ...session.SessionOption) (*SessionClient, error)
NewSessionClientWithManager creates a SessionClient that manages its own session. Pass a sessionID to create or resume a session with that ID. The session will be closed when Close() is called.
Example:
mgr := session.NewManager()
client, err := NewSessionClientWithManager(ctx, mgr, "task-001",
session.WithModel("claude-opus-4-5-20251101"),
session.WithWorkdir("/path/to/project"),
)
defer client.Close()
func (*SessionClient) Close ¶ added in v1.1.0
func (c *SessionClient) Close() error
Close closes the session if this client owns it. If the session was passed in via NewSessionClient, it is NOT closed.
func (*SessionClient) Complete ¶ added in v1.1.0
func (c *SessionClient) Complete(ctx context.Context, req CompletionRequest) (*CompletionResponse, error)
Complete implements Client by sending a message and waiting for the result. The conversation history is maintained across calls to the same SessionClient.
func (*SessionClient) Info ¶ added in v1.1.0
func (c *SessionClient) Info() session.SessionInfo
Info returns session information.
func (*SessionClient) Session ¶ added in v1.1.0
func (c *SessionClient) Session() session.Session
Session returns the underlying session for direct access. Use this when you need session-specific features not exposed by Client.
func (*SessionClient) SessionID ¶ added in v1.1.0
func (c *SessionClient) SessionID() string
SessionID returns the session identifier.
func (*SessionClient) Status ¶ added in v1.1.0
func (c *SessionClient) Status() session.SessionStatus
Status returns the current session status.
func (*SessionClient) Stream ¶ added in v1.1.0
func (c *SessionClient) Stream(ctx context.Context, req CompletionRequest) (<-chan StreamChunk, error)
Stream implements Client by sending a message and streaming responses. Each assistant message is yielded as a StreamChunk.
type SessionInfo ¶ added in v1.1.0
type SessionInfo = session.SessionInfo
SessionInfo contains metadata about a session.
type SessionManager ¶ added in v1.1.0
type SessionManager = session.SessionManager
SessionManager manages multiple Claude CLI sessions.
type SessionOption ¶ added in v1.1.0
type SessionOption = session.SessionOption
SessionOption configures session creation.
type SessionStatus ¶ added in v1.1.0
type SessionStatus = session.SessionStatus
SessionStatus represents the current state of a session.
type StreamAccumulator ¶ added in v1.1.0
type StreamAccumulator struct {
// contains filtered or unexported fields
}
StreamAccumulator collects streaming content and provides analysis. It accumulates chunks as they arrive and optionally checks for markers in real-time, enabling early detection of completion signals.
Thread-safe for concurrent append and read operations.
func NewStreamAccumulator ¶ added in v1.1.0
func NewStreamAccumulator(markers *parser.MarkerMatcher) *StreamAccumulator
NewStreamAccumulator creates an accumulator with optional marker detection. If markers is nil, marker detection methods will return false/empty.
Example:
markers := parser.NewMarkerMatcher("phase_complete", "phase_blocked")
acc := NewStreamAccumulator(markers)
for chunk := range stream {
acc.Append(chunk)
if acc.HasMarker("phase_complete") {
// Early completion detection
break
}
}
func (*StreamAccumulator) AllMarkers ¶ added in v1.1.0
func (a *StreamAccumulator) AllMarkers() []parser.Marker
AllMarkers returns all markers found in the accumulated content. Returns nil if no matcher configured or no markers found.
func (*StreamAccumulator) Append ¶ added in v1.1.0
func (a *StreamAccumulator) Append(chunk StreamChunk)
Append adds a chunk's content to the accumulator. It also captures usage data from the final chunk.
func (*StreamAccumulator) ConsumeStream ¶ added in v1.1.0
func (a *StreamAccumulator) ConsumeStream(stream <-chan StreamChunk) error
ConsumeStream reads all chunks from a stream channel into the accumulator. It blocks until the channel is closed or an error is received. Returns the final error, if any.
Example:
stream, _ := client.Stream(ctx, req)
acc := NewStreamAccumulator(nil)
if err := acc.ConsumeStream(stream); err != nil {
// Handle error
}
response := acc.ToResponse()
func (*StreamAccumulator) ConsumeStreamWithCallback ¶ added in v1.1.0
func (a *StreamAccumulator) ConsumeStreamWithCallback(stream <-chan StreamChunk, callback func(StreamChunk) bool) error
ConsumeStreamWithCallback reads chunks and calls the callback for each one. The callback can return false to stop consuming early. Returns the final error, if any.
Example:
acc := NewStreamAccumulator(markers)
err := acc.ConsumeStreamWithCallback(stream, func(chunk StreamChunk) bool {
fmt.Print(chunk.Content) // Print as we receive
return !acc.IsPhaseComplete() // Stop early on completion
})
func (*StreamAccumulator) Content ¶ added in v1.1.0
func (a *StreamAccumulator) Content() string
Content returns the accumulated content so far.
func (*StreamAccumulator) Done ¶ added in v1.1.0
func (a *StreamAccumulator) Done() bool
Done returns true if the final chunk has been received.
func (*StreamAccumulator) Error ¶ added in v1.1.0
func (a *StreamAccumulator) Error() error
Error returns any error from the stream.
func (*StreamAccumulator) GetBlockedReason ¶ added in v1.1.0
func (a *StreamAccumulator) GetBlockedReason() string
GetBlockedReason returns the reason from a phase_blocked marker, if present. Uses the global PhaseMarkers matcher.
func (*StreamAccumulator) GetMarker ¶ added in v1.1.0
func (a *StreamAccumulator) GetMarker(tag string) (parser.Marker, bool)
GetMarker returns the first marker with the given tag found in the accumulated content. Returns false if not found or no matcher configured.
func (*StreamAccumulator) GetMarkerValue ¶ added in v1.1.0
func (a *StreamAccumulator) GetMarkerValue(tag string) string
GetMarkerValue returns the value of a marker with the given tag. Returns empty string if not found.
func (*StreamAccumulator) HasMarker ¶ added in v1.1.0
func (a *StreamAccumulator) HasMarker(tag string) bool
HasMarker checks if a marker with the given tag has been detected in the accumulated content so far.
Returns false if no markers matcher was provided.
func (*StreamAccumulator) HasMarkerValue ¶ added in v1.1.0
func (a *StreamAccumulator) HasMarkerValue(tag, value string) bool
HasMarkerValue checks if a marker with the specific tag and value exists in the accumulated content.
func (*StreamAccumulator) IsPhaseBlocked ¶ added in v1.1.0
func (a *StreamAccumulator) IsPhaseBlocked() bool
IsPhaseBlocked checks if a phase_blocked marker has been detected. Uses the global PhaseMarkers matcher.
func (*StreamAccumulator) IsPhaseComplete ¶ added in v1.1.0
func (a *StreamAccumulator) IsPhaseComplete() bool
IsPhaseComplete checks if a phase_complete marker with value "true" has been detected. Uses the global PhaseMarkers matcher.
func (*StreamAccumulator) Len ¶ added in v1.1.0
func (a *StreamAccumulator) Len() int
Len returns the current length of accumulated content.
func (*StreamAccumulator) Reset ¶ added in v1.1.0
func (a *StreamAccumulator) Reset()
Reset clears the accumulator for reuse.
func (*StreamAccumulator) ToResponse ¶ added in v1.1.0
func (a *StreamAccumulator) ToResponse() *CompletionResponse
ToResponse converts the accumulated stream into a CompletionResponse. This is useful after the stream is complete.
func (*StreamAccumulator) Usage ¶ added in v1.1.0
func (a *StreamAccumulator) Usage() *TokenUsage
Usage returns the token usage from the final chunk, or nil if not yet received.
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"`
// Cache-related tokens (Claude specific)
CacheCreationInputTokens int `json:"cache_creation_input_tokens,omitempty"`
CacheReadInputTokens int `json:"cache_read_input_tokens,omitempty"`
}
TokenUsage tracks token consumption.
func (*TokenUsage) Add ¶
func (u *TokenUsage) Add(other TokenUsage)
Add calculates total tokens and adds to existing usage.
type Tool ¶
type Tool struct {
Name string `json:"name"`
Description string `json:"description"`
Parameters json.RawMessage `json:"parameters"` // JSON Schema
}
Tool defines an available tool for the LLM.
type ToolCall ¶
type ToolCall struct {
ID string `json:"id"`
Name string `json:"name"`
Arguments json.RawMessage `json:"arguments"`
}
ToolCall represents a tool invocation request from the LLM.
type UserMessage ¶ added in v1.1.0
type UserMessage = session.UserMessage
UserMessage is a message to send to Claude via stream-json input.