claudesdk

package module
v0.0.11 Latest Latest
Warning

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

Go to latest
Published: Apr 24, 2026 License: GPL-3.0 Imports: 54 Imported by: 0

README

Claude Agent SDK Go

Go SDK for building agentic applications with Claude Code.

Installation

go get github.com/ethpandaops/claude-agent-sdk-go

Prerequisites:

  • Go 1.26+
  • Claude Code CLI v2.1.59+ (npm install -g @anthropic-ai/claude-code)

Tested against Claude Code CLI 2.1.89.

Quick Start

package main

import (
    "context"
    "fmt"

    claudesdk "github.com/ethpandaops/claude-agent-sdk-go"
)

func main() {
    ctx := context.Background()
    for msg, err := range claudesdk.Query(ctx, claudesdk.Text("What is 2 + 2?")) {
        if err != nil {
            panic(err)
        }
        if result, ok := msg.(*claudesdk.ResultMessage); ok {
            if result.Result != nil {
                fmt.Println(*result.Result)
            }
        }
    }
}

Basic Usage: Query()

One-shot query execution returning an iterator of messages. Query() accepts UserMessageContent. Use Text(...) for plain prompts and Blocks(...) for structured multimodal input. Text-only queries use Claude CLI --print mode. Structured content uses streaming mode.

for msg, err := range claudesdk.Query(ctx, claudesdk.Text("Explain Go interfaces")) {
    // handle msg
}

Model Discovery

ListModels(ctx) returns the SDK's static Claude model catalog in a Codex-like payload shape. It is not a live per-user model list from the Claude CLI.

models, err := claudesdk.ListModels(ctx)
if err != nil {
    panic(err)
}
for _, model := range models {
    fmt.Println(model.ID, model.Metadata["modelContextWindow"])
}
With Options
for msg, err := range claudesdk.Query(ctx, claudesdk.Text("Hello"),
    claudesdk.WithSystemPrompt("You are a helpful assistant"),
    claudesdk.WithModel("claude-sonnet-4-6"),
    claudesdk.WithMaxTurns(3),
) {
    // handle msg
}
With Tools
for msg, err := range claudesdk.Query(ctx, claudesdk.Text("Create hello.py that prints hello world"),
    claudesdk.WithAllowedTools("Read", "Write"),
    claudesdk.WithPermissionMode(string(claudesdk.PermissionModeAcceptEdits)),
) {
    // handle msg
}
Permission Modes

Supported permission modes are default, acceptEdits, plan, auto, dontAsk, and bypassPermissions.

opts := []claudesdk.Option{
    claudesdk.WithPermissionMode(string(claudesdk.PermissionModeDontAsk)),
    claudesdk.WithMaxTurns(1),
}

Use dontAsk for headless or CI workflows where permission prompts must be denied instead of surfaced interactively.

Permission Callback Context

WithCanUseTool(...) now receives richer typed context from Claude Code, including permission suggestions, blocked_path, raw decision_reason, structured DecisionReasonType when it can be derived, UI labels like title, display_name, and description, plus derived ToolCategory, ConcurrencySafe, and InterruptBehavior hints for the requested tool. Sandbox network permission prompts are surfaced as the synthetic tool name claudesdk.SandboxNetworkAccessToolName.

Persisted Permissions

WithPersistPermissions(path) stores SDK-managed permission rules on disk and reapplies them across future sessions before your WithCanUseTool(...) callback runs. The SDK preserves update destinations such as userSettings, projectSettings, localSettings, and cliArg inside its own file and evaluates them with destination precedence, without depending on Claude CLI settings-file internals.

opts := []claudesdk.Option{
    claudesdk.WithPersistPermissions(".claude-sdk-permissions.json"),
    claudesdk.WithCanUseTool(func(
        _ context.Context,
        toolName string,
        _ map[string]any,
        _ *claudesdk.ToolPermissionContext,
    ) (claudesdk.PermissionResult, error) {
        if toolName == "Bash" {
            behavior := claudesdk.PermissionBehaviorAllow
            destination := claudesdk.PermissionUpdateDestUserSettings

            return &claudesdk.PermissionResultAllow{
                Behavior: "allow",
                UpdatedPermissions: []*claudesdk.PermissionUpdate{{
                    Type: claudesdk.PermissionUpdateTypeAddRules,
                    Rules: []*claudesdk.PermissionRuleValue{{
                        ToolName: "Bash",
                    }},
                    Behavior:    &behavior,
                    Destination: &destination,
                }},
            }, nil
        }

        return &claudesdk.PermissionResultAllow{Behavior: "allow"}, nil
    }),
}
Tool Metadata Helpers

ClassifyToolCategory(toolName), IsConcurrencySafeTool(toolName), and InterruptBehaviorForTool(toolName) expose the SDK's best-effort tool metadata for hosts building their own orchestration or streamlined UIs. Parsed ToolUseBlocks and ToolPermissionContexts also carry the same derived category/concurrency/interrupt metadata directly.

ConnectorTextBlock preserves IDE/connector-synchronized text blocks as a first-class content block instead of degrading to UnknownBlock.

TaskLifecycleTracker aggregates task_started, task_progress, and task_notification messages into a per-task snapshot view, including ActiveTasks(), TerminalTasks(), and Summary(). ModelHasOneMillionContextSuffix(...) / EffectiveModelContextWindow(...) add a small helper layer for explicit [1m] model IDs, and parsed InitMessage values now carry a derived ContextWindow when the SDK can resolve it from the live init payload, beta flags, or model ID.

