shared

package
v0.1.4 Latest Latest
Warning

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

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

Documentation

Index

Constants

View Source
const (
	MessageTypeUser      = "user"
	MessageTypeAssistant = "assistant"
	MessageTypeSystem    = "system"
	MessageTypeResult    = "result"

	// Control protocol message types
	MessageTypeControlRequest  = "control_request"
	MessageTypeControlResponse = "control_response"

	// Partial message streaming type
	MessageTypeStreamEvent = "stream_event"

	// SDK message types (from TypeScript SDK)
	MessageTypeToolProgress = "tool_progress"
	MessageTypeAuthStatus   = "auth_status"
)

Message type constants

View Source
const (
	SystemSubtypeInit            = "init"
	SystemSubtypeCompactBoundary = "compact_boundary"
	SystemSubtypeStatus          = "status"
	SystemSubtypeHookResponse    = "hook_response"
)

System message subtype constants

View Source
const (
	ContentBlockTypeText       = "text"
	ContentBlockTypeThinking   = "thinking"
	ContentBlockTypeToolUse    = "tool_use"
	ContentBlockTypeToolResult = "tool_result"
)

Content block type constants

View Source
const (
	StreamEventTypeContentBlockStart = "content_block_start"
	StreamEventTypeContentBlockDelta = "content_block_delta"
	StreamEventTypeContentBlockStop  = "content_block_stop"
	StreamEventTypeMessageStart      = "message_start"
	StreamEventTypeMessageDelta      = "message_delta"
	StreamEventTypeMessageStop       = "message_stop"
)

Stream event type constants for Event["type"] discrimination. Use these when type-switching on StreamEvent.Event to handle different event types.

View Source
const (
	ModelShortNameOpus   = "opus"
	ModelShortNameSonnet = "sonnet"
	ModelShortNameHaiku  = "haiku"
)

Model short name constants. These match the TypeScript SDK's AgentDefinition which accepts 'sonnet' | 'opus' | 'haiku' | 'inherit'.

View Source
const (
	ResultSubtypeSuccess                         = "success"
	ResultSubtypeErrorDuringExecution            = "error_during_execution"
	ResultSubtypeErrorMaxTurns                   = "error_max_turns"
	ResultSubtypeErrorMaxBudgetUSD               = "error_max_budget_usd"
	ResultSubtypeErrorMaxStructuredOutputRetries = "error_max_structured_output_retries"
)

ResultSubtype constants for result message discrimination.

Variables

View Source
var ErrNoMoreMessages = errors.New("no more messages")

ErrNoMoreMessages is returned by MessageIterator.Next when there are no more messages.

Functions

func AsErrorType

func AsErrorType[T error](err error) (T, bool)

AsErrorType extracts error of type T from err chain. Returns the extracted error and true if found, zero value and false otherwise.

func CloneEvent

func CloneEvent(event map[string]any) map[string]any

CloneEvent creates a deep copy of a stream event.

func CloseOnCancel

func CloseOnCancel(ctx context.Context, closer io.Closer) *sync.WaitGroup

CloseOnCancel starts a goroutine that closes a resource when context is cancelled. Returns a WaitGroup that completes when the cleanup goroutine finishes. This is a common pattern for ensuring resources are cleaned up on context cancellation.

Example:

wg := shared.CloseOnCancel(ctx, conn)
// ... use conn ...
wg.Wait() // ensure cleanup completed

func CloseOnCancelFunc

func CloseOnCancelFunc(ctx context.Context, cleanup func()) *sync.WaitGroup

CloseOnCancelFunc starts a goroutine that calls a cleanup function when context is cancelled. This is useful when you need custom cleanup logic beyond io.Closer.

Example:

wg := shared.CloseOnCancelFunc(ctx, func() {
    session.Close()
    conn.Disconnect()
})

func Contains

func Contains(slice []string, item string) bool

Contains checks if a string is in a slice of strings. This is a utility function used for validation throughout the package.

func DoneErr

func DoneErr(ctx context.Context) error

DoneErr returns the context error if cancelled, nil otherwise. Non-blocking version of ctx.Err() for quick checks.

func Error

func Error(msg string) error

Error creates an error message from a string.

func Errorf

func Errorf(format string, args ...any) error

Errorf creates a formatted error message.

func ExtractBlocks

func ExtractBlocks[T ContentBlock](msg Message) []T

ExtractBlocks extracts content blocks of type T from an assistant message. Returns nil if the message is not an AssistantMessage or has no matching blocks.

Example:

toolUses := ExtractBlocks[*ToolUseBlock](msg)
textBlocks := ExtractBlocks[*TextBlock](msg)

func ExtractDelta

func ExtractDelta(event map[string]any) (string, error)

ExtractDelta extracts the text content from a content_block_delta event.

func FormatStats

func FormatStats(stats StreamStats) string

FormatStats formats StreamStats into a human-readable string.

func GetContentText

func GetContentText(msg Message) string

GetContentText concatenates all text content from a message. Returns empty string if the message is not an assistant message or contains no text blocks.

func GetDefaultCommand

func GetDefaultCommand() string

GetDefaultCommand returns the default command name for the current platform.

func GetDefaultPath

func GetDefaultPath() string

GetDefaultPath returns the default installation path for the current platform.

func GetModelShortNames

func GetModelShortNames() []string

GetModelShortNames returns all recognized short model names.

func GetValue

func GetValue[T any](ctx context.Context, key ContextKey) (T, bool)

GetValue retrieves a typed value from context with type assertion. Returns the zero value and false if the key doesn't exist or type doesn't match.

func HasToolUses

func HasToolUses(msg Message) bool

HasToolUses returns true if the message contains any tool use blocks.

func IsCLINotFound

func IsCLINotFound(err error) bool

IsCLINotFound checks if an error is a CLINotFoundError.

func IsConfigurationError

func IsConfigurationError(err error) bool

IsConfigurationError checks if an error is a ConfigurationError.

func IsConnectionError

func IsConnectionError(err error) bool

IsConnectionError checks if an error is a ConnectionError.

func IsCriticalStreamEvent

func IsCriticalStreamEvent(eventType string) bool

IsCriticalStreamEvent returns true if the event type is critical for response processing.

func IsDeltaStreamEvent

func IsDeltaStreamEvent(eventType string) bool

IsDeltaStreamEvent returns true if the event type contains delta content.

func IsDone

func IsDone(ctx context.Context) bool

IsDone checks if the context has been cancelled without blocking. Useful for early exit in loops.

func IsErrorType

func IsErrorType[T error](err error) bool

IsErrorType checks if err is of type T using errors.As. This generic helper eliminates duplicate type checking functions.

func IsJSONDecodeError

func IsJSONDecodeError(err error) bool

IsJSONDecodeError checks if an error is a JSONDecodeError.

func IsMessageParseError

func IsMessageParseError(err error) bool

IsMessageParseError checks if an error is a MessageParseError.

func IsModelError

func IsModelError(err error) bool

IsModelError checks if an error is a ModelError.

func IsParserError

func IsParserError(err error) bool

IsParserError checks if an error is a ParserError.

func IsPermissionError

func IsPermissionError(err error) bool

IsPermissionError checks if an error is a PermissionError.

func IsProcessError

func IsProcessError(err error) bool

IsProcessError checks if an error is a ProcessError.

func IsProtocolError

func IsProtocolError(err error) bool

IsProtocolError checks if an error is a ProtocolError.

func IsTimeoutError

func IsTimeoutError(err error) bool

IsTimeoutError checks if an error is a TimeoutError.

func IsToolUseMessage

func IsToolUseMessage(msg Message) bool

IsToolUseMessage returns true if the message is an assistant message containing tool uses.

func IsValidModelShortName

func IsValidModelShortName(name string) bool

IsValidModelShortName reports whether name is a recognized short model name.

func MarshalWithType

func MarshalWithType(v any, typeName string) ([]byte, error)

MarshalWithType marshals a value with an explicit "type" field. This is a helper for message types that need to include their type in JSON output.

The function marshals the struct fields without calling the MarshalJSON method, then adds the type field. This avoids infinite recursion.

Example usage:

func (m *UserMessage) MarshalJSON() ([]byte, error) {
    return MarshalWithType(m, MessageTypeUser)
}

func MarshalWithTypeAndSubtype

func MarshalWithTypeAndSubtype(v any, typeName, subtype string) ([]byte, error)

MarshalWithTypeAndSubtype marshals a value with explicit "type" and "subtype" fields. This is a helper for system message types that need both fields in JSON output.

Example usage:

func (m *StatusMessage) MarshalJSON() ([]byte, error) {
    return MarshalWithTypeAndSubtype(m, MessageTypeSystem, SystemSubtypeStatus)
}

func MustGetValue

func MustGetValue[T any](ctx context.Context, key ContextKey) T

MustGetValue retrieves a typed value from context, panicking if not found. Use this only when the value is guaranteed to exist.

func ParseIndex

func ParseIndex(event map[string]any) (int, error)

ParseIndex extracts the index from a stream event.

func ResolveModelName

func ResolveModelName(name string) string

ResolveModelName resolves a short model name to its full model ID. If the input is already a full model ID (or unknown), it is returned unchanged.

func SanitizeMessage

func SanitizeMessage(msg Message) any

SanitizeMessage returns a sanitized version of a message for logging.

func StreamEventTypeToString

func StreamEventTypeToString(eventType string) string

StreamEventTypeToString converts a stream event type to a human-readable string.

func ValidateAssistantMessage

func ValidateAssistantMessage(msg *AssistantMessage) error

ValidateAssistantMessage validates an AssistantMessage.

func ValidateContentBlock

func ValidateContentBlock(block ContentBlock) error

ValidateContentBlock validates a ContentBlock.

func ValidateContextFile

func ValidateContextFile(file string) error

ValidateContextFile validates a context file path.

func ValidateContextFiles

func ValidateContextFiles(files []string) error

ValidateContextFiles validates a list of context files.

func ValidateEnvironmentVariables

func ValidateEnvironmentVariables(env map[string]string) error

ValidateEnvironmentVariables validates environment variables.

func ValidateFileExtension

func ValidateFileExtension(file string, allowedExtensions []string) error

ValidateFileExtension validates a file extension against allowed extensions.

func ValidateFileSize

func ValidateFileSize(file string, maxSize int64) error

ValidateFileSize validates a file size against a maximum size.

func ValidateMessage

func ValidateMessage(msg Message) error

ValidateMessage validates a message for protocol compliance.

func ValidateModel

func ValidateModel(model string) error

ValidateModel validates a model name. Accepts any non-empty model name to support alternate providers (zai, synthetic).

func ValidatePermissionMode

func ValidatePermissionMode(mode string) error

ValidatePermissionMode validates a permission mode.

func ValidateResultMessage

func ValidateResultMessage(msg *ResultMessage) error

ValidateResultMessage validates a ResultMessage.

func ValidateSystemMessage

func ValidateSystemMessage(msg *SystemMessage) error

ValidateSystemMessage validates a SystemMessage.

func ValidateTextBlock

func ValidateTextBlock(block *TextBlock) error

ValidateTextBlock validates a TextBlock.

func ValidateThinkingBlock

func ValidateThinkingBlock(block *ThinkingBlock) error

ValidateThinkingBlock validates a ThinkingBlock.

func ValidateTimeout

func ValidateTimeout(timeout string) error

ValidateTimeout validates a timeout string.

func ValidateToolResultBlock

func ValidateToolResultBlock(block *ToolResultBlock) error

ValidateToolResultBlock validates a ToolResultBlock.

