claude

package
v0.260414.2000 Latest Latest
Warning

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

Go to latest
Published: Apr 14, 2026 License: MPL-2.0 Imports: 23 Imported by: 0

Documentation

Index

Constants

View Source
const (
	// Environment variable names
	EnvClaudePath  = "CLAUDE_CLI_PATH"
	EnvUseBundled  = "CLAUDE_USE_BUNDLED"
	EnvUseGlobal   = "CLAUDE_USE_GLOBAL"
	EnvClaudeHome  = "CLAUDE_HOME"
	EnvBunEnv      = "BUN_INSTALL"
	EnvNodePath    = "NODE_PATH"
	EnvBunVersions = "BUN_VERSIONS"
	EnvBunInstall  = "BUN_INSTALL"

	// Default paths
	DefaultBundledPathLinux   = "/opt/claude-code/dist/claude"
	DefaultBundledPathDarwin  = "/Applications/Claude.app/Contents/MacOS/claude"
	DefaultBundledPathWindows = `C:\Program Files\Claude\claude.exe`

	// Claude version for bundled fallback
	DefaultBundledVersion = "1.0.0"
)
View Source
const (
	SDKTextMessage               = "text"
	SDKSystemMessage             = "system"
	SDKAssistantMessage          = "assistant"
	SDKUserMessage               = "user"
	SDKToolUseMessage            = "tool_use"
	SDKToolResultMessage         = "tool_result"
	SDKResultMessage             = "result"
	SDKStreamEventMessage        = "stream_event"
	SDKControlRequestMessage     = "control_request"
	SDKUserMessageReplayMessage  = "user_message_replay"
	SDKPartialAssistantMessage   = "partial_assistant"
	SDKCompactBoundaryMessage    = "compact_boundary"
	SDKStatusMessage             = "status"
	SDKLocalCommandOutputMessage = "local_command_output"
	SDKHookStartedMessage        = "hook_started"
	SDKHookProgressMessage       = "hook_progress"
	SDKHookResponseMessage       = "hook_response"
	SDKToolProgressMessage       = "tool_progress"
	SDKAuthStatusMessage         = "auth_status"
	SDKTaskNotificationMessage   = "task_notification"
	SDKTaskStartedMessage        = "task_started"
	SDKTaskProgressMessage       = "task_progress"
	SDKFilesPersistedMessage     = "files_persisted"
	SDKToolUseSummaryMessage     = "tool_use_summary"
	SDKRateLimitMessage          = "rate_limit"
	SDKPromptSuggestionMessage   = "prompt_suggestion"
)

MessageType constants for Claude Code stream JSON all of these types defined in python sdk: https://platform.claude.com/docs/en/agent-sdk/python#message-types or TypeScript sdk: https://platform.claude.com/docs/en/agent-sdk/typescript#message-types type SDKMessage =

| SDKAssistantMessage
| SDKUserMessage
| SDKUserMessageReplay
| SDKResultMessage
| SDKSystemMessage
| SDKPartialAssistantMessage
| SDKCompactBoundaryMessage
| SDKStatusMessage
| SDKLocalCommandOutputMessage
| SDKHookStartedMessage
| SDKHookProgressMessage
| SDKHookResponseMessage
| SDKToolProgressMessage
| SDKAuthStatusMessage
| SDKTaskNotificationMessage
| SDKTaskStartedMessage
| SDKTaskProgressMessage
| SDKFilesPersistedEvent
| SDKToolUseSummaryMessage
| SDKRateLimitEvent
| SDKPromptSuggestionMessage;
View Source
const (
	SystemSubtypeInit          = "init"
	SystemSubtypeTaskCompleted = "task_completed"
)

System message subtypes

View Source
const (
	AssistantErrorAuthFailed     = "authentication_failed"
	AssistantErrorBilling        = "billing_error"
	AssistantErrorRateLimit      = "rate_limit"
	AssistantErrorInvalidRequest = "invalid_request"
	AssistantErrorServer         = "server_error"
	AssistantErrorMaxTokens      = "max_output_tokens"
	AssistantErrorUnknown        = "unknown"
)

assistant message error ref: https://platform.claude.com/docs/en/agent-sdk/python#assistant-message-error

View Source
const (
	ControlMsgTypeResponse           = "control_response"
	ControlMsgTypeCancelNotification = "cancel_notification"
	ControlMsgTypeCancelRequest      = "control_cancel_request"
)

Control message types

View Source
const (
	ControlRequestSubtypeCanUseTool = "can_use_tool"
	ControlRequestSubtypeInterrupt  = "interrupt"
)

Control request subtypes

View Source
const (
	ControlRequestTypePermission = "permission"
	ControlRequestTypeCancel     = "cancel"
)

Control request types

View Source
const (
	ResultSubtypeSuccess = "success"
	ResultSubtypeError   = "error"
)

Result subtypes

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

Content block types

View Source
const (
	QueryOutputFormatStreamJSON QueryOutputFormat = "stream-json"
	QueryInputFormatStreamJSON  QueryInputFormat  = "stream-json"
)
View Source
const SDKControlPrefix = "control_"

Variables

This section is empty.

Functions

func BuildCommonArgs