QueryStream Heartbeats

Interactive Client sessions already send periodic keep_alive heartbeats. QueryStream(...) now does the same while it is still streaming input or waiting for a terminal result in callback-driven sessions, which makes long-running headless stream-json flows less fragile.

Client (Multi-turn)

WithClient manages the client lifecycle for multi-turn conversations. Client.GetServerInfo() now returns typed initialize metadata.

err := claudesdk.WithClient(ctx, func(c claudesdk.Client) error {
    if err := c.Query(ctx, claudesdk.Text("Hello, remember my name is Alice")); err != nil {
        return err
    }
    for msg, err := range c.ReceiveResponse(ctx) {
        if err != nil {
            return err
        }
        // handle response
    }

    if err := c.Query(ctx, claudesdk.Text("What's my name?")); err != nil {
        return err
    }
    for msg, err := range c.ReceiveResponse(ctx) {
        if err != nil {
            return err
        }
        // Claude remembers: "Alice"
        _ = msg
    }

    info, err := c.GetServerInfo()
    if err != nil {
        return err
    }
    fmt.Println(info.OutputStyle)

    return nil
})

Client.Interrupt(ctx) is now a soft interrupt by default. If your host wants to synthesize error tool_result blocks for unresolved tool uses before interrupting, opt in with WithInterruptToolResultPolicy(claudesdk.InterruptToolResultPolicySynthesizeErrorToolResults).

SDK MCP Servers (Custom Tools)

Create in-process tools using the Model Context Protocol.

schema := claudesdk.SimpleSchema(map[string]string{"a": "number", "b": "number"})

handler := func(ctx context.Context, req *mcp.CallToolRequest) (*mcp.CallToolResult, error) {
    args, _ := claudesdk.ParseArguments(req)
    sum := args["a"].(float64) + args["b"].(float64)
    return claudesdk.TextResult(fmt.Sprintf("%.0f", sum)), nil
}

tool := claudesdk.NewSdkMcpTool("add", "Add two numbers", schema, handler)
server := claudesdk.CreateSdkMcpServer("calc", "1.0.0", tool)

for msg, err := range claudesdk.Query(ctx, claudesdk.Text("Calculate 2 + 2"),
    claudesdk.WithMCPServers(map[string]claudesdk.MCPServerConfig{"calc": server}),
    claudesdk.WithAllowedTools("mcp__calc__add"),
) {
    // handle msg
}

Multimodal Input

The SDK now supports structured Claude CLI user content:

content := claudesdk.Blocks(
    claudesdk.TextInput("Describe these attachments briefly."),
    claudesdk.PathInput("/absolute/path/to/local-image.png"),
)

for msg, err := range claudesdk.Query(ctx, content) {
    // handle msg
}

Inline helpers are also available for fully programmatic payloads:

img, _ := claudesdk.ImageFileInput("/absolute/path/to/local-image.png")
pdf, _ := claudesdk.PDFFileInput("/absolute/path/to/spec.pdf")

content := claudesdk.Blocks(
    claudesdk.TextInput("Summarize the PDF and image."),
    img,
    pdf,
)

for msg, err := range claudesdk.Query(ctx, content) {
    // handle msg
}

Supported CLI formats validated by this SDK:

  • Text(...) for plain prompts
  • image blocks via ImageInput(...) / ImageFileInput(...)
  • document PDF blocks via PDFInput(...) / PDFFileInput(...)
  • @/absolute/path mentions via PathInput(...)

See examples/multimodal_input for a complete example that runs both path-based attachments and inline image/PDF blocks.

Hooks

Intercept and modify tool execution.

handler := func(ctx context.Context, hookCtx claudesdk.HookContext, input claudesdk.HookInput) (claudesdk.HookJSONOutput, error) {
    pre := input.(*claudesdk.PreToolUseHookInput)
    fmt.Printf("Tool: %s\n", pre.ToolName)
    return &claudesdk.SyncHookJSONOutput{}, nil
}

for msg, err := range claudesdk.Query(ctx, claudesdk.Text(prompt),
    claudesdk.WithHooks(map[claudesdk.HookEvent][]*claudesdk.HookMatcher{
        claudesdk.HookEventPreToolUse: {{
            ToolName: "Bash",
            Hooks:    []claudesdk.HookCallback{handler},
        }},
    }),
) {
    // handle msg
}

Streaming Input Priority

QueryStream and StartWithStream accept StreamingMessage.Priority so you can enqueue now, next, or later messages explicitly.

messages := claudesdk.MessagesFromSlice([]claudesdk.StreamingMessage{
    claudesdk.NewUserMessageWithPriority(
        claudesdk.Text("Reply with one word."),
        claudesdk.StreamingMessagePriorityNow,
    ),
})

for msg, err := range claudesdk.QueryStream(ctx, messages,
    claudesdk.WithPermissionMode(string(claudesdk.PermissionModeDontAsk)),
) {
    _, _ = msg, err
}

Fast Mode

WithFastMode(true) opts headless SDK sessions into fast mode through the CLI settings layer. WithFastModeTracker(...) adds a lightweight host-side tracker that observes init/result/rate-limit/retry messages and derives off / on / cooldown transitions. WithUnattendedRetry(true) sets CLAUDE_CODE_UNATTENDED_RETRY=1 for long-running autonomous sessions while still leaving retry execution to the CLI.