func ValidateToolUseBlock

func ValidateToolUseBlock(block *ToolUseBlock) error

ValidateToolUseBlock validates a ToolUseBlock.

func ValidateUserMessage

func ValidateUserMessage(msg *UserMessage) error

ValidateUserMessage validates a UserMessage.

func WithBufferSize

func WithBufferSize(size int) func(*Options)

WithBufferSize sets the buffer size for message channels.

func WithCLICommand

func WithCLICommand(command string) func(*Options)

WithCLICommand sets the CLI command option.

func WithCLIPath

func WithCLIPath(path string) func(*Options)

WithCLIPath sets the CLI path option.

func WithCacheTTL

func WithCacheTTL(ttl string) func(*Options)

WithCacheTTL sets cache expiration time.

func WithContextFiles

func WithContextFiles(files ...string) func(*Options)

WithContextFiles sets the context files option.

func WithCustomArgs

func WithCustomArgs(args ...string) func(*Options)

WithCustomArgs sets custom arguments.

func WithDisableCache

func WithDisableCache(disable bool) func(*Options)

WithDisableCache disables caching.

func WithEnableMetrics

func WithEnableMetrics(enable bool) func(*Options)

WithEnableMetrics enables performance metrics.

func WithEnableStructuredOutput

func WithEnableStructuredOutput(enable bool) func(*Options)

WithEnableStructuredOutput enables structured output.

func WithEnv

func WithEnv(env map[string]string) func(*Options)

WithEnv sets environment variables.

func WithIncludePartialMessages

func WithIncludePartialMessages(include bool) func(*Options)

WithIncludePartialMessages enables partial messages.

func WithLogger

func WithLogger(logger Logger) func(*Options)

WithLogger sets the logger interface.

func WithMaxMessages

func WithMaxMessages(max int) func(*Options)

WithMaxMessages sets the maximum number of messages.

func WithModel

func WithModel(model string) func(*Options)

WithModel sets the model option.

func WithPermissionMode

func WithPermissionMode(mode string) func(*Options)

WithPermissionMode sets the permission mode option.

func WithTimeout

func WithTimeout(timeout string) func(*Options)

WithTimeout sets the timeout option.

func WithTrace

func WithTrace(trace bool) func(*Options)

WithTrace enables detailed tracing.

func WithValue

func WithValue[T any](ctx context.Context, key ContextKey, val T) context.Context

WithValue adds a typed value to context.

Types

type AccountInfo

type AccountInfo struct {
	Email            string `json:"email,omitempty"`
	Organization     string `json:"organization,omitempty"`
	SubscriptionType string `json:"subscriptionType,omitempty"`
	TokenSource      string `json:"tokenSource,omitempty"`
	ApiKeySource     string `json:"apiKeySource,omitempty"`
}

AccountInfo contains information about the logged-in user's account.

type AgentDefinition

type AgentDefinition struct {
	Description                        string               `json:"description"`
	Tools                              []string             `json:"tools,omitempty"`
	DisallowedTools                    []string             `json:"disallowedTools,omitempty"`
	Prompt                             string               `json:"prompt"`
	Model                              AgentModel           `json:"model,omitempty"`
	McpServers                         []AgentMcpServerSpec `json:"mcpServers,omitempty"`
	CriticalSystemReminderExperimental string               `json:"criticalSystemReminder_EXPERIMENTAL,omitempty"`
}

AgentDefinition defines a custom subagent.

type AgentMcpServerSpec

type AgentMcpServerSpec struct {
	Name    string                          `json:"name,omitempty"`
	Servers map[string]McpStdioServerConfig `json:"servers,omitempty"`
}

AgentMcpServerSpec represents an MCP server specification for an agent. It can be either a simple string (server name) or a map of server configurations.

type AgentModel

type AgentModel string

AgentModel represents the model to use for an agent.

const (
	AgentModelSonnet  AgentModel = "sonnet"
	AgentModelOpus    AgentModel = "opus"
	AgentModelHaiku   AgentModel = "haiku"
	AgentModelInherit AgentModel = "inherit"
)

type AlwaysAvailableCLIChecker

type AlwaysAvailableCLIChecker struct{}

AlwaysAvailableCLIChecker is a CLIChecker that always returns true. Useful for testing without the actual CLI.

func (AlwaysAvailableCLIChecker) IsCLIAvailable

func (AlwaysAvailableCLIChecker) IsCLIAvailable() bool

IsCLIAvailable implements CLIChecker.

type ApiKeySource

type ApiKeySource string

ApiKeySource represents the source of an API key.

const (
	ApiKeySourceUser      ApiKeySource = "user"
	ApiKeySourceProject   ApiKeySource = "project"
	ApiKeySourceOrg       ApiKeySource = "org"
	ApiKeySourceTemporary ApiKeySource = "temporary"
)

type AssistantMessage

type AssistantMessage struct {
	MessageType string                 `json:"type"`
	Content     []ContentBlock         `json:"content"`
	Model       string                 `json:"model"`
	Error       *AssistantMessageError `json:"error,omitempty"`
}

AssistantMessage represents a message from the assistant.

func (*AssistantMessage) GetError

GetError returns the error type or empty string if nil.

func (*AssistantMessage) HasError

func (m *AssistantMessage) HasError() bool

HasError returns true if the message contains an error.

func (*AssistantMessage) IsRateLimited

func (m *AssistantMessage) IsRateLimited() bool

IsRateLimited returns true if the error is a rate limit error.

func (*AssistantMessage) MarshalJSON

func (m *AssistantMessage) MarshalJSON() ([]byte, error)

MarshalJSON implements custom JSON marshaling for AssistantMessage

func (*AssistantMessage) Type

func (m *AssistantMessage) Type() string

Type returns the message type for AssistantMessage.

func (*AssistantMessage) UnmarshalJSON

func (m *AssistantMessage) UnmarshalJSON(data []byte) error

UnmarshalJSON implements custom JSON unmarshaling for AssistantMessage

type AssistantMessageError

type AssistantMessageError string

AssistantMessageError represents error types in assistant messages.

const (
	AssistantMessageErrorAuthFailed     AssistantMessageError = "authentication_failed"
	AssistantMessageErrorBilling        AssistantMessageError = "billing_error"
	AssistantMessageErrorRateLimit      AssistantMessageError = "rate_limit"
	AssistantMessageErrorInvalidRequest AssistantMessageError = "invalid_request"
	AssistantMessageErrorServer         AssistantMessageError = "server_error"
	AssistantMessageErrorUnknown        AssistantMessageError = "unknown"
)

AssistantMessageError constants for error type identification.

type AsyncHookOutput

type AsyncHookOutput struct {
	Async        bool `json:"async"`
	AsyncTimeout int  `json:"asyncTimeout,omitempty"` // seconds
}

AsyncHookOutput indicates an async hook response.

type AuthStatusMessage

type AuthStatusMessage struct {
	MessageType      string   `json:"type"` // always "auth_status"
	IsAuthenticating bool     `json:"isAuthenticating"`
	Output           []string `json:"output"`
	Error            *string  `json:"error,omitempty"`
	UUID             string   `json:"uuid"`
	SessionID        string   `json:"session_id"`
}

AuthStatusMessage represents authentication status.

func (*AuthStatusMessage) MarshalJSON

func (m *AuthStatusMessage) MarshalJSON() ([]byte, error)

MarshalJSON implements custom JSON marshaling for AuthStatusMessage

func (*AuthStatusMessage) Type

func (m *AuthStatusMessage) Type() string

Type returns the message type for AuthStatusMessage.

type BaseError

type BaseError struct {
	Reason string
	Inner  error
}

BaseError provides common error functionality that can be embedded in domain-specific error types. It handles reason and inner error formatting consistently.

func (*BaseError) FormatInner

func (e *BaseError) FormatInner(b *strings.Builder)

FormatInner appends the inner error to a message builder if present.

func (*BaseError) FormatReason

func (e *BaseError) FormatReason(b *strings.Builder)

FormatReason appends the reason to a message builder if present.

func (*BaseError) Unwrap

func (e *BaseError) Unwrap() error

Unwrap returns the inner error for error chaining (errors.Is/As support).

type BaseHookInput

type BaseHookInput struct {
	SessionID      string `json:"session_id"`
	TranscriptPath string `json:"transcript_path"`
	Cwd            string `json:"cwd"`
	PermissionMode string `json:"permission_mode,omitempty"`
}

BaseHookInput contains common fields for all hook inputs.

type BaseOptionFunc

type BaseOptionFunc func(*BaseOptions)

BaseOptionFunc is a function that configures BaseOptions.

func WithBaseAdditionalDirectories

func WithBaseAdditionalDirectories(dirs ...string) BaseOptionFunc

WithBaseAdditionalDirectories sets AdditionalDirectories on BaseOptions.

func WithBaseAgent

func WithBaseAgent(agent string) BaseOptionFunc

WithBaseAgent sets Agent on BaseOptions.

func WithBaseAgents

func WithBaseAgents(agents map[string]AgentDefinition) BaseOptionFunc

WithBaseAgents sets Agents on BaseOptions.

func WithBaseAllowDangerouslySkipPermissions

func WithBaseAllowDangerouslySkipPermissions(allow bool) BaseOptionFunc

WithBaseAllowDangerouslySkipPermissions sets AllowDangerouslySkipPermissions on BaseOptions.

func WithBaseAllowedTools

func WithBaseAllowedTools(tools ...string) BaseOptionFunc

WithBaseAllowedTools sets AllowedTools on BaseOptions.

func WithBaseAppendSystemPrompt

func WithBaseAppendSystemPrompt(prompt string) BaseOptionFunc

WithBaseAppendSystemPrompt sets AppendSystemPrompt on BaseOptions.

func WithBaseBetas

func WithBaseBetas(betas ...string) BaseOptionFunc

WithBaseBetas sets Betas on BaseOptions.

func WithBaseCanUseTool

func WithBaseCanUseTool(callback CanUseToolCallback) BaseOptionFunc

WithBaseCanUseTool sets the permission callback.

func WithBaseContextFiles

func WithBaseContextFiles(files ...string) BaseOptionFunc

WithBaseContextFiles sets ContextFiles on BaseOptions.

func WithBaseContinue

func WithBaseContinue(cont bool) BaseOptionFunc

WithBaseContinue sets Continue on BaseOptions.

func WithBaseCustomArgs

func WithBaseCustomArgs(args ...string) BaseOptionFunc

WithBaseCustomArgs sets CustomArgs on BaseOptions.

func WithBaseCwd

func WithBaseCwd(cwd string) BaseOptionFunc

WithBaseCwd sets the working directory for the subprocess.

func WithBaseDebugWriter

func WithBaseDebugWriter(w io.Writer) BaseOptionFunc

WithBaseDebugWriter sets DebugWriter on BaseOptions.

func WithBaseDisallowedTools

func WithBaseDisallowedTools(tools ...string) BaseOptionFunc

WithBaseDisallowedTools sets DisallowedTools on BaseOptions.

func WithBaseEnableFileCheckpointing

func WithBaseEnableFileCheckpointing(enable bool) BaseOptionFunc

WithBaseEnableFileCheckpointing sets EnableFileCheckpointing on BaseOptions.

func WithBaseEnv

func WithBaseEnv(env map[string]string) BaseOptionFunc

WithBaseEnv sets Env on BaseOptions.

func WithBaseExtraArgs

func WithBaseExtraArgs(args map[string]string) BaseOptionFunc

WithBaseExtraArgs sets ExtraArgs on BaseOptions.