func BuildCommonArgs(config Config, opts CommonOptions) []string

BuildCommonArgs builds CLI arguments shared between Launcher and QueryLauncher This follows the original query_launcher.go behavior where config and opts arguments are added independently (both can be present).

func FormatEnv

func FormatEnv(key, value string) string

FormatEnv formats an environment variable as KEY=VALUE

func GetCleanEnv

func GetCleanEnv(ctx context.Context) ([]string, error)

GetCleanEnv is a convenience function for getting clean environment

func InvalidateDiscoveryCache

func InvalidateDiscoveryCache()

InvalidateDiscoveryCache invalidates the global discovery cache

func IsValidPermissionMode

func IsValidPermissionMode(mode string) bool

IsValidPermissionMode checks if a permission mode is valid for Claude CLI

func MergeEnv

func MergeEnv(base []string, custom []string) []string

MergeEnv merges custom environment variables with base environment Custom variables override base ones with the same key

func StreamToStdin

func StreamToStdin(ctx context.Context, stdin io.WriteCloser, messages <-chan any) error

StreamToStdin streams messages to the stdin of a running process

func ValidateQueryConfig

func ValidateQueryConfig(qc QueryConfig) error

ValidateQueryConfig validates the full QueryConfig including prompt

Types

type Agent

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

Agent implements the agentboot.Agent interface for Claude Code

func NewAgent

func NewAgent(config agentboot.Config) *Agent

NewAgent creates a new Claude agent

func (*Agent) Execute

func (a *Agent) Execute(ctx context.Context, prompt string, opts agentboot.ExecutionOptions) (*agentboot.Result, error)

Execute runs the Claude agent

func (*Agent) GetDefaultFormat

func (a *Agent) GetDefaultFormat() agentboot.OutputFormat

GetDefaultFormat returns the current default format

func (*Agent) IsAvailable

func (a *Agent) IsAvailable() bool

IsAvailable checks if Claude Code is available

func (*Agent) SetCLIPath

func (a *Agent) SetCLIPath(path string)

SetCLIPath sets an explicit CLI path

func (*Agent) SetDefaultFormat

func (a *Agent) SetDefaultFormat(format agentboot.OutputFormat)

SetDefaultFormat sets the default output format

func (*Agent) SetSkipPermissions

func (a *Agent) SetSkipPermissions(enabled bool)

SetSkipPermissions enables or disables skip permissions mode

func (*Agent) Type

func (a *Agent) Type() agentboot.AgentType

Type returns the agent type

type AssistantMessage

type AssistantMessage struct {
	Type            string            `json:"type"`
	Message         anthropic.Message `json:"message"`
	ParentToolUseID *string           `json:"parent_tool_use_id,omitempty"`
	SessionID       string            `json:"session_id"`
	UUID            string            `json:"uuid"`
	Timestamp       time.Time         `json:"timestamp,omitempty"`
	Error           string            `json:"error,omitempty"`
}

AssistantMessage represents assistant messages with content blocks

func (*AssistantMessage) GetRawData

func (m *AssistantMessage) GetRawData() map[string]interface{}

GetRawData implements Message

func (*AssistantMessage) GetTimestamp

func (m *AssistantMessage) GetTimestamp() time.Time

GetTimestamp implements Message

func (*AssistantMessage) GetType

func (m *AssistantMessage) GetType() string

GetType implements Message

func (*AssistantMessage) IsError

func (m *AssistantMessage) IsError() bool

IsError returns true if the assistant message contains an error

type CLIDiscovery

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

CLIDiscovery handles Claude CLI path discovery and version checking

func NewCLIDiscovery

func NewCLIDiscovery() *CLIDiscovery

NewCLIDiscovery creates a new CLI discovery instance

func (*CLIDiscovery) FindClaudeCLI

func (d *CLIDiscovery) FindClaudeCLI(ctx context.Context) (*CLIVariant, error)

FindClaudeCLI finds the best available Claude CLI installation

func (*CLIDiscovery) GetCleanEnv

func (d *CLIDiscovery) GetCleanEnv(ctx context.Context) ([]string, error)

GetCleanEnv returns a clean environment for running Claude CLI

func (*CLIDiscovery) InvalidateCache

func (d *CLIDiscovery) InvalidateCache()

InvalidateCache clears the cached CLI variant

type CLIVariant

type CLIVariant struct {
	Path    string
	Version string
	Source  string // "global", "bundled", "custom", "env"
}

CLIVariant represents a discovered Claude CLI installation

func FindClaudeCLI

func FindClaudeCLI(ctx context.Context) (*CLIVariant, error)

type CallToolOptions

type CallToolOptions struct {
	Signal <-chan struct{} // Cancel signal for aborting the request
}

CallToolOptions contains options for tool calls

type CanCallToolCallback

type CanCallToolCallback func(ctx context.Context, toolName string, input map[string]interface{}, opts CallToolOptions) (map[string]interface{}, error)

Callback is called when Claude requests permission to use a tool

Response format according to Claude CLI Agent Protocol: - Allow: {"behavior": "allow", "updatedInput": {...}} - Deny: {"behavior": "deny", "message": "reason"}

The updatedInput field is REQUIRED when allowing - it must contain the original or modified input that will be passed to the tool.