client := claudesdk.NewClient()
defer client.Close()

err := client.Start(ctx,
    claudesdk.WithModel("claude-opus-4-7"),
    claudesdk.WithFastMode(true),
)
if err != nil {
    log.Fatal(err)
}

info, _ := client.GetServerInfo()
if info.FastModeState != nil {
    fmt.Println(*info.FastModeState)
}

tracker := claudesdk.NewFastModeTracker()
_ = tracker

MCP Elicitation

Use WithOnElicitation to accept, decline, or cancel structured MCP prompts during a session. Pair it with WithOnElicitationComplete when you also need completion notifications for URL-mode or deferred flows.

onElicitation := func(_ context.Context, req *claudesdk.ElicitationRequest) (*claudesdk.ElicitationResponse, error) {
    return &claudesdk.ElicitationResponse{
        Action: claudesdk.ElicitationActionAccept,
        Content: map[string]any{"approved": true},
    }, nil
}

onComplete := func(_ context.Context, completion *claudesdk.ElicitationCompleteMessage) error {
    fmt.Println(completion.ElicitationID)
    return nil
}

Plan Mode User Input

Handle AskUserQuestion prompts with a typed callback:

onUserInput := func(
    _ context.Context,
    req *claudesdk.UserInputRequest,
) (*claudesdk.UserInputResponse, error) {
    answers := map[string]*claudesdk.UserInputAnswer{}
    for _, q := range req.Questions {
        if len(q.Options) > 0 {
            answers[q.Question] = &claudesdk.UserInputAnswer{
                Answers: []string{q.Options[0].Label},
            }
        }
    }
    return &claudesdk.UserInputResponse{Answers: answers}, nil
}

for msg, err := range claudesdk.Query(ctx,
    claudesdk.Text("Use AskUserQuestion to ask me to pick Go or Rust, then confirm my choice."),
    claudesdk.WithPermissionMode("plan"),
    claudesdk.WithOnUserInput(onUserInput),
) {
    _ = msg
    _ = err
}

Prompt Dialogs

WithOnPrompt handles the separate prompt request/response protocol used for generic multiple-choice dialogs. This is distinct from WithOnUserInput, which is specific to the AskUserQuestion tool.

onPrompt := func(_ context.Context, req *claudesdk.PromptRequest) (*claudesdk.PromptResponse, error) {
    return &claudesdk.PromptResponse{Selected: req.Options[0].Key}, nil
}

Cost Tracking

CostTracker now aggregates terminal-result durations, turns, token/cache/web-search totals, and can persist session-cost state under Claude home when attached with WithCostTracker(...). BudgetTracker builds on the same result stream to flag near-budget turns, diminishing returns, and continuation pressure without interrupting the session for you. EvaluateBudgetProgress(...) exposes the same host-side recommendation logic as a pure helper. CostTracker, BudgetTracker, FastModeTracker, CompactionTracker, and TaskLifecycleTracker are safe for concurrent observation from multiple goroutines.

maxCost := 2.0
budget, _ := claudesdk.NewBudgetTracker(claudesdk.BudgetTrackerOptions{MaxCostUSD: &maxCost})
_ = budget
tracker := claudesdk.NewCostTracker()
for msg, err := range claudesdk.Query(ctx, claudesdk.Text("Say hi"),
    claudesdk.WithCostTracker(tracker),
) {
    if err != nil {
        log.Fatal(err)
    }
    tracker.Observe(msg) // safe alongside WithCostTracker; results are deduplicated by UUID
}

snapshot := tracker.Snapshot()
fmt.Println(snapshot.Results, snapshot.TotalDurationMs, snapshot.TotalInputTokens)

Persisted session-cost snapshots can also be loaded or deleted directly with LoadSessionCost, SaveSessionCost, and DeleteSessionCost.

Context Pressure Helpers

EvaluateContextPressure adds source-aligned warning, error, auto-compact, and blocking tiers on top of GetContextUsage(). NewAutoCompactFailureCircuitBreaker(...) tracks repeated compaction failures so hosts can stop retrying after a configured streak, and NewAutoCompactOrchestrator(...) combines tier evaluation with the breaker into a host-facing compaction recommendation.

CompactionTracker observes StatusMessage, CompactBoundaryMessage, and terminal ResultMessage values so hosts can track compaction boundaries and infer when the next turn likely rebuilt prompt cache (LastCacheBreakLikely based on cache-creation token usage).

usage, _ := client.GetContextUsage(ctx)
status, _ := claudesdk.EvaluateContextPressure(usage, claudesdk.DefaultContextPressurePolicy())
if status.ShouldAutoCompact {
    fmt.Println("compact soon", status.RemainingTokens)
}

Rewind Files

Client.RewindFiles(...) returns a typed RewindFilesResult with CanRewind, FilesChanged, Insertions, and Deletions.

result, err := client.RewindFiles(ctx, userMessageID)
if err != nil {
    log.Fatal(err)
}
fmt.Println(result.CanRewind, result.FilesChanged)

WithEnableFileCheckpointing(true) automatically sets CLAUDE_CODE_ENABLE_SDK_FILE_CHECKPOINTING=true for SDK-launched CLI processes.

Runtime Environment Overrides

The SDK now exposes typed options for several Claude Code environment overrides:

  • WithMaxToolUseConcurrency(...)
  • WithAutoCompactPercentageOverride(...)
  • WithBlockingLimitOverride(...)
  • WithDisableCompact(...)
  • WithDisableAutoCompact(...)