func WithBaseFallbackModel

func WithBaseFallbackModel(model string) BaseOptionFunc

WithBaseFallbackModel sets FallbackModel on BaseOptions.

func WithBaseForkSession

func WithBaseForkSession(fork bool) BaseOptionFunc

WithBaseForkSession sets ForkSession on BaseOptions.

func WithBaseMaxBudgetUSD

func WithBaseMaxBudgetUSD(budget float64) BaseOptionFunc

WithBaseMaxBudgetUSD sets MaxBudgetUSD on BaseOptions.

func WithBaseMaxThinkingTokens

func WithBaseMaxThinkingTokens(tokens int) BaseOptionFunc

WithBaseMaxThinkingTokens sets MaxThinkingTokens on BaseOptions.

func WithBaseMaxTurns

func WithBaseMaxTurns(turns int) BaseOptionFunc

WithBaseMaxTurns sets MaxTurns on BaseOptions.

func WithBaseMcpServers

func WithBaseMcpServers(servers map[string]McpServerConfig) BaseOptionFunc

WithBaseMcpServers sets McpServers on BaseOptions.

func WithBaseModel

func WithBaseModel(model string) BaseOptionFunc

WithBaseModel sets Model on BaseOptions.

func WithBaseOutputFormat

func WithBaseOutputFormat(format *OutputFormat) BaseOptionFunc

WithBaseOutputFormat sets OutputFormat on BaseOptions.

func WithBasePermissionMode

func WithBasePermissionMode(mode string) BaseOptionFunc

WithBasePermissionMode sets PermissionMode on BaseOptions.

func WithBasePermissionPromptToolName

func WithBasePermissionPromptToolName(toolName string) BaseOptionFunc

WithBasePermissionPromptToolName sets PermissionPromptToolName on BaseOptions.

func WithBasePersistSession

func WithBasePersistSession(persist bool) BaseOptionFunc

WithBasePersistSession sets PersistSession on BaseOptions.

func WithBasePlugins

func WithBasePlugins(plugins ...PluginConfig) BaseOptionFunc

WithBasePlugins sets Plugins on BaseOptions.

func WithBaseResume

func WithBaseResume(sessionID string) BaseOptionFunc

WithBaseResume sets Resume session ID on BaseOptions.

func WithBaseResumeSessionAt

func WithBaseResumeSessionAt(messageUUID string) BaseOptionFunc

WithBaseResumeSessionAt sets ResumeSessionAt on BaseOptions.

func WithBaseSandbox

func WithBaseSandbox(sandbox *SandboxSettings) BaseOptionFunc

WithBaseSandbox sets Sandbox on BaseOptions.

func WithBaseSdkPluginConfig

func WithBaseSdkPluginConfig(config *SdkPluginConfig) BaseOptionFunc

WithBaseSdkPluginConfig sets the full SDK plugin configuration on BaseOptions. This provides complete control over plugin behavior including timeouts, concurrency limits, and custom configuration.

func WithBaseSettingSources

func WithBaseSettingSources(sources ...SettingSource) BaseOptionFunc

WithBaseSettingSources sets SettingSources on BaseOptions.

func WithBaseStderr

func WithBaseStderr(callback func(line string)) BaseOptionFunc

WithBaseStderr sets the stderr callback.

func WithBaseStrictMcpConfig

func WithBaseStrictMcpConfig(strict bool) BaseOptionFunc

WithBaseStrictMcpConfig sets StrictMcpConfig on BaseOptions.

func WithBaseSystemPrompt

func WithBaseSystemPrompt(prompt string) BaseOptionFunc

WithBaseSystemPrompt sets SystemPrompt on BaseOptions.

func WithBaseTools

func WithBaseTools(tools *ToolsConfig) BaseOptionFunc

WithBaseTools sets the tools configuration.

type BaseOptions

type BaseOptions struct {
	// Model specifies the Claude model to use.
	Model string

	// SystemPrompt sets the system prompt. Replaces any existing system prompt.
	SystemPrompt string

	// AppendSystemPrompt appends to the system prompt.
	// Useful for adding domain-specific instructions to the base prompt.
	AppendSystemPrompt string

	// AllowedTools restricts which tools Claude can use.
	AllowedTools []string

	// PermissionMode sets the permission mode for file operations.
	PermissionMode string

	// ContextFiles provides files to include in the context.
	ContextFiles []string

	// CustomArgs provides additional CLI arguments.
	CustomArgs []string

	// Env contains environment variables to set for the subprocess.
	Env map[string]string

	// Cwd sets the working directory for the subprocess.
	// If empty, inherits parent process working directory.
	Cwd string

	// Tools configures tool availability.
	// Can be a preset ("claude_code") or explicit tool list.
	Tools *ToolsConfig

	// Stderr is a callback invoked for each stderr line from subprocess.
	// If nil, stderr goes to parent process stderr.
	Stderr func(line string)

	// CanUseTool is a callback for runtime permission checks.
	// Invoked before each tool use when permission mode requires it.
	CanUseTool CanUseToolCallback

	// Continue continues the most recent conversation.
	Continue bool

	// Resume is the session ID to resume.
	Resume string

	// ResumeSessionAt resumes at a specific message UUID.
	ResumeSessionAt string

	// ForkSession forks instead of continuing on resume.
	ForkSession bool

	// PersistSession saves sessions to disk (default: true).
	// Pointer to distinguish unset from false.
	PersistSession *bool

	// DisallowedTools are tools explicitly disallowed.
	DisallowedTools []string

	// MaxThinkingTokens limits thinking tokens.
	MaxThinkingTokens *int

	// MaxTurns limits conversation turns.
	MaxTurns *int

	// MaxBudgetUSD is the USD budget limit.
	MaxBudgetUSD *float64

	// FallbackModel is used if primary fails.
	FallbackModel string

	// AdditionalDirectories are extra accessible directories.
	AdditionalDirectories []string

	// Agent is the main thread agent name.
	Agent string

	// Agents are custom subagent definitions.
	Agents map[string]AgentDefinition

	// Betas are beta features to enable.
	Betas []string

	// EnableFileCheckpointing tracks file changes.
	EnableFileCheckpointing bool

	// OutputFormat is for structured responses.
	OutputFormat *OutputFormat

	// Plugins are plugin configurations.
	Plugins []PluginConfig

	// SdkPluginConfig is the full SDK plugin configuration.
	// Provides complete control over plugin behavior including
	// timeouts, concurrency limits, and custom configuration.
	SdkPluginConfig *SdkPluginConfig

	// SettingSources controls which settings to load.
	SettingSources []SettingSource

	// Sandbox is sandbox configuration.
	Sandbox *SandboxSettings

	// StrictMcpConfig enables strict MCP validation.
	StrictMcpConfig bool

	// AllowDangerouslySkipPermissions is required for bypass mode.
	AllowDangerouslySkipPermissions bool

	// PermissionPromptToolName is the MCP tool for permission prompts.
	PermissionPromptToolName string

	// McpServers are MCP server configurations.
	McpServers map[string]McpServerConfig

	// ExtraArgs are additional CLI arguments.
	ExtraArgs map[string]string

	// DebugWriter specifies where to write debug output from the CLI subprocess.
	// If nil (default), stderr is suppressed or isolated.
	// Common values: os.Stderr, io.Discard, or a custom io.Writer.
	DebugWriter io.Writer
}

BaseOptions contains common options shared across different option types. This can be embedded by package-specific option types for composition.

func DefaultBaseOptions

func DefaultBaseOptions() BaseOptions

DefaultBaseOptions returns default base options.

type BufferOptionFunc

type BufferOptionFunc func(*BufferOptions)

BufferOptionFunc is a function that configures BufferOptions.

func WithBufBufferSize

func WithBufBufferSize(size int) BufferOptionFunc

WithBufBufferSize sets BufferSize on BufferOptions.

func WithBufMaxMessages

func WithBufMaxMessages(max int) BufferOptionFunc

WithBufMaxMessages sets MaxMessages on BufferOptions.

type BufferOptions

type BufferOptions struct {
	// BufferSize is the buffer size for message channels.
	BufferSize int

	// MaxMessages is the maximum number of messages to process.
	MaxMessages int
}

BufferOptions contains options for message buffering. Single Responsibility: manages buffer sizes and limits.

func DefaultBufferOptions

func DefaultBufferOptions() BufferOptions

DefaultBufferOptions returns default buffer options.

type CLIChecker

type CLIChecker interface {
	IsCLIAvailable() bool
}

CLIChecker defines the interface for checking CLI availability. This enables dependency injection for testability - tests can inject a mock that always returns true/false without requiring the actual CLI.

type CLICheckerFunc

type CLICheckerFunc func() bool

CLICheckerFunc is a function type that implements CLIChecker. This allows for easy inline checker creation in tests.

func (CLICheckerFunc) IsCLIAvailable

func (f CLICheckerFunc) IsCLIAvailable() bool

IsCLIAvailable implements CLIChecker.

type CLINotFoundError

type CLINotFoundError struct {
	Path        string // Path that was checked
	Command     string // Command that failed to execute
	Suggestions []string
}

CLINotFoundError indicates the Claude CLI executable could not be found.

func AsCLINotFoundError

func AsCLINotFoundError(err error) (*CLINotFoundError, bool)

AsCLINotFoundError extracts a CLINotFoundError from the error chain.

func NewCLINotFoundError

func NewCLINotFoundError(path, command string) *CLINotFoundError

NewCLINotFoundError creates a new CLINotFoundError with suggestions.

func (*CLINotFoundError) Error

func (e *CLINotFoundError) Error() string

Error returns a descriptive error message for CLINotFoundError.

func (*CLINotFoundError) Type

func (e *CLINotFoundError) Type() string

Type returns the error type for SDKError compliance.

type CanUseToolCallback

type CanUseToolCallback func(
	ctx context.Context,
	toolName string,
	toolInput map[string]any,
	opts CanUseToolOptions,
) (PermissionResult, error)

CanUseToolCallback is invoked before tool execution for permission checks. Returns PermissionResult indicating whether to allow/deny the tool use.

The callback can:

  • Approve: Return PermissionResult{Behavior: "allow"}
  • Deny: Return PermissionResult{Behavior: "deny", Message: "reason"}
  • Modify input: Set UpdatedInput field
  • Suggest permission updates: Set UpdatedPermissions field

Context may be cancelled if session times out.

type CanUseToolOptions

type CanUseToolOptions struct {
	Suggestions    []PermissionUpdate `json:"suggestions,omitempty"`
	BlockedPath    string             `json:"blockedPath,omitempty"`
	DecisionReason string             `json:"decisionReason,omitempty"`
	ToolUseID      string             `json:"toolUseID"`
	AgentID        string             `json:"agentID,omitempty"`
}

CanUseToolOptions contains options passed to the CanUseTool callback.

type CircuitBreaker

type CircuitBreaker interface {
	// Execute runs the given function if the circuit breaker allows it.
	Execute(ctx context.Context, fn func() error) error
	// State returns the current state of the circuit breaker.
	State() State
	// Reset manually resets the circuit breaker.
	Reset()
	// RecordFailure records a failure and potentially trips the circuit.
	RecordFailure()
	// RecordSuccess records a success and potentially resets the circuit.
	RecordSuccess()
}

CircuitBreaker interface defines the contract for a circuit breaker pattern. This is a stub implementation that can be completed later.

type CircuitBreakerConfig

