claude

package
v1.4.2 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Jan 26, 2026 License: MIT Imports: 19 Imported by: 0

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

View Source
const (
	SessionStatusCreating    = session.StatusCreating
	SessionStatusActive      = session.StatusActive
	SessionStatusClosing     = session.StatusClosing
	SessionStatusClosed      = session.StatusClosed
	SessionStatusError       = session.StatusError
	SessionStatusTerminating = session.StatusTerminating
)

Session status constants.

Variables

View Source
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.

View Source
var (
	// ErrUnavailable indicates the LLM service is unavailable.
	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.

View Source
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.

View Source
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.

View Source
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()
View Source
var NewUserMessage = session.NewUserMessage

NewUserMessage creates a new user message for sending to Claude.

Functions

func ContextWithClient added in v1.1.0

func ContextWithClient(ctx context.Context, c Client) context.Context

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 AssistantEvent added in v1.3.0

type AssistantEvent struct {
	// MessageID is the unique message identifier from the API.
	MessageID string `json:"id"`

	// Content contains the content blocks (text, tool_use, etc.).
	Content []ContentBlock `json:"content"`

	// Model is the model that generated this message.
	Model string `json:"model"`

	// StopReason indicates why generation stopped ("end_turn", "tool_use", etc.).
	StopReason string `json:"stop_reason,omitempty"`

	// Usage contains per-message token usage (includes cache tokens).
	Usage MessageUsage `json:"usage"`

	// Text is a convenience field with concatenated text content.
	Text string `json:"-"`
}

AssistantEvent contains Claude's response (one per API message).

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"`
	StructuredOutput json.RawMessage          `json:"structured_output,omitempty"`
	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 CacheDetails added in v1.3.0

type CacheDetails struct {
	Ephemeral5mInputTokens int `json:"ephemeral_5m_input_tokens,omitempty"`
	Ephemeral1hInputTokens int `json:"ephemeral_1h_input_tokens,omitempty"`
}

CacheDetails contains detailed cache token breakdown.

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

func (c *ClaudeCLI) Close() error

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

Complete implements Client. This is a convenience wrapper around StreamJSON that collects all events and returns a single CompletionResponse. If req.OnEvent is set, it will be called for each streaming event.

func (*ClaudeCLI) Provider added in v1.2.0

func (c *ClaudeCLI) Provider() string

Provider returns the provider name. Implements provider.Client.

func (*ClaudeCLI) StreamJSON added in v1.3.0

func (c *ClaudeCLI) StreamJSON(ctx context.Context, req CompletionRequest) (<-chan StreamEvent, *StreamResult, error)

StreamJSON sends a request and returns a channel of typed streaming events. The StreamResult future resolves when streaming completes with final totals.

This is the core streaming implementation. Use Complete() for a simpler blocking interface that returns a single CompletionResponse.

Example:

events, result, err := client.StreamJSON(ctx, req)
if err != nil {
    return err
}
for event := range events {
    switch event.Type {
    case StreamEventInit:
        fmt.Println("Session:", event.Init.SessionID)
    case StreamEventAssistant:
        fmt.Print(event.Assistant.Text)
    case StreamEventResult:
        fmt.Println("Cost:", event.Result.TotalCostUSD)
    }
}
final, err := result.Wait(ctx)

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 WithAgent added in v1.4.0

func WithAgent(name string) ClaudeOption

WithAgent sets an existing agent to use for the session. The agent must be defined in the project's .claude/settings.json or user settings.

func WithAgentsJSON added in v1.4.0

func WithAgentsJSON(json string) ClaudeOption

WithAgentsJSON defines custom agents inline using JSON format. The JSON should match the --agents flag format:

{
  "agent-name": {
    "description": "When to use (required)",
    "prompt": "System prompt (required)",
    "tools": ["Read", "Edit"],  // optional
    "model": "sonnet"           // optional
  }
}

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 WithAppendSystemPromptFile added in v1.4.0

func WithAppendSystemPromptFile(path string) ClaudeOption

WithAppendSystemPromptFile loads additional system prompt content from a file. The content is appended to the default system prompt. Note: Only works in print mode (-p).

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 WithDebug added in v1.4.0

func WithDebug(filter string) ClaudeOption

WithDebug enables debug mode with an optional category filter. Examples: "api,hooks" to show only those categories, "!statsig,!file" to exclude.

func WithDisableSlashCommands added in v1.4.0

func WithDisableSlashCommands() ClaudeOption

WithDisableSlashCommands disables all skills and slash commands for this session.

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 WithForkSession added in v1.4.0

func WithForkSession() ClaudeOption

WithForkSession creates a new session ID when resuming instead of reusing the original. Use with WithResume to fork from an existing session.

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 WithIncludePartialMessages added in v1.4.0

func WithIncludePartialMessages() ClaudeOption

WithIncludePartialMessages includes partial streaming events in output. Requires print mode with stream-json output format.

func WithInputFormat added in v1.4.0

func WithInputFormat(format string) ClaudeOption

WithInputFormat sets the input format for streaming. Valid values: "text" (default), "stream-json" (realtime streaming input).

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 WithModel

func WithModel(model string) ClaudeOption

WithModel sets the default model.

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 WithPluginDir added in v1.4.0

func WithPluginDir(path string) ClaudeOption

WithPluginDir adds a plugin directory to load for this session. Can be called multiple times for multiple directories.

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 WithSettings added in v1.4.0

func WithSettings(pathOrJSON string) ClaudeOption

WithSettings loads additional settings from a file path or JSON string.

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 WithSystemPromptFile added in v1.4.0

func WithSystemPromptFile(path string) ClaudeOption

WithSystemPromptFile loads the system prompt from a file, replacing the default. This is useful for version-controlled prompt templates. Note: Only works in print mode (-p).

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 WithVerbose added in v1.4.0

func WithVerbose() ClaudeOption

WithVerbose enables verbose output for debugging.

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)

	// StreamJSON sends a request and returns streaming events plus a result future.
	// Events include init (session_id), assistant (per-message content/usage), result (final totals).
	// The channel closes when streaming completes. Use result.Wait() for the final ResultEvent.
	StreamJSON(ctx context.Context, req CompletionRequest) (<-chan StreamEvent, *StreamResult, error)
}