These map to the corresponding CLI environment variables for hosts that need to tune runtime behavior without using raw WithEnv(...).

Error Classification Helpers

ClassifyResultError(result) and ClassifyAPIRetry(msg) provide typed SDK-side classification for prompt-too-long, media-too-large, rate-limit, overload, auth, billing, and generic execution failures. Each classification now includes a RecoveryAction, optional ErrorSubClass, and best-effort RetryAfterSeconds.

DefaultRetryPolicy(), EvaluateRetry(msg, policy), and EvaluateResultRetry(result, attempt, policy) add host-side retry guidance without auto-replaying turns for you. These are optional host-policy helpers rather than protocol guarantees.

Recovery Planning

RecoveryOrchestrator turns terminal ResultMessage classifications into a host-side recovery plan. PlanResult(...) can recommend media stripping, fallback-model switching, or retry-with-delay using the SDK retry policy, and ResilientQuery(...) wraps Query(...) with that planning loop for one-shot host workflows.

Turn Completion Callback

WithOnTurnComplete(...) fires after each terminal ResultMessage with lightweight turn cost, aggregate cost, and side-channel summary data such as prompt suggestions, post-turn summaries, and task notifications seen during that turn.

Structured Output Helpers

DecodeStructuredOutput[T](result) decodes ResultMessage.StructuredOutput into a typed Go value and returns ErrStructuredOutputMissing when the result did not include parsed structured output.

if result, ok := msg.(*claudesdk.ResultMessage); ok {
    person, err := claudesdk.DecodeStructuredOutput[Person](result)
    if err == nil {
        fmt.Println(person.Name)
    }
}

Result Messages

ResultMessage.Subtype is now a typed ResultSubtype. Compare it against exported constants such as ResultSubtypeSuccess, ResultSubtypeErrorMaxTurns, and ResultSubtypeErrorMaxBudgetUSD. ResultMessage.ModelUsage is also typed as map[string]ModelUsage for per-model token and cost accounting.

if result, ok := msg.(*claudesdk.ResultMessage); ok {
    if result.Subtype == claudesdk.ResultSubtypeErrorMaxBudgetUSD {
        fmt.Println("budget exceeded")
    }
    if usage, ok := result.ModelUsage["claude-sonnet-4-6"]; ok {
        fmt.Println(usage.InputTokens, usage.OutputTokens)
    }
}

Resume Metadata Helpers

NewPreservedSegmentIndex() records CompactBoundaryMessage preserved segments so hosts can resolve relinked UUIDs across compaction boundaries during resume/fork flows.

Discovery Helpers

DiscoverSessionMetadata(serverInfo, initMsg) combines slash commands, skills, plugins, output style, and fast-mode state into one helper view for host UIs.

Transport Health

Interactive clients now expose GetTransportHealth() so hosts can inspect parse/send/read failure state without waiting for a terminal client error.

Types

Core message types implement the Message interface:

  • UserMessage - User input
  • AssistantMessage - Claude response with Content []ContentBlock
  • ResultMessage - Final result with Result string
  • SystemMessage - System messages

Content blocks: TextBlock, InputImageBlock, InputDocumentBlock, ThinkingBlock, ToolUseBlock, ToolResultBlock

See types.go for complete type definitions.

Static Model Catalog

Models(), ModelByID(), and ListModels(ctx) use a static SDK catalog, not a live Claude CLI model list for the logged-in user.

The catalog includes the current concrete model IDs exposed by this SDK.

Error Handling

SDK errors can be inspected using errors.AsType (Go 1.26+):

if cliErr, ok := errors.AsType[*claudesdk.CLINotFoundError](err); ok {
    fmt.Println("Claude CLI not found:", cliErr)
}

if procErr, ok := errors.AsType[*claudesdk.ProcessError](err); ok {
    fmt.Println("Process failed:", procErr)
}

Error types:

  • CLINotFoundError - Claude CLI binary not found
  • CLIConnectionError - Failed to connect to CLI
  • ProcessError - CLI process failure
  • MessageParseError - Message parsing failure
  • CLIJSONDecodeError - JSON decode failure

Sentinel errors: ErrClientNotConnected, ErrClientAlreadyConnected, ErrClientClosed, ErrSessionNotFound

Session Metadata

Inspect locally persisted session metadata without sending a prompt:

stat, err := claudesdk.StatSession(ctx, sessionID,
    claudesdk.WithStatProjectPath("/path/to/project"), // optional
    claudesdk.WithStatClaudeHome("/custom/.claude"),   // optional
)
if err != nil {
    if errors.Is(err, claudesdk.ErrSessionNotFound) {
        // session does not exist in local persistence
    }
    // handle other errors
}
fmt.Println(stat.SizeBytes, stat.LastModified)

Examples

See the examples directory for complete working examples.

Testing Examples

The scripts/test_examples.sh script runs all examples and uses Claude CLI to verify their output.

# Run all examples
./scripts/test_examples.sh

# Run specific examples
./scripts/test_examples.sh -f hooks,sessions,tools_option

# Keep going on failure
./scripts/test_examples.sh -k

# Adjust parallelism and timeout
./scripts/test_examples.sh -n 3 -t 180

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

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

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

