Documentation
¶
Overview ¶
Package claude provides a Go SDK for interacting with the Claude CLI.
The SDK manages the lifecycle of Claude CLI processes and provides both synchronous and event-driven APIs for sending messages and receiving streaming responses.
Quick Start ¶
For simple one-shot queries:
result, err := claude.Query(ctx, "What is 2+2?")
if err != nil {
log.Fatal(err)
}
fmt.Printf("Response: %s\nCost: $%.6f\n", result.Text, result.Usage.CostUSD)
For simple synchronous usage:
session := claude.NewSession(
claude.WithModel("haiku"),
claude.WithPermissionMode(claude.PermissionModeBypass),
)
if err := session.Start(ctx); err != nil {
log.Fatal(err)
}
defer session.Stop()
// Send message and collect events until turn completes
session.SendMessage(ctx, "What is 2+2?")
for event := range session.Events() {
switch e := event.(type) {
case claude.TurnCompleteEvent:
fmt.Printf("Success: %v, Cost: $%.6f\n", e.Success, e.Usage.CostUSD)
return
}
}
Event-Driven Usage ¶
For streaming responses with real-time text output:
session := claude.NewSession(
claude.WithModel("haiku"),
claude.WithPermissionMode(claude.PermissionModeBypass),
)
if err := session.Start(ctx); err != nil {
log.Fatal(err)
}
defer session.Stop()
// Send message
session.SendMessage(ctx, "Write a haiku about Go programming")
// Collect events until turn completes
for event := range session.Events() {
switch e := event.(type) {
case claude.ReadyEvent:
fmt.Printf("Session ready: %s\n", e.Info.SessionID)
case claude.TextEvent:
fmt.Print(e.Text) // Stream text as it arrives
case claude.ToolStartEvent:
fmt.Printf("\n[Tool: %s started]\n", e.Name)
case claude.TurnCompleteEvent:
fmt.Printf("\n[Cost: $%.6f]\n", e.Usage.CostUSD)
return // Exit loop when turn completes
}
}
Permission Handling ¶
When using PermissionModeDefault, you can handle permission requests:
handler := claude.PermissionHandlerFunc(func(
ctx context.Context,
req *claude.PermissionRequest,
) (*claude.PermissionResponse, error) {
// Auto-allow Read tool
if req.ToolName == "Read" {
return &claude.PermissionResponse{
Behavior: claude.PermissionAllow,
}, nil
}
// Deny others
return &claude.PermissionResponse{
Behavior: claude.PermissionDeny,
Message: "Not allowed",
}, nil
})
session := claude.NewSession(
claude.WithPermissionMode(claude.PermissionModeDefault),
claude.WithPermissionHandler(handler),
)
Session Recording ¶
Enable recording to save session messages for debugging or replay:
session := claude.NewSession(
claude.WithRecording("./recordings"),
)
// ... run session ...
session.Stop()
// Get recording info
recording := session.Recording()
fmt.Printf("Total cost: $%.6f\n", recording.TotalCost())
// Load a previous recording
loaded, _ := claude.LoadRecording("./recordings/session-abc123")
Index ¶
- Variables
- func IsRecoverable(err error) bool
- func QueryStream(ctx context.Context, prompt string, opts ...SessionOption) (<-chan Event, error)
- type AgentDefinition
- type AllowedPrompt
- type CLINotFoundError
- type CLIToolResultEvent
- type ContentBlock
- type ContentBlockType
- type ErrorEvent
- type Event
- type EventType
- type InteractiveToolHandler
- type MCPConfig
- func (c *MCPConfig) AddHTTPServer(name, url string) *MCPConfig
- func (c *MCPConfig) AddSDKServer(name string, handler SDKToolHandler) *MCPConfig
- func (c *MCPConfig) AddSSEServer(name, url string) *MCPConfig
- func (c *MCPConfig) AddStdioServer(name, command string, args []string) *MCPConfig
- func (c MCPConfig) MarshalJSON() ([]byte, error)
- func (c *MCPConfig) SDKHandlers() map[string]SDKToolHandler
- type MCPHTTPServerConfig
- type MCPSDKServerConfig
- type MCPSSEServerConfig
- type MCPServerConfig
- type MCPServerType
- type MCPStdioServerConfig
- type PermissionBehavior
- type PermissionHandler
- type PermissionHandlerFunc
- type PermissionMode
- type PermissionRequest
- type PermissionResponse
- type PlanInfo
- type ProcessError
- type ProtocolError
- type QueryResult
- type Question
- type QuestionOption
- type ReadyEvent
- type RecordedMessage
- type RecordingMetadata
- type SDKToolHandler
- type Session
- func (s *Session) Ask(ctx context.Context, content string) (*TurnResult, error)
- func (s *Session) AskWithTimeout(content string, timeout time.Duration) (*TurnResult, error)
- func (s *Session) CLIArgs() ([]string, error)
- func (s *Session) CollectResponse(ctx context.Context) (*TurnResult, []Event, error)
- func (s *Session) CurrentTurnNumber() int
- func (s *Session) Events() <-chan Event
- func (s *Session) Info() *SessionInfo
- func (s *Session) Interrupt(ctx context.Context) error
- func (s *Session) Recording() *SessionRecording
- func (s *Session) RecordingPath() string
- func (s *Session) SendMessage(ctx context.Context, content string) (int, error)
- func (s *Session) SendToolResult(ctx context.Context, toolUseID, content string) (int, error)
- func (s *Session) SetModel(ctx context.Context, model string) error
- func (s *Session) SetPermissionMode(ctx context.Context, mode PermissionMode) error
- func (s *Session) Start(ctx context.Context) error
- func (s *Session) State() SessionState
- func (s *Session) Stop() error
- func (s *Session) WaitForTurn(ctx context.Context) (*TurnResult, error)
- type SessionConfig
- type SessionInfo
- type SessionOption
- func WithAgents(agents ...AgentDefinition) SessionOption
- func WithAllowedTools(tools ...string) SessionOption
- func WithBetas(betas ...string) SessionOption
- func WithCLIPath(path string) SessionOption
- func WithDangerouslySkipPermissions() SessionOption
- func WithDisablePlugins() SessionOption
- func WithDisallowedTools(tools ...string) SessionOption
- func WithEnv(env map[string]string) SessionOption
- func WithEventBufferSize(size int) SessionOption
- func WithExtraArgs(args ...string) SessionOption
- func WithInteractiveToolHandler(handler InteractiveToolHandler) SessionOption
- func WithMCPConfig(cfg *MCPConfig) SessionOption
- func WithMaxBudgetUSD(budget float64) SessionOption
- func WithMaxTurns(n int) SessionOption
- func WithModel(model string) SessionOption
- func WithPermissionHandler(h PermissionHandler) SessionOption
- func WithPermissionMode(mode PermissionMode) SessionOption
- func WithPermissionPromptToolStdio() SessionOption
- func WithRecording(dir string) SessionOption
- func WithResume(sessionID string) SessionOption
- func WithSDKTools(serverName string, handler SDKToolHandler) SessionOption
- func WithStderrHandler(h func([]byte)) SessionOption
- func WithSystemPrompt(prompt string) SessionOption
- func WithWorkDir(dir string) SessionOption
- type SessionRecording
- type SessionState
- type StateChangeEvent
- type StateTransition
- type TextEvent
- type ThinkingEvent
- type ToolCompleteEvent
- func (e ToolCompleteEvent) StreamEventKind() agentstream.EventKind
- func (e ToolCompleteEvent) StreamToolCallID() string
- func (e ToolCompleteEvent) StreamToolInput() map[string]interface{}
- func (e ToolCompleteEvent) StreamToolIsError() bool
- func (e ToolCompleteEvent) StreamToolName() string
- func (e ToolCompleteEvent) StreamToolResult() interface{}
- func (e ToolCompleteEvent) Type() EventType
- type ToolProgressEvent
- type ToolStartEvent
- type TurnCompleteEvent
- func (e TurnCompleteEvent) StreamCost() float64
- func (e TurnCompleteEvent) StreamDuration() int64
- func (e TurnCompleteEvent) StreamEventKind() agentstream.EventKind
- func (e TurnCompleteEvent) StreamIsSuccess() bool
- func (e TurnCompleteEvent) StreamTurnNum() int
- func (e TurnCompleteEvent) Type() EventType
- type TurnError
- type TurnResult
- type TurnSummary
- type TurnUsage
- type TypedToolRegistry
Constants ¶
This section is empty.
Variables ¶
var ( ErrAlreadyStarted = errors.New("session already started") ErrNotStarted = errors.New("session not started") ErrStopping = errors.New("session is stopping") ErrSessionClosed = errors.New("session is closed") ErrTimeout = errors.New("operation timed out") ErrProcessExited = errors.New("CLI process exited unexpectedly") ErrInvalidState = errors.New("invalid state transition") ErrPermissionDenied = errors.New("permission denied") ErrBudgetExceeded = errors.New("budget limit exceeded") ErrMaxTurnsExceeded = errors.New("max turns exceeded") )
Sentinel errors for common error conditions.
Functions ¶
func IsRecoverable ¶
IsRecoverable returns true if the error is recoverable.
func QueryStream ¶
QueryStream sends a one-shot prompt and returns an event channel. The caller should range over the channel until it closes. Defaults to PermissionModeBypass if no permission mode is specified.
Types ¶
type AgentDefinition ¶
type AgentDefinition struct {
Name string `json:"name"`
Description string `json:"description,omitempty"`
Prompt string `json:"prompt,omitempty"`
Model string `json:"model,omitempty"`
AllowedTools []string `json:"allowed_tools,omitempty"`
DisallowedTools []string `json:"disallowed_tools,omitempty"`
}
AgentDefinition defines a sub-agent for the Claude CLI.
type AllowedPrompt ¶
type AllowedPrompt struct {
Tool string // Tool name (e.g., "Bash")
Prompt string // Description of allowed action
}
AllowedPrompt represents a permission requested by the plan.
type CLINotFoundError ¶
CLINotFoundError indicates the Claude CLI binary was not found.
func (*CLINotFoundError) Error ¶
func (e *CLINotFoundError) Error() string
func (*CLINotFoundError) Unwrap ¶
func (e *CLINotFoundError) Unwrap() error
type CLIToolResultEvent ¶
type CLIToolResultEvent struct {
Content interface{}
ToolUseID string
ToolName string
TurnNumber int
IsError bool
}
CLIToolResultEvent fires when CLI sends back auto-executed tool results.
func (CLIToolResultEvent) Type ¶
func (e CLIToolResultEvent) Type() EventType
Type returns the event type.
type ContentBlock ¶
type ContentBlock struct {
ToolResult interface{} `json:"tool_result,omitempty"`
ToolInput map[string]interface{} `json:"tool_input,omitempty"`
Type ContentBlockType `json:"type"`
Text string `json:"text,omitempty"`
Thinking string `json:"thinking,omitempty"`
ToolUseID string `json:"tool_use_id,omitempty"`
ToolName string `json:"tool_name,omitempty"`
IsError bool `json:"is_error,omitempty"`
}
ContentBlock is a structured content block from a Claude response.
type ContentBlockType ¶
type ContentBlockType string
ContentBlockType identifies the kind of content block.
const ( ContentBlockTypeText ContentBlockType = "text" ContentBlockTypeThinking ContentBlockType = "thinking" ContentBlockTypeToolUse ContentBlockType = "tool_use" ContentBlockTypeToolResult ContentBlockType = "tool_result" )
type ErrorEvent ¶
ErrorEvent contains session errors.
func (ErrorEvent) StreamErr ¶
func (e ErrorEvent) StreamErr() error
func (ErrorEvent) StreamErrorContext ¶
func (e ErrorEvent) StreamErrorContext() string
func (ErrorEvent) StreamEventKind ¶
func (e ErrorEvent) StreamEventKind() agentstream.EventKind
type EventType ¶
type EventType int
EventType discriminates between event kinds.
const ( // EventTypeReady fires when the session is initialized. EventTypeReady EventType = iota // EventTypeText fires for streaming text chunks. EventTypeText // EventTypeThinking fires for thinking chunks. EventTypeThinking // EventTypeToolStart fires when a tool begins execution. EventTypeToolStart // EventTypeToolProgress fires as tool input streams in. EventTypeToolProgress // EventTypeToolComplete fires when tool input is fully parsed. EventTypeToolComplete // EventTypeCLIToolResult fires when CLI sends back auto-executed tool results. EventTypeCLIToolResult // EventTypeTurnComplete fires when a turn finishes. EventTypeTurnComplete // EventTypeError fires on session errors. EventTypeError // EventTypeStateChange fires on session state transitions. EventTypeStateChange )
type InteractiveToolHandler ¶
type InteractiveToolHandler interface {
// HandleAskUserQuestion is called when Claude asks the user questions.
// Returns a map of question text -> user's answer.
// Return error to deny the tool.
HandleAskUserQuestion(ctx context.Context, questions []Question) (map[string]string, error)
// HandleExitPlanMode is called when Claude finishes planning and awaits approval.
// Returns feedback to send back to Claude (approval message or refinement request).
// Return error to deny the tool.
HandleExitPlanMode(ctx context.Context, plan PlanInfo) (string, error)
}
InteractiveToolHandler handles tools that require user interaction. These tools are semantically different from permission-controlled tools - they need user input, not safety approval.
type MCPConfig ¶
type MCPConfig struct {
MCPServers map[string]MCPServerConfig `json:"mcpServers"`
// contains filtered or unexported fields
}
MCPConfig holds the MCP server configuration for a session. The keys are server names, values are server configurations.
func (*MCPConfig) AddHTTPServer ¶
AddHTTPServer adds an HTTP-based MCP server.
func (*MCPConfig) AddSDKServer ¶
func (c *MCPConfig) AddSDKServer(name string, handler SDKToolHandler) *MCPConfig
AddSDKServer adds an SDK-based MCP server whose tool calls are handled in-process via the stdin/stdout control protocol.
The name is used both as the MCPServers map key and in the MCPSDKServerConfig.Name field. The Name field is REQUIRED in the JSON config sent to the CLI — without it, the CLI silently hangs. See MCPSDKServerConfig for details.
func (*MCPConfig) AddSSEServer ¶
AddSSEServer adds an SSE-based MCP server.
func (*MCPConfig) AddStdioServer ¶
AddStdioServer adds a stdio-based MCP server.
func (MCPConfig) MarshalJSON ¶
MarshalJSON implements json.Marshaler for MCPConfig.
func (*MCPConfig) SDKHandlers ¶
func (c *MCPConfig) SDKHandlers() map[string]SDKToolHandler
SDKHandlers returns the registered SDK tool handlers.
type MCPHTTPServerConfig ¶
type MCPHTTPServerConfig struct {
Headers map[string]string `json:"headers,omitempty"`
Type MCPServerType `json:"type"`
URL string `json:"url"`
}
MCPHTTPServerConfig configures an HTTP-based MCP server.
type MCPSDKServerConfig ¶
type MCPSDKServerConfig struct {
Type MCPServerType `json:"type"`
Name string `json:"name"`
}
MCPSDKServerConfig is the MCP server config for SDK (type: "sdk") servers. The CLI routes MCP traffic through the existing stdin/stdout control protocol.
CRITICAL: Both Type and Name fields are required. Without the Name field, the Claude CLI silently hangs — it starts but never produces stdout output and never progresses past internal agent configuration. The JSON must be:
{"type": "sdk", "name": "server-name"}
This was discovered by comparing the working Python SDK's CLI invocation (which always includes "name") against a Go SDK that initially omitted it.
func (MCPSDKServerConfig) MarshalJSON ¶
func (c MCPSDKServerConfig) MarshalJSON() ([]byte, error)
MarshalJSON implements json.Marshaler.
type MCPSSEServerConfig ¶
type MCPSSEServerConfig struct {
Headers map[string]string `json:"headers,omitempty"`
Type MCPServerType `json:"type"`
URL string `json:"url"`
}
MCPSSEServerConfig configures an SSE-based MCP server.
type MCPServerConfig ¶
type MCPServerConfig interface {
// contains filtered or unexported methods
}
MCPServerConfig is the base interface for MCP server configurations.
type MCPServerType ¶
type MCPServerType string
MCPServerType identifies the MCP server transport type.
const ( // MCPServerTypeStdio uses stdio transport (command + args). MCPServerTypeStdio MCPServerType = "stdio" // MCPServerTypeHTTP uses HTTP transport. MCPServerTypeHTTP MCPServerType = "http" // MCPServerTypeSSE uses Server-Sent Events transport. MCPServerTypeSSE MCPServerType = "sse" // MCPServerTypeSDK uses the stdin/stdout control protocol for MCP traffic. MCPServerTypeSDK MCPServerType = "sdk" )
type MCPStdioServerConfig ¶
type MCPStdioServerConfig struct {
Env map[string]string `json:"env,omitempty"`
Type MCPServerType `json:"type,omitempty"`
Command string `json:"command"`
Args []string `json:"args,omitempty"`
}
MCPStdioServerConfig configures a stdio-based MCP server.
func (MCPStdioServerConfig) MarshalJSON ¶
func (c MCPStdioServerConfig) MarshalJSON() ([]byte, error)
MarshalJSON implements json.Marshaler.
type PermissionBehavior ¶
type PermissionBehavior string
PermissionBehavior is the behavior for a permission response.
const ( // PermissionAllow allows tool execution. PermissionAllow PermissionBehavior = "allow" // PermissionDeny denies tool execution. PermissionDeny PermissionBehavior = "deny" )
type PermissionHandler ¶
type PermissionHandler interface {
HandlePermission(ctx context.Context, req *PermissionRequest) (*PermissionResponse, error)
}
PermissionHandler handles permission requests.
func AllowAllPermissionHandler ¶
func AllowAllPermissionHandler() PermissionHandler
AllowAllPermissionHandler returns a handler that allows all permissions.
func DefaultPermissionHandler ¶
func DefaultPermissionHandler() PermissionHandler
DefaultPermissionHandler returns a handler that denies all permissions.
type PermissionHandlerFunc ¶
type PermissionHandlerFunc func(ctx context.Context, req *PermissionRequest) (*PermissionResponse, error)
PermissionHandlerFunc is a function that implements PermissionHandler.
func (PermissionHandlerFunc) HandlePermission ¶
func (f PermissionHandlerFunc) HandlePermission(ctx context.Context, req *PermissionRequest) (*PermissionResponse, error)
HandlePermission implements PermissionHandler.
type PermissionMode ¶
type PermissionMode string
PermissionMode controls tool execution approval.
const ( // PermissionModeDefault prompts the user for each dangerous operation. PermissionModeDefault PermissionMode = "default" // PermissionModeAcceptEdits auto-approves file modifications. PermissionModeAcceptEdits PermissionMode = "acceptEdits" // PermissionModePlan reviews plan before execution. PermissionModePlan PermissionMode = "plan" // PermissionModeBypass auto-approves all tools (use with caution). PermissionModeBypass PermissionMode = "bypassPermissions" )
type PermissionRequest ¶
type PermissionRequest struct {
Input map[string]interface{}
BlockedPath *string
RequestID string
ToolName string
}
PermissionRequest contains the data for a permission request.
type PermissionResponse ¶
type PermissionResponse struct {
UpdatedInput map[string]interface{}
Behavior PermissionBehavior
Message string
UpdatedPermissions []protocol.PermissionUpdate
Interrupt bool
}
PermissionResponse contains the response to a permission request.
Wire format notes (per Python SDK behavior):
- UpdatedInput: If nil, the permissionManager will use the original input from the request as fallback. The wire format requires updatedInput to be an object, NEVER null. Handlers that want to use the original input unchanged can leave this nil - the manager handles the fallback.
- UpdatedPermissions: Can be nil (will be omitted from wire format). Only set this when you want to add permission rules.
type PlanInfo ¶
type PlanInfo struct {
Plan string // The plan content (read from plan file)
AllowedPrompts []AllowedPrompt // Permissions requested for implementation
}
PlanInfo contains the plan details from ExitPlanMode.
func ParsePlanInfoFromInput ¶
ParsePlanInfoFromInput extracts PlanInfo from raw tool input.
type ProcessError ¶
ProcessError represents a process-level error.
func (*ProcessError) Error ¶
func (e *ProcessError) Error() string
func (*ProcessError) Unwrap ¶
func (e *ProcessError) Unwrap() error
type ProtocolError ¶
ProtocolError represents a protocol-level error.
func (*ProtocolError) Error ¶
func (e *ProtocolError) Error() string
func (*ProtocolError) Unwrap ¶
func (e *ProtocolError) Unwrap() error
type QueryResult ¶
type QueryResult struct {
SessionID string
TurnResult
}
QueryResult extends TurnResult with session metadata.
func Query ¶
func Query(ctx context.Context, prompt string, opts ...SessionOption) (*QueryResult, error)
Query sends a one-shot prompt and returns the result. Defaults to PermissionModeBypass if no permission mode is specified.
type Question ¶
type Question struct {
Text string // The question text
Options []QuestionOption // Available options (may be empty for free-form)
MultiSelect bool // Whether multiple options can be selected
}
Question represents a question from AskUserQuestion tool.
func ParseQuestionsFromInput ¶
ParseQuestionsFromInput extracts Question structs from raw tool input.
type QuestionOption ¶
type QuestionOption struct {
Label string // Option label (what gets selected)
}
QuestionOption represents an option for a question.
type ReadyEvent ¶
type ReadyEvent struct {
Info SessionInfo
}
ReadyEvent fires when the session is initialized.
type RecordedMessage ¶
type RecordedMessage struct {
Timestamp time.Time `json:"timestamp"`
Message interface{} `json:"message"`
Direction string `json:"direction"`
}
RecordedMessage is the container format for recorded messages. Each message is wrapped with a timestamp and direction indicator.
func LoadMessages ¶
func LoadMessages(dirPath string) ([]RecordedMessage, error)
LoadMessages loads recorded messages from a session directory. Returns all messages in chronological order with timestamps and direction.
func (RecordedMessage) MarshalJSON ¶
func (r RecordedMessage) MarshalJSON() ([]byte, error)
MarshalJSON implements custom JSON marshaling with millisecond timestamp precision.
func (*RecordedMessage) UnmarshalJSON ¶
func (r *RecordedMessage) UnmarshalJSON(data []byte) error
UnmarshalJSON implements custom JSON unmarshaling for timestamps.
type RecordingMetadata ¶
type RecordingMetadata struct {
SessionID string `json:"session_id"`
Model string `json:"model"`
WorkDir string `json:"cwd"`
ClaudeCodeVersion string `json:"claude_code_version,omitempty"`
PermissionMode string `json:"permission_mode"`
StartTime string `json:"start_time"`
Tools []string `json:"tools"`
TotalTurns int `json:"total_turns"`
}
RecordingMetadata contains metadata about a recording.
type SDKToolHandler ¶
type SDKToolHandler interface {
// Tools returns the tool definitions exposed by this handler.
Tools() []protocol.MCPToolDefinition
// HandleToolCall handles a tool invocation and returns the result.
HandleToolCall(ctx context.Context, name string, args json.RawMessage) (*protocol.MCPToolCallResult, error)
}
SDKToolHandler is the interface for handling MCP tool calls routed through the CLI's stdin/stdout control protocol (SDK MCP servers).
When a session has SDK tools registered, the Claude CLI sends MCP JSON-RPC requests (initialize, tools/list, tools/call) as control_request messages over stdin/stdout. The session dispatches these to the appropriate handler.
See SDK_PROTOCOL.md for the full protocol flow and gotchas.
type Session ¶
type Session struct {
// contains filtered or unexported fields
}
Session manages interaction with the Claude CLI.
func NewSession ¶
func NewSession(opts ...SessionOption) *Session
NewSession creates a new Claude session with options.
func (*Session) AskWithTimeout ¶
AskWithTimeout is a convenience wrapper with timeout context.
func (*Session) CLIArgs ¶
CLIArgs returns the CLI arguments that will be (or were) used to spawn the CLI. This can be called before or after Start() to see the exact flags being used.
func (*Session) CollectResponse ¶
CollectResponse loops on Events() until a TurnCompleteEvent, returning the accumulated TurnResult and all events received during the turn.
func (*Session) CurrentTurnNumber ¶
CurrentTurnNumber returns the current turn number.
func (*Session) Info ¶
func (s *Session) Info() *SessionInfo
Info returns session information (available after Ready event).
func (*Session) Recording ¶
func (s *Session) Recording() *SessionRecording
Recording returns the session recording (if enabled).
func (*Session) RecordingPath ¶
RecordingPath returns the path to recordings (if enabled).
func (*Session) SendMessage ¶
SendMessage sends a user message and starts a new turn. Returns the turn number.
func (*Session) SendToolResult ¶
SendToolResult sends a tool result for a specific tool use. This is used when the SDK handles a tool locally (like AskUserQuestion). The content is sent as a tool_result content block with the given tool_use_id.
func (*Session) SetModel ¶
SetModel sends a set_model control request to switch the model mid-session.
func (*Session) SetPermissionMode ¶
func (s *Session) SetPermissionMode(ctx context.Context, mode PermissionMode) error
SetPermissionMode changes the permission mode dynamically.
func (*Session) State ¶
func (s *Session) State() SessionState
State returns the current session state.
func (*Session) WaitForTurn ¶
func (s *Session) WaitForTurn(ctx context.Context) (*TurnResult, error)
WaitForTurn blocks until the current turn completes. If no turn is in progress, it returns immediately with nil.
type SessionConfig ¶
type SessionConfig struct {
PermissionHandler PermissionHandler
InteractiveToolHandler InteractiveToolHandler
MCPConfig *MCPConfig
StderrHandler func([]byte)
Env map[string]string
PermissionMode PermissionMode
Model string
WorkDir string
CLIPath string
SystemPrompt string
Resume string
RecordingDir string
AllowedTools []string
DisallowedTools []string
Betas []string
Agents []AgentDefinition
ExtraArgs []string
MaxTurns int
MaxBudgetUSD float64
EventBufferSize int
DisablePlugins bool
RecordMessages bool
DangerouslySkipPermissions bool
PermissionPromptToolStdio bool
}
SessionConfig holds session configuration.
type SessionInfo ¶
type SessionInfo struct {
SessionID string
Model string
WorkDir string
PermissionMode PermissionMode
Tools []string
}
SessionInfo contains session metadata.
type SessionOption ¶
type SessionOption func(*SessionConfig)
SessionOption is a functional option for configuring a Session.
func WithAgents ¶
func WithAgents(agents ...AgentDefinition) SessionOption
WithAgents sets the agent definitions for sub-agents.
func WithAllowedTools ¶
func WithAllowedTools(tools ...string) SessionOption
WithAllowedTools sets the list of tools that Claude is allowed to use.
func WithCLIPath ¶
func WithCLIPath(path string) SessionOption
WithCLIPath sets a custom CLI binary path.
func WithDangerouslySkipPermissions ¶
func WithDangerouslySkipPermissions() SessionOption
WithDangerouslySkipPermissions skips all permission prompts. This is typically used with PermissionModePlan to enable plan mode without prompts.
func WithDisablePlugins ¶
func WithDisablePlugins() SessionOption
WithDisablePlugins disables CLI plugins.
func WithDisallowedTools ¶
func WithDisallowedTools(tools ...string) SessionOption
WithDisallowedTools sets the list of tools that Claude is not allowed to use.
func WithEnv ¶
func WithEnv(env map[string]string) SessionOption
WithEnv sets additional environment variables for the CLI process.
func WithEventBufferSize ¶
func WithEventBufferSize(size int) SessionOption
WithEventBufferSize sets the event channel buffer size.
func WithExtraArgs ¶
func WithExtraArgs(args ...string) SessionOption
WithExtraArgs sets additional CLI arguments (escape hatch).
func WithInteractiveToolHandler ¶
func WithInteractiveToolHandler(handler InteractiveToolHandler) SessionOption
WithInteractiveToolHandler sets a handler for interactive tools (AskUserQuestion, ExitPlanMode). These tools require user input, not permission approval, so they bypass the permission handler.
func WithMCPConfig ¶
func WithMCPConfig(cfg *MCPConfig) SessionOption
WithMCPConfig sets the MCP server configuration for custom tools.
func WithMaxBudgetUSD ¶
func WithMaxBudgetUSD(budget float64) SessionOption
WithMaxBudgetUSD sets the SDK-enforced budget limit in USD.
func WithMaxTurns ¶
func WithMaxTurns(n int) SessionOption
WithMaxTurns sets the SDK-enforced turn limit.
func WithPermissionHandler ¶
func WithPermissionHandler(h PermissionHandler) SessionOption
WithPermissionHandler sets a custom permission handler.
func WithPermissionMode ¶
func WithPermissionMode(mode PermissionMode) SessionOption
WithPermissionMode sets the permission mode.
func WithPermissionPromptToolStdio ¶
func WithPermissionPromptToolStdio() SessionOption
WithPermissionPromptToolStdio enables stdio-based permission prompts. This causes all tool permissions to be sent as can_use_tool control requests instead of being handled by the CLI's interactive UI. Use this with WithPermissionHandler to implement programmatic permission control.
func WithRecording ¶
func WithRecording(dir string) SessionOption
WithRecording enables session recording.
func WithResume ¶
func WithResume(sessionID string) SessionOption
WithResume sets a session ID to resume instead of starting a new session. When resuming, the CLI will load the previous conversation context.
func WithSDKTools ¶
func WithSDKTools(serverName string, handler SDKToolHandler) SessionOption
WithSDKTools is a convenience option that configures an SDK MCP server. If the session already has an MCPConfig, the SDK server is added to it; otherwise a new MCPConfig is created.
func WithStderrHandler ¶
func WithStderrHandler(h func([]byte)) SessionOption
WithStderrHandler sets a handler for CLI stderr output.
func WithSystemPrompt ¶
func WithSystemPrompt(prompt string) SessionOption
WithSystemPrompt sets a custom system prompt.
func WithWorkDir ¶
func WithWorkDir(dir string) SessionOption
WithWorkDir sets the working directory.
type SessionRecording ¶
type SessionRecording struct {
Turns []TurnSummary `json:"turns"`
Metadata RecordingMetadata `json:"metadata"`
}
SessionRecording contains a complete recording.
func LoadRecording ¶
func LoadRecording(dirPath string) (*SessionRecording, error)
LoadRecording loads a recording from disk.
func (*SessionRecording) TotalCost ¶
func (r *SessionRecording) TotalCost() float64
TotalCost returns the total cost of all turns.
type SessionState ¶
type SessionState int
SessionState represents the current state of a session.
const ( // StateUninitialized is the initial state before Start() is called. StateUninitialized SessionState = iota // StateStarting is the state while the CLI process is starting. StateStarting // StateReady is the state when the session is ready to receive messages. StateReady // StateProcessing is the state while processing a user message. StateProcessing // StateClosed is the final state after Stop() is called. StateClosed )
func (SessionState) String ¶
func (s SessionState) String() string
String returns a string representation of the state.
type StateChangeEvent ¶
type StateChangeEvent struct {
From SessionState
To SessionState
}
StateChangeEvent fires on session state transitions.
func (StateChangeEvent) Type ¶
func (e StateChangeEvent) Type() EventType
Type returns the event type.
type StateTransition ¶
type StateTransition int
StateTransition represents a state transition event.
const ( // TransitionStarted transitions from Uninitialized to Starting. TransitionStarted StateTransition = iota // TransitionInitReceived transitions from Starting to Ready. TransitionInitReceived // TransitionUserMessageSent transitions from Ready to Processing. TransitionUserMessageSent // TransitionResultReceived transitions from Processing to Ready. TransitionResultReceived // TransitionClosed transitions any state to Closed. TransitionClosed )
type TextEvent ¶
TextEvent contains streaming text chunks.
func (TextEvent) StreamDelta ¶
func (TextEvent) StreamEventKind ¶
func (e TextEvent) StreamEventKind() agentstream.EventKind
type ThinkingEvent ¶
ThinkingEvent contains thinking chunks.
func (ThinkingEvent) StreamDelta ¶
func (e ThinkingEvent) StreamDelta() string
func (ThinkingEvent) StreamEventKind ¶
func (e ThinkingEvent) StreamEventKind() agentstream.EventKind
type ToolCompleteEvent ¶
type ToolCompleteEvent struct {
Timestamp time.Time
Input map[string]interface{}
ID string
Name string
TurnNumber int
}
ToolCompleteEvent fires when tool input is fully parsed.
func (ToolCompleteEvent) StreamEventKind ¶
func (e ToolCompleteEvent) StreamEventKind() agentstream.EventKind
func (ToolCompleteEvent) StreamToolCallID ¶
func (e ToolCompleteEvent) StreamToolCallID() string
func (ToolCompleteEvent) StreamToolInput ¶
func (e ToolCompleteEvent) StreamToolInput() map[string]interface{}
func (ToolCompleteEvent) StreamToolIsError ¶
func (e ToolCompleteEvent) StreamToolIsError() bool
func (ToolCompleteEvent) StreamToolName ¶
func (e ToolCompleteEvent) StreamToolName() string
func (ToolCompleteEvent) StreamToolResult ¶
func (e ToolCompleteEvent) StreamToolResult() interface{}
func (ToolCompleteEvent) Type ¶
func (e ToolCompleteEvent) Type() EventType
Type returns the event type.
type ToolProgressEvent ¶
type ToolProgressEvent struct {
ID string
Name string
PartialInput string
InputChunk string
TurnNumber int
}
ToolProgressEvent contains partial tool input.
func (ToolProgressEvent) Type ¶
func (e ToolProgressEvent) Type() EventType
Type returns the event type.
type ToolStartEvent ¶
ToolStartEvent fires when a tool begins execution.
func (ToolStartEvent) StreamEventKind ¶
func (e ToolStartEvent) StreamEventKind() agentstream.EventKind
func (ToolStartEvent) StreamToolCallID ¶
func (e ToolStartEvent) StreamToolCallID() string
func (ToolStartEvent) StreamToolInput ¶
func (e ToolStartEvent) StreamToolInput() map[string]interface{}
func (ToolStartEvent) StreamToolName ¶
func (e ToolStartEvent) StreamToolName() string
type TurnCompleteEvent ¶
type TurnCompleteEvent struct {
Error error
Usage TurnUsage
TurnNumber int
DurationMs int64
Success bool
}
TurnCompleteEvent fires when a turn finishes.
func (TurnCompleteEvent) StreamCost ¶
func (e TurnCompleteEvent) StreamCost() float64
func (TurnCompleteEvent) StreamDuration ¶
func (e TurnCompleteEvent) StreamDuration() int64
func (TurnCompleteEvent) StreamEventKind ¶
func (e TurnCompleteEvent) StreamEventKind() agentstream.EventKind
func (TurnCompleteEvent) StreamIsSuccess ¶
func (e TurnCompleteEvent) StreamIsSuccess() bool
func (TurnCompleteEvent) StreamTurnNum ¶
func (e TurnCompleteEvent) StreamTurnNum() int
func (TurnCompleteEvent) Type ¶
func (e TurnCompleteEvent) Type() EventType
Type returns the event type.
type TurnResult ¶
type TurnResult struct {
Error error
Text string
Thinking string
ContentBlocks []ContentBlock
Usage TurnUsage
TurnNumber int
DurationMs int64
Success bool
}
TurnResult contains the result of a completed turn.
type TurnSummary ¶
type TurnSummary struct {
StartTime time.Time `json:"start_time"`
EndTime time.Time `json:"end_time,omitempty"`
UserMessage string `json:"user_message,omitempty"`
Number int `json:"number"`
DurationMs int64 `json:"duration_ms,omitempty"`
CostUSD float64 `json:"cost_usd,omitempty"`
Success bool `json:"success"`
}
TurnSummary contains a summary of a recorded turn.
type TypedToolRegistry ¶
type TypedToolRegistry struct {
// contains filtered or unexported fields
}
TypedToolRegistry implements SDKToolHandler using Go generics for type-safe tool registration. It automatically generates JSON schemas from struct tags and eliminates manual unmarshaling.
func AddTool ¶
func AddTool[T any]( registry *TypedToolRegistry, name, description string, handler func(context.Context, T) (string, error), ) *TypedToolRegistry
AddTool is a helper function that registers a type-safe tool handler using generics. It returns the modified registry for method chaining.
The generic type parameter T should be a struct with json and jsonschema struct tags.
Example:
type EchoParams struct {
Text string `json:"text" jsonschema:"required,description=Text to echo back"`
}
registry := NewTypedToolRegistry()
AddTool(registry, "echo", "Echo back the input text",
func(ctx context.Context, params EchoParams) (string, error) {
return fmt.Sprintf("Echo: %s", params.Text), nil
})
func NewTypedToolRegistry ¶
func NewTypedToolRegistry() *TypedToolRegistry
NewTypedToolRegistry creates a new empty TypedToolRegistry.
func (*TypedToolRegistry) HandleToolCall ¶
func (r *TypedToolRegistry) HandleToolCall( ctx context.Context, name string, args json.RawMessage, ) (*protocol.MCPToolCallResult, error)
HandleToolCall implements SDKToolHandler interface.
func (*TypedToolRegistry) Tools ¶
func (r *TypedToolRegistry) Tools() []protocol.MCPToolDefinition
Tools implements SDKToolHandler interface.