Returning an error will also deny the tool with the error message as the reason.

type CancelRequestBuilder

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

CancelRequestBuilder builds cancel control requests

func NewCancelRequestBuilder

func NewCancelRequestBuilder() *CancelRequestBuilder

NewCancelRequestBuilder creates a new cancel request builder

func (*CancelRequestBuilder) Build

Build creates the control request

func (*CancelRequestBuilder) WithCancel

WithCancel sets the cancel ID

func (*CancelRequestBuilder) WithReason

func (b *CancelRequestBuilder) WithReason(reason string) *CancelRequestBuilder

WithReason sets the cancellation reason

func (*CancelRequestBuilder) WithRequestID

func (b *CancelRequestBuilder) WithRequestID(id string) *CancelRequestBuilder

WithRequestID sets the request ID

type CommonOptions

type CommonOptions struct {
	Model                string
	FallbackModel        string
	MaxTurns             int
	CustomSystemPrompt   string
	AppendSystemPrompt   string
	ContinueConversation bool
	Resume               string
	AllowedTools         []string
	DisallowedTools      []string
	MCPServers           map[string]interface{}
	StrictMcpConfig      bool
	PermissionMode       string
	SettingsPath         string

	// PermissionPromptTool specifies the tool for permission prompts (e.g., "stdio")
	PermissionPromptTool string
}

CommonOptions represents per-execution options that can override config

type Config

type Config struct {
	// Stream Options
	EnableStreamJSON bool `json:"enable_stream_json"`
	StreamBufferSize int  `json:"stream_buffer_size"`

	// Execution Timeout
	// DefaultExecutionTimeout is the default timeout for agent execution
	DefaultExecutionTimeout time.Duration `json:"default_execution_timeout,omitempty"`

	// Model Selection
	Model         string `json:"model,omitempty"`
	FallbackModel string `json:"fallback_model,omitempty"`

	// MaxTurns limits the number of agentic turns
	MaxTurns int `json:"max_turns,omitempty"`

	// System Prompt Options
	CustomSystemPrompt string `json:"custom_system_prompt,omitempty"`
	// AppendSystemPrompt adds additional system prompt content
	AppendSystemPrompt string `json:"append_system_prompt,omitempty"`

	// Conversation Continuation
	ContinueConversation bool `json:"continue_conversation,omitempty"`
	// ResumeSessionID resumes a specific session
	ResumeSessionID string `json:"resume_session_id,omitempty"`

	// Tool Filtering
	AllowedTools    []string `json:"allowed_tools,omitempty"`
	DisallowedTools []string `json:"disallowed_tools,omitempty"`

	// Permission Handling
	PermissionMode PermissionMode `json:"permission_mode,omitempty"`

	// Configuration Paths
	SettingsPath string `json:"settings_path,omitempty"`

	// MCP Server Configuration
	// MCPServers maps server names to their configurations
	MCPServers map[string]interface{} `json:"mcp_servers,omitempty"`
	// StrictMcpConfig enables strict MCP configuration validation
	StrictMcpConfig bool `json:"strict_mcp_config,omitempty"`

	// Custom Environment Variables
	// CustomEnv allows passing additional environment variables to the Claude CLI
	CustomEnv []string `json:"custom_env,omitempty"`

	// CLI Path Override
	// CLIPath explicitly sets the path to the Claude CLI executable
	CLIPath string `json:"cli_path,omitempty"`

	// UseBundled forces use of the bundled Claude CLI
	UseBundled bool `json:"use_bundled,omitempty"`

	// UseGlobal forces use of the global Claude CLI
	UseGlobal bool `json:"use_global,omitempty"`
}

Config holds Claude-specific configuration

func DefaultConfig

func DefaultConfig() *Config

DefaultConfig returns a config with sensible defaults

func (*Config) WithContinue

func (c *Config) WithContinue() *Config

WithContinue returns a new config configured for continuing a conversation

func (*Config) WithModel

func (c *Config) WithModel(model string) *Config

WithModel returns a new config with the specified model

func (*Config) WithResume

func (c *Config) WithResume(sessionID string) *Config

WithResume returns a new config configured for resuming a session

type ContentBlock

type ContentBlock interface {
	GetContentType() string
}

ContentBlock types

func UnmarshalContentBlock

func UnmarshalContentBlock(data []byte) (ContentBlock, error)

UnmarshalContentBlock unmarshals a content block from JSON

type ControlManager

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

ControlManager manages control request/response lifecycle

func NewControlManager

func NewControlManager() *ControlManager

NewControlManager creates a new control manager

func (*ControlManager) Close

func (m *ControlManager) Close() error

Close closes the control manager and cleans up resources

func (*ControlManager) HandleCancel

func (m *ControlManager) HandleCancel(cancelID string)

HandleCancel handles a cancel notification from Claude

func (*ControlManager) HandleControlMessage

func (m *ControlManager) HandleControlMessage(data map[string]interface{}) error

HandleControlMessage processes a raw control message from the event stream

func (*ControlManager) HandleResponse

func (m *ControlManager) HandleResponse(resp ControlResponse)

HandleResponse processes a control response from Claude

func (*ControlManager) IsClosed