Client is the interface for LLM providers. Implementations must be safe for concurrent use.

func ClientFromContext added in v1.1.0

func ClientFromContext(ctx context.Context) Client

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

func MustClientFromContext(ctx context.Context) Client

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"`

	// JSONSchema forces structured output matching the given JSON schema.
	// When set, Claude will output valid JSON conforming to this schema.
	// This overrides any client-level schema set via WithJSONSchema().
	JSONSchema string `json:"json_schema,omitempty"`

	// OnEvent is called for each streaming event during execution.
	// Use this to capture transcripts in real-time, track progress, or log activity.
	// Events include: StreamEventInit, StreamEventAssistant, StreamEventResult, StreamEventHook.
	// If nil, events are still processed internally but not exposed to caller.
	// This callback is invoked synchronously - keep handlers fast to avoid blocking.
	OnEvent func(StreamEvent) `json:"-"`
}

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.

func StreamToComplete added in v1.3.0

func StreamToComplete(ctx context.Context, events <-chan StreamEvent, result *StreamResult) (*CompletionResponse, error)

StreamToComplete converts streaming events to a CompletionResponse. This drains the events channel and waits for the final result.

func StreamToCompleteWithCallback added in v1.3.0

func StreamToCompleteWithCallback(ctx context.Context, events <-chan StreamEvent, result *StreamResult, onEvent func(StreamEvent)) (*CompletionResponse, error)

StreamToCompleteWithCallback converts streaming events to a CompletionResponse, calling the optional onEvent callback for each event as it arrives. Use this to capture transcripts in real-time, track progress, or log activity.

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.

func (*Config) Validate added in v1.1.0

func (c *Config) Validate() error

Validate checks if the configuration is valid.

type ContentBlock added in v1.3.0

type ContentBlock struct {
	Type      string          `json:"type"` // "text", "tool_use", "tool_result", "thinking"
	Text      string          `json:"text,omitempty"`
	ID        string          `json:"id,omitempty"`        // For tool_use
	Name      string          `json:"name,omitempty"`      // For tool_use
	Input     json.RawMessage `json:"input,omitempty"`     // For tool_use
	Thinking  string          `json:"thinking,omitempty"`  // For thinking blocks (extended thinking)
	Signature string          `json:"signature,omitempty"` // For thinking blocks (cryptographic signature)
}

ContentBlock represents a block of content in a message.

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.

func NewError

func NewError(op string, err error, retryable bool) *Error

NewError creates a new LLM error.

func (*Error) Error

func (e *Error) Error() string

Error implements the error interface.

func (*Error) Unwrap