type CircuitBreakerConfig struct {
	// FailureThreshold is the number of failures before tripping the circuit.
	FailureThreshold int
	// RecoveryTimeout is the time to wait before transitioning to half-open state.
	RecoveryTimeout time.Duration
	// HalfOpenMaxRequests is the maximum requests allowed in half-open state.
	HalfOpenMaxRequests int
}

CircuitBreakerConfig holds configuration for a circuit breaker.

func DefaultCircuitBreakerConfig

func DefaultCircuitBreakerConfig() CircuitBreakerConfig

DefaultCircuitBreakerConfig returns sensible defaults for the circuit breaker.

type CompactBoundaryMessage

type CompactBoundaryMessage struct {
	MessageType     string           `json:"type"`    // always "system"
	Subtype         string           `json:"subtype"` // always "compact_boundary"
	CompactMetadata *CompactMetadata `json:"compact_metadata,omitempty"`
	UUID            string           `json:"uuid"`
	SessionID       string           `json:"session_id"`
}

CompactBoundaryMessage represents a conversation compaction boundary. This is a system message with subtype "compact_boundary".

func (*CompactBoundaryMessage) MarshalJSON

func (m *CompactBoundaryMessage) MarshalJSON() ([]byte, error)

MarshalJSON implements custom JSON marshaling for CompactBoundaryMessage

func (*CompactBoundaryMessage) Type

func (m *CompactBoundaryMessage) Type() string

Type returns the message type for CompactBoundaryMessage.

type CompactMetadata

type CompactMetadata struct {
	Trigger   string `json:"trigger"` // "manual" | "auto"
	PreTokens int    `json:"pre_tokens"`
}

CompactMetadata contains metadata about conversation compaction.

type ConfigScope

type ConfigScope string

ConfigScope represents the scope for settings.

const (
	ConfigScopeLocal   ConfigScope = "local"
	ConfigScopeUser    ConfigScope = "user"
	ConfigScopeProject ConfigScope = "project"
)

type ConfigurationError

type ConfigurationError struct {
	BaseError
	Field string
	Value string
}

ConfigurationError indicates invalid configuration.

func AsConfigurationError

func AsConfigurationError(err error) (*ConfigurationError, bool)

AsConfigurationError extracts a ConfigurationError from the error chain.

func NewConfigurationError

func NewConfigurationError(field, value, reason string) *ConfigurationError

NewConfigurationError creates a new ConfigurationError.

func (*ConfigurationError) Error

func (e *ConfigurationError) Error() string

Error returns a descriptive error message for ConfigurationError.

func (*ConfigurationError) Type

func (e *ConfigurationError) Type() string

Type returns the error type for SDKError compliance.

type ConnectionError

type ConnectionError struct {
	BaseError
}

ConnectionError indicates a failure to connect to or communicate with Claude CLI.

func AsConnectionError

func AsConnectionError(err error) (*ConnectionError, bool)

AsConnectionError extracts a ConnectionError from the error chain.

func NewConnectionError

func NewConnectionError(reason string, inner error) *ConnectionError

NewConnectionError creates a new ConnectionError.

func (*ConnectionError) Error

func (e *ConnectionError) Error() string

Error returns a descriptive error message for ConnectionError.

func (*ConnectionError) Type

func (e *ConnectionError) Type() string

Type returns the error type for SDKError compliance.

type ConnectionOptionFunc

type ConnectionOptionFunc func(*ConnectionOptions)

ConnectionOptionFunc is a function that configures ConnectionOptions.

func WithConnCLICommand

func WithConnCLICommand(command string) ConnectionOptionFunc

WithConnCLICommand sets CLICommand on ConnectionOptions.

func WithConnCLIPath

func WithConnCLIPath(path string) ConnectionOptionFunc

WithConnCLIPath sets CLIPath on ConnectionOptions.

func WithConnEnv

func WithConnEnv(env map[string]string) ConnectionOptionFunc

WithConnEnv sets Env on ConnectionOptions (merges with existing).

func WithConnTimeout

func WithConnTimeout(timeout string) ConnectionOptionFunc

WithConnTimeout sets Timeout on ConnectionOptions.

type ConnectionOptions

type ConnectionOptions struct {
	// CLIPath specifies the path to the Claude CLI executable.
	// If empty, the CLI will be discovered in PATH.
	CLIPath string

	// CLICommand specifies the command to run the Claude CLI.
	// If empty, defaults to "claude".
	CLICommand string

	// Timeout specifies the timeout for operations.
	Timeout string

	// Env contains environment variables to set for the subprocess.
	Env map[string]string
}

ConnectionOptions contains options for CLI connection. Single Responsibility: manages how we connect to the CLI.

func DefaultConnectionOptions

func DefaultConnectionOptions() ConnectionOptions

DefaultConnectionOptions returns default connection options.

type ConstructorFunc

type ConstructorFunc[T any, O any] func(opts *O) (T, error)

ConstructorFunc represents a function that constructs a T from options O. This is the actual creation logic that DefaultFactory wraps.

type ContentBlock

type ContentBlock interface {
	BlockType() string
}

ContentBlock represents any content block within a message.

type ContextKey

type ContextKey string

ContextKey is a type for context value keys to avoid collisions.

type ContextResult

type ContextResult[T any] struct {
	Value T
	Err   error
}

ContextResult wraps an operation result with context-aware error handling. Useful for select statements that handle both results and context cancellation.

func SelectWithContext

func SelectWithContext[T any](ctx context.Context, ch <-chan T) ContextResult[T]

SelectWithContext helps implement the common pattern of selecting between a channel result and context cancellation. Returns the result or context error.

Example:

result := shared.SelectWithContext(ctx, resultChan)
if result.Err != nil {
    return result.Err
}
return result.Value

func SelectWithContextAndError

func SelectWithContextAndError[T any](ctx context.Context, valueChan <-chan T, errChan <-chan error) ContextResult[T]

SelectWithContextAndError handles the common pattern of selecting between a value channel, an error channel, and context cancellation. This consolidates the repetitive three-way select pattern found throughout the codebase.

Example:

result := shared.SelectWithContextAndError(ctx, msgChan, errChan)
if result.Err != nil {
    return result.Err
}
msg := result.Value

type DebugOptionFunc

type DebugOptionFunc func(*DebugOptions)

DebugOptionFunc is a function that configures DebugOptions.

func WithDebugCacheTTL

func WithDebugCacheTTL(ttl string) DebugOptionFunc

WithDebugCacheTTL sets CacheTTL on DebugOptions.

func WithDebugDisableCache

func WithDebugDisableCache(disable bool) DebugOptionFunc

WithDebugDisableCache sets DisableCache on DebugOptions.

func WithDebugEnableMetrics

func WithDebugEnableMetrics(enable bool) DebugOptionFunc

WithDebugEnableMetrics sets EnableMetrics on DebugOptions.

func WithDebugLogger

func WithDebugLogger(logger Logger) DebugOptionFunc

WithDebugLogger sets Logger on DebugOptions.

func WithDebugTrace

func WithDebugTrace(trace bool) DebugOptionFunc

WithDebugTrace sets Trace on DebugOptions.

type DebugOptions

type DebugOptions struct {
	// Trace enables detailed tracing of protocol messages.
	Trace bool

	// DisableCache disables message caching.
	DisableCache bool

	// CacheTTL sets the cache expiration time.
	CacheTTL string

	// Logger interface for logging operations.
	Logger Logger

	// EnableMetrics enables performance metrics collection.
	EnableMetrics bool
}

DebugOptions contains options for debugging and tracing. Single Responsibility: manages logging and diagnostic settings.

func DefaultDebugOptions

func DefaultDebugOptions() DebugOptions

DefaultDebugOptions returns default debug options.

type DefaultFactoryHolder

type DefaultFactoryHolder[T any, O any] struct {
	// contains filtered or unexported fields
}

DefaultFactoryHolder holds a default factory instance with thread-safe access. Use this to implement package-level default factories.

func NewDefaultFactoryHolder

func NewDefaultFactoryHolder[T any, O any](fallback Factory[T, O]) *DefaultFactoryHolder[T, O]

NewDefaultFactoryHolder creates a new holder with the given fallback factory.

func (*DefaultFactoryHolder[T, O]) Get

func (h *DefaultFactoryHolder[T, O]) Get() Factory[T, O]

Get returns the current factory.

func (*DefaultFactoryHolder[T, O]) Set

func (h *DefaultFactoryHolder[T, O]) Set(factory Factory[T, O])

Set sets the factory, or resets to fallback if nil.

type ErrorBuilder

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

ErrorBuilder provides a fluent interface for building error messages. This reduces boilerplate in Error() implementations.

func NewErrorBuilder

func NewErrorBuilder(prefix string) *ErrorBuilder

NewErrorBuilder creates a new error builder starting with the given prefix.

func (*ErrorBuilder) Field

func (eb *ErrorBuilder) Field(name string, value string, quoted bool) *ErrorBuilder

Field adds a named field to the error message. Format: (name=value) or (name="value") if quoted is true.

func (*ErrorBuilder) InField

func (eb *ErrorBuilder) InField(prefix string, value string) *ErrorBuilder

InField adds a field in the format " in value" (e.g., " in connect"). This is for the "client error in {operation}" pattern.

func (*ErrorBuilder) Inner

func (eb *ErrorBuilder) Inner(base *BaseError) *ErrorBuilder

Inner appends the inner error from BaseError if present.

func (*ErrorBuilder) IntField

func (eb *ErrorBuilder) IntField(name string, value int) *ErrorBuilder

IntField adds a named integer field to the error message.

func (*ErrorBuilder) Reason

func (eb *ErrorBuilder) Reason(base *BaseError) *ErrorBuilder

Reason appends the reason from BaseError if present.

func (*ErrorBuilder) String

func (eb *ErrorBuilder) String() string

String returns the built error message.

type ExitReason

type ExitReason string

ExitReason represents session exit reasons.

const (
	ExitReasonClear                     ExitReason = "clear"
	ExitReasonLogout                    ExitReason = "logout"
	ExitReasonPromptInputExit           ExitReason = "prompt_input_exit"
	ExitReasonOther                     ExitReason = "other"
	ExitReasonBypassPermissionsDisabled ExitReason = "bypass_permissions_disabled"
)

type Factory

type Factory[T any, O any] interface {
	// New creates a new instance of T with the given options.
	New(opts ...func(*O)) (T, error)
}

Factory is a generic interface for creating instances of type T with options of type O. This enables dependency injection and testability across packages.

func DefaultFactory

func DefaultFactory[T any, O any](constructor ConstructorFunc[T, O], defaults func() *O) Factory[T, O]

DefaultFactory creates a factory from a constructor and default options provider. This is a helper for creating simple factories without custom logic.

type FactoryFunc

type FactoryFunc[T any, O any] func(opts ...func(*O)) (T, error)

FactoryFunc is a function type that implements Factory[T, O]. This allows for easy inline factory creation.

func (FactoryFunc[T, O]) New

func (f FactoryFunc[T, O]) New(opts ...func(*O)) (T, error)

New implements Factory[T, O].

type HookConfig

type HookConfig struct {
	// Event is the hook event type this handler responds to.
	Event HookEvent
	// Matcher is an optional regex pattern to match tool names.
	// Only applies to tool-related events (PreToolUse, PostToolUse, etc.).
	// Empty string matches all tools.
	Matcher string
	// Handler is the function to execute when the hook fires.
	Handler HookHandler
	// Timeout overrides the default hook timeout (30s).
	// If zero, the default timeout is used.
	Timeout time.Duration
}

HookConfig configures a single hook handler with optional tool name matching.