func (m *ControlManager) IsClosed() bool

IsClosed returns true if the manager is closed

func (*ControlManager) RegisterCancelController

func (m *ControlManager) RegisterCancelController(id string, cancel context.CancelFunc)

RegisterCancelController registers a cancel controller for an operation

func (*ControlManager) SendRequest

func (m *ControlManager) SendRequest(ctx context.Context, req ControlRequest, stdin io.Writer) (ControlResponse, error)

SendRequest sends a control request and waits for a response

func (*ControlManager) SendRequestAsync

func (m *ControlManager) SendRequestAsync(req ControlRequest, stdin io.Writer) error

SendRequestAsync sends a control request without waiting for response

func (*ControlManager) SetRequestTimeout

func (m *ControlManager) SetRequestTimeout(d time.Duration)

SetRequestTimeout sets the timeout for control requests

func (*ControlManager) UnregisterCancelController

func (m *ControlManager) UnregisterCancelController(id string)

UnregisterCancelController removes a cancel controller

type ControlRequest

type ControlRequest struct {
	RequestID string                 `json:"request_id"`
	Type      string                 `json:"type"` // e.g., "permission", "cancel"
	Request   map[string]interface{} `json:"request"`
}

ControlRequest represents a control request sent to Claude

func (*ControlRequest) GetRawData

func (m *ControlRequest) GetRawData() map[string]interface{}

GetRawData implements Message

func (*ControlRequest) GetTimestamp

func (m *ControlRequest) GetTimestamp() time.Time

GetTimestamp implements Message

func (*ControlRequest) GetType

func (m *ControlRequest) GetType() string

GetType implements Message

type ControlResponse

type ControlResponse struct {
	RequestID string                 `json:"request_id"`
	Type      string                 `json:"type"` // e.g., "permission_response", "cancel_response"
	Response  map[string]interface{} `json:"response"`
}

ControlResponse represents a control response received from Claude

type Formatter

type Formatter interface {
	Format(msg Message) string
}

Formatter converts messages to structured text

type InputJSONDelta

type InputJSONDelta struct {
	Type        string `json:"type"`
	PartialJSON string `json:"partial_json"`
}

InputJSONDelta represents incremental tool input JSON

type Launcher

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

Launcher handles Claude Code CLI execution

func NewLauncher

func NewLauncher(config Config) *Launcher

NewLauncher creates a new Claude launcher

func (*Launcher) Execute

func (l *Launcher) Execute(ctx context.Context, prompt string, opts agentboot.ExecutionOptions) (*agentboot.Result, error)

Execute runs Claude Code with the given prompt

func (*Launcher) ExecuteWithHandler

func (l *Launcher) ExecuteWithHandler(ctx context.Context,
	prompt string,
	timeout time.Duration,
	opts agentboot.ExecutionOptions,
	handler agentboot.MessageHandler,
) error

func (*Launcher) ExecuteWithTimeout

func (l *Launcher) ExecuteWithTimeout(
	ctx context.Context,
	prompt string,
	timeout time.Duration,
	opts agentboot.ExecutionOptions,
) (*agentboot.Result, error)

ExecuteWithTimeout runs Claude Code with a specific timeout

func (*Launcher) GetControlManager

func (l *Launcher) GetControlManager() *ControlManager

GetControlManager returns the control manager

func (*Launcher) GetDefaultFormat

func (l *Launcher) GetDefaultFormat() agentboot.OutputFormat

GetDefaultFormat returns the current default format

func (*Launcher) GetDiscovery

func (l *Launcher) GetDiscovery() *CLIDiscovery

GetDiscovery returns the CLI discovery instance

func (*Launcher) Interrupt

func (l *Launcher) Interrupt(ctx context.Context, stdin io.WriteCloser, reason string) error

Interrupt sends an interrupt request to the Claude process

func (*Launcher) IsAvailable

func (l *Launcher) IsAvailable() bool

IsAvailable checks if Claude Code CLI is available using CLI discovery

func (*Launcher) SendPermissionRequest

func (l *Launcher) SendPermissionRequest(ctx context.Context, req agentboot.PermissionRequest, stdin io.WriteCloser) (agentboot.PermissionResult, error)

SendPermissionRequest sends a permission request and waits for response

func (*Launcher) SetCLIPath

func (l *Launcher) SetCLIPath(path string)

SetCLIPath sets an explicit CLI path

func (*Launcher) SetDefaultFormat

func (l *Launcher) SetDefaultFormat(format agentboot.OutputFormat)

SetDefaultFormat sets the default output format

func (*Launcher) SetSkipPermissions

func (l *Launcher) SetSkipPermissions(enabled bool)

SetSkipPermissions enables or disables skip permissions mode

func (*Launcher) Type

func (l *Launcher) Type() agentboot.AgentType

Type returns the agent type

type Message

type Message interface {
	GetType() string
	GetTimestamp() time.Time
	GetRawData() map[string]interface{}
}

Message is the interface for all Claude message types

type MessageAccumulator

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

MessageAccumulator collects related events into complete messages

func NewMessageAccumulator

func NewMessageAccumulator() *MessageAccumulator

NewMessageAccumulator creates a new message accumulator