func (e *Error) Unwrap() error

Unwrap returns the underlying error for errors.Is/As support.

type FileResult added in v1.3.0

type FileResult struct {
	FilePath   string `json:"filePath"`
	Content    string `json:"content"`
	NumLines   int    `json:"numLines"`
	StartLine  int    `json:"startLine"`
	TotalLines int    `json:"totalLines"`
}

FileResult contains data from a file read operation.

type HookEvent added in v1.3.0

type HookEvent struct {
	SessionID string `json:"session_id"`
	HookName  string `json:"hook_name"`
	HookEvent string `json:"hook_event"`
	Stdout    string `json:"stdout"`
	Stderr    string `json:"stderr"`
	ExitCode  int    `json:"exit_code"`
}

HookEvent contains hook execution output.

type InitEvent added in v1.3.0

type InitEvent struct {
	SessionID         string      `json:"session_id"`
	Model             string      `json:"model"`
	CWD               string      `json:"cwd"`
	Tools             []string    `json:"tools"`
	MCPServers        []MCPServer `json:"mcp_servers,omitempty"`
	ClaudeCodeVersion string      `json:"claude_code_version"`
	PermissionMode    string      `json:"permissionMode"`
}

InitEvent contains session initialization data. Emitted once at the start of streaming, after the first message is sent.

type InitMessage added in v1.1.0

type InitMessage = session.InitMessage

InitMessage contains session initialization data.

type MCPServer added in v1.3.0

type MCPServer struct {
	Name   string `json:"name"`
	Status string `json:"status"`
}

MCPServer represents an MCP server's connection status.

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 MessageUsage added in v1.3.0

type MessageUsage struct {
	InputTokens              int           `json:"input_tokens"`
	OutputTokens             int           `json:"output_tokens"`
	CacheCreationInputTokens int           `json:"cache_creation_input_tokens,omitempty"`
	CacheReadInputTokens     int           `json:"cache_read_input_tokens,omitempty"`
	CacheCreation            *CacheDetails `json:"cache_creation,omitempty"`
	ServiceTier              string        `json:"service_tier,omitempty"`
}

MessageUsage tracks token usage for a single message.

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 StreamJSON was called.

func (*MockClient) Complete

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) StreamJSON added in v1.3.0

func (m *MockClient) StreamJSON(ctx context.Context, req CompletionRequest) (<-chan StreamEvent, *StreamResult, error)

StreamJSON 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) WithStreamJSONFunc added in v1.3.0

func (m *MockClient) WithStreamJSONFunc(fn func(ctx context.Context, req CompletionRequest) (<-chan StreamEvent, *StreamResult, error)) *MockClient

WithStreamJSONFunc sets a custom handler for StreamJSON calls.

type ModelUsageDetail added in v1.3.0

type ModelUsageDetail struct {
	InputTokens              int     `json:"inputTokens"`
	OutputTokens             int     `json:"outputTokens"`
	CacheReadInputTokens     int     `json:"cacheReadInputTokens,omitempty"`
	CacheCreationInputTokens int     `json:"cacheCreationInputTokens,omitempty"`
	WebSearchRequests        int     `json:"webSearchRequests,omitempty"`
	CostUSD                  float64 `json:"costUSD"`
	ContextWindow            int     `json:"contextWindow,omitempty"`
	MaxOutputTokens          int     `json:"maxOutputTokens,omitempty"`
}

ModelUsageDetail contains per-model token usage and cost.

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 ResultEvent added in v1.3.0

type ResultEvent struct {
	// Subtype is "success" or "error".
	Subtype string `json:"subtype"`

	// IsError indicates if this is an error result.
	IsError bool `json:"is_error"`

	// Result is the text result (for non-schema requests).
	Result string `json:"result"`

	// StructuredOutput contains JSON when --json-schema was used.
	StructuredOutput json.RawMessage `json:"structured_output,omitempty"`

	// SessionID is the session identifier.
	SessionID string `json:"session_id"`

	// DurationMS is the total request duration in milliseconds.
	DurationMS int `json:"duration_ms"`

	// DurationAPIMS is the time spent in API calls.
	DurationAPIMS int `json:"duration_api_ms"`

	// NumTurns is the number of agentic turns taken.
	NumTurns int `json:"num_turns"`

	// TotalCostUSD is the total cost of this request.
	TotalCostUSD float64 `json:"total_cost_usd"`

	// Usage contains cumulative token usage.
	Usage ResultUsage `json:"usage"`

	// ModelUsage contains per-model usage breakdown.
	ModelUsage map[string]ModelUsageDetail `json:"modelUsage,omitempty"`
}