View Source
const (
	ToolCategorySearch  = toolmeta.CategorySearch
	ToolCategoryRead    = toolmeta.CategoryRead
	ToolCategoryWrite   = toolmeta.CategoryWrite
	ToolCategoryCommand = toolmeta.CategoryCommand
	ToolCategoryOther   = toolmeta.CategoryOther
)
View Source
const (
	ToolInterruptBehaviorCancel = toolmeta.InterruptBehaviorCancel
	ToolInterruptBehaviorBlock  = toolmeta.InterruptBehaviorBlock
)
View Source
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
)
View Source
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
)
View Source
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
)
View Source
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
)
View Source
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
)
View Source
const (
	TaskTypeLocalBash         = message.TaskTypeLocalBash
	TaskTypeLocalAgent        = message.TaskTypeLocalAgent
	TaskTypeRemoteAgent       = message.TaskTypeRemoteAgent
	TaskTypeInProcessTeammate = message.TaskTypeInProcessTeammate
	TaskTypeLocalWorkflow     = message.TaskTypeLocalWorkflow
	TaskTypeMonitorMCP        = message.TaskTypeMonitorMCP
	TaskTypeDream             = message.TaskTypeDream
)
View Source
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
)
View Source
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
)
View Source
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
)
View Source
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
)
View Source
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
)
View Source
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
)
View Source
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
)
View Source
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
)
View Source
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
)
View Source
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
)
View Source
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
)
View Source
const (
	PermissionDecisionReasonTypeRule            = permission.DecisionReasonTypeRule
	PermissionDecisionReasonTypeMode            = permission.DecisionReasonTypeMode
	PermissionDecisionReasonTypeHook            = permission.DecisionReasonTypeHook
	PermissionDecisionReasonTypeClassifier      = permission.DecisionReasonTypeClassifier
	PermissionDecisionReasonTypeSandboxOverride = permission.DecisionReasonTypeSandboxOverride
	PermissionDecisionReasonTypeWorkingDir      = permission.DecisionReasonTypeWorkingDir
	PermissionDecisionReasonTypeSafetyCheck     = permission.DecisionReasonTypeSafetyCheck
)
View Source
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
)
View Source
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
)
View Source
const (
	// ElicitationModeForm requests form-mode elicitation.
	ElicitationModeForm = elicitation.ModeForm
	// ElicitationModeURL requests URL-mode elicitation.
	ElicitationModeURL = elicitation.ModeURL
)
View Source
const (
	// ElicitationActionAccept accepts the elicitation.
	ElicitationActionAccept = elicitation.ActionAccept
	// ElicitationActionDecline declines the elicitation.
	ElicitationActionDecline = elicitation.ActionDecline
	// ElicitationActionCancel cancels the elicitation.
	ElicitationActionCancel = elicitation.ActionCancel
)
View Source
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
)
View Source
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
)
View Source
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
)
View Source
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
)
View Source
const MinimumCLIVersion = "2.1.59"

MinimumCLIVersion is the minimum required Claude CLI version.

View Source
const SandboxNetworkAccessToolName = permission.SandboxNetworkAccessToolName

SandboxNetworkAccessToolName is the synthetic tool name used for sandbox network permission prompts.

View Source
const (
	// SdkBetaContext1M enables 1 million token context window.
	SdkBetaContext1M = config.BetaContext1M
)
View Source
const (
	// StatusStateCompacting indicates the session is compacting.
	StatusStateCompacting = message.StatusStateCompacting
)
View Source
const Version = "0.1.0"

Version is the SDK version.

Variables

View Source
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 indicates initialize metadata is not available.
	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.

View Source
var AgentMCPServerInline = config.AgentMCPServerInline

AgentMCPServerInline creates an inline spec for a single MCP server config.

View Source
var AgentMCPServerReference = config.AgentMCPServerReference

AgentMCPServerReference creates a reference spec for an existing MCP server.

View Source
var ClassifyToolCategory = toolmeta.Classify

ClassifyToolCategory returns the SDK's best-effort category for a tool name.

View Source
var DescribeTool = toolmeta.Describe

DescribeTool returns the SDK's derived metadata for one tool.

View Source
var InterruptBehaviorForTool = toolmeta.InterruptMode

InterruptBehaviorForTool reports the SDK's best-effort interrupt behavior hint.

View Source
var IsConcurrencySafeTool = toolmeta.IsConcurrencySafe

IsConcurrencySafeTool reports whether a tool is treated as safe for concurrent execution.

View Source
var NewAgentEffortLevel = config.NewAgentEffortLevel

NewAgentEffortLevel creates an agent effort value from a named level.

View Source
var NewAgentEffortValue = config.NewAgentEffortValue

NewAgentEffortValue creates an agent effort value from an integer.

View Source
var NewAuditEnvelope = message.NewAuditEnvelope

NewAuditEnvelope creates an audit envelope from a typed payload.

View Source
var NewUserMessageContent = message.NewUserMessageContent

NewUserMessageContent creates UserMessageContent from a string.

View Source
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 along with its sibling {session_id}/ directory holding subagent transcripts (if any). The subagent directory is removed best-effort — most sessions never spawn subagents.

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

func EffectiveModelContextWindow(modelID string) (int, bool)

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 ListSubagents added in v0.0.9

func ListSubagents(sessionID string, options GetSessionInfoOptions) []string

ListSubagents lists subagent IDs for a given session by scanning the subagents directory. Subagent transcripts are stored at ~/.claude/projects/<project>/<sessionID>/subagents/agent-<agentID>.jsonl (and may be nested in subdirectories such as workflows/<runID>/).

Returns an empty list if the session is not found, sessionID is not a valid UUID, or the session has no subagents.

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