func (*MessageAccumulator) AddEvent

func (a *MessageAccumulator) AddEvent(event events.Event) ([]Message, bool, bool)

AddEvent adds a parsed event and returns any newly complete messages Returns: (newMessages, hasResult, resultSuccess)

func (*MessageAccumulator) GetAssistantMessages

func (a *MessageAccumulator) GetAssistantMessages() []*AssistantMessage

GetAssistantMessages returns all assistant messages

func (*MessageAccumulator) GetMessages

func (a *MessageAccumulator) GetMessages() []Message

GetMessages returns all accumulated messages

func (*MessageAccumulator) GetMessagesByType

func (a *MessageAccumulator) GetMessagesByType(msgType string) []Message

GetMessagesByType returns messages of a specific type

func (*MessageAccumulator) GetSessionID

func (a *MessageAccumulator) GetSessionID() string

GetSessionID returns the session ID if available

func (*MessageAccumulator) GetToolUses

func (a *MessageAccumulator) GetToolUses() map[string]*PendingToolUse

GetToolUses returns all tool uses with their results

func (*MessageAccumulator) Reset

func (a *MessageAccumulator) Reset()

Reset clears the accumulator state

type MessageDelta

type MessageDelta struct {
	Type       string     `json:"type"`
	StopReason string     `json:"stop_reason,omitempty"`
	Usage      *UsageInfo `json:"usage,omitempty"`
}

MessageDelta represents message-level updates

type PendingToolUse

type PendingToolUse struct {
	ToolUseID string
	ToolUse   *ToolUseBlock
	Result    *ToolResultMessage
	Complete  bool
}

PendingToolUse tracks a tool_use waiting for its result

type PermissionDenial

type PermissionDenial struct {
	RequestID string `json:"request_id"`
	Reason    string `json:"reason"`
}

PermissionDenial represents a denied permission request

type PermissionMode

type PermissionMode string

PermissionMode defines how permission requests are handled These values must match Claude Code CLI's --permission-mode options

const (
	// PermissionModeDefault uses the default permission behavior (asks for permissions)
	PermissionModeDefault PermissionMode = "default"
	// PermissionModeAuto auto-approves permissions (equivalent to bypassPermissions)
	PermissionModeAuto PermissionMode = "auto"
	// PermissionModeDontAsk doesn't ask for permissions
	PermissionModeDontAsk PermissionMode = "dontAsk"
	// PermissionModeBypassPermissions bypasses all permission checks
	PermissionModeBypassPermissions PermissionMode = "bypassPermissions"
	// PermissionModeAcceptEdits accepts edit operations
	PermissionModeAcceptEdits PermissionMode = "acceptEdits"
	// PermissionModePlan enables plan mode
	PermissionModePlan PermissionMode = "plan"
)

func MapAskModeToPermissionMode

func MapAskModeToPermissionMode(askMode string) PermissionMode

MapAskModeToPermissionMode maps the internal ask.Mode to Claude CLI permission mode This is used when converting from bot handler's ask mode to Claude CLI permission mode

type PermissionRequestBuilder

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

PermissionRequestBuilder builds permission control requests

func NewPermissionRequestBuilder

func NewPermissionRequestBuilder() *PermissionRequestBuilder

NewPermissionRequestBuilder creates a new permission request builder

func (*PermissionRequestBuilder) Build

Build creates the control request

func (*PermissionRequestBuilder) WithRequestID

WithRequestID sets the request ID

func (*PermissionRequestBuilder) WithTool

func (b *PermissionRequestBuilder) WithTool(name string, input map[string]interface{}) *PermissionRequestBuilder

WithTool sets the tool name and input

type Query

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

Query manages the interaction with Claude process in stdio mode It implements an iterator-like pattern for consuming messages

func NewQuery

func NewQuery(
	ctx context.Context,
	childStdin io.WriteCloser,
	childStdout io.Reader,
	options QueryOptions,
) *Query

NewQuery creates a new Query instance for stdio-based communication

func (*Query) Close

func (q *Query) Close() error

Close closes the query and cleans up resources

func (*Query) Done

func (q *Query) Done() <-chan struct{}

Done returns a channel that's closed when the query is complete

func (*Query) Errors

func (q *Query) Errors() <-chan error

Errors returns the read-only channel of errors

func (*Query) Interrupt

func (q *Query) Interrupt() error

Interrupt sends an interrupt request to Claude

func (*Query) IsClosed

func (q *Query) IsClosed() bool

IsClosed returns true if the query is closed

func (*Query) Messages

func (q *Query) Messages() <-chan SDKMessage

Messages returns the read-only channel of messages

func (*Query) Next

func (q *Query) Next() (SDKMessage, bool)

Next returns the next message from the stream Returns (message, true) when a message is available Returns (nil, false) when the stream is complete Returns error via Errors() channel if an error occurs

func (*Query) SendMessage

func (q *Query) SendMessage(msg map[string]interface{}) error

SendMessage sends a user message (e.g., tool result) to Claude

func (*Query) SetError

func (q *Query) SetError(err error)

SetError sets an error on the query stream

type QueryConfig