func (*HookConfig) MatchesToolName

func (c *HookConfig) MatchesToolName(toolName string) bool

MatchesToolName checks if this hook config should execute for the given tool name. Returns true if: - Matcher is empty (matches all) - Tool name matches the regex pattern

type HookEvent

type HookEvent string

HookEvent represents the type of hook event.

const (
	HookEventPreToolUse         HookEvent = "PreToolUse"
	HookEventPostToolUse        HookEvent = "PostToolUse"
	HookEventPostToolUseFailure HookEvent = "PostToolUseFailure"
	HookEventNotification       HookEvent = "Notification"
	HookEventUserPromptSubmit   HookEvent = "UserPromptSubmit"
	HookEventSessionStart       HookEvent = "SessionStart"
	HookEventSessionEnd         HookEvent = "SessionEnd"
	HookEventStop               HookEvent = "Stop"
	HookEventSubagentStart      HookEvent = "SubagentStart"
	HookEventSubagentStop       HookEvent = "SubagentStop"
	HookEventPreCompact         HookEvent = "PreCompact"
	HookEventPermissionRequest  HookEvent = "PermissionRequest"
)

func AllHookEvents

func AllHookEvents() []HookEvent

AllHookEvents returns all valid hook event types.

type HookEventMessage

type HookEventMessage struct {
	Type           string         `json:"type"` // "hook_event"
	HookEventName  string         `json:"hook_event_name"`
	SessionID      string         `json:"session_id"`
	TranscriptPath string         `json:"transcript_path"`
	Cwd            string         `json:"cwd"`
	PermissionMode string         `json:"permission_mode,omitempty"`
	ToolName       string         `json:"tool_name,omitempty"`
	ToolInput      map[string]any `json:"tool_input,omitempty"`
	ToolUseID      string         `json:"tool_use_id,omitempty"`
	ToolResponse   any            `json:"tool_response,omitempty"`
	Error          string         `json:"error,omitempty"`

	// UserPromptSubmit fields
	Prompt string `json:"prompt,omitempty"`

	// Stop/SubagentStop fields
	StopHookActive bool `json:"stop_hook_active,omitempty"`

	// PreCompact fields
	Trigger            string  `json:"trigger,omitempty"`
	CustomInstructions *string `json:"custom_instructions,omitempty"`

	// SessionStart fields
	Source    string `json:"source,omitempty"`
	AgentType string `json:"agent_type,omitempty"`
	Model     string `json:"model,omitempty"`

	// SessionEnd fields
	Reason string `json:"reason,omitempty"`

	// Notification fields
	Message          string `json:"message,omitempty"`
	Title            string `json:"title,omitempty"`
	NotificationType string `json:"notification_type,omitempty"`

	// SubagentStart/SubagentStop fields
	AgentID             string `json:"agent_id,omitempty"`
	AgentTranscriptPath string `json:"agent_transcript_path,omitempty"`
}

HookEventMessage represents a hook event message from the CLI. This is the canonical representation of all hook event data.

type HookHandler

type HookHandler func(ctx context.Context, input any) (*SyncHookOutput, error)

HookHandler is the function signature for hook handlers. It receives a context (with timeout) and the typed hook input. Returns a SyncHookOutput and optional error.

type HookOutput

type HookOutput struct {
	Type           string `json:"type"` // "hook_response"
	ToolUseID      string `json:"tool_use_id,omitempty"`
	Continue       bool   `json:"continue"`
	SuppressOutput bool   `json:"suppress_output,omitempty"`
	Decision       string `json:"decision,omitempty"` // "approve" | "block"
	StopReason     string `json:"stop_reason,omitempty"`
	SystemMessage  string `json:"system_message,omitempty"`
	Reason         string `json:"reason,omitempty"`
}

HookOutput represents the response sent back to the CLI after hook execution. This is distinct from HookResponseMessage which is a system message type.

type HookResponseMessage

type HookResponseMessage struct {
	MessageType string `json:"type"`    // always "system"
	Subtype     string `json:"subtype"` // always "hook_response"
	HookName    string `json:"hook_name"`
	HookEvent   string `json:"hook_event"`
	Stdout      string `json:"stdout"`
	Stderr      string `json:"stderr"`
	ExitCode    *int   `json:"exit_code,omitempty"`
	UUID        string `json:"uuid"`
	SessionID   string `json:"session_id"`
}

HookResponseMessage represents hook execution response. This is a system message with subtype "hook_response".

func (*HookResponseMessage) MarshalJSON

func (m *HookResponseMessage) MarshalJSON() ([]byte, error)

MarshalJSON implements custom JSON marshaling for HookResponseMessage

func (*HookResponseMessage) Type

func (m *HookResponseMessage) Type() string

Type returns the message type for HookResponseMessage.

type JSONDecodeError

type JSONDecodeError struct {
	BaseError
	Line          int   // Line number where parsing failed
	Position      int   // Character position within the line
	OriginalError error // The underlying JSON decoder error
}

JSONDecodeError represents JSON parsing failures. This is an alias/wrapper for richer JSON error information compared to ParserError (which is for general parsing).

func AsJSONDecodeError

func AsJSONDecodeError(err error) (*JSONDecodeError, bool)

AsJSONDecodeError extracts a JSONDecodeError from the error chain.

func NewJSONDecodeError

func NewJSONDecodeError(line, position int, reason string, originalErr error) *JSONDecodeError

NewJSONDecodeError creates a new JSONDecodeError.

func (*JSONDecodeError) Error

func (e *JSONDecodeError) Error() string

Error returns a descriptive error message for JSONDecodeError.

func (*JSONDecodeError) Type

func (e *JSONDecodeError) Type() string

Type returns the error type for SDKError compliance.

func (*JSONDecodeError) Unwrap

func (e *JSONDecodeError) Unwrap() error

Unwrap returns the inner error for error chaining.

type Logger

type Logger interface {
	Debugf(format string, args ...any)
	Infof(format string, args ...any)
	Warnf(format string, args ...any)
	Errorf(format string, args ...any)
}

Logger defines the interface for logging operations.

type McpHttpServerConfig

type McpHttpServerConfig struct {
	Type    string            `json:"type"` // "http"
	URL     string            `json:"url"`
	Headers map[string]string `json:"headers,omitempty"`
}

McpHttpServerConfig configures an MCP server using HTTP.

type McpSSEServerConfig

type McpSSEServerConfig struct {
	Type    string            `json:"type"` // "sse"
	URL     string            `json:"url"`
	Headers map[string]string `json:"headers,omitempty"`
}

McpSSEServerConfig configures an MCP server using Server-Sent Events.

type McpSdkServerConfig

type McpSdkServerConfig struct {
	Type     string `json:"type"` // "sdk"
	Name     string `json:"name"`
	Instance any    `json:"-"` // MCP Server instance (not serialized)
}

McpSdkServerConfig configures an in-process MCP server.

func (McpSdkServerConfig) MarshalJSON

func (c McpSdkServerConfig) MarshalJSON() ([]byte, error)

MarshalJSON allows JSON serialization (excluding Instance field).

type McpServerConfig

type McpServerConfig interface {
	// contains filtered or unexported methods
}

McpServerConfig is the interface for MCP server configurations.

type McpServerInfo

type McpServerInfo struct {
	Name    string `json:"name"`
	Version string `json:"version"`
}

McpServerInfo contains information about a connected MCP server.

type McpServerStatus

type McpServerStatus struct {
	Name       string         `json:"name"`
	Status     string         `json:"status"` // "connected" | "failed" | "needs-auth" | "pending"
	ServerInfo *McpServerInfo `json:"serverInfo,omitempty"`
	Error      string         `json:"error,omitempty"`
}

McpServerStatus represents the connection status of an MCP server.

type McpSetServersResult

type McpSetServersResult struct {
	Added   []string          `json:"added"`
	Removed []string          `json:"removed"`
	Errors  map[string]string `json:"errors"`
}

McpSetServersResult is the result of a setMcpServers operation.

type McpStdioServerConfig

type McpStdioServerConfig struct {
	Type    string            `json:"type,omitempty"` // "stdio" (default)
	Command string            `json:"command"`
	Args    []string          `json:"args,omitempty"`
	Env     map[string]string `json:"env,omitempty"`
}

McpStdioServerConfig configures an MCP server using stdio.

type Message

type Message interface {
	Type() string
}

Message represents any message type in the Claude Code protocol.

type MessageIterator

type MessageIterator interface {
	// Next returns the next message in the stream.
	// Returns ErrNoMoreMessages when the stream is exhausted.
	// Returns context.Canceled or context.DeadlineExceeded if the context is cancelled.
	Next(ctx context.Context) (Message, error)
	// Close releases any resources held by the iterator.
	Close() error
}

MessageIterator provides an iterator pattern for streaming messages. This is the recommended way to consume messages from a streaming session.

Example:

iter := client.ReceiveResponse(ctx)
defer iter.Close()
for {
    msg, err := iter.Next(ctx)
    if errors.Is(err, shared.ErrNoMoreMessages) {
        break
    }
    if err != nil {
        return err
    }
    // Process message
}

type MessageParseError

type MessageParseError struct {
	BaseError
	Data        any    // The data that failed to parse
	MessageType string // Expected message type (if known)
}

MessageParseError represents message structure parsing failures. This is for higher-level message format issues rather than JSON syntax.

func AsMessageParseError

func AsMessageParseError(err error) (*MessageParseError, bool)

AsMessageParseError extracts a MessageParseError from the error chain.

func NewMessageParseError

func NewMessageParseError(data any, messageType, reason string) *MessageParseError

NewMessageParseError creates a new MessageParseError.

func (*MessageParseError) Error

func (e *MessageParseError) Error() string

Error returns a descriptive error message for MessageParseError.

func (*MessageParseError) Type

func (e *MessageParseError) Type() string

Type returns the error type for SDKError compliance.

type ModelError

type ModelError struct {
	BaseError
	Model           string   // The model that failed
	SupportedModels []string // List of supported models (if known)
}

ModelError indicates a model is unavailable or invalid.

func AsModelError

func AsModelError(err error) (*ModelError, bool)

AsModelError extracts a ModelError from the error chain.

func NewModelError

func NewModelError(model, reason string, supportedModels []string) *ModelError

NewModelError creates a new ModelError.

func (*ModelError) Error

func (e *ModelError) Error() string

Error returns a descriptive error message for ModelError.

func (*ModelError) Type

func (e *ModelError) Type() string

Type returns the error type for SDKError compliance.

type ModelInfo

type ModelInfo struct {
	Value       string `json:"value"`
	DisplayName string `json:"displayName"`
	Description string `json:"description"`
}

ModelInfo contains information about an available model.

type ModelOptionFunc

type ModelOptionFunc func(*ModelOptions)

ModelOptionFunc is a function that configures ModelOptions.

func WithModelContextFiles

func WithModelContextFiles(files ...string) ModelOptionFunc

WithModelContextFiles sets ContextFiles on ModelOptions.

func WithModelCustomArgs

func WithModelCustomArgs(args ...string) ModelOptionFunc

WithModelCustomArgs sets CustomArgs on ModelOptions.

func WithModelModel

func WithModelModel(model string) ModelOptionFunc

WithModelModel sets Model on ModelOptions.

func WithModelPermissionMode

func WithModelPermissionMode(mode string) ModelOptionFunc

WithModelPermissionMode sets PermissionMode on ModelOptions.

type ModelOptions