func ModelCapabilities(modelID string) []string

ModelCapabilities returns capability strings for the given model ID. Returns nil if the model is not found.

func ModelHasOneMillionContextSuffix added in v0.0.7

func ModelHasOneMillionContextSuffix(modelID string) bool

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

func NopLogger() *slog.Logger

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

func WithClient(ctx context.Context, fn func(Client) error, opts ...Option) error

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 AgentInfo added in v0.0.7

type AgentInfo = protocol.AgentInfo

AgentInfo describes an available agent returned by the CLI.

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

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

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

type BaseHookInput = hook.BaseInput

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

type ClaudeAgentOptions = config.Options

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...
}

func NewClient

func NewClient() Client

NewClient creates a new interactive client.

Call Start() with options to begin a session:

client := NewClient()
err := client.Start(ctx,
    WithLogger(slog.Default()),
    WithPermissionMode(string(PermissionModeDefault)),
)

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

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

type DeleteSessionOptions struct {
	Directory  string
	ClaudeHome string
}

DeleteSessionOptions controls DeleteSession behavior.

type Effort

type Effort = config.Effort

Effort controls thinking depth.

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

type FastModeState = fastmode.State

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

type GetSessionInfoOptions struct {
	Directory  string
	ClaudeHome string
}

GetSessionInfoOptions controls GetSessionInfo behavior.

type HookCallback

type HookCallback = hook.Callback

HookCallback is the function signature for hook callbacks.

type HookContext

type HookContext = hook.Context

HookContext provides context for hook execution.

type HookEvent

type HookEvent = hook.Event

HookEvent represents the type of event that triggers a hook.

type HookInput

type HookInput = hook.Input

HookInput is the interface for all hook input types.

type HookJSONOutput

type HookJSONOutput = hook.JSONOutput

HookJSONOutput is the interface for hook output types.

type HookMatcher

type HookMatcher = hook.Matcher

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 MCPStatus

type MCPStatus = mcp.Status

MCPStatus represents the connection status of all configured MCP servers.

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

type MCPToolInfo = mcp.ToolInfo

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

type McpContent = mcp.Content

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 McpTool

type McpTool = mcp.Tool

McpTool represents an MCP tool definition from the official SDK.

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 Message

type Message = message.Message

Message represents any message in the conversation.

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

type Model = models.Model

Model holds metadata for a single Claude model.

func ModelByID

func ModelByID(id string) *Model

ModelByID looks up a model by exact ID. Returns nil if no model is found.

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

type ModelCostTier = models.CostTier

ModelCostTier represents a provider-agnostic relative cost tier.

type ModelInfo added in v0.0.2

type ModelInfo = models.Info

ModelInfo describes a model exposed by ListModels.

func ListModels added in v0.0.2

func ListModels(_ context.Context) ([]ModelInfo, error)

ListModels returns a Codex-like model list payload backed by the SDK's static Claude catalog. This is not a live account-specific list from the Claude CLI.

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

func WithAddDirs(dirs ...string) Option

WithAddDirs adds additional directories to make accessible.

func WithAgentProgressSummaries added in v0.0.7

func WithAgentProgressSummaries(enable bool) Option

WithAgentProgressSummaries enables background post-turn summaries.

func WithAgents

func WithAgents(agents map[string]*AgentDefinition) Option

WithAgents defines custom agent configurations.

func WithAllowedTools

func WithAllowedTools(tools ...string) Option

WithAllowedTools sets pre-approved tools that can be used without prompting.

func WithAutoCompactPercentageOverride added in v0.0.7

func WithAutoCompactPercentageOverride(percentage int) Option

WithAutoCompactPercentageOverride overrides the CLI auto-compaction percentage threshold.

func WithBetas

func WithBetas(betas ...SdkBeta) Option

WithBetas enables beta features.

func WithBlockingLimitOverride added in v0.0.7

func WithBlockingLimitOverride(limit int) Option

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

func WithClaudeHome(path string) Option

WithClaudeHome overrides the Claude home directory (default: ~/.claude).

func WithCliPath

func WithCliPath(path string) Option

WithCliPath sets the explicit path to the claude CLI binary. If not set, the CLI will be searched in PATH.

func WithContinueConversation

func WithContinueConversation(cont bool) Option

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 WithCwd

func WithCwd(cwd string) Option

WithCwd sets the working directory for the CLI process.

func WithDisableAutoCompact added in v0.0.7

func WithDisableAutoCompact(disable bool) Option

WithDisableAutoCompact disables automatic compaction in the CLI.

func WithDisableCompact added in v0.0.7

func WithDisableCompact(disable bool) Option

WithDisableCompact disables compaction in the CLI.

func WithDisableSettingSources added in v0.0.9

func WithDisableSettingSources() Option

WithDisableSettingSources disables all filesystem setting sources by passing an empty --setting-sources= flag to the CLI. Equivalent to Python's setting_sources=[] and TypeScript's settingSources: [].

func WithDisallowedTools

func WithDisallowedTools(tools ...string) Option

WithDisallowedTools sets tools that are explicitly blocked.

func WithEffort

func WithEffort(effort config.Effort) Option

WithEffort sets the thinking effort level.

func WithEnableFileCheckpointing

func WithEnableFileCheckpointing(enable bool) Option

WithEnableFileCheckpointing enables file change tracking and rewinding.

func WithEnv

func WithEnv(env map[string]string) Option

WithEnv provides additional environment variables for the CLI process.