type QueryConfig struct {
	// Prompt can be either a string or a channel of messages
	Prompt QueryPrompt

	// Options for the query
	Options *QueryOptionsConfig
}

QueryConfig is the configuration for creating a Query

type QueryInputFormat

type QueryInputFormat string

QueryInputFormat is the input format for prompts

type QueryOptions

type QueryOptions struct {
	CanCallTool CanCallToolCallback
	AbortSignal <-chan struct{}
	ProcessDone <-chan struct{}
}

QueryOptions contains options for creating a Query

type QueryOptionsConfig

type QueryOptionsConfig struct {
	// Working directory
	CWD string

	// Path to Claude executable
	ClaudePath string

	// Model selection
	Model         string
	FallbackModel string

	// System prompts
	CustomSystemPrompt string
	AppendSystemPrompt string

	// Conversation control
	ContinueConversation bool
	Resume               string

	// Tool filtering
	AllowedTools    []string
	DisallowedTools []string

	// Permission mode
	PermissionMode string

	// MCP servers
	MCPServers      map[string]interface{}
	StrictMcpConfig bool

	// Settings path
	SettingsPath string

	// Maximum turns
	MaxTurns int

	// Callback for tool permission requests
	CanCallTool CanCallToolCallback

	// Abort signal
	AbortSignal <-chan struct{}

	// Custom environment
	CustomEnv []string
}

QueryOptionsConfig contains options for Query execution

func (*QueryOptionsConfig) Validate

func (c *QueryOptionsConfig) Validate() error

Validate validates the query configuration

type QueryOutputFormat

type QueryOutputFormat string

QueryOutputFormat is the input/output format for Query mode

type QueryPrompt

type QueryPrompt interface{}

QueryPrompt represents either a string prompt or a channel of messages

type ResultCollector

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

ResultCollector collects messages and builds an agentboot.Result It implements MessageHandler for use with ExecuteWithHandler

func NewResultCollector

func NewResultCollector() *ResultCollector

NewResultCollector creates a new result collector

func (*ResultCollector) BuildTextOutput

func (r *ResultCollector) BuildTextOutput() string

BuildTextOutput constructs the text output from collected messages

func (*ResultCollector) GetMessages

func (r *ResultCollector) GetMessages() []Message

GetMessages returns all collected messages

func (*ResultCollector) IsComplete

func (r *ResultCollector) IsComplete() bool

IsComplete returns true if collection is complete

func (*ResultCollector) OnAsk

func (*ResultCollector) OnComplete

func (r *ResultCollector) OnComplete(completion *agentboot.CompletionResult)

OnComplete implements MessageHandler

func (*ResultCollector) OnError

func (r *ResultCollector) OnError(err error)

OnError implements MessageHandler

func (*ResultCollector) OnMessage

func (r *ResultCollector) OnMessage(msg any) error

OnMessage implements MessageHandler

func (*ResultCollector) Result

func (r *ResultCollector) Result() *agentboot.Result

Result returns the collected result

type ResultMessage

type ResultMessage struct {
	Type              string             `json:"type"`
	SubType           string             `json:"subtype,omitempty"`
	Result            string             `json:"result,omitempty"`
	TotalCostUSD      float64            `json:"total_cost_usd,omitempty"`
	IsError           bool               `json:"is_error,omitempty"`
	DurationMS        int64              `json:"duration_ms,omitempty"`
	DurationAPIMS     int64              `json:"duration_api_ms,omitempty"`
	NumTurns          int                `json:"num_turns,omitempty"`
	Usage             UsageInfo          `json:"usage,omitempty"`
	SessionID         string             `json:"session_id,omitempty"`
	PermissionDenials []PermissionDenial `json:"permission_denials,omitempty"`
	Timestamp         time.Time          `json:"timestamp,omitempty"`
}

ResultMessage represents the final result message

func (*ResultMessage) GetRawData

func (m *ResultMessage) GetRawData() map[string]interface{}

GetRawData implements Message

func (*ResultMessage) GetTimestamp

func (m *ResultMessage) GetTimestamp() time.Time

GetTimestamp implements Message

func (*ResultMessage) GetType

func (m *ResultMessage) GetType() string

GetType implements Message

func (*ResultMessage) IsSuccess

func (m *ResultMessage) IsSuccess() bool

IsSuccess returns true if the result indicates success

type SDKMessage

type SDKMessage struct {
	Type      string                 `json:"type"`
	RequestID string                 `json:"request_id,omitempty"`
	Request   map[string]interface{} `json:"request,omitempty"`
	Response  map[string]interface{} `json:"response,omitempty"`
	// Message fields for regular messages
	SessionID string                 `json:"session_id,omitempty"`
	Message   map[string]interface{} `json:"message,omitempty"`
	SubType   string                 `json:"subtype,omitempty"`
	Result    string                 `json:"result,omitempty"`
	UUID      string                 `json:"uuid,omitempty"`
	Timestamp string                 `json:"timestamp,omitempty"`
	RawData   map[string]interface{} `json:"-"`
}

SDKMessage represents a message from Claude SDK via stdout

type StreamEvent

type StreamEvent struct {
	Type  string      `json:"type"` // content_block_delta, content_block_start, etc.
	Index int         `json:"index,omitempty"`
	Delta interface{} `json:"delta,omitempty"` // TextDelta, InputJSONDelta, etc.
}

