Documentation
¶
Overview ¶
Logging ¶
For detailed operation tracking, use WithLogger:
logger := slog.New(slog.NewTextHandler(os.Stderr, &slog.HandlerOptions{Level: slog.LevelDebug}))
for msg, err := range claudesdk.Query(ctx, claudesdk.Text("Hello Claude"),
claudesdk.WithLogger(logger),
) {
_ = msg
_ = err
}
Error Handling ¶
The SDK provides typed errors for different failure scenarios:
for _, err := range claudesdk.Query(ctx, claudesdk.Text(prompt), claudesdk.WithPermissionMode(string(claudesdk.PermissionModeDontAsk))) {
if err != nil {
if cliErr, ok := errors.AsType[*claudesdk.CLINotFoundError](err); ok {
log.Fatalf("Claude CLI not installed, searched: %v", cliErr.SearchedPaths)
}
if procErr, ok := errors.AsType[*claudesdk.ProcessError](err); ok {
log.Fatalf("CLI process failed with exit code %d: %s", procErr.ExitCode, procErr.Stderr)
}
log.Fatal(err)
}
}
Requirements ¶
This SDK requires the Claude CLI to be installed and available in your system PATH. You can specify a custom CLI path using the WithCliPath option.
Index ¶
- Constants
- Variables
- func DecodeStructuredOutput[T any](result *ResultMessage) (T, error)
- func DeleteSession(sessionID string, options DeleteSessionOptions) error
- func DeleteSessionCost(sessionID string, options SessionCostOptions) error
- func EffectiveModelContextWindow(modelID string) (int, bool)
- func ErrorResult(message string) *mcp.CallToolResult
- func ExtractNestedModelUsage(event RawStreamEvent) map[string]ModelUsage
- func ImageResult(data []byte, mimeType string) *mcp.CallToolResult
- func MessagesFromChannel(ch <-chan StreamingMessage) iter.Seq[StreamingMessage]
- func MessagesFromContent(content UserMessageContent) iter.Seq[StreamingMessage]
- func MessagesFromSlice(msgs []StreamingMessage) iter.Seq[StreamingMessage]
- func ModelCapabilities(modelID string) []string
- func ModelHasOneMillionContextSuffix(modelID string) bool
- func NewMcpTool(name, description string, inputSchema *jsonschema.Schema) *mcp.Tool
- func NopLogger() *slog.Logger
- func ParseArguments(req *mcp.CallToolRequest) (map[string]any, error)
- func Query(ctx context.Context, content UserMessageContent, opts ...Option) iter.Seq2[Message, error]
- func QueryStream(ctx context.Context, messages iter.Seq[StreamingMessage], opts ...Option) iter.Seq2[Message, error]
- func RenameSession(sessionID, title string, options RenameSessionOptions) error
- func ResilientQuery(ctx context.Context, content UserMessageContent, ...) iter.Seq2[Message, error]
- func SaveSessionCost(sessionID string, snapshot CostSnapshot, options SessionCostOptions) error
- func SimpleSchema(props map[string]string) *jsonschema.Schema
- func SingleMessage(content UserMessageContent) iter.Seq[StreamingMessage]
- func TagSession(sessionID string, tag *string, options TagSessionOptions) error
- func TextResult(text string) *mcp.CallToolResult
- func WithClient(ctx context.Context, fn func(Client) error, opts ...Option) error
- type APIRetryMessage
- type AccountInfo
- type AgentDefinition
- type AgentEffort
- type AgentInfo
- type AgentMCPServerSpec
- type AppliedSettings
- type AssistantMessage
- type AssistantMessageError
- type AsyncHookJSONOutput
- type AuditEnvelope
- type AuthStatusMessage
- type AutoCompactAction
- type AutoCompactFailureCircuitBreaker
- type AutoCompactObservation
- type AutoCompactOrchestrator
- type AutoCompactOrchestratorOptions
- type AvailableModelInfo
- type Base64Source
- type BaseHookInput
- type BudgetProgressAction
- type BudgetProgressStatus
- type BudgetSnapshot
- type BudgetTracker
- type BudgetTrackerOptions
- type CLIConnectionError
- type CLIJSONDecodeError
- type CLINotFoundError
- type CallToolRequest
- type CallToolResult
- type CancelAsyncMessageResult
- type ClaudeAgentOptions
- type ClaudeSDKError
- type Client
- type CompactBoundaryMessage
- type CompactMetadata
- type CompactPreservedSegment
- type CompactionSnapshot
- type CompactionTracker
- type ConfigChangeHookInput
- type ConnectorTextBlock
- type ContentBlock
- type ContextAPIUsage
- type ContextAgent
- type ContextAttachmentBreakdown
- type ContextCategory
- type ContextDeferredBuiltinTool
- type ContextGridSquare
- type ContextMCPTool
- type ContextMemoryFile
- type ContextMessageBreakdown
- type ContextPressurePolicy
- type ContextPressureStatus
- type ContextPressureTier
- type ContextPromptSection
- type ContextSkillFrontmatter
- type ContextSkills
- type ContextSlashCommands
- type ContextSystemTool
- type ContextThresholdStatus
- type ContextThresholdWatcher
- type ContextToolCallBreakdown
- type ContextUsage
- type CostSnapshot
- type CostTracker
- func (t *CostTracker) CostSummary() turncomplete.CostSummary
- func (t *CostTracker) LoadSessionCost(sessionID, claudeHome string) error
- func (t *CostTracker) Observe(msg Message)
- func (t *CostTracker) ObserveResult(result *ResultMessage)
- func (t *CostTracker) SaveSessionCost(sessionID, claudeHome string) error
- func (t *CostTracker) Snapshot() CostSnapshot
- type CwdChangedHookInput
- type CwdChangedHookSpecificOutput
- type DeleteSessionOptions
- type Effort
- type ElicitationAction
- type ElicitationCallback
- type ElicitationCompleteCallback
- type ElicitationCompleteMessage
- type ElicitationHookInput
- type ElicitationHookSpecificOutput
- type ElicitationMode
- type ElicitationRequest
- type ElicitationResponse
- type ElicitationResultHookInput
- type ElicitationResultHookSpecificOutput
- type ErrorClass
- type ErrorClassification
- type ErrorSubClass
- type FastModeSnapshot
- type FastModeState
- type FastModeTracker
- type FastModeTransitionReason
- type FileChangedHookInput
- type FileChangedHookSpecificOutput
- type FilesPersistedFailure
- type FilesPersistedFile
- type FilesPersistedMessage
- type ForkSessionOptions
- type ForkSessionResult
- type GetSessionInfoOptions
- type HookCallback
- type HookContext
- type HookEvent
- type HookInput
- type HookJSONOutput
- type HookMatcher
- type HookProgressMessage
- type HookResponseMessage
- type HookResponseOutcome
- type HookSpecificOutput
- type HookStartedMessage
- type InitMCPServerStatus
- type InitMessage
- type InitPluginInfo
- type InputDocumentBlock
- type InputImageBlock
- type InstructionsLoadedHookInput
- type InterruptToolResultPolicy
- type LocalCommandOutputMessage
- type MCPHTTPServerConfig
- type MCPSSEServerConfig
- type MCPSdkServerConfig
- type MCPServerConfig
- type MCPServerConnectionStatus
- type MCPServerInfo
- type MCPServerStatus
- type MCPServerStatusConfig
- type MCPServerType
- type MCPSetServersResult
- type MCPStatus
- type MCPStdioServerConfig
- type MCPToolAnnotations
- type MCPToolInfo
- type MCPWebSocketServerConfig
- type McpAudioContent
- type McpContent
- type McpImageContent
- type McpTextContent
- type McpTool
- type McpToolAnnotations
- type McpToolHandler
- type Message
- type MessageParseError
- type MessageStream
- type Model
- type ModelCapability
- type ModelCostTier
- type ModelInfo
- type ModelListResponse
- type ModelUsage
- type NotificationHookInput
- type NotificationHookSpecificOutput
- type Option
- func WithAddDirs(dirs ...string) Option
- func WithAgentProgressSummaries(enable bool) Option
- func WithAgents(agents map[string]*AgentDefinition) Option
- func WithAllowedTools(tools ...string) Option
- func WithAutoCompactPercentageOverride(percentage int) Option
- func WithBetas(betas ...SdkBeta) Option
- func WithBlockingLimitOverride(limit int) Option
- func WithCanUseTool(callback ToolPermissionCallback) Option
- func WithClaudeHome(path string) Option
- func WithCliPath(path string) Option
- func WithContinueConversation(cont bool) Option
- func WithCostTracker(tracker *CostTracker) Option
- func WithCwd(cwd string) Option
- func WithDisableAutoCompact(disable bool) Option
- func WithDisableCompact(disable bool) Option
- func WithDisallowedTools(tools ...string) Option
- func WithEffort(effort config.Effort) Option
- func WithEnableFileCheckpointing(enable bool) Option
- func WithEnv(env map[string]string) Option
- func WithExtraArgs(args map[string]*string) Option
- func WithFallbackModel(model string) Option
- func WithFastMode(enabled bool) Option
- func WithFastModeTracker(tracker *FastModeTracker) Option
- func WithForkSession(fork bool) Option
- func WithHooks(hooks map[HookEvent][]*HookMatcher) Option
- func WithIncludePartialMessages(include bool) Option
- func WithInitializeTimeout(timeout time.Duration) Option
- func WithInterruptToolResultPolicy(policy InterruptToolResultPolicy) Option
- func WithLogger(logger *slog.Logger) Option
- func WithMCPConfig(config string) Option
- func WithMCPServers(servers map[string]MCPServerConfig) Option
- func WithMaxBudgetUSD(budget float64) Option
- func WithMaxBufferSize(size int) Option
- func WithMaxToolUseConcurrency(limit int) Option
- func WithMaxTurns(maxTurns int) Option
- func WithModel(model string) Option
- func WithOnElicitation(callback ElicitationCallback) Option
- func WithOnElicitationComplete(callback ElicitationCompleteCallback) Option
- func WithOnPrompt(callback PromptCallback) Option
- func WithOnTurnComplete(callback TurnCompleteCallback) Option
- func WithOnUserInput(callback UserInputCallback) Option
- func WithOutputFormat(format map[string]any) Option
- func WithPermissionMode(mode string) Option
- func WithPermissionPromptToolName(name string) Option
- func WithPersistPermissions(path string) Option
- func WithPlugins(plugins ...*SdkPluginConfig) Option
- func WithPromptSuggestions(enable bool) Option
- func WithResume(sessionID string) Option
- func WithSDKTools(tools ...Tool) Option
- func WithSandboxSettings(settings *SandboxSettings) Option
- func WithSettingSources(sources ...SettingSource) Option
- func WithSettings(path string) Option
- func WithStderr(handler func(string)) Option
- func WithSystemPrompt(prompt string) Option
- func WithSystemPromptFile(path string) Option
- func WithSystemPromptPreset(preset *SystemPromptPreset) Option
- func WithTaskBudget(total int) Option
- func WithThinking(thinking config.ThinkingConfig) Option
- func WithTools(tools config.ToolsConfig) Option
- func WithTransport(transport config.Transport) Option
- func WithUnattendedRetry(enabled bool) Option
- func WithUser(user string) Option
- type PermissionBehavior
- type PermissionDecisionClassification
- type PermissionDecisionReasonType
- type PermissionDenial
- type PermissionDeniedHookInput
- type PermissionDeniedHookSpecificOutput
- type PermissionMode
- type PermissionRequestHookInput
- type PermissionRequestHookSpecificOutput
- type PermissionResult
- type PermissionResultAllow
- type PermissionResultDeny
- type PermissionRuleValue
- type PermissionUpdate
- type PermissionUpdateDestination
- type PermissionUpdateType
- type PluginInfo
- type PostCompactHookInput
- type PostToolUseFailureHookInput
- type PostToolUseFailureHookSpecificOutput
- type PostToolUseHookInput
- type PostToolUseHookSpecificOutput
- type PostTurnSummaryMessage
- type PreCompactHookInput
- type PreToolUseHookInput
- type PreToolUseHookSpecificOutput
- type PreservedSegmentIndex
- type PreservedSegmentRecord
- type ProcessError
- type PromptCallback
- type PromptRequest
- type PromptRequestOption
- type PromptResponse
- type PromptSuggestionMessage
- type PromptTooLongDetails
- type RateLimitEvent
- type RateLimitInfo
- type RateLimitOverageDisabledReason
- type RateLimitStatus
- type RateLimitType
- type RawStreamEvent
- type ReasoningEffortOption
- type RecoveryAction
- type RecoveryOrchestrator
- type RecoveryOrchestratorOptions
- type RecoveryPlan
- type ReloadPluginsResult
- type RenameSessionOptions
- type ResultMessage
- type ResultSubtype
- type RetryClass
- type RetryDecision
- type RetryDecisionAction
- type RetryPolicy
- type RewindFilesResult
- type SDKSessionInfo
- type SandboxIgnoreViolations
- type SandboxNetworkConfig
- type SandboxSettings
- type Schema
- type SdkBeta
- type SdkMcpServerInstance
- type SdkMcpTool
- type SdkMcpToolHandler
- type SdkMcpToolOption
- type SdkPluginConfig
- type ServerInfo
- type SessionCostOptions
- type SessionDiscovery
- type SessionEndHookInput
- type SessionListOptions
- type SessionMessage
- type SessionMessagesOptions
- type SessionStartHookInput
- type SessionStartHookSpecificOutput
- type SessionStat
- type SessionState
- type SessionStateChangedMessage
- type SettingSource
- type SettingsSnapshot
- type SettingsSourceSnapshot
- type SetupHookInput
- type SetupHookSpecificOutput
- type SlashCommand
- type StatusMessage
- type StatusState
- type StopFailureHookInput
- type StopHookInput
- type StreamEvent
- type StreamingMessage
- type StreamingMessageContent
- type StreamingMessagePriority
- type StreamlinedTextMessage
- type StreamlinedToolUseSummaryMessage
- type SubagentStartHookInput
- type SubagentStartHookSpecificOutput
- type SubagentStopHookInput
- type SyncHookJSONOutput
- type SystemMessage
- type SystemPromptPreset
- type TagSessionOptions
- type TaskCompletedHookInput
- type TaskCreatedHookInput
- type TaskLifecycleState
- type TaskLifecycleSummary
- type TaskLifecycleTracker
- func (t *TaskLifecycleTracker) ActiveTasks() []TaskSnapshot
- func (t *TaskLifecycleTracker) Observe(msg Message)
- func (t *TaskLifecycleTracker) Summary() TaskLifecycleSummary
- func (t *TaskLifecycleTracker) Task(taskID string) (TaskSnapshot, bool)
- func (t *TaskLifecycleTracker) Tasks() []TaskSnapshot
- func (t *TaskLifecycleTracker) TerminalTasks() []TaskSnapshot
- type TaskNotificationMessage
- type TaskNotificationStatus
- type TaskProgressMessage
- type TaskSnapshot
- type TaskStartedMessage
- type TaskType
- type TaskUsage
- type TeammateIdleHookInput
- type TextBlock
- type ThinkingBlock
- type ThinkingConfig
- type ThinkingConfigAdaptive
- type ThinkingConfigDisabled
- type ThinkingConfigEnabled
- type Tool
- type ToolCategory
- type ToolFunc
- type ToolInterruptBehavior
- type ToolMetadata
- type ToolPermissionCallback
- type ToolPermissionContext
- type ToolProgressMessage
- type ToolReferenceBlock
- type ToolResultBlock
- type ToolUseBlock
- type ToolUseSummaryMessage
- type ToolsConfig
- type ToolsList
- type ToolsPreset
- type Transport
- type TransportHealth
- type TurnCompleteCallback
- type TurnCompleteCostSummary
- type TurnCompleteInfo
- type UnknownBlock
- type UnknownHookInput
- type UnknownMessage
- type Usage
- type UserInputAnswer
- type UserInputCallback
- type UserInputQuestion
- type UserInputQuestionOption
- type UserInputRequest
- type UserInputResponse
- type UserMessage
- type UserMessageContent
- type UserPromptSubmitHookInput
- type UserPromptSubmitHookSpecificOutput
- type WorktreeCreateHookInput
- type WorktreeCreateHookSpecificOutput
- type WorktreeRemoveHookInput
Constants ¶
const ( // ModelCapVision indicates the model supports image/vision inputs. ModelCapVision = models.CapVision // ModelCapToolUse indicates the model supports tool/function calling. ModelCapToolUse = models.CapToolUse // ModelCapReasoning indicates the model supports extended reasoning. ModelCapReasoning = models.CapReasoning // ModelCapStructuredOutput indicates the model supports structured JSON output. ModelCapStructuredOutput = models.CapStructuredOutput )
Model capability constants.
const ( // ModelCostTierHigh represents opus-class pricing. ModelCostTierHigh = models.CostTierHigh // ModelCostTierMedium represents sonnet-class pricing. ModelCostTierMedium = models.CostTierMedium // ModelCostTierLow represents haiku-class pricing. ModelCostTierLow = models.CostTierLow )
Model cost tier constants.
const ( ToolCategorySearch = toolmeta.CategorySearch ToolCategoryRead = toolmeta.CategoryRead ToolCategoryWrite = toolmeta.CategoryWrite ToolCategoryCommand = toolmeta.CategoryCommand ToolCategoryOther = toolmeta.CategoryOther )
const ( ToolInterruptBehaviorCancel = toolmeta.InterruptBehaviorCancel ToolInterruptBehaviorBlock = toolmeta.InterruptBehaviorBlock )
const ( // SettingSourceUser loads from user-level settings. SettingSourceUser = config.SettingSourceUser // SettingSourceProject loads from project-level settings. SettingSourceProject = config.SettingSourceProject // SettingSourceLocal loads from local-level settings. SettingSourceLocal = config.SettingSourceLocal )
const ( // EffortLow uses minimal thinking. EffortLow = config.EffortLow // EffortMedium uses moderate thinking. EffortMedium = config.EffortMedium // EffortHigh uses deep thinking. EffortHigh = config.EffortHigh // EffortMax uses maximum thinking depth. EffortMax = config.EffortMax )
const ( // InterruptToolResultPolicyNone sends a plain interrupt and leaves pending // tool_use reconciliation to the host or resumed session. InterruptToolResultPolicyNone = config.InterruptToolResultPolicyNone // InterruptToolResultPolicySynthesizeErrorToolResults synthesizes error // tool_result blocks for unresolved tool_use IDs before interrupting. InterruptToolResultPolicySynthesizeErrorToolResults = config.InterruptToolResultPolicySynthesizeErrorToolResults )
const ( // AssistantMessageErrorAuthFailed indicates authentication failure. AssistantMessageErrorAuthFailed = message.AssistantMessageErrorAuthFailed // AssistantMessageErrorBilling indicates a billing error. AssistantMessageErrorBilling = message.AssistantMessageErrorBilling // AssistantMessageErrorRateLimit indicates rate limiting. AssistantMessageErrorRateLimit = message.AssistantMessageErrorRateLimit // AssistantMessageErrorInvalidReq indicates an invalid request. AssistantMessageErrorInvalidReq = message.AssistantMessageErrorInvalidReq // AssistantMessageErrorServer indicates a server error. AssistantMessageErrorServer = message.AssistantMessageErrorServer // AssistantMessageErrorMaxOutputTokens indicates max output token exhaustion. AssistantMessageErrorMaxOutputTokens = message.AssistantMessageErrorMaxOutputTokens // AssistantMessageErrorUnknown indicates an unknown error. AssistantMessageErrorUnknown = message.AssistantMessageErrorUnknown )
const ( // TaskNotificationStatusCompleted indicates the task finished successfully. TaskNotificationStatusCompleted = message.TaskNotificationStatusCompleted // TaskNotificationStatusFailed indicates the task failed. TaskNotificationStatusFailed = message.TaskNotificationStatusFailed // TaskNotificationStatusStopped indicates the task was stopped. TaskNotificationStatusStopped = message.TaskNotificationStatusStopped )
const ( TaskTypeLocalBash = message.TaskTypeLocalBash TaskTypeLocalAgent = message.TaskTypeLocalAgent TaskTypeRemoteAgent = message.TaskTypeRemoteAgent TaskTypeInProcessTeammate = message.TaskTypeInProcessTeammate TaskTypeLocalWorkflow = message.TaskTypeLocalWorkflow TaskTypeMonitorMCP = message.TaskTypeMonitorMCP TaskTypeDream = message.TaskTypeDream )
const ( // ResultSubtypeSuccess indicates normal completion. ResultSubtypeSuccess = message.ResultSubtypeSuccess // ResultSubtypeErrorDuringExecution indicates a runtime execution error. ResultSubtypeErrorDuringExecution = message.ResultSubtypeErrorDuringExecution // ResultSubtypeErrorMaxTurns indicates the max-turn budget was exhausted. ResultSubtypeErrorMaxTurns = message.ResultSubtypeErrorMaxTurns // ResultSubtypeErrorMaxBudgetUSD indicates the USD budget was exhausted. ResultSubtypeErrorMaxBudgetUSD = message.ResultSubtypeErrorMaxBudgetUSD // ResultSubtypeErrorMaxStructuredOutputRetries indicates structured output retries were exhausted. ResultSubtypeErrorMaxStructuredOutputRetries = message.ResultSubtypeErrorMaxStructuredOutputRetries )
const ( // HookResponseOutcomeSuccess indicates a hook completed successfully. HookResponseOutcomeSuccess = message.HookResponseOutcomeSuccess // HookResponseOutcomeError indicates a hook failed. HookResponseOutcomeError = message.HookResponseOutcomeError // HookResponseOutcomeCancelled indicates a hook was cancelled. HookResponseOutcomeCancelled = message.HookResponseOutcomeCancelled )
const ( // SessionStateIdle indicates the session is idle. SessionStateIdle = message.SessionStateIdle // SessionStateRunning indicates the session is running. SessionStateRunning = message.SessionStateRunning // SessionStateRequiresAction indicates the session requires action. SessionStateRequiresAction = message.SessionStateRequiresAction )
const ( // RateLimitStatusAllowed indicates the request is within rate limits. RateLimitStatusAllowed = message.RateLimitStatusAllowed // RateLimitStatusAllowedWarning indicates the request is allowed but approaching limits. RateLimitStatusAllowedWarning = message.RateLimitStatusAllowedWarning // RateLimitStatusRejected indicates the request was rejected due to rate limits. RateLimitStatusRejected = message.RateLimitStatusRejected )
const ( // RateLimitTypeFiveHour represents a 5-hour rate limit window. RateLimitTypeFiveHour = message.RateLimitTypeFiveHour // RateLimitTypeSevenDay represents a 7-day rate limit window. RateLimitTypeSevenDay = message.RateLimitTypeSevenDay // RateLimitTypeSevenDayOpus represents a 7-day rate limit for Opus models. RateLimitTypeSevenDayOpus = message.RateLimitTypeSevenDayOpus // RateLimitTypeSevenDaySonnet represents a 7-day rate limit for Sonnet models. RateLimitTypeSevenDaySonnet = message.RateLimitTypeSevenDaySonnet // RateLimitTypeOverage represents an overage rate limit. RateLimitTypeOverage = message.RateLimitTypeOverage )
const ( // RateLimitOverageDisabledReasonOverageNotProvisioned indicates overage was not provisioned. RateLimitOverageDisabledReasonOverageNotProvisioned = message.RateLimitOverageDisabledReasonOverageNotProvisioned // RateLimitOverageDisabledReasonOrgLevelDisabled indicates overage is disabled at the org level. RateLimitOverageDisabledReasonOrgLevelDisabled = message.RateLimitOverageDisabledReasonOrgLevelDisabled // RateLimitOverageDisabledReasonOrgLevelDisabledUntil indicates overage is temporarily disabled at the org level. RateLimitOverageDisabledReasonOrgLevelDisabledUntil = message.RateLimitOverageDisabledReasonOrgLevelDisabledUntil // RateLimitOverageDisabledReasonOutOfCredits indicates the account is out of credits. RateLimitOverageDisabledReasonOutOfCredits = message.RateLimitOverageDisabledReasonOutOfCredits // RateLimitOverageDisabledReasonSeatTierLevelDisabled indicates overage is disabled for the seat tier. RateLimitOverageDisabledReasonSeatTierLevelDisabled = message.RateLimitOverageDisabledReasonSeatTierLevelDisabled // RateLimitOverageDisabledReasonMemberLevelDisabled indicates overage is disabled for the member. RateLimitOverageDisabledReasonMemberLevelDisabled = message.RateLimitOverageDisabledReasonMemberLevelDisabled // RateLimitOverageDisabledReasonSeatTierZeroCreditLimit indicates the seat tier credit limit is zero. RateLimitOverageDisabledReasonSeatTierZeroCreditLimit = message.RateLimitOverageDisabledReasonSeatTierZeroCreditLimit // RateLimitOverageDisabledReasonGroupZeroCreditLimit indicates the group credit limit is zero. RateLimitOverageDisabledReasonGroupZeroCreditLimit = message.RateLimitOverageDisabledReasonGroupZeroCreditLimit // RateLimitOverageDisabledReasonMemberZeroCreditLimit indicates the member credit limit is zero. RateLimitOverageDisabledReasonMemberZeroCreditLimit = message.RateLimitOverageDisabledReasonMemberZeroCreditLimit // RateLimitOverageDisabledReasonOrgServiceLevelDisabled indicates overage is disabled for the org service level. RateLimitOverageDisabledReasonOrgServiceLevelDisabled = message.RateLimitOverageDisabledReasonOrgServiceLevelDisabled // RateLimitOverageDisabledReasonOrgServiceZeroCreditLimit indicates the org service credit limit is zero. RateLimitOverageDisabledReasonOrgServiceZeroCreditLimit = message.RateLimitOverageDisabledReasonOrgServiceZeroCreditLimit // RateLimitOverageDisabledReasonNoLimitsConfigured indicates no limits are configured. RateLimitOverageDisabledReasonNoLimitsConfigured = message.RateLimitOverageDisabledReasonNoLimitsConfigured // RateLimitOverageDisabledReasonUnknown indicates the CLI reported an unknown reason. RateLimitOverageDisabledReasonUnknown = message.RateLimitOverageDisabledReasonUnknown )
const ( // BlockTypeText contains plain text content. BlockTypeText = message.BlockTypeText // BlockTypeImage contains inline image input content. BlockTypeImage = message.BlockTypeImage // BlockTypeDocument contains inline PDF document input content. BlockTypeDocument = message.BlockTypeDocument // BlockTypeConnector contains IDE/connector-synchronized text context. BlockTypeConnector = message.BlockTypeConnector )
const ( // HookEventPreToolUse is triggered before a tool is used. HookEventPreToolUse = hook.EventPreToolUse // HookEventPostToolUse is triggered after a tool is used. HookEventPostToolUse = hook.EventPostToolUse // HookEventUserPromptSubmit is triggered when a user submits a prompt. HookEventUserPromptSubmit = hook.EventUserPromptSubmit // HookEventSessionStart is triggered when a session starts. HookEventSessionStart = hook.EventSessionStart // HookEventSessionEnd is triggered when a session ends. HookEventSessionEnd = hook.EventSessionEnd // HookEventStop is triggered when a session stops. HookEventStop = hook.EventStop // HookEventStopFailure is triggered when a stop operation fails. HookEventStopFailure = hook.EventStopFailure // HookEventSubagentStart is triggered when a subagent starts. HookEventSubagentStart = hook.EventSubagentStart // HookEventSubagentStop is triggered when a subagent stops. HookEventSubagentStop = hook.EventSubagentStop // HookEventPreCompact is triggered before compaction. HookEventPreCompact = hook.EventPreCompact // HookEventPostCompact is triggered after compaction. HookEventPostCompact = hook.EventPostCompact // HookEventPostToolUseFailure is triggered after a tool use fails. HookEventPostToolUseFailure = hook.EventPostToolUseFailure // HookEventNotification is triggered when a notification is sent. HookEventNotification = hook.EventNotification // HookEventPermissionRequest is triggered when a permission is requested. HookEventPermissionRequest = hook.EventPermissionRequest // HookEventPermissionDenied is triggered when a permission is denied. HookEventPermissionDenied = hook.EventPermissionDenied // HookEventSetup is triggered during setup. HookEventSetup = hook.EventSetup // HookEventTeammateIdle is triggered when a teammate is idle. HookEventTeammateIdle = hook.EventTeammateIdle // HookEventTaskCreated is triggered when a task is created. HookEventTaskCreated = hook.EventTaskCreated // HookEventTaskCompleted is triggered when a task completes. HookEventTaskCompleted = hook.EventTaskCompleted // HookEventElicitation is triggered for MCP elicitation requests. HookEventElicitation = hook.EventElicitation // HookEventElicitationResult is triggered for elicitation responses. HookEventElicitationResult = hook.EventElicitationResult // HookEventConfigChange is triggered when configuration changes. HookEventConfigChange = hook.EventConfigChange // HookEventWorktreeCreate is triggered when a worktree is created. HookEventWorktreeCreate = hook.EventWorktreeCreate // HookEventWorktreeRemove is triggered when a worktree is removed. HookEventWorktreeRemove = hook.EventWorktreeRemove // HookEventInstructionsLoaded is triggered when instructions are loaded. HookEventInstructionsLoaded = hook.EventInstructionsLoaded // HookEventCwdChanged is triggered when cwd changes. HookEventCwdChanged = hook.EventCwdChanged // HookEventFileChanged is triggered when a watched file changes. HookEventFileChanged = hook.EventFileChanged )
const ( // PermissionModeDefault uses standard permission prompts. PermissionModeDefault = permission.ModeDefault // PermissionModeAcceptEdits automatically accepts file edits. PermissionModeAcceptEdits = permission.ModeAcceptEdits // PermissionModePlan enables plan mode for implementation planning. PermissionModePlan = permission.ModePlan // PermissionModeAuto lets Claude dynamically decide permission behavior. PermissionModeAuto = permission.ModeAuto // PermissionModeDontAsk disables prompts and denies anything not pre-approved. PermissionModeDontAsk = permission.ModeDontAsk // PermissionModeBypassPermissions bypasses all permission checks. PermissionModeBypassPermissions = permission.ModeBypassPermissions )
const ( // PermissionUpdateTypeAddRules adds new permission rules. PermissionUpdateTypeAddRules = permission.UpdateTypeAddRules // PermissionUpdateTypeReplaceRules replaces existing permission rules. PermissionUpdateTypeReplaceRules = permission.UpdateTypeReplaceRules // PermissionUpdateTypeRemoveRules removes permission rules. PermissionUpdateTypeRemoveRules = permission.UpdateTypeRemoveRules // PermissionUpdateTypeSetMode sets the permission mode. PermissionUpdateTypeSetMode = permission.UpdateTypeSetMode // PermissionUpdateTypeAddDirectories adds accessible directories. PermissionUpdateTypeAddDirectories = permission.UpdateTypeAddDirectories // PermissionUpdateTypeRemoveDirectories removes accessible directories. PermissionUpdateTypeRemoveDirectories = permission.UpdateTypeRemoveDirectories )
const ( // PermissionDecisionClassificationUserTemporary indicates a temporary user approval. PermissionDecisionClassificationUserTemporary = permission.DecisionClassificationUserTemporary // PermissionDecisionClassificationUserPermanent indicates a permanent user approval. PermissionDecisionClassificationUserPermanent = permission.DecisionClassificationUserPermanent // PermissionDecisionClassificationUserReject indicates a rejected request. PermissionDecisionClassificationUserReject = permission.DecisionClassificationUserReject )
const ( PermissionDecisionReasonTypeRule = permission.DecisionReasonTypeRule PermissionDecisionReasonTypeMode = permission.DecisionReasonTypeMode PermissionDecisionReasonTypeHook = permission.DecisionReasonTypeHook PermissionDecisionReasonTypeClassifier = permission.DecisionReasonTypeClassifier PermissionDecisionReasonTypeSandboxOverride = permission.DecisionReasonTypeSandboxOverride PermissionDecisionReasonTypeWorkingDir = permission.DecisionReasonTypeWorkingDir PermissionDecisionReasonTypeSafetyCheck = permission.DecisionReasonTypeSafetyCheck )
const ( // PermissionUpdateDestUserSettings stores in user-level settings. PermissionUpdateDestUserSettings = permission.UpdateDestUserSettings // PermissionUpdateDestProjectSettings stores in project-level settings. PermissionUpdateDestProjectSettings = permission.UpdateDestProjectSettings // PermissionUpdateDestLocalSettings stores in local-level settings. PermissionUpdateDestLocalSettings = permission.UpdateDestLocalSettings // PermissionUpdateDestSession stores in the current session only. PermissionUpdateDestSession = permission.UpdateDestSession // PermissionUpdateDestCLIArg stores in runtime CLI-argument permissions. PermissionUpdateDestCLIArg = permission.UpdateDestCLIArg )
const ( // PermissionBehaviorAllow automatically allows the operation. PermissionBehaviorAllow = permission.BehaviorAllow // PermissionBehaviorDeny automatically denies the operation. PermissionBehaviorDeny = permission.BehaviorDeny // PermissionBehaviorAsk prompts the user for permission. PermissionBehaviorAsk = permission.BehaviorAsk )
const ( // ElicitationModeForm requests form-mode elicitation. ElicitationModeForm = elicitation.ModeForm // ElicitationModeURL requests URL-mode elicitation. ElicitationModeURL = elicitation.ModeURL )
const ( // ElicitationActionAccept accepts the elicitation. ElicitationActionAccept = elicitation.ActionAccept // ElicitationActionDecline declines the elicitation. ElicitationActionDecline = elicitation.ActionDecline // ElicitationActionCancel cancels the elicitation. ElicitationActionCancel = elicitation.ActionCancel )
const ( // MCPServerTypeStdio uses stdio for communication. MCPServerTypeStdio = mcp.ServerTypeStdio // MCPServerTypeSSE uses Server-Sent Events. MCPServerTypeSSE = mcp.ServerTypeSSE // MCPServerTypeHTTP uses HTTP for communication. MCPServerTypeHTTP = mcp.ServerTypeHTTP // MCPServerTypeWS uses WebSocket for communication. MCPServerTypeWS = mcp.ServerTypeWS // MCPServerTypeSDK uses the SDK interface. MCPServerTypeSDK = mcp.ServerTypeSDK // MCPServerTypeClaudeAIProxy is the output-only Claude.ai proxy MCP transport. MCPServerTypeClaudeAIProxy = mcp.ServerTypeClaudeAIProxy )
const ( // MCPServerConnectionStatusConnected indicates the server is connected. MCPServerConnectionStatusConnected = mcp.ServerConnectionStatusConnected // MCPServerConnectionStatusFailed indicates the server failed to connect. MCPServerConnectionStatusFailed = mcp.ServerConnectionStatusFailed // MCPServerConnectionStatusNeedsAuth indicates the server requires authentication. MCPServerConnectionStatusNeedsAuth = mcp.ServerConnectionStatusNeedsAuth // MCPServerConnectionStatusPending indicates the server is still connecting. MCPServerConnectionStatusPending = mcp.ServerConnectionStatusPending // MCPServerConnectionStatusDisabled indicates the server is disabled. MCPServerConnectionStatusDisabled = mcp.ServerConnectionStatusDisabled )
const ( // FastModeStateOff indicates fast mode is off. FastModeStateOff = fastmode.StateOff // FastModeStateCooldown indicates fast mode is cooling down. FastModeStateCooldown = fastmode.StateCooldown // FastModeStateOn indicates fast mode is on. FastModeStateOn = fastmode.StateOn )
const ( // StreamingMessagePriorityNow executes immediately ahead of queued messages. StreamingMessagePriorityNow = message.StreamingMessagePriorityNow // StreamingMessagePriorityNext executes after the current turn and before notifications. StreamingMessagePriorityNext = message.StreamingMessagePriorityNext // StreamingMessagePriorityLater executes after higher-priority queued messages. StreamingMessagePriorityLater = message.StreamingMessagePriorityLater )
const MinimumCLIVersion = "2.1.59"
MinimumCLIVersion is the minimum required Claude CLI version.
const SandboxNetworkAccessToolName = permission.SandboxNetworkAccessToolName
SandboxNetworkAccessToolName is the synthetic tool name used for sandbox network permission prompts.
const ( // SdkBetaContext1M enables 1 million token context window. SdkBetaContext1M = config.BetaContext1M )
const ( // StatusStateCompacting indicates the session is compacting. StatusStateCompacting = message.StatusStateCompacting )
const Version = "0.1.0"
Version is the SDK version.
Variables ¶
var ( // ErrClientNotConnected indicates the client is not connected. ErrClientNotConnected = errors.ErrClientNotConnected // ErrClientAlreadyConnected indicates the client is already connected. ErrClientAlreadyConnected = errors.ErrClientAlreadyConnected // ErrClientClosed indicates the client has been closed and cannot be reused. ErrClientClosed = errors.ErrClientClosed // ErrTransportNotConnected indicates the transport is not connected. ErrTransportNotConnected = errors.ErrTransportNotConnected // ErrRequestTimeout indicates a request timed out. ErrRequestTimeout = errors.ErrRequestTimeout ErrServerInfoUnavailable = errors.ErrServerInfoUnavailable // ErrSessionNotFound indicates no persisted session was found for the given session ID. ErrSessionNotFound = errors.ErrSessionNotFound // ErrSessionCostNotFound indicates no persisted session-cost snapshot was found for the given session ID. ErrSessionCostNotFound = errors.ErrSessionCostNotFound // ErrStructuredOutputMissing indicates the result did not include structured output. ErrStructuredOutputMissing = errors.ErrStructuredOutputMissing )
Public sentinel errors.
var AgentMCPServerInline = config.AgentMCPServerInline
AgentMCPServerInline creates an inline spec for a single MCP server config.
var AgentMCPServerReference = config.AgentMCPServerReference
AgentMCPServerReference creates a reference spec for an existing MCP server.
var ClassifyToolCategory = toolmeta.Classify
ClassifyToolCategory returns the SDK's best-effort category for a tool name.
var DescribeTool = toolmeta.Describe
DescribeTool returns the SDK's derived metadata for one tool.
var InterruptBehaviorForTool = toolmeta.InterruptMode
InterruptBehaviorForTool reports the SDK's best-effort interrupt behavior hint.
var IsConcurrencySafeTool = toolmeta.IsConcurrencySafe
IsConcurrencySafeTool reports whether a tool is treated as safe for concurrent execution.
var NewAgentEffortLevel = config.NewAgentEffortLevel
NewAgentEffortLevel creates an agent effort value from a named level.
var NewAgentEffortValue = config.NewAgentEffortValue
NewAgentEffortValue creates an agent effort value from an integer.
var NewAuditEnvelope = message.NewAuditEnvelope
NewAuditEnvelope creates an audit envelope from a typed payload.
var NewUserMessageContent = message.NewUserMessageContent
NewUserMessageContent creates UserMessageContent from a string.
var NewUserMessageContentBlocks = message.NewUserMessageContentBlocks
NewUserMessageContentBlocks creates UserMessageContent from blocks.
Functions ¶
func DecodeStructuredOutput ¶ added in v0.0.7
func DecodeStructuredOutput[T any](result *ResultMessage) (T, error)
DecodeStructuredOutput decodes parsed structured output into the requested Go type.
func DeleteSession ¶ added in v0.0.6
func DeleteSession(sessionID string, options DeleteSessionOptions) error
DeleteSession removes a session JSONL file from disk.
func DeleteSessionCost ¶ added in v0.0.7
func DeleteSessionCost(sessionID string, options SessionCostOptions) error
DeleteSessionCost removes a persisted session-cost snapshot.
func EffectiveModelContextWindow ¶ added in v0.0.7
EffectiveModelContextWindow returns the SDK's best-effort effective context window. Explicit "[1m]" model suffixes override the static catalog.
func ErrorResult ¶
func ErrorResult(message string) *mcp.CallToolResult
ErrorResult creates a CallToolResult indicating an error.
func ExtractNestedModelUsage ¶ added in v0.0.7
func ExtractNestedModelUsage(event RawStreamEvent) map[string]ModelUsage
ExtractNestedModelUsage best-effort extracts usage reported inside provider-native stream payloads, including nested server_tool_use web-search counts.
func ImageResult ¶
func ImageResult(data []byte, mimeType string) *mcp.CallToolResult
ImageResult creates a CallToolResult with image content.
func MessagesFromChannel ¶
func MessagesFromChannel(ch <-chan StreamingMessage) iter.Seq[StreamingMessage]
MessagesFromChannel creates a MessageStream from a channel. This is useful for dynamic message generation where messages are produced over time. The iterator completes when the channel is closed.
func MessagesFromContent ¶ added in v0.0.5
func MessagesFromContent(content UserMessageContent) iter.Seq[StreamingMessage]
MessagesFromContent creates a single-message stream from user content.
func MessagesFromSlice ¶
func MessagesFromSlice(msgs []StreamingMessage) iter.Seq[StreamingMessage]
MessagesFromSlice creates a MessageStream from a slice of StreamingMessages. This is useful for sending a fixed set of messages in streaming mode.
func ModelCapabilities ¶
ModelCapabilities returns capability strings for the given model ID. Returns nil if the model is not found.
func ModelHasOneMillionContextSuffix ¶ added in v0.0.7
ModelHasOneMillionContextSuffix reports whether a model ID carries the CLI's explicit "[1m]" context-window suffix.
func NewMcpTool ¶
func NewMcpTool(name, description string, inputSchema *jsonschema.Schema) *mcp.Tool
NewMcpTool creates an mcp.Tool with the given parameters. This is useful when you need direct access to the MCP Tool type.
func NopLogger ¶
NopLogger returns a logger that discards all output. Use this when you want silent operation with no logging overhead.
func ParseArguments ¶
func ParseArguments(req *mcp.CallToolRequest) (map[string]any, error)
ParseArguments unmarshals CallToolRequest arguments into a map. This is a convenience function for extracting tool input.
func Query ¶
func Query( ctx context.Context, content UserMessageContent, opts ...Option, ) iter.Seq2[Message, error]
Query executes a one-shot query to Claude and returns an iterator of messages.
By default, logging is disabled. Use WithLogger to enable logging:
logger := slog.New(slog.NewTextHandler(os.Stderr, nil))
for msg, err := range Query(ctx, Text("What is 2+2?"),
WithLogger(logger),
WithPermissionMode(string(PermissionModeBypassPermissions)),
) {
if err != nil {
log.Fatal(err)
}
// handle msg
}
The iterator yields messages as they arrive from Claude, including assistant responses, tool use, and a final result message. Any errors during setup or execution are yielded inline with messages, allowing callers to handle all error conditions.
Query supports hooks, CanUseTool callbacks, OnUserInput callbacks, and SDK MCP servers through the protocol controller. When these options are configured, an initialization request is sent to the CLI before processing messages.
Example usage:
ctx := context.Background()
for msg, err := range Query(ctx, Text("What is 2+2?"),
WithPermissionMode(string(PermissionModeBypassPermissions)),
WithMaxTurns(1),
) {
if err != nil {
log.Fatal(err)
}
switch m := msg.(type) {
case *AssistantMessage:
// Handle assistant response
case *ResultMessage:
// Handle final result
}
}
Error Handling:
Errors are yielded inline as the second return value.
Parse errors, transport failures, context cancellation, and controller errors all stop iteration after yielding the error.
Callers can always stop iteration early by breaking from the loop, regardless of error type.
func QueryStream ¶
func QueryStream( ctx context.Context, messages iter.Seq[StreamingMessage], opts ...Option, ) iter.Seq2[Message, error]
QueryStream executes a streaming query with multiple input messages.
The messages iterator yields StreamingMessage values that are sent to Claude via stdin in streaming mode. The transport uses --input-format stream-json.
By default, logging is disabled. Use WithLogger to enable logging.
The iterator yields messages as they arrive from Claude, including assistant responses, tool use, and a final result message. Any errors during setup or execution are yielded inline with messages, allowing callers to handle all error conditions.
QueryStream supports hooks, CanUseTool callbacks, OnUserInput callbacks, and SDK MCP servers through the protocol controller. When these options are configured, an initialization request is sent to the CLI before processing messages.
Example usage:
ctx := context.Background()
logger := slog.New(slog.NewTextHandler(os.Stderr, nil))
messages := claudesdk.MessagesFromSlice([]claudesdk.StreamingMessage{
claudesdk.NewUserMessageWithPriority(Text("Hello"), StreamingMessagePriorityNow),
claudesdk.NewUserMessage(Text("How are you?")),
})
for msg, err := range claudesdk.QueryStream(ctx, messages,
claudesdk.WithLogger(logger),
claudesdk.WithPermissionMode(string(PermissionModeBypassPermissions)),
) {
if err != nil {
log.Fatal(err)
}
// Handle messages
}
Error Handling:
Errors are yielded inline as the second return value.
Parse errors, transport failures, context cancellation, and controller errors all stop iteration after yielding the error.
Callers can always stop iteration early by breaking from the loop, regardless of error type.
func RenameSession ¶ added in v0.0.6
func RenameSession(sessionID, title string, options RenameSessionOptions) error
RenameSession sets a custom title for an existing session by appending a custom-title entry to the session JSONL file.
func ResilientQuery ¶ added in v0.0.7
func ResilientQuery( ctx context.Context, content UserMessageContent, orchestrator *RecoveryOrchestrator, opts ...Option, ) iter.Seq2[Message, error]
ResilientQuery reruns a one-shot query when the recovery orchestrator can safely retry the request.
func SaveSessionCost ¶ added in v0.0.7
func SaveSessionCost(sessionID string, snapshot CostSnapshot, options SessionCostOptions) error
SaveSessionCost writes a persisted session-cost snapshot under Claude home.
func SimpleSchema ¶
func SimpleSchema(props map[string]string) *jsonschema.Schema
SimpleSchema creates a jsonschema.Schema from a simple type map.
Input format: {"a": "float64", "b": "string"}
Type mappings:
- "string" → {"type": "string"}
- "int", "int64" → {"type": "integer"}
- "float64", "float" → {"type": "number"}
- "bool" → {"type": "boolean"}
- "[]string" → {"type": "array", "items": {"type": "string"}}
- "any", "object" → {"type": "object"}
func SingleMessage ¶
func SingleMessage(content UserMessageContent) iter.Seq[StreamingMessage]
SingleMessage creates a MessageStream with a single user message. This is a convenience function for simple one-message streaming queries.
func TagSession ¶ added in v0.0.6
func TagSession(sessionID string, tag *string, options TagSessionOptions) error
TagSession sets or clears a tag on an existing session by appending a tag entry to the session JSONL file. Pass nil to clear the tag.
func TextResult ¶
func TextResult(text string) *mcp.CallToolResult
TextResult creates a CallToolResult with text content.
func WithClient ¶
WithClient manages client lifecycle with automatic cleanup.
This helper creates a client, starts it with the provided options, executes the callback function, and ensures proper cleanup via Close() when done.
The callback receives a fully initialized Client that is ready for use. If the callback returns an error, it is returned to the caller. If Close() fails, a warning is logged but does not override the callback's error.
Example usage:
err := claudesdk.WithClient(ctx, func(c claudesdk.Client) error {
if err := c.Query(ctx, Text("Hello")); err != nil {
return err
}
for msg, err := range c.ReceiveResponse(ctx) {
if err != nil {
return err
}
// process message...
}
return nil
},
claudesdk.WithLogger(log),
claudesdk.WithPermissionMode(string(claudesdk.PermissionModeDefault)),
)
Types ¶
type APIRetryMessage ¶ added in v0.0.7
type APIRetryMessage = message.APIRetryMessage
APIRetryMessage reports an API retry event.
type AccountInfo ¶ added in v0.0.7
type AccountInfo = protocol.AccountInfo
AccountInfo describes the active CLI account.
type AgentDefinition ¶
type AgentDefinition = config.AgentDefinition
AgentDefinition defines a custom agent configuration.
type AgentEffort ¶ added in v0.0.7
type AgentEffort = config.AgentEffort
AgentEffort encodes the upstream agent effort union.
type AgentMCPServerSpec ¶ added in v0.0.7
type AgentMCPServerSpec = config.AgentMCPServerSpec
AgentMCPServerSpec defines one agent-scoped MCP server requirement.
type AppliedSettings ¶ added in v0.0.7
type AppliedSettings = protocol.AppliedSettings
AppliedSettings describes runtime-applied settings.
type AssistantMessage ¶
type AssistantMessage = message.AssistantMessage
AssistantMessage represents a message from Claude.
type AssistantMessageError ¶
type AssistantMessageError = message.AssistantMessageError
AssistantMessageError represents error types from the assistant.
type AsyncHookJSONOutput ¶
type AsyncHookJSONOutput = hook.AsyncJSONOutput
AsyncHookJSONOutput represents an async hook output.
type AuditEnvelope ¶ added in v0.0.7
type AuditEnvelope = message.AuditEnvelope
AuditEnvelope captures the provider-native event payload emitted by the SDK.
type AuthStatusMessage ¶ added in v0.0.7
type AuthStatusMessage = message.AuthStatusMessage
AuthStatusMessage reports CLI authentication progress.
type AutoCompactAction ¶ added in v0.0.7
type AutoCompactAction string
AutoCompactAction describes the host-facing recommendation after observing context pressure.
const ( AutoCompactActionNone AutoCompactAction = "none" AutoCompactActionWarn AutoCompactAction = "warn" AutoCompactActionCompact AutoCompactAction = "compact" AutoCompactActionSuppress AutoCompactAction = "suppress" AutoCompactActionStop AutoCompactAction = "stop" )
type AutoCompactFailureCircuitBreaker ¶ added in v0.0.7
type AutoCompactFailureCircuitBreaker struct {
// contains filtered or unexported fields
}
AutoCompactFailureCircuitBreaker tracks repeated compaction failures.
func NewAutoCompactFailureCircuitBreaker ¶ added in v0.0.7
func NewAutoCompactFailureCircuitBreaker(failureLimit int) (*AutoCompactFailureCircuitBreaker, error)
NewAutoCompactFailureCircuitBreaker creates a new compaction failure breaker.
func (*AutoCompactFailureCircuitBreaker) ConsecutiveFailures ¶ added in v0.0.7
func (b *AutoCompactFailureCircuitBreaker) ConsecutiveFailures() int
ConsecutiveFailures returns the current failure streak.
func (*AutoCompactFailureCircuitBreaker) IsOpen ¶ added in v0.0.7
func (b *AutoCompactFailureCircuitBreaker) IsOpen() bool
IsOpen reports whether the breaker has reached the failure limit.
func (*AutoCompactFailureCircuitBreaker) RecordFailure ¶ added in v0.0.7
func (b *AutoCompactFailureCircuitBreaker) RecordFailure() bool
RecordFailure increments the breaker and reports whether it is now open.
func (*AutoCompactFailureCircuitBreaker) RecordSuccess ¶ added in v0.0.7
func (b *AutoCompactFailureCircuitBreaker) RecordSuccess()
RecordSuccess resets the breaker failure count.
type AutoCompactObservation ¶ added in v0.0.7
type AutoCompactObservation struct {
TurnCounter int
TurnsSinceLastCompact int
Status *ContextPressureStatus
CircuitOpen bool
ConsecutiveFailures int
Action AutoCompactAction
ShouldAttemptCompact bool
}
AutoCompactObservation summarizes one turn's compaction recommendation.
type AutoCompactOrchestrator ¶ added in v0.0.7
type AutoCompactOrchestrator struct {
// contains filtered or unexported fields
}
AutoCompactOrchestrator coordinates context-pressure evaluation with a circuit breaker.
func NewAutoCompactOrchestrator ¶ added in v0.0.7
func NewAutoCompactOrchestrator(options AutoCompactOrchestratorOptions) (*AutoCompactOrchestrator, error)
NewAutoCompactOrchestrator creates a new observational compaction orchestrator.
func (*AutoCompactOrchestrator) ObserveTurn ¶ added in v0.0.7
func (o *AutoCompactOrchestrator) ObserveTurn(usage *ContextUsage) (*AutoCompactObservation, error)
ObserveTurn evaluates one turn's context usage and returns the recommended action.
func (*AutoCompactOrchestrator) RecordCompactFailure ¶ added in v0.0.7
func (o *AutoCompactOrchestrator) RecordCompactFailure() bool
RecordCompactFailure records a failed compaction attempt.
func (*AutoCompactOrchestrator) RecordCompactSuccess ¶ added in v0.0.7
func (o *AutoCompactOrchestrator) RecordCompactSuccess()
RecordCompactSuccess resets failure state after a successful compaction.
type AutoCompactOrchestratorOptions ¶ added in v0.0.7
type AutoCompactOrchestratorOptions struct {
Policy ContextPressurePolicy
FailureLimit int
}
AutoCompactOrchestratorOptions configure observational compaction guidance.
type AvailableModelInfo ¶ added in v0.0.7
type AvailableModelInfo = protocol.AvailableModelInfo
AvailableModelInfo describes a model returned by the live CLI.
type Base64Source ¶ added in v0.0.5
type Base64Source = message.Base64Source
Base64Source contains inline base64 content for Claude CLI multimodal inputs.
type BaseHookInput ¶
BaseHookInput contains common fields for all hook inputs.
type BudgetProgressAction ¶ added in v0.0.7
type BudgetProgressAction string
BudgetProgressAction describes the recommended host action for the current budget state.
const ( BudgetProgressActionContinue BudgetProgressAction = "continue" BudgetProgressActionStop BudgetProgressAction = "stop" )
type BudgetProgressStatus ¶ added in v0.0.7
type BudgetProgressStatus struct {
Action BudgetProgressAction
Reason string
CompletionRatio float64
NearCompletion bool
BudgetExceeded bool
DiminishingReturns bool
ContinuationCount int
LastTokenDelta int
DiminishingReturnsWindow int
DiminishingReturnsMinTokenDelta int
}
BudgetProgressStatus summarizes budget progress and continuation heuristics.
func EvaluateBudgetProgress ¶ added in v0.0.7
func EvaluateBudgetProgress( cost CostSnapshot, maxCostUSD *float64, maxTaskTokens *int, results int, lastTokenDelta int, completionThreshold float64, diminishingReturnsWindow int, diminishingReturnsMinTokenDelta int, diminishingReturns bool, ) BudgetProgressStatus
EvaluateBudgetProgress returns the current budget recommendation for a host.
type BudgetSnapshot ¶ added in v0.0.7
type BudgetSnapshot struct {
Cost CostSnapshot
Results int
ContinuationCount int
LastTokenDelta int
RecentTokenDeltas []int
CompletionRatio float64
NearCompletion bool
BudgetExceeded bool
DiminishingReturns bool
ShouldContinue bool
SuggestedNudge *string
MaxCostUSD *float64
MaxTaskTokens *int
CompletionThreshold float64
DiminishingReturnsWindow int
DiminishingReturnsMinTokenDelta int
}
BudgetSnapshot summarizes accumulated budget and continuation state.
type BudgetTracker ¶ added in v0.0.7
type BudgetTracker struct {
// contains filtered or unexported fields
}
BudgetTracker provides SDK-side observational budget heuristics.
func NewBudgetTracker ¶ added in v0.0.7
func NewBudgetTracker(options BudgetTrackerOptions) (*BudgetTracker, error)
NewBudgetTracker creates a new observational budget tracker.
func (*BudgetTracker) Observe ¶ added in v0.0.7
func (t *BudgetTracker) Observe(msg Message)
Observe records usage from a message when it is a terminal result.
func (*BudgetTracker) ObserveResult ¶ added in v0.0.7
func (t *BudgetTracker) ObserveResult(result *ResultMessage)
ObserveResult records usage from a terminal result.
func (*BudgetTracker) Snapshot ¶ added in v0.0.7
func (t *BudgetTracker) Snapshot() BudgetSnapshot
Snapshot returns the current observational budget state.
type BudgetTrackerOptions ¶ added in v0.0.7
type BudgetTrackerOptions struct {
MaxCostUSD *float64
MaxTaskTokens *int
CompletionThreshold float64
DiminishingReturnsWindow int
DiminishingReturnsMinTokenDelta int
}
BudgetTrackerOptions configures observational budget tracking.
type CLIConnectionError ¶
type CLIConnectionError = errors.CLIConnectionError
CLIConnectionError indicates failure to connect to the CLI.
type CLIJSONDecodeError ¶
type CLIJSONDecodeError = errors.CLIJSONDecodeError
CLIJSONDecodeError indicates JSON parsing failed for CLI output.
type CLINotFoundError ¶
type CLINotFoundError = errors.CLINotFoundError
CLINotFoundError indicates the Claude CLI binary was not found.
type CallToolRequest ¶
type CallToolRequest = mcp.CallToolRequest
CallToolRequest is the request passed to tool handlers.
type CallToolResult ¶
type CallToolResult = mcp.CallToolResult
CallToolResult is the server's response to a tool call. Use TextResult, ErrorResult, or ImageResult helpers to create results.
type CancelAsyncMessageResult ¶ added in v0.0.7
type CancelAsyncMessageResult = protocol.CancelAsyncMessageResult
CancelAsyncMessageResult is the typed result of CancelAsyncMessage.
type ClaudeAgentOptions ¶
ClaudeAgentOptions configures the behavior of the Claude agent.
type ClaudeSDKError ¶
type ClaudeSDKError = errors.ClaudeSDKError
ClaudeSDKError is the base interface for all SDK errors.
type Client ¶
type Client interface {
// Start establishes a connection to the Claude CLI.
// Must be called before any other methods.
// Returns CLINotFoundError if CLI not found, CLIConnectionError on failure.
Start(ctx context.Context, opts ...Option) error
// StartWithContent establishes a connection and immediately sends initial user content.
// Equivalent to calling Start() followed by Query(ctx, Text(content))).
// The content is sent to the "default" session.
// Returns CLINotFoundError if CLI not found, CLIConnectionError on failure.
StartWithContent(ctx context.Context, content UserMessageContent, opts ...Option) error
// StartWithStream establishes a connection and streams initial messages.
// Messages are consumed from the iterator and sent via stdin.
// The iterator runs in a separate goroutine; use context cancellation to abort.
// EndInput is called automatically when the iterator completes.
// Returns CLINotFoundError if CLI not found, CLIConnectionError on failure.
StartWithStream(ctx context.Context, messages iter.Seq[StreamingMessage], opts ...Option) error
// Query sends user content to Claude.
// Returns immediately after sending; use ReceiveMessages() or ReceiveResponse() to get responses.
// Optional sessionID defaults to "default" for multi-session support.
Query(ctx context.Context, content UserMessageContent, sessionID ...string) error
// ReceiveMessages returns an iterator that yields messages indefinitely.
// Messages are yielded as they arrive until EOF, an error occurs, or context is cancelled.
// Unlike ReceiveResponse, this iterator does not stop at ResultMessage.
// Use iter.Pull2 if you need pull-based iteration instead of range.
ReceiveMessages(ctx context.Context) iter.Seq2[Message, error]
// GetTransportHealth returns the current observed transport-health snapshot.
GetTransportHealth() TransportHealth
// ReceiveResponse returns an iterator that yields messages until a ResultMessage is received.
// Messages are yielded as they arrive for streaming consumption.
// The iterator stops after yielding the ResultMessage.
// Use iter.Pull2 if you need pull-based iteration instead of range.
// To collect all messages into a slice, use slices.Collect or a simple loop.
ReceiveResponse(ctx context.Context) iter.Seq2[Message, error]
// Interrupt sends an interrupt signal to stop Claude's current processing.
// By default this is a soft interrupt and does not synthesize missing
// tool_result blocks. Use WithInterruptToolResultPolicy to opt into
// synthetic tool_result cleanup before interrupting.
Interrupt(ctx context.Context) error
// SetPermissionMode changes the permission mode during conversation.
// Valid modes: "default", "acceptEdits", "plan", "dontAsk", "bypassPermissions"
SetPermissionMode(ctx context.Context, mode string) error
// SetModel changes the AI model during conversation.
// Pass nil to use the default model.
SetModel(ctx context.Context, model *string) error
// SetMaxThinkingTokens changes the max thinking token budget during conversation.
// Pass nil to clear the override.
SetMaxThinkingTokens(ctx context.Context, maxTokens *int) error
// ListModels returns the SDK's static Claude model catalog in the ListModels payload shape.
// This is not a live account-specific list from the Claude CLI.
ListModels(ctx context.Context) ([]ModelInfo, error)
// GetServerInfo returns typed server initialization info including commands and account data.
// Returns ErrClientNotConnected when no session is active, or ErrServerInfoUnavailable
// if initialize metadata has not been received.
GetServerInfo() (*ServerInfo, error)
// GetMCPStatus queries the CLI for live MCP server connection status.
// Returns the status of all configured MCP servers.
GetMCPStatus(ctx context.Context) (*MCPStatus, error)
// GetContextUsage queries the CLI for the current context usage breakdown.
GetContextUsage(ctx context.Context) (*ContextUsage, error)
// SetMCPServers replaces the dynamically managed MCP server set.
SetMCPServers(ctx context.Context, servers map[string]MCPServerConfig) (*MCPSetServersResult, error)
// ReconnectMCPServer reconnects a disconnected or failed MCP server.
ReconnectMCPServer(ctx context.Context, serverName string) error
// ToggleMCPServer enables or disables an MCP server.
ToggleMCPServer(ctx context.Context, serverName string, enabled bool) error
// ReloadPlugins reloads plugins from disk and returns refreshed session metadata.
ReloadPlugins(ctx context.Context) (*ReloadPluginsResult, error)
// ApplyFlagSettings merges the provided settings into the flag settings layer.
ApplyFlagSettings(ctx context.Context, settings map[string]any) error
// GetSettings returns the effective merged settings and per-source raw settings.
GetSettings(ctx context.Context) (*SettingsSnapshot, error)
// StopTask stops a running task by task ID.
StopTask(ctx context.Context, taskID string) error
// RewindFiles rewinds tracked files to their state at a specific user message.
// The userMessageID should be the ID of a previous user message in the conversation.
// Requires EnableFileCheckpointing=true in ClaudeAgentOptions.
RewindFiles(ctx context.Context, userMessageID string) (*RewindFilesResult, error)
// CancelAsyncMessage cancels a queued async message by UUID.
CancelAsyncMessage(ctx context.Context, messageUUID string) (*CancelAsyncMessageResult, error)
// SeedReadState seeds the CLI read-state cache for Edit validation.
SeedReadState(ctx context.Context, path string, mtime int64) error
// UpdateEnvironmentVariables updates environment variables for the running session.
UpdateEnvironmentVariables(ctx context.Context, variables map[string]string) error
// SendToolResult sends a tool_result message back to Claude for a pending tool_use.
// This is used when the SDK intercepts a tool_use (e.g. AskUserQuestion) and needs
// to provide the result back to Claude so it can continue processing.
SendToolResult(ctx context.Context, toolUseID, content string, isError bool) error
// Close terminates the session and cleans up resources.
// After Close(), the client cannot be reused. Safe to call multiple times.
Close() error
}
Client provides an interactive, stateful interface for multi-turn conversations with Claude.
Unlike the one-shot Query() function, Client maintains session state across multiple exchanges. It supports interruption and bidirectional communication with the Claude CLI. Lifecycle: Clients are single-use. After Close(), create a new client with NewClient().
Example usage:
client := NewClient()
defer client.Close(ctx)
err := client.Start(ctx,
WithLogger(slog.Default()),
WithPermissionMode(string(PermissionModeDefault)),
)
if err != nil {
log.Fatal(err)
}
// Send a query
err = client.Query(ctx, Text("What is 2+2?"))
if err != nil {
log.Fatal(err)
}
// Receive all messages for this response (stops at ResultMessage)
for msg, err := range client.ReceiveResponse(ctx) {
if err != nil {
log.Fatal(err)
}
// Process message...
}
// Or receive messages indefinitely (for continuous streaming)
for msg, err := range client.ReceiveMessages(ctx) {
if err != nil {
break
}
// Process message...
}
type CompactBoundaryMessage ¶ added in v0.0.7
type CompactBoundaryMessage = message.CompactBoundaryMessage
CompactBoundaryMessage reports conversation compaction boundaries.
type CompactMetadata ¶ added in v0.0.7
type CompactMetadata = message.CompactMetadata
CompactMetadata captures compaction boundary metadata.
type CompactPreservedSegment ¶ added in v0.0.7
type CompactPreservedSegment = message.CompactPreservedSegment
CompactPreservedSegment identifies a preserved compaction segment.
type CompactionSnapshot ¶ added in v0.0.7
type CompactionSnapshot struct {
IsCompacting bool
CompactionCount int
PendingCacheRebuild bool
LastBoundaryUUID *string
LastSessionID *string
LastTrigger *string
LastPreTokens *int
LastCacheCreationInputTokens int
LastCacheBreakLikely bool
LastResultUUID *string
}
CompactionSnapshot summarizes observed compaction lifecycle state.
type CompactionTracker ¶ added in v0.0.7
type CompactionTracker struct {
// contains filtered or unexported fields
}
CompactionTracker observes compaction lifecycle messages and result usage.
func NewCompactionTracker ¶ added in v0.0.7
func NewCompactionTracker() *CompactionTracker
NewCompactionTracker creates an empty compaction tracker.
func (*CompactionTracker) Observe ¶ added in v0.0.7
func (t *CompactionTracker) Observe(msg Message)
Observe records compaction-related state transitions from typed messages.
func (*CompactionTracker) Snapshot ¶ added in v0.0.7
func (t *CompactionTracker) Snapshot() CompactionSnapshot
Snapshot returns a copy of the current compaction-tracker state.
type ConfigChangeHookInput ¶ added in v0.0.7
type ConfigChangeHookInput = hook.ConfigChangeInput
ConfigChangeHookInput is the input for ConfigChange hooks.
type ConnectorTextBlock ¶ added in v0.0.7
type ConnectorTextBlock = message.ConnectorTextBlock
ConnectorTextBlock contains IDE/connector-synchronized text context.
type ContentBlock ¶
type ContentBlock = message.ContentBlock
ContentBlock represents a block of content within a message.
type ContextAPIUsage ¶ added in v0.0.7
type ContextAPIUsage = protocol.ContextAPIUsage
ContextAPIUsage describes API token usage within the current context.
type ContextAgent ¶ added in v0.0.7
type ContextAgent = protocol.ContextAgent
ContextAgent describes one agent in context usage.
type ContextAttachmentBreakdown ¶ added in v0.0.7
type ContextAttachmentBreakdown = protocol.ContextAttachmentBreakdown
ContextAttachmentBreakdown describes one attachment usage bucket.
type ContextCategory ¶ added in v0.0.7
type ContextCategory = protocol.ContextCategory
ContextCategory describes one context-usage category.
type ContextDeferredBuiltinTool ¶ added in v0.0.7
type ContextDeferredBuiltinTool = protocol.ContextDeferredBuiltinTool
ContextDeferredBuiltinTool describes one deferred builtin tool in context usage.
type ContextGridSquare ¶ added in v0.0.7
type ContextGridSquare = protocol.ContextGridSquare
ContextGridSquare describes one context grid square.
type ContextMCPTool ¶ added in v0.0.7
type ContextMCPTool = protocol.ContextMCPTool
ContextMCPTool describes one MCP tool in context usage.
type ContextMemoryFile ¶ added in v0.0.7
type ContextMemoryFile = protocol.ContextMemoryFile
ContextMemoryFile describes one memory file in context usage.
type ContextMessageBreakdown ¶ added in v0.0.7
type ContextMessageBreakdown = protocol.ContextMessageBreakdown
ContextMessageBreakdown describes message token usage.
type ContextPressurePolicy ¶ added in v0.0.7
type ContextPressurePolicy struct {
AutoCompactOffsetTokens int
WarningOffsetTokens int
ErrorOffsetTokens int
BlockingOffsetTokens int
}
ContextPressurePolicy defines token offsets from MaxTokens for context-pressure tiers.
func DefaultContextPressurePolicy ¶ added in v0.0.7
func DefaultContextPressurePolicy() ContextPressurePolicy
DefaultContextPressurePolicy returns the source-aligned default offsets.
type ContextPressureStatus ¶ added in v0.0.7
type ContextPressureStatus struct {
Tier ContextPressureTier
RemainingTokens int
RemainingPercentage float64
AutoCompactThreshold int
WarningThreshold int
ErrorThreshold int
BlockingThreshold int
ExceededWarning bool
ExceededError bool
ExceededAutoCompact bool
ExceededBlocking bool
ShouldWarn bool
ShouldPreventNewToolUse bool
ShouldAutoCompact bool
ShouldStop bool
Usage *ContextUsage
}
ContextPressureStatus summarizes multi-tier context pressure.
func EvaluateContextPressure ¶ added in v0.0.7
func EvaluateContextPressure( usage *ContextUsage, policy ContextPressurePolicy, ) (*ContextPressureStatus, error)
EvaluateContextPressure evaluates usage against the configured multi-tier policy.
type ContextPressureTier ¶ added in v0.0.7
type ContextPressureTier string
ContextPressureTier identifies the highest currently exceeded context-pressure tier.
const ( ContextPressureTierNormal ContextPressureTier = "normal" ContextPressureTierWarning ContextPressureTier = "warning" ContextPressureTierError ContextPressureTier = "error" ContextPressureTierAutoCompact ContextPressureTier = "auto_compact" ContextPressureTierBlocking ContextPressureTier = "blocking" )
type ContextPromptSection ¶ added in v0.0.7
type ContextPromptSection = protocol.ContextPromptSection
ContextPromptSection describes one prompt section in context usage.
type ContextSkillFrontmatter ¶ added in v0.0.7
type ContextSkillFrontmatter = protocol.ContextSkillFrontmatter
ContextSkillFrontmatter describes one skill frontmatter entry in context usage.
type ContextSkills ¶ added in v0.0.7
type ContextSkills = protocol.ContextSkills
ContextSkills describes aggregate skill usage in context usage.
type ContextSlashCommands ¶ added in v0.0.7
type ContextSlashCommands = protocol.ContextSlashCommands
ContextSlashCommands describes slash command usage in context usage.
type ContextSystemTool ¶ added in v0.0.7
type ContextSystemTool = protocol.ContextSystemTool
ContextSystemTool describes one system tool in context usage.
type ContextThresholdStatus ¶ added in v0.0.7
type ContextThresholdStatus struct {
ThresholdPercentage float64
CurrentPercentage float64
Exceeded bool
TotalTokens int
MaxTokens int
RemainingTokens int
RemainingPercentage float64
Usage *ContextUsage
}
ContextThresholdStatus summarizes whether current context usage has crossed a threshold.
func EvaluateContextThreshold ¶ added in v0.0.7
func EvaluateContextThreshold( usage *ContextUsage, thresholdPercentage float64, ) (*ContextThresholdStatus, error)
EvaluateContextThreshold evaluates a single context-usage sample against a threshold.
type ContextThresholdWatcher ¶ added in v0.0.7
type ContextThresholdWatcher struct {
// contains filtered or unexported fields
}
ContextThresholdWatcher tracks threshold crossings across repeated usage samples.
func NewContextThresholdWatcher ¶ added in v0.0.7
func NewContextThresholdWatcher(thresholdPercentage float64) (*ContextThresholdWatcher, error)
NewContextThresholdWatcher creates a watcher for the given percentage threshold.
func (*ContextThresholdWatcher) Observe ¶ added in v0.0.7
func (w *ContextThresholdWatcher) Observe( usage *ContextUsage, ) (*ContextThresholdStatus, bool, error)
Observe evaluates usage and reports whether the watcher just crossed the threshold.
type ContextToolCallBreakdown ¶ added in v0.0.7
type ContextToolCallBreakdown = protocol.ContextToolCallBreakdown
ContextToolCallBreakdown describes one tool-call usage bucket.
type ContextUsage ¶ added in v0.0.7
type ContextUsage = protocol.ContextUsage
ContextUsage describes the current context-window usage breakdown.
type CostSnapshot ¶ added in v0.0.7
type CostSnapshot struct {
TotalCostUSD float64
ModelUsage map[string]ModelUsage
Results int
TotalDurationMs int
TotalDurationAPIMs int
TotalTurns int
TotalInputTokens int
TotalOutputTokens int
TotalCacheReadInputTokens int
TotalCacheCreateInputTokens int
TotalWebSearchRequests int
}
CostSnapshot contains accumulated per-model usage and terminal result metrics.
func LoadSessionCost ¶ added in v0.0.7
func LoadSessionCost(sessionID string, options SessionCostOptions) (*CostSnapshot, error)
LoadSessionCost reads a persisted session-cost snapshot from Claude home.
type CostTracker ¶ added in v0.0.7
type CostTracker struct {
// contains filtered or unexported fields
}
CostTracker accumulates model usage and result metrics across terminal results.
func NewCostTracker ¶ added in v0.0.7
func NewCostTracker() *CostTracker
NewCostTracker creates an empty cost tracker.
func (*CostTracker) CostSummary ¶ added in v0.0.7
func (t *CostTracker) CostSummary() turncomplete.CostSummary
CostSummary returns the current aggregate cost summary in turn-complete shape.
func (*CostTracker) LoadSessionCost ¶ added in v0.0.7
func (t *CostTracker) LoadSessionCost(sessionID, claudeHome string) error
LoadSessionCost merges a previously persisted session-cost snapshot into the tracker. Loading the same session ID multiple times is a no-op.
func (*CostTracker) Observe ¶ added in v0.0.7
func (t *CostTracker) Observe(msg Message)
Observe records usage from a typed message.
func (*CostTracker) ObserveResult ¶ added in v0.0.7
func (t *CostTracker) ObserveResult(result *ResultMessage)
ObserveResult records usage from a terminal result.
func (*CostTracker) SaveSessionCost ¶ added in v0.0.7
func (t *CostTracker) SaveSessionCost(sessionID, claudeHome string) error
SaveSessionCost persists the tracker's current snapshot for the given session ID.
func (*CostTracker) Snapshot ¶ added in v0.0.7
func (t *CostTracker) Snapshot() CostSnapshot
Snapshot returns a copy of the accumulated usage.
type CwdChangedHookInput ¶ added in v0.0.7
type CwdChangedHookInput = hook.CwdChangedInput
CwdChangedHookInput is the input for CwdChanged hooks.
type CwdChangedHookSpecificOutput ¶ added in v0.0.7
type CwdChangedHookSpecificOutput = hook.CwdChangedSpecificOutput
CwdChangedHookSpecificOutput is the hook-specific output for CwdChanged.
type DeleteSessionOptions ¶ added in v0.0.6
DeleteSessionOptions controls DeleteSession behavior.
type ElicitationAction ¶ added in v0.0.7
type ElicitationAction = elicitation.Action
ElicitationAction identifies the SDK consumer's elicitation decision.
type ElicitationCallback ¶ added in v0.0.7
type ElicitationCallback = elicitation.Callback
ElicitationCallback handles MCP elicitation requests.
type ElicitationCompleteCallback ¶ added in v0.0.7
type ElicitationCompleteCallback = elicitation.CompleteCallback
ElicitationCompleteCallback handles completion notifications for prior elicitation requests.
type ElicitationCompleteMessage ¶ added in v0.0.7
type ElicitationCompleteMessage = message.ElicitationCompleteMessage
ElicitationCompleteMessage reports an MCP elicitation completion event.
type ElicitationHookInput ¶ added in v0.0.7
type ElicitationHookInput = hook.ElicitationInput
ElicitationHookInput is the input for Elicitation hooks.
type ElicitationHookSpecificOutput ¶ added in v0.0.7
type ElicitationHookSpecificOutput = hook.ElicitationSpecificOutput
ElicitationHookSpecificOutput is the hook-specific output for Elicitation.
type ElicitationMode ¶ added in v0.0.7
type ElicitationMode = elicitation.Mode
ElicitationMode identifies the requested elicitation UX.
type ElicitationRequest ¶ added in v0.0.7
type ElicitationRequest = elicitation.Request
ElicitationRequest contains an MCP elicitation request.
type ElicitationResponse ¶ added in v0.0.7
type ElicitationResponse = elicitation.Response
ElicitationResponse contains an MCP elicitation response.
type ElicitationResultHookInput ¶ added in v0.0.7
type ElicitationResultHookInput = hook.ElicitationResultInput
ElicitationResultHookInput is the input for ElicitationResult hooks.
type ElicitationResultHookSpecificOutput ¶ added in v0.0.7
type ElicitationResultHookSpecificOutput = hook.ElicitationResultSpecificOutput
ElicitationResultHookSpecificOutput is the hook-specific output for ElicitationResult.
type ErrorClass ¶ added in v0.0.7
type ErrorClass string
ErrorClass identifies a classified SDK-visible failure mode.
const ( ErrorClassUnknown ErrorClass = "unknown" ErrorClassPromptTooLong ErrorClass = "prompt_too_long" ErrorClassMediaTooLarge ErrorClass = "media_too_large" ErrorClassRateLimit ErrorClass = "rate_limit" ErrorClassOverload ErrorClass = "overload" ErrorClassAuthentication ErrorClass = "authentication" ErrorClassBilling ErrorClass = "billing" ErrorClassExecution ErrorClass = "execution" )
type ErrorClassification ¶ added in v0.0.7
type ErrorClassification struct {
Class ErrorClass
SubClass ErrorSubClass
RecoveryAction RecoveryAction
Retryable bool
HTTPStatus *int
RetryAfterSeconds *float64
PromptTooLong *PromptTooLongDetails
Messages []string
}
ErrorClassification summarizes a classified failure.
func ClassifyAPIRetry ¶ added in v0.0.7
func ClassifyAPIRetry(msg *APIRetryMessage) ErrorClassification
ClassifyAPIRetry classifies an API retry event.
func ClassifyResultError ¶ added in v0.0.7
func ClassifyResultError(result *ResultMessage) ErrorClassification
ClassifyResultError classifies terminal result errors.
type ErrorSubClass ¶ added in v0.0.7
type ErrorSubClass string
ErrorSubClass identifies finer-grained actionable failure modes.
const ( ErrorSubClassNone ErrorSubClass = "" ErrorSubClassPDFPasswordProtected ErrorSubClass = "pdf_password_protected" ErrorSubClassToolUseMismatch ErrorSubClass = "tool_use_mismatch" ErrorSubClassDuplicateToolUseID ErrorSubClass = "duplicate_tool_use_id" ErrorSubClassInvalidModel ErrorSubClass = "invalid_model" ErrorSubClassSSLCertError ErrorSubClass = "ssl_cert_error" ErrorSubClassTokenRevoked ErrorSubClass = "token_revoked" ErrorSubClassCapacityOffSwitch ErrorSubClass = "capacity_off_switch" ErrorSubClassMaxOutputTokens ErrorSubClass = "max_output_tokens" )
type FastModeSnapshot ¶ added in v0.0.7
type FastModeSnapshot struct {
Current *FastModeState
Previous *FastModeState
LastTransitionReason *FastModeTransitionReason
LastRetryDelayMs *int
LastErrorStatus *int
}
FastModeSnapshot summarizes observed fast-mode state.
type FastModeState ¶ added in v0.0.7
FastModeState describes the current fast-mode state.
type FastModeTracker ¶ added in v0.0.7
type FastModeTracker struct {
// contains filtered or unexported fields
}
FastModeTracker observes fast-mode related messages and derives host-facing state.
func NewFastModeTracker ¶ added in v0.0.7
func NewFastModeTracker() *FastModeTracker
NewFastModeTracker creates an empty fast-mode tracker.
func (*FastModeTracker) Observe ¶ added in v0.0.7
func (t *FastModeTracker) Observe(msg Message)
Observe records fast-mode signals from typed messages.
func (*FastModeTracker) Snapshot ¶ added in v0.0.7
func (t *FastModeTracker) Snapshot() FastModeSnapshot
Snapshot returns a copy of the observed fast-mode state.
type FastModeTransitionReason ¶ added in v0.0.7
type FastModeTransitionReason string
FastModeTransitionReason identifies why the tracker changed state.
const ( FastModeTransitionReasonInit FastModeTransitionReason = "init" FastModeTransitionReasonResult FastModeTransitionReason = "result" FastModeTransitionReasonRateLimit FastModeTransitionReason = "rate_limit" FastModeTransitionReasonRetry FastModeTransitionReason = "api_retry" )
type FileChangedHookInput ¶ added in v0.0.7
type FileChangedHookInput = hook.FileChangedInput
FileChangedHookInput is the input for FileChanged hooks.
type FileChangedHookSpecificOutput ¶ added in v0.0.7
type FileChangedHookSpecificOutput = hook.FileChangedSpecificOutput
FileChangedHookSpecificOutput is the hook-specific output for FileChanged.
type FilesPersistedFailure ¶ added in v0.0.7
type FilesPersistedFailure = message.FilesPersistedFailure
FilesPersistedFailure describes a failed file persistence result.
type FilesPersistedFile ¶ added in v0.0.7
type FilesPersistedFile = message.FilesPersistedFile
FilesPersistedFile describes a persisted file result.
type FilesPersistedMessage ¶ added in v0.0.7
type FilesPersistedMessage = message.FilesPersistedMessage
FilesPersistedMessage reports persisted file IDs.
type ForkSessionOptions ¶ added in v0.0.6
type ForkSessionOptions struct {
Directory string
ClaudeHome string
UpToMessageID string
Title string
}
ForkSessionOptions controls ForkSession behavior.
type ForkSessionResult ¶ added in v0.0.6
type ForkSessionResult struct {
SessionID string
}
ForkSessionResult contains the result of a ForkSession operation.
func ForkSession ¶ added in v0.0.6
func ForkSession(sessionID string, options ForkSessionOptions) (*ForkSessionResult, error)
ForkSession creates a new session from an existing one, remapping all UUIDs and optionally truncating at a specific message.
type GetSessionInfoOptions ¶ added in v0.0.6
GetSessionInfoOptions controls GetSessionInfo behavior.
type HookCallback ¶
HookCallback is the function signature for hook callbacks.
type HookJSONOutput ¶
type HookJSONOutput = hook.JSONOutput
HookJSONOutput is the interface for hook output types.
type HookMatcher ¶
HookMatcher configures which tools/events a hook applies to.
type HookProgressMessage ¶ added in v0.0.7
type HookProgressMessage = message.HookProgressMessage
HookProgressMessage reports hook progress output.
type HookResponseMessage ¶ added in v0.0.7
type HookResponseMessage = message.HookResponseMessage
HookResponseMessage reports the final result of an async hook.
type HookResponseOutcome ¶ added in v0.0.7
type HookResponseOutcome = message.HookResponseOutcome
HookResponseOutcome describes the final outcome of an async hook.
type HookSpecificOutput ¶
type HookSpecificOutput = hook.SpecificOutput
HookSpecificOutput is the interface for hook-specific outputs.
type HookStartedMessage ¶ added in v0.0.7
type HookStartedMessage = message.HookStartedMessage
HookStartedMessage reports the start of an async hook.
type InitMCPServerStatus ¶ added in v0.0.7
type InitMCPServerStatus = message.InitMCPServerStatus
InitMCPServerStatus describes one MCP server entry in an init message.
type InitMessage ¶ added in v0.0.7
type InitMessage = message.InitMessage
InitMessage represents the typed init system message.
type InitPluginInfo ¶ added in v0.0.7
type InitPluginInfo = message.InitPluginInfo
InitPluginInfo describes one plugin entry in an init message.
type InputDocumentBlock ¶ added in v0.0.5
type InputDocumentBlock = message.InputDocumentBlock
InputDocumentBlock contains an inline PDF document input for multimodal prompts.
func PDFFileInput ¶ added in v0.0.5
func PDFFileInput(path string) (*InputDocumentBlock, error)
PDFFileInput reads a local PDF file and returns an inline PDF document block.
func PDFInput ¶ added in v0.0.5
func PDFInput(data string) *InputDocumentBlock
PDFInput creates an inline PDF document block from base64 data.
type InputImageBlock ¶ added in v0.0.5
type InputImageBlock = message.InputImageBlock
InputImageBlock contains an inline image input for multimodal prompts.
func ImageFileInput ¶ added in v0.0.5
func ImageFileInput(path string) (*InputImageBlock, error)
ImageFileInput reads a local image file and returns an inline image block.
func ImageInput ¶ added in v0.0.5
func ImageInput(mediaType, data string) *InputImageBlock
ImageInput creates an inline image block from base64 data and media type.
type InstructionsLoadedHookInput ¶ added in v0.0.7
type InstructionsLoadedHookInput = hook.InstructionsLoadedInput
InstructionsLoadedHookInput is the input for InstructionsLoaded hooks.
type InterruptToolResultPolicy ¶ added in v0.0.7
type InterruptToolResultPolicy = config.InterruptToolResultPolicy
InterruptToolResultPolicy controls whether Client.Interrupt synthesizes unresolved tool_result blocks before sending the interrupt control request.
type LocalCommandOutputMessage ¶ added in v0.0.7
type LocalCommandOutputMessage = message.LocalCommandOutputMessage
LocalCommandOutputMessage reports output from a local slash command.
type MCPHTTPServerConfig ¶
type MCPHTTPServerConfig = mcp.HTTPServerConfig
MCPHTTPServerConfig configures an HTTP-based MCP server.
type MCPSSEServerConfig ¶
type MCPSSEServerConfig = mcp.SSEServerConfig
MCPSSEServerConfig configures a Server-Sent Events MCP server.
type MCPSdkServerConfig ¶
type MCPSdkServerConfig = mcp.SdkServerConfig
MCPSdkServerConfig configures an SDK-provided MCP server.
func CreateSdkMcpServer ¶
func CreateSdkMcpServer(name, version string, tools ...*SdkMcpTool) *MCPSdkServerConfig
CreateSdkMcpServer creates an in-process MCP server configuration with SdkMcpTool tools.
This function creates an MCP server that runs within your application, providing better performance than external MCP servers.
The returned config can be used directly in ClaudeAgentOptions.MCPServers:
addTool := claudesdk.NewSdkMcpTool("add", "Add two numbers",
claudesdk.SimpleSchema(map[string]string{"a": "float64", "b": "float64"}),
func(ctx context.Context, req *claudesdk.CallToolRequest) (*claudesdk.CallToolResult, error) {
args, _ := claudesdk.ParseArguments(req)
a, b := args["a"].(float64), args["b"].(float64)
return claudesdk.TextResult(fmt.Sprintf("Result: %v", a+b)), nil
},
)
calculator := claudesdk.CreateSdkMcpServer("calculator", "1.0.0", addTool)
options := &claudesdk.ClaudeAgentOptions{
MCPServers: map[string]claudesdk.MCPServerConfig{
"calculator": calculator,
},
AllowedTools: []string{"mcp__calculator__add"},
}
Parameters:
- name: Server name (also used as key in MCPServers map, determines tool naming: mcp__<name>__<toolName>)
- version: Server version string
- tools: SdkMcpTool instances to register with the server
type MCPServerConfig ¶
type MCPServerConfig = mcp.ServerConfig
MCPServerConfig is the interface for MCP server configurations.
type MCPServerConnectionStatus ¶ added in v0.0.2
type MCPServerConnectionStatus = mcp.ServerConnectionStatus
MCPServerConnectionStatus represents the connection state of an MCP server.
type MCPServerInfo ¶ added in v0.0.2
type MCPServerInfo = mcp.ServerInfo
MCPServerInfo describes server information returned from initialize.
type MCPServerStatus ¶
type MCPServerStatus = mcp.ServerStatus
MCPServerStatus represents the connection status of a single MCP server.
type MCPServerStatusConfig ¶ added in v0.0.2
type MCPServerStatusConfig = mcp.ServerStatusConfig
MCPServerStatusConfig captures the serializable server config included in status responses.
type MCPServerType ¶
type MCPServerType = mcp.ServerType
MCPServerType represents the type of MCP server.
type MCPSetServersResult ¶ added in v0.0.7
type MCPSetServersResult = protocol.MCPSetServersResult
MCPSetServersResult is the typed result of SetMCPServers.
type MCPStdioServerConfig ¶
type MCPStdioServerConfig = mcp.StdioServerConfig
MCPStdioServerConfig configures a stdio-based MCP server.
type MCPToolAnnotations ¶ added in v0.0.2
type MCPToolAnnotations = mcp.ToolAnnotations
MCPToolAnnotations describes MCP tool capability metadata.
type MCPToolInfo ¶ added in v0.0.2
MCPToolInfo describes an MCP tool exposed by a server.
type MCPWebSocketServerConfig ¶ added in v0.0.7
type MCPWebSocketServerConfig = mcp.WebSocketServerConfig
MCPWebSocketServerConfig configures a WebSocket-based MCP server.
type McpAudioContent ¶
type McpAudioContent = mcp.AudioContent
McpAudioContent represents audio content in a tool result.
type McpContent ¶
McpContent is the interface for content types in tool results.
type McpImageContent ¶
type McpImageContent = mcp.ImageContent
McpImageContent represents image content in a tool result.
type McpTextContent ¶
type McpTextContent = mcp.TextContent
McpTextContent represents text content in a tool result.
type McpToolAnnotations ¶
type McpToolAnnotations = mcp.ToolAnnotations
McpToolAnnotations describes optional hints about tool behavior. Fields include ReadOnlyHint, DestructiveHint, IdempotentHint, OpenWorldHint, and Title.
type McpToolHandler ¶
type McpToolHandler = mcp.ToolHandler
McpToolHandler is the function signature for low-level tool handlers.
type MessageParseError ¶
type MessageParseError = errors.MessageParseError
MessageParseError indicates message parsing failed.
type MessageStream ¶
type MessageStream = iter.Seq[StreamingMessage]
MessageStream is an iterator that yields streaming messages.
type Model ¶
Model holds metadata for a single Claude model.
func Models ¶
func Models() []Model
Models returns a copy of the SDK's static Claude model catalog. It is not a live list of models available to the logged-in Claude CLI user.
func ModelsByCostTier ¶
func ModelsByCostTier(tier ModelCostTier) []Model
ModelsByCostTier returns all models matching the given cost tier.
type ModelCapability ¶
type ModelCapability = models.Capability
ModelCapability represents a model capability such as vision or tool use.
type ModelCostTier ¶
ModelCostTier represents a provider-agnostic relative cost tier.
type ModelListResponse ¶ added in v0.0.2
type ModelListResponse = models.ListResponse
ModelListResponse is the response payload backing ListModels.
func ListModelsResponse ¶ added in v0.0.2
func ListModelsResponse(_ context.Context) (*ModelListResponse, error)
ListModelsResponse returns the full static model-list response payload.
type ModelUsage ¶ added in v0.0.7
type ModelUsage = message.ModelUsage
ModelUsage describes per-model token and cost usage for a terminal result.
type NotificationHookInput ¶
type NotificationHookInput = hook.NotificationInput
NotificationHookInput is the input for Notification hooks.
type NotificationHookSpecificOutput ¶
type NotificationHookSpecificOutput = hook.NotificationSpecificOutput
NotificationHookSpecificOutput is the hook-specific output for Notification.
type Option ¶
type Option func(*ClaudeAgentOptions)
Option configures ClaudeAgentOptions using the functional options pattern. This is the primary option type for configuring clients and queries.
func WithAddDirs ¶
WithAddDirs adds additional directories to make accessible.
func WithAgentProgressSummaries ¶ added in v0.0.7
WithAgentProgressSummaries enables background post-turn summaries.
func WithAgents ¶
func WithAgents(agents map[string]*AgentDefinition) Option
WithAgents defines custom agent configurations.
func WithAllowedTools ¶
WithAllowedTools sets pre-approved tools that can be used without prompting.
func WithAutoCompactPercentageOverride ¶ added in v0.0.7
WithAutoCompactPercentageOverride overrides the CLI auto-compaction percentage threshold.
func WithBlockingLimitOverride ¶ added in v0.0.7
WithBlockingLimitOverride overrides the CLI blocking-limit token threshold.
func WithCanUseTool ¶
func WithCanUseTool(callback ToolPermissionCallback) Option
WithCanUseTool sets a callback for permission checking before each tool use.
func WithClaudeHome ¶
WithClaudeHome overrides the Claude home directory (default: ~/.claude).
func WithCliPath ¶
WithCliPath sets the explicit path to the claude CLI binary. If not set, the CLI will be searched in PATH.
func WithContinueConversation ¶
WithContinueConversation indicates whether to continue an existing conversation.
func WithCostTracker ¶ added in v0.0.7
func WithCostTracker(tracker *CostTracker) Option
WithCostTracker attaches a result-cost tracker to the session lifecycle. When used with WithResume, the tracker automatically restores persisted cost state for the resumed session and saves updated totals after each terminal result.
func WithDisableAutoCompact ¶ added in v0.0.7
WithDisableAutoCompact disables automatic compaction in the CLI.
func WithDisableCompact ¶ added in v0.0.7
WithDisableCompact disables compaction in the CLI.
func WithDisallowedTools ¶
WithDisallowedTools sets tools that are explicitly blocked.
func WithEffort ¶
WithEffort sets the thinking effort level.
func WithEnableFileCheckpointing ¶
WithEnableFileCheckpointing enables file change tracking and rewinding.
func WithExtraArgs ¶
WithExtraArgs provides arbitrary CLI flags to pass to the CLI. If the value is nil, the flag is passed without a value (boolean flag).
func WithFallbackModel ¶
WithFallbackModel specifies a model to use if the primary model fails.
func WithFastMode ¶ added in v0.0.7
WithFastMode explicitly opts the SDK into fast mode for headless sessions.
func WithFastModeTracker ¶ added in v0.0.7
func WithFastModeTracker(tracker *FastModeTracker) Option
WithFastModeTracker attaches an observational fast-mode tracker to the session lifecycle.
func WithForkSession ¶
WithForkSession indicates whether to fork the resumed session to a new ID.
func WithHooks ¶
func WithHooks(hooks map[HookEvent][]*HookMatcher) Option
WithHooks configures event hooks for tool interception.
func WithIncludePartialMessages ¶
WithIncludePartialMessages enables streaming of partial message updates.
func WithInitializeTimeout ¶
WithInitializeTimeout sets the timeout for the initialize control request.
func WithInterruptToolResultPolicy ¶ added in v0.0.7
func WithInterruptToolResultPolicy(policy InterruptToolResultPolicy) Option
WithInterruptToolResultPolicy controls whether Client.Interrupt synthesizes unresolved tool_result blocks before sending the interrupt control request.
func WithLogger ¶
WithLogger sets the logger for debug output. If not set, logging is disabled (silent operation).
func WithMCPConfig ¶
WithMCPConfig sets a path to an MCP config file or a raw JSON string. If set, this takes precedence over WithMCPServers.
func WithMCPServers ¶
func WithMCPServers(servers map[string]MCPServerConfig) Option
WithMCPServers configures external MCP servers to connect to. Map key is the server name, value is the server configuration.
func WithMaxBudgetUSD ¶
WithMaxBudgetUSD sets a cost limit for the session in USD.
func WithMaxBufferSize ¶
WithMaxBufferSize sets the maximum bytes for CLI stdout buffering.
func WithMaxToolUseConcurrency ¶ added in v0.0.7
WithMaxToolUseConcurrency overrides the CLI tool-use concurrency limit.
func WithMaxTurns ¶
WithMaxTurns limits the maximum number of conversation turns.
func WithOnElicitation ¶ added in v0.0.7
func WithOnElicitation(callback ElicitationCallback) Option
WithOnElicitation sets a callback for handling MCP elicitation requests.
func WithOnElicitationComplete ¶ added in v0.0.7
func WithOnElicitationComplete(callback ElicitationCompleteCallback) Option
WithOnElicitationComplete sets a callback for elicitation completion notifications.
func WithOnPrompt ¶ added in v0.0.7
func WithOnPrompt(callback PromptCallback) Option
WithOnPrompt sets a callback for handling generic prompt request/response dialogs.
func WithOnTurnComplete ¶ added in v0.0.7
func WithOnTurnComplete(callback TurnCompleteCallback) Option
WithOnTurnComplete sets a callback invoked after each terminal result.
func WithOnUserInput ¶
func WithOnUserInput(callback UserInputCallback) Option
WithOnUserInput sets a callback for handling AskUserQuestion prompts.
func WithOutputFormat ¶
WithOutputFormat specifies a JSON schema for structured output.
The canonical format uses a wrapper object:
claudesdk.WithOutputFormat(map[string]any{
"type": "json_schema",
"schema": map[string]any{
"type": "object",
"properties": map[string]any{...},
"required": []string{...},
},
})
Raw JSON schemas (without the wrapper) are also accepted and auto-wrapped:
claudesdk.WithOutputFormat(map[string]any{
"type": "object",
"properties": map[string]any{...},
"required": []string{...},
})
Structured output is available on ResultMessage.StructuredOutput (parsed) or ResultMessage.Result (JSON string).
func WithPermissionMode ¶
WithPermissionMode controls how permissions are handled. Valid values: "default", "acceptEdits", "plan", "auto", "dontAsk", "bypassPermissions".
func WithPermissionPromptToolName ¶
WithPermissionPromptToolName specifies the tool name to use for permission prompts.
func WithPersistPermissions ¶ added in v0.0.7
WithPersistPermissions stores SDK-managed permission rules on disk and reapplies them across future sessions before the permission callback runs.
func WithPlugins ¶
func WithPlugins(plugins ...*SdkPluginConfig) Option
WithPlugins configures plugins to load.
func WithPromptSuggestions ¶ added in v0.0.7
WithPromptSuggestions enables prompt_suggestion messages after each turn.
func WithResume ¶
WithResume sets a session ID to resume from.
func WithSDKTools ¶
WithSDKTools registers high-level Tool instances as an in-process MCP server. Tools are exposed under the "sdk" MCP server name (tool names: mcp__sdk__<name>). Each tool is automatically added to AllowedTools.
func WithSandboxSettings ¶
func WithSandboxSettings(settings *SandboxSettings) Option
WithSandboxSettings configures CLI sandbox behavior.
func WithSettingSources ¶
func WithSettingSources(sources ...SettingSource) Option
WithSettingSources specifies which setting sources to use.
func WithSettings ¶
WithSettings sets the path to a settings file to load.
func WithStderr ¶
WithStderr sets a callback function for handling stderr output.
func WithSystemPrompt ¶
WithSystemPrompt sets the system message to send to Claude.
func WithSystemPromptFile ¶ added in v0.0.6
WithSystemPromptFile sets the path to a file containing the system prompt. Precedence: WithSystemPromptPreset > WithSystemPromptFile > WithSystemPrompt.
func WithSystemPromptPreset ¶
func WithSystemPromptPreset(preset *SystemPromptPreset) Option
WithSystemPromptPreset sets a preset system prompt configuration. If set, this takes precedence over WithSystemPrompt and WithSystemPromptFile.
func WithTaskBudget ¶ added in v0.0.6
WithTaskBudget sets the total task budget (token count) for the session.
func WithThinking ¶
func WithThinking(thinking config.ThinkingConfig) Option
WithThinking sets the thinking configuration.
func WithTools ¶
func WithTools(tools config.ToolsConfig) Option
WithTools specifies which tools are available. Accepts ToolsList (tool names) or *ToolsPreset.
func WithTransport ¶
WithTransport injects a custom transport implementation. The transport must implement the Transport interface.
func WithUnattendedRetry ¶ added in v0.0.7
WithUnattendedRetry opts the CLI into its unattended retry mode.
type PermissionBehavior ¶
type PermissionBehavior = permission.Behavior
PermissionBehavior represents the permission behavior for a rule.
type PermissionDecisionClassification ¶ added in v0.0.7
type PermissionDecisionClassification = permission.DecisionClassification
PermissionDecisionClassification classifies how a permission decision was reached.
type PermissionDecisionReasonType ¶ added in v0.0.7
type PermissionDecisionReasonType = permission.DecisionReasonType
PermissionDecisionReasonType identifies the structured source of a permission decision.
type PermissionDenial ¶ added in v0.0.7
type PermissionDenial = message.PermissionDenial
PermissionDenial describes one denied tool attempt captured in the result.
type PermissionDeniedHookInput ¶ added in v0.0.7
type PermissionDeniedHookInput = hook.PermissionDeniedInput
PermissionDeniedHookInput is the input for PermissionDenied hooks.
type PermissionDeniedHookSpecificOutput ¶ added in v0.0.7
type PermissionDeniedHookSpecificOutput = hook.PermissionDeniedSpecificOutput
PermissionDeniedHookSpecificOutput is the hook-specific output for PermissionDenied.
type PermissionMode ¶
type PermissionMode = permission.Mode
PermissionMode represents different permission handling modes.
type PermissionRequestHookInput ¶
type PermissionRequestHookInput = hook.PermissionRequestInput
PermissionRequestHookInput is the input for PermissionRequest hooks.
type PermissionRequestHookSpecificOutput ¶
type PermissionRequestHookSpecificOutput = hook.PermissionRequestSpecificOutput
PermissionRequestHookSpecificOutput is the hook-specific output for PermissionRequest.
type PermissionResult ¶
type PermissionResult = permission.Result
PermissionResult is the interface for permission decision results.
type PermissionResultAllow ¶
type PermissionResultAllow = permission.ResultAllow
PermissionResultAllow represents an allow decision.
type PermissionResultDeny ¶
type PermissionResultDeny = permission.ResultDeny
PermissionResultDeny represents a deny decision.
type PermissionRuleValue ¶
type PermissionRuleValue = permission.RuleValue
PermissionRuleValue represents a permission rule.
type PermissionUpdate ¶
type PermissionUpdate = permission.Update
PermissionUpdate represents a permission update request.
type PermissionUpdateDestination ¶
type PermissionUpdateDestination = permission.UpdateDestination
PermissionUpdateDestination represents where permission updates are stored.
type PermissionUpdateType ¶
type PermissionUpdateType = permission.UpdateType
PermissionUpdateType represents the type of permission update.
type PluginInfo ¶ added in v0.0.7
type PluginInfo = protocol.PluginInfo
PluginInfo describes a plugin returned by ReloadPlugins.
type PostCompactHookInput ¶ added in v0.0.7
type PostCompactHookInput = hook.PostCompactInput
PostCompactHookInput is the input for PostCompact hooks.
type PostToolUseFailureHookInput ¶
type PostToolUseFailureHookInput = hook.PostToolUseFailureInput
PostToolUseFailureHookInput is the input for PostToolUseFailure hooks.
type PostToolUseFailureHookSpecificOutput ¶
type PostToolUseFailureHookSpecificOutput = hook.PostToolUseFailureSpecificOutput
PostToolUseFailureHookSpecificOutput is the hook-specific output for PostToolUseFailure.
type PostToolUseHookInput ¶
type PostToolUseHookInput = hook.PostToolUseInput
PostToolUseHookInput is the input for PostToolUse hooks.
type PostToolUseHookSpecificOutput ¶
type PostToolUseHookSpecificOutput = hook.PostToolUseSpecificOutput
PostToolUseHookSpecificOutput is the hook-specific output for PostToolUse.
type PostTurnSummaryMessage ¶ added in v0.0.7
type PostTurnSummaryMessage = message.PostTurnSummaryMessage
PostTurnSummaryMessage reports a background turn summary.
type PreCompactHookInput ¶
type PreCompactHookInput = hook.PreCompactInput
PreCompactHookInput is the input for PreCompact hooks.
type PreToolUseHookInput ¶
type PreToolUseHookInput = hook.PreToolUseInput
PreToolUseHookInput is the input for PreToolUse hooks.
type PreToolUseHookSpecificOutput ¶
type PreToolUseHookSpecificOutput = hook.PreToolUseSpecificOutput
PreToolUseHookSpecificOutput is the hook-specific output for PreToolUse.
type PreservedSegmentIndex ¶ added in v0.0.7
type PreservedSegmentIndex struct {
// contains filtered or unexported fields
}
PreservedSegmentIndex tracks preserved-segment relinks across compact boundaries.
func NewPreservedSegmentIndex ¶ added in v0.0.7
func NewPreservedSegmentIndex() *PreservedSegmentIndex
NewPreservedSegmentIndex creates an empty preserved-segment index.
func (*PreservedSegmentIndex) Observe ¶ added in v0.0.7
func (i *PreservedSegmentIndex) Observe(msg Message)
Observe records compact-boundary metadata from a typed message.
func (*PreservedSegmentIndex) Relinked ¶ added in v0.0.7
func (i *PreservedSegmentIndex) Relinked(sessionID, left, right string) bool
Relinked reports whether two UUIDs are part of the same preserved segment.
func (*PreservedSegmentIndex) Resolve ¶ added in v0.0.7
func (i *PreservedSegmentIndex) Resolve(sessionID, uuid string) string
Resolve returns the anchor UUID when the given UUID belongs to a preserved segment.
func (*PreservedSegmentIndex) Segments ¶ added in v0.0.7
func (i *PreservedSegmentIndex) Segments(sessionID string) []PreservedSegmentRecord
Segments returns the preserved segments observed for a session.
type PreservedSegmentRecord ¶ added in v0.0.7
type PreservedSegmentRecord struct {
SessionID string
BoundaryUUID string
Trigger string
PreTokens int
HeadUUID string
AnchorUUID string
TailUUID string
}
PreservedSegmentRecord captures one compaction-preserved UUID chain.
type ProcessError ¶
type ProcessError = errors.ProcessError
ProcessError indicates the CLI process failed.
type PromptCallback ¶ added in v0.0.7
PromptCallback handles generic CLI prompt request/response dialogs.
type PromptRequest ¶ added in v0.0.7
PromptRequest represents a generic CLI prompt request.
type PromptRequestOption ¶ added in v0.0.7
PromptRequestOption represents one selectable option in a CLI prompt request.
type PromptResponse ¶ added in v0.0.7
PromptResponse represents the selected answer for a prompt request.
type PromptSuggestionMessage ¶ added in v0.0.7
type PromptSuggestionMessage = message.PromptSuggestionMessage
PromptSuggestionMessage reports a predicted next prompt.
type PromptTooLongDetails ¶ added in v0.0.7
PromptTooLongDetails contains best-effort token-limit extraction.
type RateLimitEvent ¶ added in v0.0.6
type RateLimitEvent = message.RateLimitEvent
RateLimitEvent represents a rate limit event from the Claude CLI.
type RateLimitInfo ¶ added in v0.0.6
type RateLimitInfo = message.RateLimitInfo
RateLimitInfo contains detailed information about a rate limit check.
type RateLimitOverageDisabledReason ¶ added in v0.0.7
type RateLimitOverageDisabledReason = message.RateLimitOverageDisabledReason
RateLimitOverageDisabledReason identifies why overage is unavailable.
type RateLimitStatus ¶ added in v0.0.6
type RateLimitStatus = message.RateLimitStatus
RateLimitStatus represents the status of a rate limit check.
type RateLimitType ¶ added in v0.0.6
type RateLimitType = message.RateLimitType
RateLimitType represents the type of rate limit window.
type RawStreamEvent ¶ added in v0.0.7
type RawStreamEvent = message.RawStreamEvent
RawStreamEvent preserves the provider-native Anthropic stream event payload.
type ReasoningEffortOption ¶ added in v0.0.2
type ReasoningEffortOption = models.ReasoningEffortOption
ReasoningEffortOption describes a selectable reasoning effort level.
type RecoveryAction ¶ added in v0.0.7
type RecoveryAction string
RecoveryAction identifies the SDK's best-effort recommended next step.
const ( RecoveryActionNone RecoveryAction = "none" RecoveryActionCompact RecoveryAction = "compact" RecoveryActionStripMedia RecoveryAction = "strip_media" RecoveryActionEscalateOutputTokens RecoveryAction = "escalate_output_tokens" RecoveryActionRetryWithBackoff RecoveryAction = "retry_with_backoff" RecoveryActionSwitchModel RecoveryAction = "switch_model" RecoveryActionRefreshAuth RecoveryAction = "refresh_auth" )
type RecoveryOrchestrator ¶ added in v0.0.7
type RecoveryOrchestrator struct {
// contains filtered or unexported fields
}
RecoveryOrchestrator plans host-side retries and safe content/model adjustments.
func MustNewRecoveryOrchestrator ¶ added in v0.0.7
func MustNewRecoveryOrchestrator(options RecoveryOrchestratorOptions) *RecoveryOrchestrator
MustNewRecoveryOrchestrator is a convenience helper for examples/tests.
func NewRecoveryOrchestrator ¶ added in v0.0.7
func NewRecoveryOrchestrator(options RecoveryOrchestratorOptions) *RecoveryOrchestrator
NewRecoveryOrchestrator creates a host-side recovery planner.
func (*RecoveryOrchestrator) PlanResult ¶ added in v0.0.7
func (o *RecoveryOrchestrator) PlanResult( result *ResultMessage, content UserMessageContent, options *ClaudeAgentOptions, attempt int, ) RecoveryPlan
PlanResult returns the next recovery step for a terminal result.
type RecoveryOrchestratorOptions ¶ added in v0.0.7
type RecoveryOrchestratorOptions struct {
RetryPolicy RetryPolicy
MaxAttempts int
EnableMediaStrip bool
EnableFallbackSwitch bool
}
RecoveryOrchestratorOptions configure host-side recovery planning.
type RecoveryPlan ¶ added in v0.0.7
type RecoveryPlan struct {
Attempt int
MaxAttempts int
Classification ErrorClassification
Retry bool
Delay time.Duration
Action RecoveryAction
Reason string
Content UserMessageContent
ContentChanged bool
OverrideModel *string
}
RecoveryPlan summarizes the next recovery step after a failed result.
func (RecoveryPlan) Validate ¶ added in v0.0.7
func (p RecoveryPlan) Validate() error
Validate ensures the recovery plan is internally consistent.
type ReloadPluginsResult ¶ added in v0.0.7
type ReloadPluginsResult = protocol.ReloadPluginsResult
ReloadPluginsResult is the typed result of ReloadPlugins.
type RenameSessionOptions ¶ added in v0.0.6
RenameSessionOptions controls RenameSession behavior.
type ResultMessage ¶
type ResultMessage = message.ResultMessage
ResultMessage represents the final result of a query.
type ResultSubtype ¶ added in v0.0.7
type ResultSubtype = message.ResultSubtype
ResultSubtype identifies the terminal result reason.
type RetryClass ¶ added in v0.0.7
type RetryClass string
RetryClass identifies the host-facing retry bucket for a failure.
const ( RetryClassUnknown RetryClass = "unknown" RetryClassRateLimit RetryClass = "rate_limit" RetryClassOverload RetryClass = "overload" RetryClassTransientConnection RetryClass = "transient_connection" RetryClassPromptTooLong RetryClass = "prompt_too_long" RetryClassMediaTooLarge RetryClass = "media_too_large" RetryClassAuthentication RetryClass = "authentication" RetryClassBilling RetryClass = "billing" RetryClassExecution RetryClass = "execution" )
type RetryDecision ¶ added in v0.0.7
type RetryDecision struct {
Class RetryClass
Action RetryDecisionAction
Retryable bool
RecommendedDelay time.Duration
Attempt int
MaxRetries int
Reason string
}
RetryDecision summarizes host-side retry guidance for a classified failure.
func EvaluateResultRetry ¶ added in v0.0.7
func EvaluateResultRetry(result *ResultMessage, attempt int, policy RetryPolicy) RetryDecision
EvaluateResultRetry evaluates retry guidance for a terminal result failure.
func EvaluateRetry ¶ added in v0.0.7
func EvaluateRetry(msg *APIRetryMessage, policy RetryPolicy) RetryDecision
EvaluateRetry evaluates retry guidance for an API retry event.
type RetryDecisionAction ¶ added in v0.0.7
type RetryDecisionAction string
RetryDecisionAction describes the recommended host action.
const ( RetryDecisionActionRetry RetryDecisionAction = "retry" RetryDecisionActionStop RetryDecisionAction = "stop" )
type RetryPolicy ¶ added in v0.0.7
type RetryPolicy struct {
MaxRetries int
BaseDelay time.Duration
MaxDelay time.Duration
JitterRatio float64
MaxConsecutiveOverloadRetries int
}
RetryPolicy defines host-side retry guidance defaults.
func DefaultRetryPolicy ¶ added in v0.0.7
func DefaultRetryPolicy() RetryPolicy
DefaultRetryPolicy returns source-aligned retry defaults used for host guidance.
type RewindFilesResult ¶ added in v0.0.7
type RewindFilesResult = protocol.RewindFilesResult
RewindFilesResult reports the outcome of a rewind_files control request.
type SDKSessionInfo ¶ added in v0.0.2
type SDKSessionInfo struct {
SessionID string `json:"session_id"`
Summary string `json:"summary"`
LastModified int64 `json:"last_modified"`
FileSize int64 `json:"file_size"`
CustomTitle *string `json:"custom_title,omitempty"`
FirstPrompt *string `json:"first_prompt,omitempty"`
GitBranch *string `json:"git_branch,omitempty"`
Cwd *string `json:"cwd,omitempty"`
Tag *string `json:"tag,omitempty"`
CreatedAt *int64 `json:"created_at,omitempty"`
}
SDKSessionInfo contains metadata for a persisted Claude session.
func GetSessionInfo ¶ added in v0.0.6
func GetSessionInfo(sessionID string, options GetSessionInfoOptions) (*SDKSessionInfo, error)
GetSessionInfo returns metadata for a single session by ID. Uses the lite reader (head/tail) for efficient metadata extraction.
func ListSessions ¶ added in v0.0.2
func ListSessions(options SessionListOptions) []SDKSessionInfo
ListSessions lists Claude sessions for a project or across all projects.
type SandboxIgnoreViolations ¶
type SandboxIgnoreViolations = sandbox.IgnoreViolations
SandboxIgnoreViolations configures which violations to ignore.
type SandboxNetworkConfig ¶
type SandboxNetworkConfig = sandbox.NetworkConfig
SandboxNetworkConfig configures network access for the sandbox.
type SandboxSettings ¶
SandboxSettings configures CLI sandbox behavior.
type Schema ¶
type Schema = jsonschema.Schema
Schema is a JSON Schema object for tool input validation.
type SdkMcpServerInstance ¶
type SdkMcpServerInstance = mcp.ServerInstance
SdkMcpServerInstance is the interface that SDK MCP servers must implement.
type SdkMcpTool ¶
type SdkMcpTool struct {
ToolName string
ToolDescription string
ToolSchema *jsonschema.Schema
ToolHandler SdkMcpToolHandler
ToolAnnotations *mcp.ToolAnnotations
}
SdkMcpTool represents a tool created with NewSdkMcpTool.
func NewSdkMcpTool ¶
func NewSdkMcpTool( name, description string, inputSchema *jsonschema.Schema, handler SdkMcpToolHandler, opts ...SdkMcpToolOption, ) *SdkMcpTool
NewSdkMcpTool creates an SdkMcpTool with optional configuration.
The inputSchema should be a *jsonschema.Schema. Use SimpleSchema for convenience or create a full Schema struct for more control.
Use WithAnnotations to set MCP tool annotations (hints about tool behavior).
Example with SimpleSchema:
addTool := claudesdk.NewSdkMcpTool("add", "Add two numbers",
claudesdk.SimpleSchema(map[string]string{"a": "float64", "b": "float64"}),
func(ctx context.Context, req *claudesdk.CallToolRequest) (*claudesdk.CallToolResult, error) {
args, _ := claudesdk.ParseArguments(req)
a, b := args["a"].(float64), args["b"].(float64)
return claudesdk.TextResult(fmt.Sprintf("Result: %v", a+b)), nil
},
claudesdk.WithAnnotations(&claudesdk.McpToolAnnotations{
ReadOnlyHint: true,
}),
)
func (*SdkMcpTool) Annotations ¶
func (t *SdkMcpTool) Annotations() *mcp.ToolAnnotations
Annotations returns the tool annotations, or nil if not set.
func (*SdkMcpTool) Description ¶
func (t *SdkMcpTool) Description() string
Description returns the tool description.
func (*SdkMcpTool) Handler ¶
func (t *SdkMcpTool) Handler() SdkMcpToolHandler
Handler returns the tool handler function.
func (*SdkMcpTool) InputSchema ¶
func (t *SdkMcpTool) InputSchema() *jsonschema.Schema
InputSchema returns the JSON Schema for the tool input.
type SdkMcpToolHandler ¶
type SdkMcpToolHandler = mcp.ToolHandler
SdkMcpToolHandler is the function signature for SdkMcpTool handlers. It receives the context and request, and returns the result.
Use ParseArguments to extract input as map[string]any from the request. Use TextResult, ErrorResult, or ImageResult helpers to create results.
Example:
func(ctx context.Context, req *claudesdk.CallToolRequest) (*claudesdk.CallToolResult, error) {
args, err := claudesdk.ParseArguments(req)
if err != nil {
return claudesdk.ErrorResult(err.Error()), nil
}
a := args["a"].(float64)
return claudesdk.TextResult(fmt.Sprintf("Result: %v", a)), nil
}
type SdkMcpToolOption ¶
type SdkMcpToolOption func(*SdkMcpTool)
SdkMcpToolOption configures an SdkMcpTool during construction.
func WithAnnotations ¶
func WithAnnotations(annotations *mcp.ToolAnnotations) SdkMcpToolOption
WithAnnotations sets MCP tool annotations (hints about tool behavior). Annotations describe properties like whether a tool is read-only, destructive, idempotent, or operates in an open world.
type SdkPluginConfig ¶
type SdkPluginConfig = config.PluginConfig
SdkPluginConfig configures a plugin to load.
type ServerInfo ¶ added in v0.0.7
type ServerInfo = protocol.ServerInfo
ServerInfo contains typed initialize metadata returned by the CLI.
type SessionCostOptions ¶ added in v0.0.7
type SessionCostOptions struct {
ClaudeHome string
}
SessionCostOptions controls persisted session-cost lookups.
type SessionDiscovery ¶ added in v0.0.7
type SessionDiscovery struct {
SlashCommands []SlashCommand
Skills []string
Plugins []InitPluginInfo
OutputStyle string
FastModeState *FastModeState
ContextWindow *int
}
SessionDiscovery summarizes slash-command, skill, and plugin discovery metadata.
func DiscoverSessionMetadata ¶ added in v0.0.7
func DiscoverSessionMetadata(serverInfo *ServerInfo, init *InitMessage) SessionDiscovery
DiscoverSessionMetadata combines server and init metadata into one helper view.
type SessionEndHookInput ¶ added in v0.0.7
type SessionEndHookInput = hook.SessionEndInput
SessionEndHookInput is the input for SessionEnd hooks.
type SessionListOptions ¶ added in v0.0.2
type SessionListOptions struct {
Directory string
Limit int
Offset int
IncludeWorktrees *bool
ClaudeHome string
}
SessionListOptions controls ListSessions behavior.
type SessionMessage ¶ added in v0.0.2
type SessionMessage struct {
Type string `json:"type"`
UUID string `json:"uuid"`
SessionID string `json:"session_id"`
Message map[string]any `json:"message"`
ParentToolUseID *string `json:"parent_tool_use_id,omitempty"`
}
SessionMessage contains a top-level user or assistant message from a saved transcript.
func GetSessionMessages ¶ added in v0.0.2
func GetSessionMessages(sessionID string, options SessionMessagesOptions) []SessionMessage
GetSessionMessages returns top-level conversation messages from a saved session.
type SessionMessagesOptions ¶ added in v0.0.2
SessionMessagesOptions controls GetSessionMessages behavior.
type SessionStartHookInput ¶ added in v0.0.7
type SessionStartHookInput = hook.SessionStartInput
SessionStartHookInput is the input for SessionStart hooks.
type SessionStartHookSpecificOutput ¶ added in v0.0.7
type SessionStartHookSpecificOutput = hook.SessionStartSpecificOutput
SessionStartHookSpecificOutput is the hook-specific output for SessionStart.
type SessionStat ¶
type SessionStat struct {
SessionID string
SizeBytes int64
LastModified time.Time
MessageCount *int
CreatedAt *time.Time
UpdatedAt *time.Time
}
SessionStat contains local metadata for a persisted Claude session.
This metadata is read from local Claude persistence files. It does not represent live remote state or lock/occupancy status.
func StatSession ¶
StatSession returns metadata for a locally persisted session.
The lookup is project-scoped and read-only; no prompt is sent and no session content is modified. Returns ErrSessionNotFound when the session cannot be found in local Claude persistence for the resolved project path.
type SessionState ¶ added in v0.0.7
type SessionState = message.SessionState
SessionState identifies the current live session state.
type SessionStateChangedMessage ¶ added in v0.0.7
type SessionStateChangedMessage = message.SessionStateChangedMessage
SessionStateChangedMessage reports authoritative session state changes.
type SettingSource ¶
type SettingSource = config.SettingSource
SettingSource represents where settings should be loaded from.
type SettingsSnapshot ¶ added in v0.0.7
type SettingsSnapshot = protocol.SettingsSnapshot
SettingsSnapshot describes effective and per-source settings.
type SettingsSourceSnapshot ¶ added in v0.0.7
type SettingsSourceSnapshot = protocol.SettingsSourceSnapshot
SettingsSourceSnapshot describes one settings layer.
type SetupHookInput ¶ added in v0.0.7
type SetupHookInput = hook.SetupInput
SetupHookInput is the input for Setup hooks.
type SetupHookSpecificOutput ¶ added in v0.0.7
type SetupHookSpecificOutput = hook.SetupSpecificOutput
SetupHookSpecificOutput is the hook-specific output for Setup.
type SlashCommand ¶ added in v0.0.7
type SlashCommand = protocol.SlashCommand
SlashCommand describes a slash command available to the session.
type StatusMessage ¶ added in v0.0.7
type StatusMessage = message.StatusMessage
StatusMessage reports session status changes.
type StatusState ¶ added in v0.0.7
type StatusState = message.StatusState
StatusState identifies a session status value.
type StopFailureHookInput ¶ added in v0.0.7
type StopFailureHookInput = hook.StopFailureInput
StopFailureHookInput is the input for StopFailure hooks.
type StreamEvent ¶
type StreamEvent = message.StreamEvent
StreamEvent represents a streaming event from the Claude API.
type StreamingMessage ¶
type StreamingMessage = message.StreamingMessage
StreamingMessage represents a message sent in streaming mode.
func NewUserMessage ¶
func NewUserMessage(content UserMessageContent) StreamingMessage
NewUserMessage creates a StreamingMessage with type "user". This is a convenience constructor for creating user messages.
func NewUserMessageWithPriority ¶ added in v0.0.7
func NewUserMessageWithPriority(content UserMessageContent, priority StreamingMessagePriority) StreamingMessage
NewUserMessageWithPriority creates a user StreamingMessage with an explicit queue priority.
type StreamingMessageContent ¶
type StreamingMessageContent = message.StreamingMessageContent
StreamingMessageContent represents the content of a streaming message.
type StreamingMessagePriority ¶ added in v0.0.7
type StreamingMessagePriority = message.StreamingMessagePriority
StreamingMessagePriority controls scheduling order for streamed user messages.
type StreamlinedTextMessage ¶ added in v0.0.7
type StreamlinedTextMessage = message.StreamlinedTextMessage
StreamlinedTextMessage reports text-only streamlined output.
type StreamlinedToolUseSummaryMessage ¶ added in v0.0.7
type StreamlinedToolUseSummaryMessage = message.StreamlinedToolUseSummaryMessage
StreamlinedToolUseSummaryMessage reports streamlined tool-use summaries.
type SubagentStartHookInput ¶
type SubagentStartHookInput = hook.SubagentStartInput
SubagentStartHookInput is the input for SubagentStart hooks.
type SubagentStartHookSpecificOutput ¶
type SubagentStartHookSpecificOutput = hook.SubagentStartSpecificOutput
SubagentStartHookSpecificOutput is the hook-specific output for SubagentStart.
type SubagentStopHookInput ¶
type SubagentStopHookInput = hook.SubagentStopInput
SubagentStopHookInput is the input for SubagentStop hooks.
type SyncHookJSONOutput ¶
type SyncHookJSONOutput = hook.SyncJSONOutput
SyncHookJSONOutput represents a sync hook output.
type SystemMessage ¶
type SystemMessage = message.SystemMessage
SystemMessage represents a system message.
type SystemPromptPreset ¶
type SystemPromptPreset = config.SystemPromptPreset
SystemPromptPreset defines a system prompt preset configuration.
type TagSessionOptions ¶ added in v0.0.6
TagSessionOptions controls TagSession behavior.
type TaskCompletedHookInput ¶ added in v0.0.7
type TaskCompletedHookInput = hook.TaskCompletedInput
TaskCompletedHookInput is the input for TaskCompleted hooks.
type TaskCreatedHookInput ¶ added in v0.0.7
type TaskCreatedHookInput = hook.TaskCreatedInput
TaskCreatedHookInput is the input for TaskCreated hooks.
type TaskLifecycleState ¶ added in v0.0.7
type TaskLifecycleState string
TaskLifecycleState identifies the latest known lifecycle phase of a task.
const ( TaskLifecycleStateStarted TaskLifecycleState = "started" TaskLifecycleStateRunning TaskLifecycleState = "running" TaskLifecycleStateCompleted TaskLifecycleState = "completed" TaskLifecycleStateFailed TaskLifecycleState = "failed" TaskLifecycleStateStopped TaskLifecycleState = "stopped" )
type TaskLifecycleSummary ¶ added in v0.0.7
type TaskLifecycleSummary struct {
TotalTasks int
ActiveTasks int
TerminalTasks int
CompletedTasks int
FailedTasks int
StoppedTasks int
TotalTokens int
TotalToolUses int
TotalDurationMs int
OutputFiles []string
}
TaskLifecycleSummary aggregates high-level task counts and latest usage totals.
type TaskLifecycleTracker ¶ added in v0.0.7
type TaskLifecycleTracker struct {
// contains filtered or unexported fields
}
TaskLifecycleTracker accumulates task lifecycle state from streamed messages.
func NewTaskLifecycleTracker ¶ added in v0.0.7
func NewTaskLifecycleTracker() *TaskLifecycleTracker
NewTaskLifecycleTracker creates an empty task lifecycle tracker.
func (*TaskLifecycleTracker) ActiveTasks ¶ added in v0.0.7
func (t *TaskLifecycleTracker) ActiveTasks() []TaskSnapshot
ActiveTasks returns the subset of currently non-terminal tasks.
func (*TaskLifecycleTracker) Observe ¶ added in v0.0.7
func (t *TaskLifecycleTracker) Observe(msg Message)
Observe records task-related messages into the current snapshot set.
func (*TaskLifecycleTracker) Summary ¶ added in v0.0.7
func (t *TaskLifecycleTracker) Summary() TaskLifecycleSummary
Summary returns an aggregate view of the currently observed tasks.
func (*TaskLifecycleTracker) Task ¶ added in v0.0.7
func (t *TaskLifecycleTracker) Task(taskID string) (TaskSnapshot, bool)
Task returns the current snapshot for one task ID.
func (*TaskLifecycleTracker) Tasks ¶ added in v0.0.7
func (t *TaskLifecycleTracker) Tasks() []TaskSnapshot
Tasks returns all current task snapshots sorted by task ID.
func (*TaskLifecycleTracker) TerminalTasks ¶ added in v0.0.7
func (t *TaskLifecycleTracker) TerminalTasks() []TaskSnapshot
TerminalTasks returns the subset of terminal tasks.
type TaskNotificationMessage ¶ added in v0.0.2
type TaskNotificationMessage = message.TaskNotificationMessage
TaskNotificationMessage is emitted when a task completes, fails, or stops.
type TaskNotificationStatus ¶ added in v0.0.2
type TaskNotificationStatus = message.TaskNotificationStatus
TaskNotificationStatus represents the final status of a task.
type TaskProgressMessage ¶ added in v0.0.2
type TaskProgressMessage = message.TaskProgressMessage
TaskProgressMessage is emitted while a task is running.
type TaskSnapshot ¶ added in v0.0.7
type TaskSnapshot struct {
TaskID string
Description string
State TaskLifecycleState
TaskType *TaskType
WorkflowName *string
LastToolName *string
Summary *string
OutputFile *string
Usage *TaskUsage
SessionID string
ParentUUID *string
ToolUseID *string
}
TaskSnapshot is the SDK's aggregated view of one task's observed lifecycle.
func (TaskSnapshot) IsTerminal ¶ added in v0.0.7
func (s TaskSnapshot) IsTerminal() bool
IsTerminal reports whether the task has reached a terminal notification state.
type TaskStartedMessage ¶ added in v0.0.2
type TaskStartedMessage = message.TaskStartedMessage
TaskStartedMessage is emitted when a task starts.
type TeammateIdleHookInput ¶ added in v0.0.7
type TeammateIdleHookInput = hook.TeammateIdleInput
TeammateIdleHookInput is the input for TeammateIdle hooks.
type TextBlock ¶
TextBlock contains plain text content.
type ThinkingBlock ¶
type ThinkingBlock = message.ThinkingBlock
ThinkingBlock contains Claude's thinking process.
type ThinkingConfig ¶
type ThinkingConfig = config.ThinkingConfig
ThinkingConfig controls extended thinking behavior.
type ThinkingConfigAdaptive ¶
type ThinkingConfigAdaptive = config.ThinkingConfigAdaptive
ThinkingConfigAdaptive enables adaptive thinking mode.
type ThinkingConfigDisabled ¶
type ThinkingConfigDisabled = config.ThinkingConfigDisabled
ThinkingConfigDisabled disables extended thinking.
type ThinkingConfigEnabled ¶
type ThinkingConfigEnabled = config.ThinkingConfigEnabled
ThinkingConfigEnabled enables thinking with a specific token budget.
type Tool ¶
type Tool interface {
// Name returns the unique identifier for this tool.
Name() string
// Description returns a human-readable description for Claude.
Description() string
// InputSchema returns a JSON schema describing expected input.
// The schema should follow JSON Schema Draft 7 specification.
InputSchema() map[string]any
// Execute runs the tool with the provided input.
// The input will be validated against InputSchema before execution.
Execute(ctx context.Context, input map[string]any) (map[string]any, error)
}
Tool represents a custom tool that Claude can invoke.
Tools allow users to extend Claude's capabilities with domain-specific functionality. When registered, Claude can discover and execute these tools during a session.
Example:
tool := claudesdk.NewTool(
"calculator",
"Performs basic arithmetic operations",
map[string]any{
"type": "object",
"properties": map[string]any{
"operation": map[string]any{
"type": "string",
"enum": []string{"add", "subtract", "multiply", "divide"},
},
"a": map[string]any{"type": "number"},
"b": map[string]any{"type": "number"},
},
"required": []string{"operation", "a", "b"},
},
func(ctx context.Context, input map[string]any) (map[string]any, error) {
op := input["operation"].(string)
a := input["a"].(float64)
b := input["b"].(float64)
var result float64
switch op {
case "add":
result = a + b
case "subtract":
result = a - b
case "multiply":
result = a * b
case "divide":
if b == 0 {
return nil, fmt.Errorf("division by zero")
}
result = a / b
}
return map[string]any{"result": result}, nil
},
)
func NewTool ¶
NewTool creates a Tool from a function.
This is a convenience constructor for creating tools without implementing the full Tool interface.
Parameters:
- name: Unique identifier for the tool (e.g., "calculator", "search_database")
- description: Human-readable description of what the tool does
- schema: JSON Schema defining the expected input structure
- fn: Function that executes the tool logic
type ToolCategory ¶ added in v0.0.7
ToolCategory identifies the high-level behavior class of a Claude tool.
type ToolInterruptBehavior ¶ added in v0.0.7
type ToolInterruptBehavior = toolmeta.InterruptBehavior
type ToolMetadata ¶ added in v0.0.7
type ToolPermissionCallback ¶
type ToolPermissionCallback = permission.Callback
ToolPermissionCallback is called before each tool use for permission checking.
type ToolPermissionContext ¶
type ToolPermissionContext = permission.Context
ToolPermissionContext provides context for tool permission callbacks.
type ToolProgressMessage ¶ added in v0.0.7
type ToolProgressMessage = message.ToolProgressMessage
ToolProgressMessage reports long-running tool execution progress.
type ToolReferenceBlock ¶ added in v0.0.2
type ToolReferenceBlock = message.ToolReferenceBlock
ToolReferenceBlock points to a deferred tool selected by Claude tool search.
type ToolResultBlock ¶
type ToolResultBlock = message.ToolResultBlock
ToolResultBlock contains the result of a tool execution.
type ToolUseBlock ¶
type ToolUseBlock = message.ToolUseBlock
ToolUseBlock represents Claude using a tool.
type ToolUseSummaryMessage ¶ added in v0.0.7
type ToolUseSummaryMessage = message.ToolUseSummaryMessage
ToolUseSummaryMessage reports a summarized tool-use event.
type ToolsConfig ¶
type ToolsConfig = config.ToolsConfig
ToolsConfig is an interface for configuring available tools. It represents either a list of tool names or a preset configuration.
type ToolsPreset ¶
type ToolsPreset = config.ToolsPreset
ToolsPreset represents a preset configuration for available tools.
type Transport ¶
Transport defines the interface for Claude CLI communication. Implement this to provide custom transports for testing, mocking, or alternative communication methods (e.g., remote connections).
The default implementation is CLITransport which spawns a subprocess. Custom transports can be injected via ClaudeAgentOptions.Transport.
type TransportHealth ¶ added in v0.0.7
type TransportHealth = internalclient.TransportHealth
TransportHealth summarizes current observed client transport health.
type TurnCompleteCallback ¶ added in v0.0.7
type TurnCompleteCallback = turncomplete.Callback
TurnCompleteCallback handles a completed-turn summary.
type TurnCompleteCostSummary ¶ added in v0.0.7
type TurnCompleteCostSummary = turncomplete.CostSummary
TurnCompleteCostSummary contains lightweight turn and aggregate cost totals.
type TurnCompleteInfo ¶ added in v0.0.7
type TurnCompleteInfo = turncomplete.Info
TurnCompleteInfo summarizes one completed turn.
type UnknownBlock ¶ added in v0.0.2
type UnknownBlock = message.UnknownBlock
UnknownBlock preserves unrecognized content block payloads without failing parsing.
type UnknownHookInput ¶ added in v0.0.7
type UnknownHookInput = hook.UnknownInput
UnknownHookInput preserves future hook events the SDK does not yet type explicitly.
type UnknownMessage ¶ added in v0.0.7
type UnknownMessage = message.UnknownMessage
UnknownMessage preserves unrecognized top-level message payloads.
type UserInputAnswer ¶
UserInputAnswer contains response(s) for a question.
type UserInputCallback ¶
UserInputCallback handles AskUserQuestion prompts.
type UserInputQuestion ¶
UserInputQuestion represents a single AskUserQuestion prompt.
type UserInputQuestionOption ¶
type UserInputQuestionOption = userinput.QuestionOption
UserInputQuestionOption represents a selectable choice within a question.
type UserInputRequest ¶
UserInputRequest contains parsed AskUserQuestion payload data.
type UserInputResponse ¶
UserInputResponse contains answers keyed by question text.
type UserMessage ¶
type UserMessage = message.UserMessage
UserMessage represents a message from the user.
type UserMessageContent ¶
type UserMessageContent = message.UserMessageContent
UserMessageContent represents content that can be either a string or []ContentBlock.
func Blocks ¶ added in v0.0.5
func Blocks(blocks ...ContentBlock) UserMessageContent
Blocks creates block-based user content.
func StripMediaContent ¶ added in v0.0.7
func StripMediaContent(content UserMessageContent) (UserMessageContent, bool)
StripMediaContent removes inline image and document blocks from block-based user content so a retry can proceed without large attachments.
func Text ¶ added in v0.0.5
func Text(text string) UserMessageContent
Text creates text-only user content.
type UserPromptSubmitHookInput ¶
type UserPromptSubmitHookInput = hook.UserPromptSubmitInput
UserPromptSubmitHookInput is the input for UserPromptSubmit hooks.
type UserPromptSubmitHookSpecificOutput ¶
type UserPromptSubmitHookSpecificOutput = hook.UserPromptSubmitSpecificOutput
UserPromptSubmitHookSpecificOutput is the hook-specific output for UserPromptSubmit.
type WorktreeCreateHookInput ¶ added in v0.0.7
type WorktreeCreateHookInput = hook.WorktreeCreateInput
WorktreeCreateHookInput is the input for WorktreeCreate hooks.
type WorktreeCreateHookSpecificOutput ¶ added in v0.0.7
type WorktreeCreateHookSpecificOutput = hook.WorktreeCreateSpecificOutput
WorktreeCreateHookSpecificOutput is the hook-specific output for WorktreeCreate.
type WorktreeRemoveHookInput ¶ added in v0.0.7
type WorktreeRemoveHookInput = hook.WorktreeRemoveInput
WorktreeRemoveHookInput is the input for WorktreeRemove hooks.
Source Files
¶
- auto_compact_orchestrator.go
- budget_tracker.go
- client.go
- client_impl.go
- compaction_tracker.go
- context_pressure.go
- context_threshold.go
- cost_runtime.go
- cost_tracker.go
- discovery.go
- doc.go
- error_classification.go
- errors.go
- fast_mode_tracker.go
- hooks.go
- input.go
- logger.go
- mcp.go
- model_context.go
- models.go
- options.go
- preserved_segments.go
- query.go
- recovery_orchestrator.go
- retry_policy.go
- sdk_mcp_server.go
- sdk_mcp_tool.go
- session_mutations.go
- session_stat.go
- sessions.go
- stream.go
- structured_output_decode.go
- task_lifecycle.go
- tool_metadata.go
- transport.go
- turn_complete.go
- types.go
- usage_extraction.go
- version.go
- with_client.go
Directories
¶
| Path | Synopsis |
|---|---|
|
examples
|
|
|
agents
command
|
|
|
cancellation
command
|
|
|
client_multi_turn
command
|
|
|
compaction_hook
command
Package main demonstrates context compaction monitoring using the PreCompact hook.
|
Package main demonstrates context compaction monitoring using the PreCompact hook. |
|
context_pressure
command
|
|
|
elicitation
command
|
|
|
error_handling
command
|
|
|
extended_thinking
command
Package main demonstrates extended thinking capabilities with Claude.
|
Package main demonstrates extended thinking capabilities with Claude. |
|
fast_mode
command
|
|
|
filesystem_agents
command
|
|
|
hooks
command
|
|
|
include_partial_messages
command
|
|
|
max_budget_usd
command
|
|
|
mcp_calculator
command
Package main demonstrates how to create calculator tools using MCP servers.
|
Package main demonstrates how to create calculator tools using MCP servers. |
|
mcp_status
command
Package main demonstrates querying MCP server connection status.
|
Package main demonstrates querying MCP server connection status. |
|
memory_tool
command
Package main demonstrates a filesystem-backed memory tool for agent state persistence.
|
Package main demonstrates a filesystem-backed memory tool for agent state persistence. |
|
multimodal_input
command
|
|
|
parallel_queries
command
|
|
|
pipeline
command
|
|
|
plugin_example
command
Package main demonstrates how to use plugins with Claude Code SDK.
|
Package main demonstrates how to use plugins with Claude Code SDK. |
|
query_stream
command
|
|
|
quick_start
command
|
|
|
session_mutations
command
|
|
|
sessions
command
|
|
|
setting_sources
command
|
|
|
stderr_callback
command
|
|
|
structured_output
command
|
|
|
system_prompt
command
|
|
|
task_budget
command
|
|
|
tool_permission_callback
command
|
|
|
tools_option
command
|
|
|
turn_complete
command
|
|
|
user_input_callback
command
|
|
|
internal
|
|
|
cli
Package cli provides CLI discovery, version validation, and command building for the Claude Code CLI binary.
|
Package cli provides CLI discovery, version validation, and command building for the Claude Code CLI binary. |
|
client
Package client implements the interactive Client for multi-turn conversations with Claude.
|
Package client implements the interactive Client for multi-turn conversations with Claude. |
|
config
Package config provides configuration types for the Claude SDK.
|
Package config provides configuration types for the Claude SDK. |
|
elicitation
Package elicitation provides typed structures for MCP elicitation handling.
|
Package elicitation provides typed structures for MCP elicitation handling. |
|
errors
Package errors defines error types for the Claude SDK.
|
Package errors defines error types for the Claude SDK. |
|
hook
Package hook provides hook types for intercepting Claude CLI events.
|
Package hook provides hook types for intercepting Claude CLI events. |
|
mcp
Package mcp implements an in-process Model Context Protocol server.
|
Package mcp implements an in-process Model Context Protocol server. |
|
message
Package message provides message and content block types for Claude conversations.
|
Package message provides message and content block types for Claude conversations. |
|
models
Package models provides a catalog of known Claude models and their capabilities.
|
Package models provides a catalog of known Claude models and their capabilities. |
|
permission
Package permission provides permission handling types for the Claude CLI.
|
Package permission provides permission handling types for the Claude CLI. |
|
prompt
Package prompt provides typed structures for the CLI prompt request/response protocol.
|
Package prompt provides typed structures for the CLI prompt request/response protocol. |
|
protocol
Package protocol implements bidirectional control message handling for the Claude CLI.
|
Package protocol implements bidirectional control message handling for the Claude CLI. |
|
sandbox
Package sandbox provides sandbox configuration types for the Claude CLI.
|
Package sandbox provides sandbox configuration types for the Claude CLI. |
|
subprocess
Package subprocess provides subprocess-based transport for the Claude CLI.
|
Package subprocess provides subprocess-based transport for the Claude CLI. |
|
userinput
Package userinput provides typed structures for AskUserQuestion handling.
|
Package userinput provides typed structures for AskUserQuestion handling. |