func WithExcludeDynamicSections added in v0.0.8

func WithExcludeDynamicSections(exclude bool) Option

WithExcludeDynamicSections controls whether dynamic sections (working directory, auto-memory, git status) are excluded from the system prompt preset. When true, the CLI strips per-user dynamic content for cross-user prompt caching.

func WithExtraArgs

func WithExtraArgs(args map[string]*string) Option

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

func WithFallbackModel(model string) Option

WithFallbackModel specifies a model to use if the primary model fails.

func WithFastMode added in v0.0.7

func WithFastMode(enabled bool) Option

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

func WithForkSession(fork bool) Option

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

func WithIncludePartialMessages(include bool) Option

WithIncludePartialMessages enables streaming of partial message updates.

func WithInitializeTimeout

func WithInitializeTimeout(timeout time.Duration) Option

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

func WithLogger(logger *slog.Logger) Option

WithLogger sets the logger for debug output. If not set, logging is disabled (silent operation).

func WithMCPConfig

func WithMCPConfig(config string) Option

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

func WithMaxBudgetUSD(budget float64) Option

WithMaxBudgetUSD sets a cost limit for the session in USD.

func WithMaxBufferSize

func WithMaxBufferSize(size int) Option

WithMaxBufferSize sets the maximum bytes for CLI stdout buffering.

func WithMaxToolUseConcurrency added in v0.0.7

func WithMaxToolUseConcurrency(limit int) Option

WithMaxToolUseConcurrency overrides the CLI tool-use concurrency limit.

func WithMaxTurns

func WithMaxTurns(maxTurns int) Option

WithMaxTurns limits the maximum number of conversation turns.

func WithMeterProvider added in v0.0.9

func WithMeterProvider(mp metric.MeterProvider) Option

WithMeterProvider sets an OpenTelemetry MeterProvider for metrics collection. When set, the SDK emits token usage, cost, duration, and operational metrics at existing observation points. Recording is completely noop when not set.

func WithModel

func WithModel(model string) Option

WithModel specifies which Claude model ID to use (e.g., "claude-sonnet-4-6").

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

func WithOutputFormat(format map[string]any) Option

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

func WithPermissionMode(mode string) Option

WithPermissionMode controls how permissions are handled. Valid values: "default", "acceptEdits", "plan", "auto", "dontAsk", "bypassPermissions".

func WithPermissionPromptToolName

func WithPermissionPromptToolName(name string) Option

WithPermissionPromptToolName specifies the tool name to use for permission prompts.

func WithPersistPermissions added in v0.0.7

func WithPersistPermissions(path string) Option

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

func WithPromptSuggestions(enable bool) Option

WithPromptSuggestions enables prompt_suggestion messages after each turn.

func WithResume

func WithResume(sessionID string) Option

WithResume sets a session ID to resume from.

func WithSDKTools

func WithSDKTools(tools ...Tool) Option

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 WithSessionID added in v0.0.8

func WithSessionID(id string) Option

WithSessionID sets an explicit session ID for this session.

func WithSettingSources

func WithSettingSources(sources ...SettingSource) Option

WithSettingSources specifies which setting sources to use. When not called, the CLI loads its default sources (user, project, local). Use WithDisableSettingSources to disable all filesystem settings instead.

func WithSettings

func WithSettings(path string) Option

WithSettings sets the path to a settings file to load.

func WithStderr

func WithStderr(handler func(string)) Option

WithStderr sets a callback function for handling stderr output.

func WithSystemPrompt

func WithSystemPrompt(prompt string) Option

WithSystemPrompt sets the system message to send to Claude.

func WithSystemPromptFile added in v0.0.6

func WithSystemPromptFile(path string) Option

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

func WithTaskBudget(total int) Option

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 WithTracerProvider added in v0.0.9

func WithTracerProvider(tp trace.TracerProvider) Option

WithTracerProvider sets an OpenTelemetry TracerProvider for distributed tracing. When set, the SDK creates spans for query operations and adds trace context. Recording is completely noop when not set.

func WithTransport

func WithTransport(transport config.Transport) Option

WithTransport injects a custom transport implementation. The transport must implement the Transport interface.

func WithUnattendedRetry added in v0.0.7

func WithUnattendedRetry(enabled bool) Option

WithUnattendedRetry opts the CLI into its unattended retry mode.

func WithUser

func WithUser(user string) Option

WithUser sets a user identifier for tracking purposes.

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

type PromptCallback = prompt.Callback

PromptCallback handles generic CLI prompt request/response dialogs.

type PromptRequest added in v0.0.7

type PromptRequest = prompt.Request

PromptRequest represents a generic CLI prompt request.

type PromptRequestOption added in v0.0.7

type PromptRequestOption = prompt.Option

PromptRequestOption represents one selectable option in a CLI prompt request.

type PromptResponse added in v0.0.7

type PromptResponse = prompt.Response

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

type PromptTooLongDetails struct {
	ActualTokens *int
	LimitTokens  *int
}

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

type RenameSessionOptions struct {
	Directory  string
	ClaudeHome string
}

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

type SandboxSettings = sandbox.Settings

SandboxSettings configures CLI sandbox behavior.

type Schema

type Schema = jsonschema.Schema

Schema is a JSON Schema object for tool input validation.

type SdkBeta

type SdkBeta = config.Beta

SdkBeta represents a beta feature flag for the SDK.

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
	MaxResultSizeChars *int
}

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.

func (*SdkMcpTool) Name

func (t *SdkMcpTool) Name() string

Name returns the tool name.

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.

func WithMaxResultSizeChars added in v0.0.8

func WithMaxResultSizeChars(n int) SdkMcpToolOption

WithMaxResultSizeChars sets the maximum result size in characters for this tool. This overrides the CLI's default 50K character limit for tool output by sending the value via _meta in the tools/list response.

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.

func GetSubagentMessages added in v0.0.9

func GetSubagentMessages(
	sessionID, agentID string,
	options SessionMessagesOptions,
) []SessionMessage

GetSubagentMessages reads a subagent's conversation messages from its JSONL transcript file. Parses the subagent transcript, builds the conversation chain via parentUuid links, and returns user/assistant messages in chronological order.

Returns an empty list if the session or subagent is not found, sessionID is not a valid UUID, or the transcript contains no user/assistant messages.

type SessionMessagesOptions added in v0.0.2

type SessionMessagesOptions struct {
	Directory  string
	Limit      int
	Offset     int
	ClaudeHome string
}

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

func StatSession(
	ctx context.Context,
	sessionID string,
	opts ...Option,
) (*SessionStat, error)

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 StopHookInput

type StopHookInput = hook.StopInput

StopHookInput is the input for Stop 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

type TagSessionOptions struct {
	Directory  string
	ClaudeHome string
}

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

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 TaskType added in v0.0.7

type TaskType = message.TaskType

TaskType identifies the runtime class of a background task.

type TaskUsage added in v0.0.2

type TaskUsage = message.TaskUsage

TaskUsage contains task progress usage statistics.

type TeammateIdleHookInput added in v0.0.7

type TeammateIdleHookInput = hook.TeammateIdleInput

TeammateIdleHookInput is the input for TeammateIdle hooks.

type TextBlock

type TextBlock = message.TextBlock

TextBlock contains plain text content.

func PathInput added in v0.0.5

func PathInput(path string) *TextBlock

PathInput creates a text block containing a Claude CLI @path mention.

func TextInput added in v0.0.5

func TextInput(text string) *TextBlock

TextInput creates a text block for block-based multimodal user 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

func NewTool(name, description string, schema map[string]any, fn ToolFunc) Tool

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

type ToolCategory = toolmeta.Category

ToolCategory identifies the high-level behavior class of a Claude tool.

type ToolFunc

type ToolFunc func(ctx context.Context, input map[string]any) (map[string]any, error)

ToolFunc is a function-based tool implementation.

type ToolInterruptBehavior added in v0.0.7

type ToolInterruptBehavior = toolmeta.InterruptBehavior

type ToolMetadata added in v0.0.7

type ToolMetadata = toolmeta.Metadata

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 ToolsList

type ToolsList = config.ToolsList

ToolsList is a list of tool names to make available.

type ToolsPreset

type ToolsPreset = config.ToolsPreset

ToolsPreset represents a preset configuration for available tools.

type Transport

type Transport = config.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 Usage

type Usage = message.Usage

Usage contains token usage information.

type UserInputAnswer

type UserInputAnswer = userinput.Answer

UserInputAnswer contains response(s) for a question.

type UserInputCallback

type UserInputCallback = userinput.Callback

UserInputCallback handles AskUserQuestion prompts.

type UserInputQuestion

type UserInputQuestion = userinput.Question

UserInputQuestion represents a single AskUserQuestion prompt.

type UserInputQuestionOption

type UserInputQuestionOption = userinput.QuestionOption

UserInputQuestionOption represents a selectable choice within a question.

type UserInputRequest

type UserInputRequest = userinput.Request

UserInputRequest contains parsed AskUserQuestion payload data.

type UserInputResponse

type UserInputResponse = userinput.Response

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.

Directories

Path Synopsis
contrib
prometheus
Package prometheus provides a convenience helper for wiring Prometheus metrics into the Claude Agent SDK without pulling OTel SDK dependencies into the root module for every consumer.
Package prometheus provides a convenience helper for wiring Prometheus metrics into the Claude Agent SDK without pulling OTel SDK dependencies into the root module for every consumer.
examples
agents command
cancellation command
compaction_hook command
Package main demonstrates context compaction monitoring using the PreCompact hook.
Package main demonstrates context compaction monitoring using the PreCompact hook.
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
hooks 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.
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.
prometheus_metrics command
Example prometheus_metrics demonstrates how to expose SDK metrics via a Prometheus /metrics endpoint using the contrib/prometheus helper.
Example prometheus_metrics demonstrates how to expose SDK metrics via a Prometheus /metrics endpoint using the contrib/prometheus helper.
query_stream command
quick_start command
sessions command
setting_sources command
stderr_callback command
system_prompt command
task_budget command
tools_option command
traceparent_propagation command
Example traceparent_propagation demonstrates that the SDK propagates an active W3C OpenTelemetry trace context to the Claude CLI subprocess as TRACEPARENT/TRACESTATE env vars, so the CLI's spans parent under the caller's distributed trace.
Example traceparent_propagation demonstrates that the SDK propagates an active W3C OpenTelemetry trace context to the Claude CLI subprocess as TRACEPARENT/TRACESTATE env vars, so the CLI's spans parent under the caller's distributed trace.
turn_complete 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.
observability
Package observability provides OpenTelemetry metrics and tracing for the SDK.
Package observability provides OpenTelemetry metrics and tracing for the SDK.
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.

Jump to

Keyboard shortcuts

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