StreamEvent represents a streaming event

type StreamEventMessage

type StreamEventMessage struct {
	Type      string      `json:"type"`
	Event     StreamEvent `json:"event"`
	SessionID string      `json:"session_id,omitempty"`
	Timestamp time.Time   `json:"timestamp,omitempty"`
}

StreamEventMessage represents real-time streaming delta events

func (*StreamEventMessage) GetRawData

func (m *StreamEventMessage) GetRawData() map[string]interface{}

GetRawData implements Message

func (*StreamEventMessage) GetTimestamp

func (m *StreamEventMessage) GetTimestamp() time.Time

GetTimestamp implements Message

func (*StreamEventMessage) GetType

func (m *StreamEventMessage) GetType() string

GetType implements Message

type StreamPrompt

type StreamPrompt <-chan any

StreamPrompt is a channel-based prompt for streaming

type StreamPromptBuilder

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

StreamPromptBuilder helps build stream prompts

func NewStreamPromptBuilder

func NewStreamPromptBuilder() *StreamPromptBuilder

NewStreamPromptBuilder creates a new stream prompt builder

func (*StreamPromptBuilder) Add

func (b *StreamPromptBuilder) Add(msg map[string]interface{}) error

Add adds a message to the stream

func (*StreamPromptBuilder) AddText

func (b *StreamPromptBuilder) AddText(text string) error

AddText adds a text message to the stream

func (*StreamPromptBuilder) AddUserMessage

func (b *StreamPromptBuilder) AddUserMessage(content string) error

AddUserMessage adds a user message to the stream

func (*StreamPromptBuilder) Close

func (b *StreamPromptBuilder) Close() StreamPrompt

Close closes the stream and returns the channel for use with Query

func (*StreamPromptBuilder) IsClosed

func (b *StreamPromptBuilder) IsClosed() bool

IsClosed returns true if the builder is closed

func (*StreamPromptBuilder) Messages

func (b *StreamPromptBuilder) Messages() StreamPrompt

Messages returns the underlying message channel

type StreamReader

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

StreamReader reads line-delimited JSON from a reader

func NewStreamReader

func NewStreamReader(r io.Reader) *StreamReader

NewStreamReader creates a new stream reader

func (*StreamReader) Next

func (r *StreamReader) Next() (map[string]interface{}, error)

Next reads the next JSON object from the stream

func (*StreamReader) ReadAll

func (r *StreamReader) ReadAll() ([]map[string]interface{}, error)

ReadAll reads all remaining objects from the stream

type StreamWriter

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

StreamWriter writes line-delimited JSON to a writer

func NewStreamWriter

func NewStreamWriter(w io.Writer) *StreamWriter

NewStreamWriter creates a new stream writer

func (*StreamWriter) Close

func (w *StreamWriter) Close() error

Close closes the stream writer

func (*StreamWriter) Write

func (w *StreamWriter) Write(data map[string]interface{}) error

Write writes a JSON object to the stream

type StringPrompt

type StringPrompt string

StringPrompt is a string prompt

type SystemMessage

type SystemMessage struct {
	Type      string    `json:"type"`
	SubType   string    `json:"subtype,omitempty"`
	SessionID string    `json:"session_id"`
	Timestamp time.Time `json:"timestamp"`

	// Subagent task fields (populated when SubType is task_started/task_notification/task_completed)
	Description string `json:"description,omitempty"`
	Prompt      string `json:"prompt,omitempty"`
	TaskID      string `json:"task_id,omitempty"`
	TaskType    string `json:"task_type,omitempty"`
	ToolUseID   string `json:"tool_use_id,omitempty"`
}

SystemMessage represents system/init messages

func (*SystemMessage) GetRawData

func (m *SystemMessage) GetRawData() map[string]interface{}

GetRawData implements Message

func (*SystemMessage) GetTimestamp

func (m *SystemMessage) GetTimestamp() time.Time

GetTimestamp implements Message

func (*SystemMessage) GetType

func (m *SystemMessage) GetType() string

GetType implements Message

type TextBlock

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

TextBlock represents text content

func (*TextBlock) GetContentType

func (b *TextBlock) GetContentType() string

GetContentType implements ContentBlock

type TextDelta

type TextDelta struct {
	Type string `json:"type"`
	Text string `json:"text"`
}

TextDelta represents incremental text content

type TextFormatter

type TextFormatter struct {
	IncludeTimestamp bool
	Verbose          bool
	ShowToolDetails  bool
	// contains filtered or unexported fields
}

TextFormatter implements Formatter using Go templates

func NewTextFormatter

func NewTextFormatter() *TextFormatter

NewTextFormatter creates a new text formatter with default templates

func (*TextFormatter) Format

func (f *TextFormatter) Format(msg Message) string

Format formats a message using sprintf for better performance

func (*TextFormatter) SetIncludeTimestamp

func (f *TextFormatter) SetIncludeTimestamp(include bool)

SetIncludeTimestamp sets whether to include timestamps in output

func (*TextFormatter) SetShowToolDetails

func (f *TextFormatter) SetShowToolDetails(show bool)