ResultEvent contains the final result of a streaming request. This is the last event emitted and contains cumulative totals.

type ResultMessage added in v1.1.0

type ResultMessage = session.ResultMessage

ResultMessage contains the final result of a session turn.

type ResultUsage added in v1.3.0

type ResultUsage struct {
	InputTokens              int           `json:"input_tokens"`
	OutputTokens             int           `json:"output_tokens"`
	CacheCreationInputTokens int           `json:"cache_creation_input_tokens,omitempty"`
	CacheReadInputTokens     int           `json:"cache_read_input_tokens,omitempty"`
	CacheCreation            *CacheDetails `json:"cache_creation,omitempty"`
	ServiceTier              string        `json:"service_tier,omitempty"`
}

ResultUsage contains aggregate token usage from a result.

type Role

type Role string

Role identifies the message sender.

const (
	RoleUser      Role = "user"
	RoleAssistant Role = "assistant"
	RoleTool      Role = "tool"
	RoleSystem    Role = "system"
)

Standard message roles.

type Session added in v1.1.0

type Session = session.Session

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

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) StreamJSON added in v1.3.0

func (c *SessionClient) StreamJSON(ctx context.Context, req CompletionRequest) (<-chan StreamEvent, *StreamResult, error)

StreamJSON implements Client by sending a message and streaming responses. Each assistant message is yielded as a StreamEvent.

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 events and provides analysis. It accumulates events as they arrive.

Thread-safe for concurrent append and read operations.

func NewStreamAccumulator added in v1.1.0

func NewStreamAccumulator() *StreamAccumulator

NewStreamAccumulator creates an accumulator for collecting stream events.

Example:

acc := NewStreamAccumulator()

for event := range events {
    acc.Append(event)
}

func (*StreamAccumulator) Append added in v1.1.0

func (a *StreamAccumulator) Append(event StreamEvent)

Append adds an event's content to the accumulator. It captures assistant text, usage data, and session info.

func (*StreamAccumulator) ConsumeStream added in v1.1.0

func (a *StreamAccumulator) ConsumeStream(events <-chan StreamEvent) error

ConsumeStream reads all events 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:

events, result, _ := client.StreamJSON(ctx, req)
acc := NewStreamAccumulator()
if err := acc.ConsumeStream(events); err != nil {
    // Handle error
}
response := acc.ToResponse()

func (*StreamAccumulator) ConsumeStreamWithCallback added in v1.1.0

func (a *StreamAccumulator) ConsumeStreamWithCallback(events <-chan StreamEvent, callback func(StreamEvent) bool) error

ConsumeStreamWithCallback reads events 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()
err := acc.ConsumeStreamWithCallback(events, func(event StreamEvent) bool {
    if event.Type == StreamEventAssistant {
        fmt.Print(event.Assistant.Text) // Print as we receive
    }
    return true // Continue consuming
})

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 result event 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) Len added in v1.1.0

func (a *StreamAccumulator) Len() int

Len returns the current length of accumulated content.

func (*StreamAccumulator) Model added in v1.3.0

func (a *StreamAccumulator) Model() string

Model returns the model name from events.

func (*StreamAccumulator) Reset added in v1.1.0

func (a *StreamAccumulator) Reset()

Reset clears the accumulator for reuse.

func (*StreamAccumulator) SessionID added in v1.3.0

func (a *StreamAccumulator) SessionID() string

SessionID returns the session ID from init/result events.

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, or nil if not yet received.

type StreamEvent added in v1.3.0

type StreamEvent struct {
	// Type identifies which field is populated.
	Type StreamEventType

	// SessionID is available on all events after init.
	SessionID string

	// Init is populated when Type == StreamEventInit.
	Init *InitEvent

	// Assistant is populated when Type == StreamEventAssistant.
	Assistant *AssistantEvent

	// Result is populated when Type == StreamEventResult.
	Result *ResultEvent

	// User is populated when Type == StreamEventUser.
	// Contains tool results from tool executions.
	User *UserEvent

	// Hook is populated when Type == StreamEventHook.
	Hook *HookEvent

	// Error is populated when Type == StreamEventError.
	Error error

	// Raw contains the original JSON for advanced parsing.
	Raw json.RawMessage
}