type ModelOptions struct {
	// Model specifies the Claude model to use.
	Model string

	// PermissionMode sets the permission mode for file operations.
	PermissionMode string

	// ContextFiles specifies files to include in the context.
	ContextFiles []string

	// CustomArgs provides additional arguments for the Claude CLI.
	CustomArgs []string
}

ModelOptions contains options for Claude model configuration. Single Responsibility: manages model and context settings.

func DefaultModelOptions

func DefaultModelOptions() ModelOptions

DefaultModelOptions returns default model options.

type ModelUsage

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

ModelUsage represents token usage and cost for a model.

type NeverAvailableCLIChecker

type NeverAvailableCLIChecker struct{}

NeverAvailableCLIChecker is a CLIChecker that always returns false. Useful for testing CLI unavailability scenarios.

func (NeverAvailableCLIChecker) IsCLIAvailable

func (NeverAvailableCLIChecker) IsCLIAvailable() bool

IsCLIAvailable implements CLIChecker.

type NopLogger

type NopLogger struct{}

NopLogger is a logger that does nothing.

func (*NopLogger) Debugf

func (l *NopLogger) Debugf(format string, args ...any)

func (*NopLogger) Errorf

func (l *NopLogger) Errorf(format string, args ...any)

func (*NopLogger) Infof

func (l *NopLogger) Infof(format string, args ...any)

func (*NopLogger) Warnf

func (l *NopLogger) Warnf(format string, args ...any)

type NotificationHookInput

type NotificationHookInput struct {
	BaseHookInput
	HookEventName    string `json:"hook_event_name"` // always "Notification"
	Message          string `json:"message"`
	Title            string `json:"title,omitempty"`
	NotificationType string `json:"notification_type"`
}

NotificationHookInput is the input for Notification hooks.

type Options

type Options struct {
	// Model specifies the Claude model to use.
	Model string

	// CLIPath specifies the path to the Claude CLI executable.
	// If empty, the CLI will be discovered in PATH.
	CLIPath string

	// CLICommand specifies the command to run the Claude CLI.
	// If empty, defaults to "claude".
	CLICommand string

	// PermissionMode sets the permission mode for the session.
	PermissionMode string

	// ContextFiles specifies files to include in the context.
	ContextFiles []string

	// IncludePartialMessages enables streaming of partial messages during response generation.
	IncludePartialMessages bool

	// EnableStructuredOutput enables structured output mode.
	EnableStructuredOutput bool

	// Timeout specifies the timeout for operations.
	Timeout string

	// CustomArgs provides additional arguments for the Claude CLI.
	CustomArgs []string

	// Environment variables to set for the subprocess.
	Env map[string]string

	// Maximum number of messages to process before returning an error.
	MaxMessages int

	// Buffer size for message channels.
	BufferSize int

	// Logger interface for logging operations.
	Logger Logger

	// Enable performance metrics collection.
	EnableMetrics bool

	// Trace enables detailed tracing of protocol messages.
	Trace bool

	// DisableCache disables message caching.
	DisableCache bool

	// CacheTTL sets the cache expiration time.
	CacheTTL string
}

Options provides configuration for the Claude client.

func DefaultOptions

func DefaultOptions() *Options

DefaultOptions returns default options for the Claude client.

func (*Options) Validate

func (o *Options) Validate() error

Validate validates the options and returns an error if invalid.

type OutputFormat

type OutputFormat struct {
	Type   string         `json:"type"` // "json_schema"
	Schema map[string]any `json:"schema"`
}

OutputFormat represents structured output configuration.

type ParserError

type ParserError struct {
	BaseError
	Line   int    // Line number where parsing failed
	Offset int    // Character offset within the line
	Data   string // Raw data that failed to parse
}

ParserError indicates a JSON parsing failure.

func AsParserError

func AsParserError(err error) (*ParserError, bool)

AsParserError extracts a ParserError from the error chain.

func NewParserError

func NewParserError(line, offset int, data, reason string) *ParserError

NewParserError creates a new ParserError.

func (*ParserError) Error

func (e *ParserError) Error() string

Error returns a descriptive error message for ParserError.

func (*ParserError) Type

func (e *ParserError) Type() string

Type returns the error type for SDKError compliance.

type PermissionBehavior

type PermissionBehavior string

PermissionBehavior determines how a permission request is handled.

const (
	PermissionBehaviorAllow PermissionBehavior = "allow"
	PermissionBehaviorDeny  PermissionBehavior = "deny"
	PermissionBehaviorAsk   PermissionBehavior = "ask"
)

type PermissionError

type PermissionError struct {
	BaseError
	Tool      string // Tool that was denied (if applicable)
	Path      string // Path that was denied (if applicable)
	Operation string // Operation that was denied (e.g., "read", "write", "execute")
}

PermissionError indicates a tool or file access was denied.

func AsPermissionError

func AsPermissionError(err error) (*PermissionError, bool)

AsPermissionError extracts a PermissionError from the error chain.

func NewPermissionError

func NewPermissionError(tool, path, operation, reason string) *PermissionError

NewPermissionError creates a new PermissionError.

func (*PermissionError) Error

func (e *PermissionError) Error() string

Error returns a descriptive error message for PermissionError.

func (*PermissionError) Type

func (e *PermissionError) Type() string

Type returns the error type for SDKError compliance.

type PermissionMode

type PermissionMode string

PermissionMode controls how tool executions are handled.

const (
	PermissionModeDefault           PermissionMode = "default"
	PermissionModeAcceptEdits       PermissionMode = "acceptEdits"
	PermissionModeBypassPermissions PermissionMode = "bypassPermissions"
	PermissionModePlan              PermissionMode = "plan"
	PermissionModeDelegate          PermissionMode = "delegate"
	PermissionModeDontAsk           PermissionMode = "dontAsk"
)

type PermissionRequestHookInput

type PermissionRequestHookInput struct {
	BaseHookInput
	HookEventName         string             `json:"hook_event_name"` // always "PermissionRequest"
	ToolName              string             `json:"tool_name"`
	ToolInput             any                `json:"tool_input"`
	PermissionSuggestions []PermissionUpdate `json:"permission_suggestions,omitempty"`
}

PermissionRequestHookInput is the input for PermissionRequest hooks.

type PermissionResult

type PermissionResult struct {
	Behavior           PermissionBehavior `json:"behavior"` // "allow" or "deny"
	UpdatedInput       map[string]any     `json:"updatedInput,omitempty"`
	UpdatedPermissions []PermissionUpdate `json:"updatedPermissions,omitempty"`
	ToolUseID          string             `json:"toolUseID,omitempty"`
	Message            string             `json:"message,omitempty"`   // for deny
	Interrupt          bool               `json:"interrupt,omitempty"` // for deny
}

PermissionResult represents the result of a permission check. This is a discriminated union based on the Behavior field.

func NewPermissionResultAllow

func NewPermissionResultAllow(opts ...PermissionResultOption) PermissionResult

NewPermissionResultAllow creates a permission result that allows tool execution. Optionally modify input or suggest permission updates via options.

Example:

return shared.NewPermissionResultAllow(
    shared.WithUpdatedInput(map[string]any{"path": "/safe/path"}),
), nil

func NewPermissionResultDeny

func NewPermissionResultDeny(message string, opts ...PermissionResultOption) PermissionResult

NewPermissionResultDeny creates a permission result that denies tool execution. The message explains why the tool use was denied.

Example:

return shared.NewPermissionResultDeny("Path outside allowed directories"), nil

type PermissionResultOption

type PermissionResultOption func(*PermissionResult)

PermissionResultOption configures a PermissionResult.

func WithInterrupt

func WithInterrupt(interrupt bool) PermissionResultOption

WithInterrupt terminates the session on denial. Only applicable to deny results.

func WithPermissionUpdates

func WithPermissionUpdates(updates ...PermissionUpdate) PermissionResultOption

WithPermissionUpdates suggests permission rule changes. Can be used with both allow and deny results.

func WithToolUseID

func WithToolUseID(toolUseID string) PermissionResultOption

WithToolUseID sets the tool use ID on the result.

func WithUpdatedInput

func WithUpdatedInput(input map[string]any) PermissionResultOption

WithUpdatedInput modifies the tool input before execution. Only applicable to allow results.

type PermissionRuleValue

type PermissionRuleValue struct {
	ToolName    string  `json:"toolName"`
	RuleContent *string `json:"ruleContent,omitempty"`
}

PermissionRuleValue represents a permission rule.

type PermissionUpdate

type PermissionUpdate struct {
	Type        string                      `json:"type"` // "addRules", "replaceRules", "removeRules", "setMode", "addDirectories", "removeDirectories"
	Rules       []PermissionRuleValue       `json:"rules,omitempty"`
	Behavior    PermissionBehavior          `json:"behavior,omitempty"`
	Destination PermissionUpdateDestination `json:"destination,omitempty"`
	Mode        PermissionMode              `json:"mode,omitempty"`
	Directories []string                    `json:"directories,omitempty"`
}

PermissionUpdate represents an update to permission configuration. This is a discriminated union based on the Type field.

type PermissionUpdateDestination

type PermissionUpdateDestination string

PermissionUpdateDestination specifies where permission updates are stored.

const (
	PermissionDestUserSettings    PermissionUpdateDestination = "userSettings"
	PermissionDestProjectSettings PermissionUpdateDestination = "projectSettings"
	PermissionDestLocalSettings   PermissionUpdateDestination = "localSettings"
	PermissionDestSession         PermissionUpdateDestination = "session"
	PermissionDestCLIArg          PermissionUpdateDestination = "cliArg"
)

type PluginConfig

type PluginConfig struct {
	Type string `json:"type"` // "local"
	Path string `json:"path"`
}

PluginConfig represents a plugin configuration.

type PluginInfo

type PluginInfo struct {
	Name string `json:"name"`
	Path string `json:"path"`
}

PluginInfo contains information about an active plugin.

type PostToolUseFailureHookInput

type PostToolUseFailureHookInput struct {
	BaseHookInput
	HookEventName string         `json:"hook_event_name"` // always "PostToolUseFailure"
	ToolName      string         `json:"tool_name"`
	ToolInput     map[string]any `json:"tool_input"`
	ToolUseID     string         `json:"tool_use_id"`
	Error         string         `json:"error"`
	IsInterrupt   bool           `json:"is_interrupt,omitempty"`
}

PostToolUseFailureHookInput is the input for PostToolUseFailure hooks.

type PostToolUseHookInput

type PostToolUseHookInput struct {
	BaseHookInput
	HookEventName string         `json:"hook_event_name"` // always "PostToolUse"
	ToolName      string         `json:"tool_name"`
	ToolInput     map[string]any `json:"tool_input"`
	ToolResponse  any            `json:"tool_response"`
	ToolUseID     string         `json:"tool_use_id"`
}

PostToolUseHookInput is the input for PostToolUse hooks.

type PreCompactHookInput

type PreCompactHookInput struct {
	BaseHookInput
	HookEventName      string  `json:"hook_event_name"` // always "PreCompact"
	Trigger            string  `json:"trigger"`         // "manual" | "auto"
	CustomInstructions *string `json:"custom_instructions"`
}

PreCompactHookInput is the input for PreCompact hooks.

type PreToolUseHookInput

type PreToolUseHookInput struct {
	BaseHookInput
	HookEventName string         `json:"hook_event_name"` // always "PreToolUse"
	ToolName      string         `json:"tool_name"`
	ToolInput     map[string]any `json:"tool_input"`
	ToolUseID     string         `json:"tool_use_id"`
}

PreToolUseHookInput is the input for PreToolUse hooks.

type ProcessError

type ProcessError struct {
	BaseError
	PID     int
	Command string
	Signal  string // Signal that caused the process to exit (if applicable)
}

ProcessError indicates a subprocess-related error.

func AsProcessError

func AsProcessError(err error) (*ProcessError, bool)

AsProcessError extracts a ProcessError from the error chain.

func NewProcessError

func NewProcessError(pid int, command, reason, signal string) *ProcessError

NewProcessError creates a new ProcessError.

func (*ProcessError) Error

func (e *ProcessError) Error() string

Error returns a descriptive error message for ProcessError.

func (*ProcessError) Type

func (e *ProcessError) Type() string

Type returns the error type for SDKError compliance.

type ProtocolError

type ProtocolError struct {
	BaseError
	MessageType string
}

ProtocolError indicates a protocol violation or invalid message received.

func AsProtocolError

func AsProtocolError(err error) (*ProtocolError, bool)

AsProtocolError extracts a ProtocolError from the error chain.

func NewProtocolError

func NewProtocolError(messageType, reason string) *ProtocolError

NewProtocolError creates a new ProtocolError.

func (*ProtocolError) Error

func (e *ProtocolError) Error() string

Error returns a descriptive error message for ProtocolError.

func (*ProtocolError) Type

func (e *ProtocolError) Type() string

Type returns the error type for SDKError compliance.

type RawControlMessage

type RawControlMessage struct {
	MessageType string
	Data        map[string]any
}

RawControlMessage wraps raw control protocol messages for passthrough to the control handler. Control messages are not parsed into typed structs by the parser - they are routed directly to the control protocol handler which performs its own parsing.

func (*RawControlMessage) Type

func (m *RawControlMessage) Type() string

Type returns the message type for RawControlMessage.

type ResultMessage

type ResultMessage struct {
	MessageType       string                `json:"type"`
	Subtype           string                `json:"subtype"`
	DurationMs        int                   `json:"duration_ms"`
	DurationAPIMs     int                   `json:"duration_api_ms"`
	IsError           bool                  `json:"is_error"`
	NumTurns          int                   `json:"num_turns"`
	SessionID         string                `json:"session_id"`
	TotalCostUSD      *float64              `json:"total_cost_usd,omitempty"`
	Usage             *map[string]any       `json:"usage,omitempty"`
	Result            *string               `json:"result,omitempty"`
	StructuredOutput  any                   `json:"structured_output,omitempty"`
	ModelUsage        map[string]ModelUsage `json:"modelUsage,omitempty"`
	PermissionDenials []SDKPermissionDenial `json:"permission_denials,omitempty"`
	Errors            []string              `json:"errors,omitempty"` // for error subtypes
}

ResultMessage represents the final result of a conversation turn. The Subtype field indicates the result status: - "success": normal completion - "error_during_execution": error occurred during execution - "error_max_turns": maximum turns reached - "error_max_budget_usd": budget limit exceeded - "error_max_structured_output_retries": structured output retry limit exceeded

func (*ResultMessage) MarshalJSON

func (m *ResultMessage) MarshalJSON() ([]byte, error)

MarshalJSON implements custom JSON marshaling for ResultMessage

func (*ResultMessage) Type

func (m *ResultMessage) Type() string

Type returns the message type for ResultMessage.

type RewindFilesResult

type RewindFilesResult struct {
	CanRewind    bool     `json:"canRewind"`
	Error        string   `json:"error,omitempty"`
	FilesChanged []string `json:"filesChanged,omitempty"`
	Insertions   int      `json:"insertions,omitempty"`
	Deletions    int      `json:"deletions,omitempty"`
}

RewindFilesResult is the result of a rewindFiles operation.

type RipgrepConfig

type RipgrepConfig struct {
	Command string   `json:"command"`
	Args    []string `json:"args,omitempty"`
}

RipgrepConfig configures ripgrep in sandbox.

type SDKError

type SDKError interface {
	error
	Type() string
}

SDKError is the base interface for all Claude Agent SDK errors. It provides a Type() method for programmatic error type discrimination.

type SDKPermissionDenial

type SDKPermissionDenial struct {
	ToolName  string         `json:"tool_name"`
	ToolUseID string         `json:"tool_use_id"`
	ToolInput map[string]any `json:"tool_input"`
}

SDKPermissionDenial represents a denied permission request.

type SandboxConfig

type SandboxConfig struct {
	Enabled                   bool                  `json:"enabled,omitempty"`
	AutoAllowBashIfSandboxed  bool                  `json:"autoAllowBashIfSandboxed,omitempty"`
	AllowUnsandboxedCommands  bool                  `json:"allowUnsandboxedCommands,omitempty"`
	Network                   *SandboxNetworkConfig `json:"network,omitempty"`
	IgnoreViolations          map[string][]string   `json:"ignoreViolations,omitempty"`
	EnableWeakerNestedSandbox bool                  `json:"enableWeakerNestedSandbox,omitempty"`
	ExcludedCommands          []string              `json:"excludedCommands,omitempty"`
	Ripgrep                   *RipgrepConfig        `json:"ripgrep,omitempty"`
}

SandboxConfig provides comprehensive sandbox configuration. This extends the basic SandboxSettings with additional isolation options.

type SandboxNetworkConfig

type SandboxNetworkConfig struct {
	AllowedDomains      []string `json:"allowedDomains,omitempty"`
	AllowUnixSockets    []string `json:"allowUnixSockets,omitempty"`
	AllowAllUnixSockets bool     `json:"allowAllUnixSockets,omitempty"`
	AllowLocalBinding   bool     `json:"allowLocalBinding,omitempty"`
	HttpProxyPort       int      `json:"httpProxyPort,omitempty"`
	SocksProxyPort      int      `json:"socksProxyPort,omitempty"`
}

SandboxNetworkConfig configures network access in sandbox.

type SandboxSettings

type SandboxSettings struct {
	Enabled    bool              `json:"enabled"`
	Type       string            `json:"type,omitempty"` // "docker", "nsjail", etc.
	Image      string            `json:"image,omitempty"`
	Options    map[string]string `json:"options,omitempty"`
	WorkingDir string            `json:"workingDir,omitempty"`
}

SandboxSettings represents sandbox configuration.

type SdkBeta

type SdkBeta string

SdkBeta represents beta features.

const (
	SdkBetaContext1M SdkBeta = "context-1m-2025-08-07"
)

type SdkPluginConfig

type SdkPluginConfig struct {
	// Enabled controls whether the plugin is active.
	Enabled bool `json:"enabled"`

	// PluginPath is the filesystem path to the plugin.
	PluginPath string `json:"pluginPath"`

	// Config contains plugin-specific configuration.
	Config map[string]any `json:"config,omitempty"`

	// Timeout is the maximum time allowed for each plugin call.
	// Zero means no timeout.
	Timeout time.Duration `json:"timeout,omitempty"`

	// MaxConcurrent is the maximum number of concurrent plugin calls.
	// Zero means unlimited.
	MaxConcurrent int `json:"maxConcurrent,omitempty"`
}

SdkPluginConfig represents full SDK plugin configuration. This provides complete control over plugin behavior including timeouts, concurrency limits, and custom configuration.

type SessionEndHookInput

type SessionEndHookInput struct {
	BaseHookInput
	HookEventName string `json:"hook_event_name"` // always "SessionEnd"
	Reason        string `json:"reason"`
}

SessionEndHookInput is the input for SessionEnd hooks.

type SessionStartHookInput

type SessionStartHookInput struct {
	BaseHookInput
	HookEventName string `json:"hook_event_name"` // always "SessionStart"
	Source        string `json:"source"`          // "startup" | "resume" | "clear" | "compact"
	AgentType     string `json:"agent_type,omitempty"`
	Model         string `json:"model,omitempty"`
}

SessionStartHookInput is the input for SessionStart hooks.

type SettingSource

type SettingSource string

SettingSource specifies which settings to load.

const (
	SettingSourceUser    SettingSource = "user"
	SettingSourceProject SettingSource = "project"
	SettingSourceLocal   SettingSource = "local"
)

type SlashCommand

type SlashCommand struct {
	Name         string `json:"name"`
	Description  string `json:"description"`
	ArgumentHint string `json:"argumentHint"`
}

SlashCommand contains information about an available slash command.

type State

type State int

State represents the state of a circuit breaker.

const (
	// Closed state means the circuit breaker is operational and requests are allowed.
	Closed State = iota
	// Open state means the circuit breaker is tripped and requests are rejected.
	Open
	// HalfOpen state means the circuit breaker is testing after being open.
	HalfOpen
)

func (State) String

func (s State) String() string

String returns the string representation of the state.

type StatusMessage

type StatusMessage struct {
	MessageType string  `json:"type"`    // always "system"
	Subtype     string  `json:"subtype"` // always "status"
	Status      *string `json:"status"`  // "compacting" | null
	UUID        string  `json:"uuid"`
	SessionID   string  `json:"session_id"`
}

StatusMessage represents a system status update. This is a system message with subtype "status".

func (*StatusMessage) MarshalJSON

func (m *StatusMessage) MarshalJSON() ([]byte, error)

MarshalJSON implements custom JSON marshaling for StatusMessage

func (*StatusMessage) Type

func (m *StatusMessage) Type() string

Type returns the message type for StatusMessage.

type StopHookInput

type StopHookInput struct {
	BaseHookInput
	HookEventName  string `json:"hook_event_name"` // always "Stop"
	StopHookActive bool   `json:"stop_hook_active"`
}

StopHookInput is the input for Stop hooks.

type StreamEvent

type StreamEvent struct {
	UUID            string         `json:"uuid"`
	SessionID       string         `json:"session_id"`
	Event           map[string]any `json:"event"`
	ParentToolUseID *string        `json:"parent_tool_use_id,omitempty"`
}

StreamEvent represents a partial message update during streaming. Emitted when IncludePartialMessages is enabled in Options.

The Event field contains varying structure depending on event type:

  • content_block_start: {"type": "content_block_start", "index": <int>, "content_block": {...}}
  • content_block_delta: {"type": "content_block_delta", "index": <int>, "delta": {...}}
  • content_block_stop: {"type": "content_block_stop", "index": <int>}
  • message_start: {"type": "message_start", "message": {...}}
  • message_delta: {"type": "message_delta", "delta": {...}, "usage": {...}}
  • message_stop: {"type": "message_stop"}

Consumer code should type-switch on Event["type"] to handle different event types:

switch event.Event["type"] {
case shared.StreamEventTypeContentBlockDelta:
    // Handle content delta
case shared.StreamEventTypeMessageStop:
    // Handle message completion
}

func ParseStreamEvent

func ParseStreamEvent(raw string) (*StreamEvent, error)

ParseStreamEvent parses a raw JSON message into a StreamEvent.

func (*StreamEvent) MarshalJSON

func (m *StreamEvent) MarshalJSON() ([]byte, error)

MarshalJSON implements custom JSON marshaling for StreamEvent

func (*StreamEvent) Type

func (m *StreamEvent) Type() string

Type returns the message type for StreamEvent.

type StreamIssue

type StreamIssue struct {
	UUID   string
	Type   string
	Detail string
}

StreamIssue represents a validation issue with a stream message.

func ValidateStreamEvent

func ValidateStreamEvent(event StreamEvent) []StreamIssue

ValidateStreamEvent validates a stream event and returns any issues.

type StreamStats

type StreamStats struct {
	TotalMessages   int
	PartialMessages int
	Errors          int
	ProcessingTime  string // Duration in human-readable format
}

StreamStats collects statistics about stream processing.

type StreamValidator

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

StreamValidator tracks tool requests and results to detect incomplete streams. It provides validation for stream integrity and collects statistics about message processing.

func NewStreamValidator

func NewStreamValidator() *StreamValidator

NewStreamValidator creates a new stream validator.

func (*StreamValidator) GetIssues

func (v *StreamValidator) GetIssues() []StreamIssue

GetIssues returns validation issues detected in the stream. Call after MarkStreamEnd for complete results.

func (*StreamValidator) GetStats

func (v *StreamValidator) GetStats() StreamStats

GetStats returns statistics about the stream.

func (*StreamValidator) IsComplete

func (v *StreamValidator) IsComplete() bool

IsComplete returns true if the stream is complete and has no issues.

func (*StreamValidator) MarkStreamEnd

func (v *StreamValidator) MarkStreamEnd()

MarkStreamEnd marks the stream as ended. Call this when the stream closes normally.

func (*StreamValidator) PendingToolCount

func (v *StreamValidator) PendingToolCount() int

PendingToolCount returns the number of tool requests awaiting results.

func (*StreamValidator) Reset

func (v *StreamValidator) Reset()

Reset resets the validator state for reuse.

func (*StreamValidator) TrackError

func (v *StreamValidator) TrackError()

TrackError records an error encountered during stream processing.

func (*StreamValidator) TrackMessage

func (v *StreamValidator) TrackMessage(msg Message)

TrackMessage tracks a message and updates validation state. Call this for each message received from the stream.

func (*StreamValidator) TrackToolRequest

func (v *StreamValidator) TrackToolRequest(toolUseID string)

TrackToolRequest records a tool use request by ID.

func (*StreamValidator) TrackToolResult

func (v *StreamValidator) TrackToolResult(toolUseID string)

TrackToolResult records a tool result by ID.

type StubCircuitBreaker

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

StubCircuitBreaker is a basic circuit breaker implementation. This is a stub and can be enhanced with more sophisticated logic.

func NewStubCircuitBreaker

func NewStubCircuitBreaker(config CircuitBreakerConfig) *StubCircuitBreaker

NewStubCircuitBreaker creates a new stub circuit breaker.

func (*StubCircuitBreaker) Execute

func (cb *StubCircuitBreaker) Execute(ctx context.Context, fn func() error) error

Execute runs the function if the circuit breaker allows it.

func (*StubCircuitBreaker) RecordFailure

func (cb *StubCircuitBreaker) RecordFailure()

RecordFailure records a failure and potentially trips the circuit.

func (*StubCircuitBreaker) RecordSuccess

func (cb *StubCircuitBreaker) RecordSuccess()

RecordSuccess records a success and potentially resets the circuit.

func (*StubCircuitBreaker) Reset

func (cb *StubCircuitBreaker) Reset()

Reset manually resets the circuit breaker.

func (*StubCircuitBreaker) State

func (cb *StubCircuitBreaker) State() State

State returns the current state of the circuit breaker.

type SubagentStartHookInput

type SubagentStartHookInput struct {
	BaseHookInput
	HookEventName string `json:"hook_event_name"` // always "SubagentStart"
	AgentID       string `json:"agent_id"`
	AgentType     string `json:"agent_type"`
}

SubagentStartHookInput is the input for SubagentStart hooks.

type SubagentStopHookInput

type SubagentStopHookInput struct {
	BaseHookInput
	HookEventName       string `json:"hook_event_name"` // always "SubagentStop"
	StopHookActive      bool   `json:"stop_hook_active"`
	AgentID             string `json:"agent_id"`
	AgentTranscriptPath string `json:"agent_transcript_path"`
}

SubagentStopHookInput is the input for SubagentStop hooks.

type SyncHookOutput

type SyncHookOutput struct {
	Continue           bool           `json:"continue,omitempty"`
	SuppressOutput     bool           `json:"suppressOutput,omitempty"`
	StopReason         string         `json:"stopReason,omitempty"`
	Decision           string         `json:"decision,omitempty"` // "approve" | "block"
	SystemMessage      string         `json:"systemMessage,omitempty"`
	Reason             string         `json:"reason,omitempty"`
	HookSpecificOutput map[string]any `json:"hookSpecificOutput,omitempty"`
}

SyncHookOutput is the output for synchronous hooks.

type SystemMessage

type SystemMessage struct {
	MessageType       string         `json:"type"`
	Subtype           string         `json:"subtype"`
	Data              map[string]any `json:"-"` // Preserve all original data
	Agents            []string       `json:"-"` // Populated when subtype is "init"
	Betas             []string       `json:"-"` // Populated when subtype is "init"
	ClaudeCodeVersion string         `json:"-"` // Populated when subtype is "init"
	Skills            []string       `json:"-"` // Populated when subtype is "init"
	Plugins           []PluginInfo   `json:"-"` // Populated when subtype is "init"
}

SystemMessage represents a system message. When Subtype is "init", the following fields are populated: - Agents: list of active agent names - Betas: list of active beta features - ClaudeCodeVersion: version string of Claude Code - Skills: list of active skills - Plugins: list of active plugins

func (*SystemMessage) MarshalJSON

func (m *SystemMessage) MarshalJSON() ([]byte, error)

MarshalJSON implements custom JSON marshaling for SystemMessage

func (*SystemMessage) Type

func (m *SystemMessage) Type() string

Type returns the message type for SystemMessage.

type TextBlock

type TextBlock struct {
	MessageType string `json:"type"`
	Text        string `json:"text"`
}

TextBlock represents text content.

func ExtractTextBlocks

func ExtractTextBlocks(msg Message) []*TextBlock

ExtractTextBlocks extracts text blocks from an assistant message. Returns a slice of TextBlock found in the message content.

func (*TextBlock) BlockType

func (b *TextBlock) BlockType() string

BlockType returns the content block type for TextBlock.

func (*TextBlock) MarshalJSON

func (b *TextBlock) MarshalJSON() ([]byte, error)

MarshalJSON implements custom JSON marshaling for TextBlock

type ThinkingBlock

type ThinkingBlock struct {
	MessageType string `json:"type"`
	Thinking    string `json:"thinking"`
	Signature   string `json:"signature"`
}

ThinkingBlock represents thinking content with signature.

func ExtractThinkingBlocks

func ExtractThinkingBlocks(msg Message) []*ThinkingBlock

ExtractThinkingBlocks extracts thinking blocks from an assistant message. Returns a slice of ThinkingBlock found in the message content.

func (*ThinkingBlock) BlockType

func (b *ThinkingBlock) BlockType() string

BlockType returns the content block type for ThinkingBlock.

func (*ThinkingBlock) MarshalJSON

func (b *ThinkingBlock) MarshalJSON() ([]byte, error)

MarshalJSON implements custom JSON marshaling for ThinkingBlock

type TimeoutError

type TimeoutError struct {
	BaseError
	Operation string
	Timeout   string
}

TimeoutError indicates an operation timed out.

func AsTimeoutError

func AsTimeoutError(err error) (*TimeoutError, bool)

AsTimeoutError extracts a TimeoutError from the error chain.

func NewTimeoutError

func NewTimeoutError(operation, timeout string) *TimeoutError

NewTimeoutError creates a new TimeoutError.

func (*TimeoutError) Error

func (e *TimeoutError) Error() string

Error returns a descriptive error message for TimeoutError.

func (*TimeoutError) Type

func (e *TimeoutError) Type() string

Type returns the error type for SDKError compliance.

type ToolProgressMessage

type ToolProgressMessage struct {
	MessageType        string  `json:"type"` // always "tool_progress"
	ToolUseID          string  `json:"tool_use_id"`
	ToolName           string  `json:"tool_name"`
	ParentToolUseID    *string `json:"parent_tool_use_id,omitempty"`
	ElapsedTimeSeconds float64 `json:"elapsed_time_seconds"`
	UUID               string  `json:"uuid"`
	SessionID          string  `json:"session_id"`
}

ToolProgressMessage represents tool execution progress.

func (*ToolProgressMessage) MarshalJSON

func (m *ToolProgressMessage) MarshalJSON() ([]byte, error)

MarshalJSON implements custom JSON marshaling for ToolProgressMessage

func (*ToolProgressMessage) Type

func (m *ToolProgressMessage) Type() string

Type returns the message type for ToolProgressMessage.

type ToolResultBlock

type ToolResultBlock struct {
	MessageType string `json:"type"`
	ToolUseID   string `json:"tool_use_id"`
	Content     any    `json:"content"` // string or structured data
	IsError     *bool  `json:"is_error,omitempty"`
}

ToolResultBlock represents the result of a tool use.

func (*ToolResultBlock) BlockType

func (b *ToolResultBlock) BlockType() string

BlockType returns the content block type for ToolResultBlock.

func (*ToolResultBlock) MarshalJSON

func (b *ToolResultBlock) MarshalJSON() ([]byte, error)

MarshalJSON implements custom JSON marshaling for ToolResultBlock

type ToolUseBlock

type ToolUseBlock struct {
	MessageType string         `json:"type"`
	ToolUseID   string         `json:"tool_use_id"`
	Name        string         `json:"name"`
	Input       map[string]any `json:"input"`
}

ToolUseBlock represents a tool use request.

func ExtractToolUses

func ExtractToolUses(msg Message) []*ToolUseBlock

ExtractToolUses extracts tool use blocks from an assistant message. Returns a slice of ToolUseBlock found in the message content.

func (*ToolUseBlock) BlockType

func (b *ToolUseBlock) BlockType() string

BlockType returns the content block type for ToolUseBlock.

func (*ToolUseBlock) MarshalJSON

func (b *ToolUseBlock) MarshalJSON() ([]byte, error)

MarshalJSON implements custom JSON marshaling for ToolUseBlock

type ToolsConfig

type ToolsConfig struct {
	Type   string   // "preset" | "explicit"
	Preset string   // "claude_code" (when Type == "preset")
	Tools  []string // Tool names (when Type == "explicit")
}

ToolsConfig is a discriminated union for tool configuration.

func ToolsExplicit

func ToolsExplicit(tools ...string) *ToolsConfig

ToolsExplicit creates a tools config for explicit tool list.

func ToolsPreset

func ToolsPreset(preset string) *ToolsConfig

ToolsPreset creates a tools config for a preset.

type UserMessage

type UserMessage struct {
	MessageType     string  `json:"type"`
	Content         any     `json:"content"` // string or []ContentBlock
	UUID            *string `json:"uuid,omitempty"`
	ParentToolUseID *string `json:"parent_tool_use_id,omitempty"`
}

UserMessage represents a message from the user.

func (*UserMessage) GetParentToolUseID

func (m *UserMessage) GetParentToolUseID() string

GetParentToolUseID returns the parent tool use ID or empty string if nil.

func (*UserMessage) GetUUID

func (m *UserMessage) GetUUID() string

GetUUID returns the UUID or empty string if nil.

func (*UserMessage) MarshalJSON

func (m *UserMessage) MarshalJSON() ([]byte, error)

MarshalJSON implements custom JSON marshaling for UserMessage

func (*UserMessage) Type

func (m *UserMessage) Type() string

Type returns the message type for UserMessage.

type UserPromptSubmitHookInput

type UserPromptSubmitHookInput struct {
	BaseHookInput
	HookEventName string `json:"hook_event_name"` // always "UserPromptSubmit"
	Prompt        string `json:"prompt"`
}

UserPromptSubmitHookInput is the input for UserPromptSubmit hooks.

Directories

Path Synopsis

Jump to

Keyboard shortcuts

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