SetShowToolDetails sets whether to show tool details

func (*TextFormatter) SetTemplate

func (f *TextFormatter) SetTemplate(msgType string, tmpl string) error

SetTemplate sets a custom template for a message type

func (*TextFormatter) SetTemplateFromFile

func (f *TextFormatter) SetTemplateFromFile(msgType, filename string) error

SetTemplateFromFile sets a custom template from a file

func (*TextFormatter) SetVerbose

func (f *TextFormatter) SetVerbose(verbose bool)

SetVerbose sets verbose mode for detailed output

type ThinkingBlock

type ThinkingBlock struct {
	Type     string `json:"type"`
	Thinking string `json:"thinking"`
}

ThinkingBlock represents reasoning/thinking content

func (*ThinkingBlock) GetContentType

func (b *ThinkingBlock) GetContentType() string

GetContentType implements ContentBlock

type ToolCallInfo

type ToolCallInfo struct {
	CallID    string      `json:"call_id"`
	ToolName  string      `json:"tool_name"`
	Input     interface{} `json:"input"`
	Result    interface{} `json:"result"`
	Completed bool        `json:"completed"`
}

ToolCallInfo represents a tool call

type ToolResultContentBlock

type ToolResultContentBlock struct {
	Type      string `json:"type"`
	ToolUseID string `json:"tool_use_id"`
	Content   string `json:"content"`
	IsError   bool   `json:"is_error,omitempty"`
}

ToolResultContentBlock represents tool result content (within message content array)

func (*ToolResultContentBlock) GetContentType

func (b *ToolResultContentBlock) GetContentType() string

GetContentType implements ContentBlock

type ToolResultMessage

type ToolResultMessage struct {
	Type      string         `json:"type"`
	Output    string         `json:"output,omitempty"`  // String output
	Content   []ContentBlock `json:"content,omitempty"` // Or structured content
	ToolUseID string         `json:"tool_use_id"`
	IsError   bool           `json:"is_error,omitempty"`
	SessionID string         `json:"session_id,omitempty"`
	Timestamp time.Time      `json:"timestamp,omitempty"`
}

ToolResultMessage represents a tool result message

func (*ToolResultMessage) GetRawData

func (m *ToolResultMessage) GetRawData() map[string]interface{}

GetRawData implements Message

func (*ToolResultMessage) GetTimestamp

func (m *ToolResultMessage) GetTimestamp() time.Time

GetTimestamp implements Message

func (*ToolResultMessage) GetType

func (m *ToolResultMessage) GetType() string

GetType implements Message

type ToolUseBlock

type ToolUseBlock struct {
	Type  string                 `json:"type"`
	ID    string                 `json:"id"`
	Name  string                 `json:"name"`
	Input map[string]interface{} `json:"input"`
}

ToolUseBlock represents a tool use invocation

func (*ToolUseBlock) GetContentType

func (b *ToolUseBlock) GetContentType() string

GetContentType implements ContentBlock

type ToolUseMessage

type ToolUseMessage struct {
	Type      string                 `json:"type"`
	Name      string                 `json:"name"`
	Input     map[string]interface{} `json:"input"`
	ToolUseID string                 `json:"tool_use_id"`
	SessionID string                 `json:"session_id,omitempty"`
	Timestamp time.Time              `json:"timestamp,omitempty"`
}

ToolUseMessage represents a standalone tool use message (from stream)

func (*ToolUseMessage) GetRawData

func (m *ToolUseMessage) GetRawData() map[string]interface{}

GetRawData implements Message

func (*ToolUseMessage) GetTimestamp

func (m *ToolUseMessage) GetTimestamp() time.Time

GetTimestamp implements Message

func (*ToolUseMessage) GetType

func (m *ToolUseMessage) GetType() string

GetType implements Message

type UnknownBlock

type UnknownBlock struct {
	Data map[string]interface{}
}

UnknownBlock represents an unrecognized content block

func (*UnknownBlock) GetContentType

func (b *UnknownBlock) GetContentType() string

GetContentType implements ContentBlock

type UsageInfo

type UsageInfo struct {
	InputTokens              int `json:"input_tokens"`
	CacheCreationInputTokens int `json:"cache_creation_input_tokens,omitempty"`
	CacheReadInputTokens     int `json:"cache_read_input_tokens,omitempty"`
	OutputTokens             int `json:"output_tokens"`
}

UsageInfo contains token usage statistics

type UserMessage

type UserMessage struct {
	Type            string    `json:"type"`
	Message         string    `json:"message"`
	ParentToolUseID *string   `json:"parent_tool_use_id,omitempty"`
	SessionID       string    `json:"session_id,omitempty"`
	Timestamp       time.Time `json:"timestamp,omitempty"`
}

UserMessage represents user messages

func (*UserMessage) GetRawData

func (m *UserMessage) GetRawData() map[string]interface{}

GetRawData implements Message

func (*UserMessage) GetTimestamp

func (m *UserMessage) GetTimestamp() time.Time

GetTimestamp implements Message

func (*UserMessage) GetType

func (m *UserMessage) GetType() string

GetType implements Message

Directories

Path Synopsis
examples
query command
server command

Jump to

Keyboard shortcuts

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