StreamEvent represents a single event from Claude CLI stream-json output. Check Type to determine which field is populated.

type StreamEventType added in v1.3.0

type StreamEventType string

StreamEventType identifies the type of streaming event.

const (
	StreamEventInit      StreamEventType = "init"
	StreamEventAssistant StreamEventType = "assistant"
	StreamEventUser      StreamEventType = "user"
	StreamEventResult    StreamEventType = "result"
	StreamEventHook      StreamEventType = "hook"
	StreamEventError     StreamEventType = "error"
)

type StreamResult added in v1.3.0

type StreamResult struct {
	// contains filtered or unexported fields
}

StreamResult is a future that resolves when streaming completes. Use Wait() to block until the final result is available.

func NewTestStreamResult added in v1.3.0

func NewTestStreamResult() *StreamResult

NewTestStreamResult creates a StreamResult for testing. Use TestComplete() to complete it from test code.

func (*StreamResult) Done added in v1.3.0

func (sr *StreamResult) Done() <-chan struct{}

Done returns a channel that closes when streaming completes.

func (*StreamResult) TestComplete added in v1.3.0

func (sr *StreamResult) TestComplete(result *ResultEvent, err error)

TestComplete is a test helper to complete a StreamResult. Only use in tests.

func (*StreamResult) Wait added in v1.3.0

func (sr *StreamResult) Wait(ctx context.Context) (*ResultEvent, error)

Wait blocks until streaming completes and returns the final result.

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 ToolResultContent added in v1.3.0

type ToolResultContent struct {
	Type      string `json:"type"`               // "tool_result"
	ToolUseID string `json:"tool_use_id"`        // Matches the tool_use block's ID
	IsError   bool   `json:"is_error,omitempty"` // True if tool execution failed

	// ContentRaw holds the raw content field which can be:
	// - A string (simple tool result)
	// - An array of objects (complex result like subagent output)
	ContentRaw json.RawMessage `json:"content"`
}

ToolResultContent represents a tool result in the user message content.

func (*ToolResultContent) GetContent added in v1.3.0

func (t *ToolResultContent) GetContent() string

GetContent returns the content as a string. For simple results, returns the string directly. For complex results (arrays), returns the concatenated text.

type ToolUseResult added in v1.3.0

type ToolUseResult struct {
	Type string `json:"type"` // "text", "image", etc.

	// File is populated for file read operations.
	File *FileResult `json:"file,omitempty"`
}

ToolUseResult contains structured data about tool execution.

type UserEvent added in v1.3.0

type UserEvent struct {
	// SessionID is the session identifier.
	SessionID string `json:"session_id"`

	// Message contains the tool result content.
	Message UserEventMessage `json:"message"`

	// ParentToolUseID links this result to a subagent's tool use (if any).
	ParentToolUseID *string `json:"parent_tool_use_id"`

	// ToolUseResultRaw contains the raw tool_use_result field.
	// Can be a string (error message) or object (structured result).
	// Use GetToolUseResult() to get the parsed value.
	ToolUseResultRaw json.RawMessage `json:"tool_use_result,omitempty"`

	// UUID is the unique event identifier.
	UUID string `json:"uuid,omitempty"`
}

UserEvent contains tool execution results. Emitted after a tool is executed, containing the tool's output.

func (*UserEvent) GetToolUseResult added in v1.3.0

func (u *UserEvent) GetToolUseResult() *ToolUseResult

GetToolUseResult parses ToolUseResultRaw and returns the structured result. Returns nil if the field is a string (error message) or not present.

func (*UserEvent) GetToolUseResultError added in v1.3.0

func (u *UserEvent) GetToolUseResultError() string

GetToolUseResultError returns the error string if ToolUseResultRaw is a string. Returns empty string if not an error or not present.

type UserEventMessage added in v1.3.0

type UserEventMessage struct {
	Role    string              `json:"role"`
	Content []ToolResultContent `json:"content"`
}

UserEventMessage represents the message content in a user event (tool result).

type UserMessage added in v1.1.0

type UserMessage = session.UserMessage

UserMessage is a message to send to Claude via stream-json input.

Directories

Path Synopsis
Package jsonl provides reading and tailing of Claude Code session JSONL files.
Package jsonl provides reading and tailing of Claude Code session JSONL files.
Package session provides long-running Claude CLI session management with bidirectional stream-json I/O.
Package session provides long-running Claude CLI session management with bidirectional stream-json I/O.

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL