claudeagent

package module
v0.1.0 Latest Latest
Warning

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

Go to latest
Published: Sep 8, 2026 License: MIT Imports: 24 Imported by: ? modules, 0 packages

The first number is the count of modules that contain a package that imports this one. The module count is a better indicator of popularity than the package count. A module with 100 importing packages is counted only once instead of 100 times, reflecting the fact that the choice to use the package was likely made only once, not 100 times.
A '?' means that the value hasn't been computed yet.

README

Claude Agent SDK for Go

A Go SDK for building agentic applications powered by Claude Code CLI.

Installation

go get github.com/character-ai/claude-agent-sdk-go

Prerequisites:

  • Claude Code CLI must be installed and authenticated (for Client and Agent)
  • ANTHROPIC_API_KEY environment variable must be set (for APIAgent)

Quick Start

Simple Query
package main

import (
    "context"
    "fmt"
    "log"

    claude "github.com/character-ai/claude-agent-sdk-go"
)

func main() {
    ctx := context.Background()

    text, result, err := claude.QuerySync(ctx, "What is 2 + 2?")
    if err != nil {
        log.Fatal(err)
    }

    fmt.Println("Response:", text)
    fmt.Printf("Cost: $%.4f\n", result.Cost)
}
Streaming Response
events, err := claude.Query(ctx, "Explain quantum computing", claude.Options{
    MaxTurns: 5,
})
if err != nil {
    log.Fatal(err)
}

for event := range events {
    if event.Text != "" {
        fmt.Print(event.Text)
    }
}
With Tools
opts := claude.Options{
    AllowedTools:   []string{"Read", "Write", "Bash"},
    PermissionMode: claude.PermissionAcceptEdits,
    MaxTurns:       10,
}

client := claude.NewClient(opts)
events, err := client.Query(ctx, "Create a hello.txt file")
Custom Tools (API Agent)

The APIAgent calls the Anthropic API directly (no CLI needed). It reads ANTHROPIC_API_KEY from the environment by default, or you can pass it explicitly via APIAgentConfig.APIKey.

tools := claude.NewToolRegistry()

claude.RegisterFunc(tools, claude.ToolDefinition{
    Name:        "generate_image",
    Description: "Generate an image from a text prompt",
    InputSchema: claude.ObjectSchema(map[string]any{
        "prompt": claude.StringParam("Image description"),
        "style":  claude.EnumParam("Style", "photo", "anime", "illustration"),
    }, "prompt"),
}, func(ctx context.Context, input struct {
    Prompt string `json:"prompt"`
    Style  string `json:"style"`
}) (string, error) {
    // Your image generation logic
    return `{"url": "https://example.com/image.png"}`, nil
})

agent := claude.NewAPIAgent(claude.APIAgentConfig{
    Model:        "claude-sonnet-4-20250514",
    SystemPrompt: "You are a creative AI assistant.",
    Tools:        tools,
    MaxTurns:     5,
})

events, err := agent.Run(ctx, "Generate a sunset image")
HTTP Server with SSE
http.HandleFunc("/api/generate", func(w http.ResponseWriter, r *http.Request) {
    sse, _ := claude.NewSSEWriter(w)

    agent := claude.NewAgent(claude.AgentConfig{
        Options: claude.Options{
            PermissionMode: claude.PermissionAcceptEdits,
        },
        Tools:    tools,
        MaxTurns: 10,
    })

    events, _ := agent.Run(r.Context(), prompt)

    for event := range events {
        sse.WriteAgentEvent(event)
    }
    sse.Close()
})

Permission Callback (CanUseTool)

The CanUseToolFunc callback gives you interactive control over tool execution. It is called before hooks, allowing you to approve, deny, or modify tool invocations programmatically.

agent := claude.NewAgent(claude.AgentConfig{
    Options: claude.Options{
        PermissionMode: claude.PermissionAcceptEdits,
    },
    Tools:    tools,
    MaxTurns: 10,
    CanUseTool: func(ctx context.Context, toolName, toolUseID string, input json.RawMessage) claude.PermissionDecision {
        // Deny all Bash commands
        if toolName == "Bash" {
            return claude.PermissionDecision{
                Allow:  false,
                Reason: "Bash is not allowed in this environment",
            }
        }

        // Modify input for specific tools
        if toolName == "Write" {
            // Example: inject a safety header into the input
            return claude.PermissionDecision{
                Allow:         true,
                ModifiedInput: input, // optionally modify input here
            }
        }

        // Allow everything else
        return claude.PermissionDecision{Allow: true}
    },
})

The CanUseToolFunc is also available on APIAgentConfig for API-based agents.

Hooks System

Hooks allow you to intercept and control tool execution. This is useful for:

  • Blocking dangerous operations
  • Modifying tool inputs
  • Logging and auditing
  • Implementing custom permission logic
  • Monitoring lifecycle events
PreToolUse Hooks
hooks := claude.NewHooks()

// Block specific tools
hooks.OnTool("Bash").Before(func(ctx context.Context, hc claude.HookContext) claude.HookResult {
    var input struct {
        Command string `json:"command"`
    }
    json.Unmarshal(hc.Input, &input)

    // Block rm commands
    if strings.Contains(input.Command, "rm -rf") {
        return claude.DenyHook("Destructive commands are not allowed")
    }
    return claude.AllowHook()
})

// Log all tool executions
hooks.OnAllTools().Before(func(ctx context.Context, hc claude.HookContext) claude.HookResult {
    log.Printf("Tool called: %s", hc.ToolName)
    return claude.AllowHook()
})

// Modify tool input
hooks.OnTool("Write").Before(func(ctx context.Context, hc claude.HookContext) claude.HookResult {
    // Example: modify the input before execution
    return claude.ModifyHook(hc.Input) // optionally transform hc.Input here
})

agent := claude.NewAgent(claude.AgentConfig{
    Hooks: hooks,
    Tools: tools,
})
PostToolUse Hooks
hooks.OnAllTools().After(func(ctx context.Context, hc claude.HookContext, result string, isError bool) claude.HookResult {
    if isError {
        log.Printf("Tool %s failed: %s", hc.ToolName, result)
    }
    return claude.AllowHook()
})
Regex Matchers

Match tools by regular expression pattern instead of exact name:

// Match all MCP tools
hooks.OnToolRegex(`^mcp__.*`).Before(func(ctx context.Context, hc claude.HookContext) claude.HookResult {
    log.Printf("MCP tool called: %s", hc.ToolName)
    return claude.AllowHook()
})

// Match tools by prefix pattern
hooks.OnToolRegex(`^(Read|Write|Edit)$`).Before(func(ctx context.Context, hc claude.HookContext) claude.HookResult {
    log.Printf("File operation: %s", hc.ToolName)
    return claude.AllowHook()
})
Hook Timeouts

Protect against slow hooks with timeout support:

hooks.OnTool("external_api").WithTimeout(5 * time.Second).Before(func(ctx context.Context, hc claude.HookContext) claude.HookResult {
    // If this takes longer than 5 seconds, the hook is denied with "hook timed out"
    // Perform validation logic here (e.g., call an external service)
    log.Printf("Validating tool input for %s", hc.ToolName)
    return claude.AllowHook()
})
Enhanced Hook Results

Hook results support additional fields for richer control:

hooks.OnTool("search").Before(func(ctx context.Context, hc claude.HookContext) claude.HookResult {
    return claude.HookResult{
        Decision:          claude.HookAllow,
        AdditionalContext: "Remember to cite sources",  // Injected into conversation
        SystemMessage:     "Be concise in responses",   // System-level instruction
        Continue:          true,                         // Continue execution
        SuppressOutput:    false,                        // Show tool output
    }
})
Lifecycle Event Handlers

Monitor agent lifecycle events beyond tool execution:

hooks := claude.NewHooks()

hooks.OnEvent(claude.HookSessionStart, func(ctx context.Context, data claude.HookEventData) {
    log.Printf("Session started: %s", data.SessionID)
})

hooks.OnEvent(claude.HookSessionEnd, func(ctx context.Context, data claude.HookEventData) {
    log.Printf("Session ended: %s", data.Message)
})

hooks.OnEvent(claude.HookStop, func(ctx context.Context, data claude.HookEventData) {
    log.Printf("Agent stopped: %s", data.Message)
})

hooks.OnEvent(claude.HookPostToolUseFailure, func(ctx context.Context, data claude.HookEventData) {
    log.Printf("Tool %s failed: %s", data.ToolName, data.Error)
})

hooks.OnEvent(claude.HookSubagentStart, func(ctx context.Context, data claude.HookEventData) {
    log.Printf("Subagent %s started", data.SubagentName)
})

hooks.OnEvent(claude.HookSubagentStop, func(ctx context.Context, data claude.HookEventData) {
    log.Printf("Subagent %s stopped", data.SubagentName)
})

hooks.OnEvent(claude.HookNotification, func(ctx context.Context, data claude.HookEventData) {
    log.Printf("Notification: %s", data.Message)
})

Available Hook Events:

Event Description
HookPreToolUse Before a tool is executed
HookPostToolUse After a tool is executed successfully
HookPostToolUseFailure After a tool execution fails
HookStop When the agent stops (e.g., max turns reached)
HookSubagentStart When a subagent begins execution
HookSubagentStop When a subagent finishes execution
HookNotification General notifications
HookSessionStart When a session begins
HookSessionEnd When a session ends

Metrics

The MetricsCollector gathers per-turn LLM latency and per-tool execution stats with no overhead when not configured. Attach it via AgentConfig.Metrics or APIAgentConfig.Metrics.

mc := claude.NewMetricsCollector()

agent := claude.NewAPIAgent(claude.APIAgentConfig{
    Model:   "claude-sonnet-4-20250514",
    Tools:   tools,
    Metrics: mc,
})

events, _ := agent.Run(ctx, "...")
for range events {}

snap := mc.Snapshot()
fmt.Printf("Session duration:   %v\n", snap.SessionDuration)
fmt.Printf("Turns completed:    %d\n", len(snap.Turns))
for _, t := range snap.Turns {
    fmt.Printf("  turn %d: LLM=%v  tools=%v\n", t.TurnIndex, t.LLMLatency, t.ToolsInvoked)
}
for name, s := range snap.ToolStats {
    fmt.Printf("  %-20s calls=%d failures=%d avg=%v\n", name, s.Calls, s.Failures, s.AvgTime())
}

Snapshot() is safe to call concurrently with a running agent and returns a deep copy.

Live per-turn metrics in the event stream

When a MetricsCollector is configured, every AgentEventTurnComplete event carries a populated TurnMetrics field so you can react to each turn's data immediately:

for event := range events {
    if event.Type == claude.AgentEventTurnComplete && event.TurnMetrics != nil {
        tm := event.TurnMetrics
        log.Printf("turn %d: LLM latency=%v tools=%v", tm.TurnIndex, tm.LLMLatency, tm.ToolsInvoked)
    }
}
Metrics types
Type Fields
LoopMetrics SessionDuration, Turns []TurnMetrics, ToolStats map[string]*ToolStats
TurnMetrics TurnIndex int, LLMLatency time.Duration, ToolsInvoked []string
ToolStats Name, Calls, Failures, TotalTime, AvgTime() time.Duration

Parallel Tool Execution

By default, tool calls within a turn execute sequentially. Set ParallelTools: true to run them all concurrently:

agent := claude.NewAgent(claude.AgentConfig{
    Tools:         tools,
    ParallelTools: true, // all tools in a turn run concurrently
})

This is also available on APIAgentConfig.ParallelTools.

Results always preserve input order — if Claude invokes [search, write, read], the results slice is always [search_result, write_result, read_result] regardless of completion order.

Only enable this for independent, side-effect-free tools. If your tools share state, write to the same files, or must run in a specific order, keep the default (false).

Example speedup: 3 tools each taking 100 ms run in ~100 ms parallel vs ~300 ms sequential.

Retry Logic

RetryConfig adds automatic retry with exponential backoff to tool execution. Configure it globally on the agent or per-tool on ToolDefinition — the per-tool setting takes precedence.

// Global retry: all tools retry up to 3 times with 500 ms base backoff
agent := claude.NewAPIAgent(claude.APIAgentConfig{
    Tools: tools,
    Retry: &claude.RetryConfig{
        MaxAttempts: 3,
        Backoff:     500 * time.Millisecond,
        RetryOn: func(err error) bool {
            // Only retry on transient errors; stop immediately on permanent ones
            return strings.Contains(err.Error(), "rate limit") ||
                strings.Contains(err.Error(), "timeout")
        },
    },
})

Per-tool override — useful when one tool is flaky but others should fail fast:

claude.RegisterFunc(tools, claude.ToolDefinition{
    Name:        "external_api",
    Description: "Call an external API",
    InputSchema: claude.ObjectSchema(map[string]any{
        "endpoint": claude.StringParam("API endpoint"),
    }, "endpoint"),
    RetryConfig: &claude.RetryConfig{
        MaxAttempts: 5,
        Backoff:     time.Second,
        // nil RetryOn means retry on any error
    },
}, handler)

Backoff schedule for Backoff: 500ms, MaxAttempts: 4: 0 ms → fail → 500 ms → fail → 1 s → fail → 2 s → fail → error returned

When RetryOn is nil, all errors are retried. Set MaxAttempts: 1 (or 0) to disable retry entirely.

Budget Controls

BudgetConfig stops the session with a *BudgetExceededError when any resource limit is hit. All three limits are independent; any zero value means unlimited.

agent := claude.NewAPIAgent(claude.APIAgentConfig{
    Budget: &claude.BudgetConfig{
        MaxTokens:   50_000,            // cumulative input+output tokens
        MaxCostUSD:  0.50,              // cumulative cost in USD (Agent/CLI only)
        MaxDuration: 2 * time.Minute,   // wall-clock session time
    },
})

Detect the error in the event stream:

for event := range events {
    if event.Type == claude.AgentEventError {
        var budgetErr *claude.BudgetExceededError
        if errors.As(event.Error, &budgetErr) {
            log.Printf("session stopped: %v", budgetErr)
        }
    }
}
Limit Agent (CLI) APIAgent
MaxTokens ✓ via ResultMessage.Usage ✓ via streaming events
MaxCostUSD ✓ via ResultMessage.Cost — (not available)
MaxDuration ✓ ✓

History Compaction

HistoryConfig prevents context-window growth in long sessions by compacting the conversation history sent to the LLM on each turn. The full history is always kept in memory — only the LLM's view is trimmed.

agent := claude.NewAgent(claude.AgentConfig{
    History: &claude.HistoryConfig{
        // Only include the last 5 turns in each LLM call.
        // The initial user prompt is always preserved.
        MaxTurns: 5,

        // Replace tool-result content in older turns with a placeholder.
        // Saves tokens while keeping the conversation structure valid.
        // (CLI Agent only; use MaxTurns for APIAgent.)
        DropToolResults: true,
    },
})

With MaxTurns: 3 and a 6-turn history, the LLM receives:

[user]       initial prompt          ← always kept
[assistant]  turn 4 response
[tool]       turn 4 result
[assistant]  turn 5 response
[tool]       turn 5 result
[assistant]  turn 6 response
[tool]       turn 6 result

Turns 1–3 are omitted. With DropToolResults: true, the tool-result lines in older kept turns are replaced with [tool result omitted].

Todo Tracking

Enable the built-in write_todos and read_todos tools so the agent can plan its work and track progress. The host app receives AgentEventTodosUpdated events whenever the list changes. The read_todos tool lets the agent refresh its view of pending work after long conversations where earlier context may have been compressed by HistoryConfig.

agent := claude.NewAPIAgent(claude.APIAgentConfig{
    SystemPrompt: "Plan your work using write_todos before starting.",
    EnableTodos:  true,
})

events, _ := agent.Run(ctx, "Build a REST API in Go")

for event := range events {
    if event.Type == claude.AgentEventTodosUpdated {
        for _, todo := range event.Todos {
            fmt.Printf("[%s] %s — %s\n", todo.Status, todo.ID, todo.Description)
        }
    }
}
Shared TodoStore across agents

Pass a pre-existing TodoStore to share state between parent and child agents:

shared := claude.NewTodoStore()

parent := claude.NewAgent(claude.AgentConfig{
    EnableTodos: true,
    TodoStore:   shared,
})

// Read the live todo list at any time
todos := shared.List()
TodoItem fields
Field Type Description
ID string Unique identifier
Description string What needs to be done
Status TodoStatus pending, in_progress, or completed
Priority TodoPriority high, medium, or low
ParentID string Optional parent ID for subtasks (validated to exist in same batch)

Subagents

Subagents allow you to define specialized child agents that can be invoked via a Task tool. When you configure subagents, a Task tool is automatically registered that Claude can use to delegate work.

// Create tools for the researcher subagent
researchTools := claude.NewToolRegistry()
claude.RegisterFunc(researchTools, claude.ToolDefinition{
    Name:        "search",
    Description: "Search for information",
    InputSchema: claude.ObjectSchema(map[string]any{
        "query": claude.StringParam("Search query"),
    }, "query"),
}, func(ctx context.Context, input struct{ Query string `json:"query"` }) (string, error) {
    return fmt.Sprintf("Results for: %s", input.Query), nil
})

// Define subagents
subagents := claude.NewSubagentConfig()

subagents.Add(&claude.AgentDefinition{
    Name:        "researcher",
    Description: "Researches topics and returns summarized findings",
    Prompt:      "You are a research assistant. Use the search tool to find information.",
    Tools:       researchTools,
    Model:       "haiku",      // Use a faster model for research
    MaxTurns:    5,
})

subagents.Add(&claude.AgentDefinition{
    Name:        "coder",
    Description: "Writes code based on specifications",
    Prompt:      "You are a coding assistant. Write clean, documented code.",
    Model:       "sonnet",
    MaxTurns:    10,
})

// Create the main agent with subagents
agent := claude.NewAgent(claude.AgentConfig{
    Options: claude.Options{
        Model:          "claude-sonnet-4-20250514",
        PermissionMode: claude.PermissionAcceptEdits,
    },
    MaxTurns:  10,
    Subagents: subagents,
})

// Claude can now use the Task tool to delegate to subagents:
// Task(description="Research Go generics patterns", subagent_name="researcher")
events, err := agent.Run(ctx, "Research Go generics and write an example")
AgentDefinition Fields
Field Type Description
Name string Unique identifier for the subagent
Description string Explains what the subagent does (shown to Claude)
Prompt string System prompt for the subagent
Tools *ToolRegistry Tool registry for the subagent
Model string Model to use: "sonnet", "opus", "haiku", or "inherit" (parent's model)
MaxTurns int Max turns for the subagent (default: 10)
Hooks *Hooks Lifecycle hooks for the subagent
Subagent Events

Agent events include subagent metadata when events originate from a child agent:

for event := range events {
    if event.SubagentName != "" {
        fmt.Printf("[%s] ", event.SubagentName)
    }
    if event.Content != "" {
        fmt.Print(event.Content)
    }
}

File Checkpointing

Enable file checkpointing to rewind file changes to previous states:

agent := claude.NewAgent(claude.AgentConfig{
    Options: claude.Options{
        EnableFileCheckpointing: true,
    },
    MaxTurns: 10,
})

events, _ := agent.Run(ctx, "Refactor the codebase")

// Later, rewind file changes to a specific message
err := agent.RewindFiles(ctx, "msg_01234567")

You can also use CheckpointManager directly:

cm := claude.NewCheckpointManager(sessionID, "", ".")
err := cm.RewindFiles(ctx, userMessageID)

Unified Store

All tools, skills, and hooks are stored in a unified go-memdb-backed store with indexed lookups and thread-safe access. Components can share a store for cross-cutting queries.

// Create a shared store.
store := claude.NewStore()

// Create registries that share the store.
tools := claude.NewToolRegistryWithStore(store)
hooks := claude.NewHooksWithStore(store)
skills := claude.NewSkillRegistry(store)

// Query tools by source or tag.
mcpTools, _ := store.ListToolsBySource("mcp:my-server")
webTools, _ := store.ListToolsByTag("web")

// Point-in-time snapshot for consistent reads.
snap := store.Snapshot()
defer snap.Close()
allTools, _ := snap.Tools()
allSkills, _ := snap.Skills()

Skills

Skills are composable capability bundles — groups of related tools with rich metadata (tags, categories, dependencies, examples). They enable semantic tool selection and modular agent composition.

Registering Skills
store := claude.NewStore()
skillReg := claude.NewSkillRegistry(store)

// Create tools for the skill.
webTools := claude.NewToolRegistry()
claude.RegisterFunc(webTools, claude.ToolDefinition{
    Name:        "web_search",
    Description: "Search the web for information",
    InputSchema: claude.ObjectSchema(map[string]any{
        "query": claude.StringParam("The search query"),
    }, "query"),
}, func(ctx context.Context, input struct {
    Query string `json:"query"`
}) (string, error) {
    return fmt.Sprintf("Results for: %s", input.Query), nil
})

// Register the skill with its tools.
err := skillReg.Register(claude.Skill{
    Name:        "web-research",
    Description: "Search the web and fetch page content",
    Tags:        []string{"web", "search", "research"},
    Category:    "research",
    Examples: []claude.SkillExample{
        {Query: "Find the latest news about Go", ToolsUsed: []string{"web_search"}},
    },
}, webTools)
Querying Skills
// By tag.
webSkills, _ := skillReg.ByTag("web")

// By category.
researchSkills, _ := skillReg.ByCategory("research")

// All skills.
all, _ := skillReg.All()
Dependency Resolution

Skills can declare dependencies. Resolve performs transitive resolution with cycle detection:

// "web-research" depends on "text-processing".
skillReg.Register(claude.Skill{
    Name:         "web-research",
    Dependencies: []string{"text-processing"},
}, webTools)

// Resolve returns a ToolRegistry with tools from both skills.
resolved, _ := skillReg.Resolve("web-research")

The SDK includes a zero-dependency BM25 keyword search index for semantic skill/tool selection:

index := claude.NewBM25Index()

// Index skills by description + tags.
_ = index.Index("web-research", "Search the web and fetch page content", []string{"web", "search"})
_ = index.Index("math", "Perform mathematical calculations", []string{"math", "calculation"})

// Search returns ranked results.
results := index.Search("search the web for information", 3)
for _, r := range results {
    fmt.Printf("  %s (score: %.3f)\n", r.ID, r.Score)
}

You can also implement the SkillIndex interface for custom search backends (e.g., vector search).

Context Builder (Dynamic Tool Selection)

The ContextBuilder selects relevant tools per turn using BM25 search over skill descriptions. This keeps the tool list small and focused, improving model performance.

store := claude.NewStore()
index := claude.NewBM25Index()
skillReg := claude.NewSkillRegistry(store)

// ... register skills and index them ...

cb := claude.NewContextBuilder(store, claude.WithIndex(index), claude.WithMaxTools(10))

// Use with APIAgent for dynamic per-turn tool selection.
agent := claude.NewAPIAgent(claude.APIAgentConfig{
    Tools:          claude.NewToolRegistryWithStore(store),
    Skills:         skillReg,
    ContextBuilder: cb,
    SystemPrompt:   "You are a helpful assistant.",
})

When ContextBuilder is configured:

  • Each turn, tools are selected based on the current query context
  • Dependencies are resolved transitively with decaying relevance scores
  • Falls back to all tools if no index is configured or query is empty

Graceful Shutdown

The SDK provides both immediate and graceful shutdown methods:

agent := claude.NewAgent(cfg)
events, _ := agent.Run(ctx, prompt)

// Graceful shutdown: sends SIGINT, waits up to 5s, then SIGKILL
err := agent.Close()

// Immediate shutdown: cancels context
agent.Stop()

For the low-level client:

client := claude.NewClient(opts)
events, _ := client.Query(ctx, prompt)

// Graceful: SIGINT → wait 5s → SIGKILL
client.Close()

// Immediate: SIGKILL
client.Stop()

Streaming Input

Send follow-up messages to a running agent via stdin:

client := claude.NewClient(opts)
events, _ := client.Query(ctx, "Start a conversation")

// Send additional input while the query is running
client.Send("Here is some additional context")

// Agent-level wrapper
agent := claude.NewAgent(cfg)
events, _ := agent.Run(ctx, "Start working")
agent.Send(ctx, "Also consider edge cases")

MCP Server Integration

The SDK supports Model Context Protocol (MCP) servers for custom tool integration.

In-Process MCP Server
// Create an in-process MCP server
server := claude.NewSDKMCPServer("my-tools", "1.0.0")

// Add a tool with typed input
type GreetInput struct {
    Name string `json:"name"`
}

claude.AddToolFunc(server, claude.MCPTool{
    Name:        "greet",
    Description: "Greet a user by name",
    InputSchema: claude.ObjectSchema(map[string]any{
        "name": claude.StringParam("The user's name"),
    }, "name"),
}, func(ctx context.Context, args GreetInput) (string, error) {
    return fmt.Sprintf("Hello, %s!", args.Name), nil
})

// Add another tool
type CalcInput struct {
    A  float64 `json:"a"`
    B  float64 `json:"b"`
    Op string  `json:"op"`
}

claude.AddToolFunc(server, claude.MCPTool{
    Name:        "calculate",
    Description: "Perform math operations",
    InputSchema: claude.ObjectSchema(map[string]any{
        "a":  claude.IntParam("First number"),
        "b":  claude.IntParam("Second number"),
        "op": claude.EnumParam("Operation", "add", "subtract", "multiply"),
    }, "a", "b", "op"),
}, func(ctx context.Context, args CalcInput) (string, error) {
    var result float64
    switch args.Op {
    case "add":
        result = args.A + args.B
    case "subtract":
        result = args.A - args.B
    case "multiply":
        result = args.A * args.B
    }
    return fmt.Sprintf("%.2f", result), nil
})

// Configure MCP servers
mcpServers := claude.NewMCPServers()
mcpServers.AddInProcess("tools", server)

// Convert to tool registry for use with Agent
registry := claude.NewMCPToolRegistry(mcpServers).ToToolRegistry()

// Tools are named: mcp__<server>__<tool>
// e.g., mcp__tools__greet, mcp__tools__calculate
MCP Tool Annotations

Provide hints about tool behavior using annotations:

server.AddTool(claude.MCPTool{
    Name:        "read_file",
    Description: "Read a file from disk",
    InputSchema: schema,
    Annotations: &claude.MCPToolAnnotations{
        ReadOnlyHint:    true,  // Only reads data, no side effects
        DestructiveHint: false, // Does not cause irreversible changes
        IdempotentHint:  true,  // Same input always produces same result
        OpenWorldHint:   true,  // Interacts with the filesystem
    },
}, handler)
Combining MCP Tools with Custom Tools
// Create custom tools
customTools := claude.NewToolRegistry()
claude.RegisterFunc(customTools, claude.ToolDefinition{
    Name: "custom_tool",
    // ...
}, handler)

// Create MCP tools
mcpRegistry := claude.NewMCPToolRegistry(mcpServers).ToToolRegistry()

// Merge all tools
allTools := claude.MergeToolRegistries(customTools, mcpRegistry)

agent := claude.NewAgent(claude.AgentConfig{
    Tools: allTools,
})
MCP Server Status
server := claude.NewSDKMCPServer("tools", "1.0.0")
// ... add tools ...

fmt.Println(server.ToolCount()) // Number of registered tools
fmt.Println(server.HasTool("greet")) // Check if a tool exists

Configuration

Options
Field Type Description
Cwd string Working directory for the agent
CLIPath string Path to Claude CLI (defaults to "claude" in PATH)
Model string Model to use (e.g., "claude-sonnet-4-20250514")
PermissionMode PermissionMode Tool permission handling
AllowedTools []string List of allowed tools (filter)
DisallowedTools []string List of disallowed tools (filter)
MaxTurns int Maximum conversation turns
SystemPrompt string System prompt override
SessionID string Continue from previous session
MCPServers *MCPServers MCP server configuration
ExtraArgs []string Additional CLI arguments
Tools *ToolsConfig Built-in tool specification (preset or explicit names)
CustomSessionID string Explicit session ID instead of auto-generated
ForkSession bool Fork the session specified by SessionID
Debug bool Enable debug logging
DebugFile string Write debug output to file instead of stderr
Betas []string Enable beta features by name
AdditionalDirectories []string Extra directories to add to agent context
SettingSources []string Additional settings source files
Plugins []PluginConfig Plugins to load
EnableFileCheckpointing bool Enable file checkpointing for rewind
AgentConfig
Field Type Description
Options Options Base client options
Tools *ToolRegistry Custom tool registry
Hooks *Hooks Hook handlers for tool lifecycle
MaxTurns int Max turns (default: 10)
CanUseTool CanUseToolFunc Permission callback (called before hooks)
Subagents *SubagentConfig Subagent definitions for Task tool
Skills *SkillRegistry Skill-based tool organization
ContextBuilder *ContextBuilder Dynamic per-turn tool selection
Metrics *MetricsCollector Collect per-turn and per-tool metrics (nil = disabled)
ParallelTools bool Run multiple tool calls per turn concurrently (default: false)
Retry *RetryConfig Global retry policy for tool execution (nil = no retry)
Budget *BudgetConfig Resource limits: tokens, cost, time (nil = unlimited)
History *HistoryConfig History compaction to bound context window (nil = disabled)
EnableTodos bool Register write_todos tool for agent self-planning (default: false)
TodoStore *TodoStore Shared todo store; auto-created if nil and EnableTodos is true
APIAgentConfig
Field Type Description
APIKey string Anthropic API key (defaults to ANTHROPIC_API_KEY env var)
Model string Model to use (default: claude-sonnet-4-20250514)
SystemPrompt string System prompt
Tools *ToolRegistry Custom tool registry
Hooks *Hooks Hook handlers for tool lifecycle
MaxTurns int Max turns (default: 10)
CanUseTool CanUseToolFunc Permission callback (called before hooks)
Subagents *SubagentConfig Subagent definitions for Task tool
Skills *SkillRegistry Skill-based tool organization
ContextBuilder *ContextBuilder Dynamic per-turn tool selection
Metrics *MetricsCollector Collect per-turn and per-tool metrics (nil = disabled)
ParallelTools bool Run multiple tool calls per turn concurrently (default: false)
Retry *RetryConfig Global retry policy for tool execution (nil = no retry)
Budget *BudgetConfig Resource limits: tokens, time (nil = unlimited)
History *HistoryConfig History compaction to bound context window (nil = disabled)
EnableTodos bool Register write_todos tool for agent self-planning (default: false)
TodoStore *TodoStore Shared todo store; auto-created if nil and EnableTodos is true
Built-in Tool Control

Use ToolsConfig to specify exactly which built-in tools are available (different from AllowedTools/DisallowedTools which are filters):

opts := claude.Options{
    Tools: &claude.ToolsConfig{
        Preset: "code",                           // Use a preset
        Names:  []string{"Read", "Write", "Bash"}, // Or specify individual tools
    },
}
Plugins

Load plugins from files:

opts := claude.Options{
    Plugins: []claude.PluginConfig{
        {Type: "file", Path: "/path/to/plugin.js"},
    },
}
Permission Modes
  • PermissionDefault - Default permission handling
  • PermissionAcceptEdits - Auto-accept file edits
  • PermissionPlan - Plan mode only
  • PermissionBypassAll - Bypass all permissions (use with caution)

Error Handling

import "errors"

events, err := claude.Query(ctx, "Hello")
if err != nil {
    if errors.Is(err, claude.ErrCLINotFound) {
        log.Fatal("Claude CLI not installed")
    }
    if errors.Is(err, claude.ErrAlreadyRunning) {
        log.Fatal("Client already running")
    }
    log.Fatal(err)
}

for event := range events {
    if event.Error != nil {
        var procErr *claude.ProcessError
        if errors.As(event.Error, &procErr) {
            log.Printf("Process failed (exit %d): %s", procErr.ExitCode, procErr.Stderr)
        }
        var jsonErr *claude.JSONDecodeError
        if errors.As(event.Error, &jsonErr) {
            log.Printf("JSON decode error: %v", jsonErr.Err)
        }
    }
}
Error Types
Error Description
ErrCLINotFound Claude CLI not found in PATH
ErrAlreadyRunning Client is already processing a query
ErrNotRunning No query in progress
ProcessError CLI process exited with error (has ExitCode, Stderr)
JSONDecodeError Failed to parse JSON response
ToolNotFoundError Tool not found in registry

Event Types

When streaming, you'll receive events of these types:

Client Events
  • EventMessageStart - New assistant message starting
  • EventContentBlockStart - Content block (text or tool use) starting
  • EventContentBlockDelta - Incremental content update
  • EventContentBlockStop - Content block finished
  • EventToolResult - Result from tool execution
  • EventResult - Final result with cost and token counts
Agent Events
  • AgentEventMessageStart - New message starting
  • AgentEventContentDelta - Text content delta
  • AgentEventMessageEnd - Message finished
  • AgentEventToolUseStart - Tool invocation starting
  • AgentEventToolUseDelta - Tool input streaming
  • AgentEventToolUseEnd - Tool invocation complete
  • AgentEventToolResult - Tool execution result
  • AgentEventTodosUpdated - Todo list changed (includes Todos []TodoItem); requires EnableTodos
  • AgentEventTurnComplete - Turn finished (tool results sent back); includes TurnMetrics when a MetricsCollector is configured
  • AgentEventComplete - Agent finished (includes Result with StopReason)
  • AgentEventError - Error occurred

Examples

See the examples directory:

  • simple - Basic synchronous query
  • streaming - Real-time event streaming
  • tools - Working with built-in tools
  • generation - Custom tools for image/video generation (API agent)
  • hooks - Hook patterns: regex, timeout, lifecycle events, permissions
  • subagents - Subagent definitions with the Task tool
  • skills - Skills, BM25 search, context builder, and dynamic tool selection
  • metrics - Per-turn LLM latency, per-tool stats, and parallel tool execution
  • resilience - Retry logic, budget controls, and history compaction
  • todos - Built-in todo tracking with AgentEventTodosUpdated
  • artifacts - Artifact generation (HTML/JSX/text) with API agent

Python SDK Parity

This Go SDK aims for feature parity with the official Python Claude Agent SDK.

Feature Comparison
Feature Python SDK Go SDK Notes
Core API
Simple query function query() Query() / QuerySync()
Streaming responses AsyncIterator <-chan Event Go-idiomatic channels
Stateful client ClaudeSDKClient Client
Agents
CLI-based agent via ClaudeSDKClient Agent
Direct API agent - APIAgent Go-only feature
Subagents SubagentConfig SubagentConfig Auto-registers Task tool
Tools
Built-in tools Read, Write, Bash Read, Write, Bash
Built-in tool control tools ToolsConfig Preset or explicit names
Custom tools @tool decorator RegisterFunc Type-safe generics
Tool registry implicit ToolRegistry Explicit registry
Permissions
Permission callback can_use_tool CanUseToolFunc Called before hooks
Permission modes permission_mode PermissionMode
MCP Integration
In-process MCP servers create_sdk_mcp_server NewSDKMCPServer
External MCP servers stdio config MCPServerConfig
Tool naming mcp__server__tool mcp__server__tool Same convention
Tool annotations MCPToolAnnotations MCPToolAnnotations Behavior hints
Hooks
PreToolUse HookMatcher hooks.OnTool().Before() Fluent API
PostToolUse - hooks.OnTool().After()
Hook decisions allow/deny AllowHook/DenyHook/ModifyHook
Wildcard matching "*" OnAllTools()
Regex matching regex matchers OnToolRegex()
Hook timeout timeout config WithTimeout()
Lifecycle events event handlers OnEvent() / EmitEvent() 9 event types
Enhanced results additional fields AdditionalContext, SuppressOutput, etc.
Sessions
Session continuation session_id SessionID
Custom session ID custom_session_id CustomSessionID
Session forking fork_session ForkSession
File checkpointing enable_file_checkpointing EnableFileCheckpointing
File rewind rewind_files() RewindFiles()
Configuration
Working directory cwd Cwd
CLI path override cli_path CLIPath
System prompt system_prompt SystemPrompt
Max turns max_turns MaxTurns
Debug mode debug Debug / DebugFile
Betas betas Betas
Additional directories additional_directories AdditionalDirectories
Setting sources setting_sources SettingSources
Plugins plugins Plugins
Lifecycle
Graceful shutdown close() Close() SIGINT → SIGKILL
Streaming input send() Send() Stdin pipe
Stop reason stop_reason StopReason In ResultMessage
Error Handling
CLI not found CLINotFoundError ErrCLINotFound
Process error ProcessError ProcessError
JSON decode error CLIJSONDecodeError JSONDecodeError
Connection error CLIConnectionError - Not implemented
Content Types
TextBlock ✓ ✓
ToolUseBlock ✓ ✓
ToolResultBlock ✓ ✓
Skills & Context
Skill registry - SkillRegistry Go-only: composable capability bundles
BM25 search - BM25Index Go-only: zero-dependency keyword search
Context builder - ContextBuilder Go-only: dynamic per-turn tool selection
Unified store - Store Go-only: go-memdb backed indexed storage
Metrics collection - MetricsCollector Go-only: per-turn LLM latency + per-tool stats
Parallel tool execution - ParallelTools Go-only: concurrent tool calls within a turn
Retry logic - RetryConfig Go-only: per-tool exponential backoff
Budget controls - BudgetConfig Go-only: token, cost, and time limits
History compaction - HistoryConfig Go-only: rolling window + tool-result pruning
Todo tracking - EnableTodos / TodoStore Go-only: built-in write_todos tool for agent self-planning
Artifact generation - ArtifactRegistry Go-only: in-memory HTML/JSX/text artifact system
Extras
SSE HTTP helpers - SSEWriter Go-only feature
HTTP handler - AgentHTTPHandler Go-only feature
Go-Specific Features

Features available in the Go SDK but not in Python:

  1. Direct API Agent (APIAgent) - Bypasses CLI and calls Anthropic API directly
  2. SSE Helpers - Built-in Server-Sent Events support for HTTP streaming
  3. HTTP Handler - Ready-to-use HTTP handler for agent endpoints
  4. Type-Safe Tool Registration - Generics-based RegisterFunc[T]
  5. Skills & Context Builder - Composable capability bundles with BM25-based dynamic tool selection
  6. Unified Store - go-memdb-backed indexed storage for tools, skills, and hooks
  7. Metrics Collection - MetricsCollector for per-turn LLM latency and per-tool execution stats
  8. Parallel Tool Execution - ParallelTools flag for concurrent tool calls within a turn
  9. Retry Logic - RetryConfig with exponential backoff, configurable globally or per-tool
  10. Budget Controls - BudgetConfig with token, cost, and time limits per session
  11. History Compaction - HistoryConfig rolling window to keep context window bounded
  12. Todo Tracking - EnableTodos / TodoStore for agent self-planning with AgentEventTodosUpdated events
  13. Artifact Generation - ArtifactRegistry for generating self-contained HTML, JSX, or text artifacts
Python-Specific Features

Features in the Python SDK not yet in Go:

  1. CLIConnectionError - Specific error type for connection issues

License

MIT

Documentation

Overview

Package claudeagent provides a Go SDK for interacting with Claude Code CLI.

Index

Constants

View Source
const ReadTodosToolName = "read_todos"

ReadTodosToolName is the registered name of the read_todos tool.

View Source
const TodoToolName = "write_todos"

TodoToolName is the registered name of the write_todos tool.

Variables

View Source
var (
	// ErrCLINotFound indicates the claude CLI is not installed or not in PATH.
	ErrCLINotFound = errors.New("claude CLI not found in PATH")

	// ErrAlreadyRunning indicates the client is already processing a query.
	ErrAlreadyRunning = errors.New("client already running")

	// ErrNotRunning indicates no query is in progress.
	ErrNotRunning = errors.New("no query in progress")
)

Functions

func AddToolFunc

func AddToolFunc[T any](s *SDKMCPServer, tool MCPTool, handler func(ctx context.Context, args T) (string, error))

AddToolFunc registers a typed tool handler.

func AgentHTTPHandler

func AgentHTTPHandler(agent *Agent) http.HandlerFunc

AgentHTTPHandler creates an HTTP handler that runs an agent and streams SSE.

func BoolParam

func BoolParam(description string) map[string]any

BoolParam creates a boolean parameter schema.

func CollectText

func CollectText(events <-chan Event) (string, error)

CollectText is a helper that extracts all text from a stream of events.

func DefaultDockerImages

func DefaultDockerImages() map[Language]string

DefaultDockerImages returns the default Docker images for each language.

func DeleteSession

func DeleteSession(sessionID, directory, configDir string) error

DeleteSession permanently removes a session transcript and its sibling subdirectory, including all nested subagent transcripts.

func DeleteSessionFromStore

func DeleteSessionFromStore(ctx context.Context, store SessionStore, projectKey, sessionID string) error

DeleteSessionFromStore deletes a main transcript. SessionStore implementations must cascade a main-key delete to that session's subkeys.

func EnumParam

func EnumParam(description string, values ...string) map[string]any

EnumParam creates an enum parameter schema.

func FormatReminder

func FormatReminder(r SystemReminder) string

FormatReminder wraps content in <system-reminder> XML tags.

func FormatReminders

func FormatReminders(reminders []SystemReminder) string

FormatReminders formats multiple reminders into a single string.

func GetToolName

func GetToolName(serverName, toolName string) string

GetToolName returns the full tool name for an MCP tool (mcp__serverName__toolName).

func IntParam

func IntParam(description string) map[string]any

IntParam creates an integer parameter schema.

func MarshalToolInput

func MarshalToolInput(v any) json.RawMessage

MarshalToolInput is a helper to marshal tool input to JSON.

func ObjectSchema

func ObjectSchema(properties map[string]any, required ...string) map[string]any

ObjectSchema creates an object schema for tool input.

func ProjectKeyForDirectory

func ProjectKeyForDirectory(directory string) (string, error)

ProjectKeyForDirectory derives the SessionStore project key used by Claude Code for directory-backed transcripts.

func Query

func Query(ctx context.Context, prompt string, opts ...Options) (<-chan Event, error)

Query sends a prompt to Claude and returns a channel of streaming events. This is a convenience function that creates a temporary client.

func QueryWithCallback

func QueryWithCallback(ctx context.Context, prompt string, callback StreamCallback, opts ...Options) error

QueryWithCallback sends a prompt and calls the callback for each event.

func RegisterFunc

func RegisterFunc[T any](r *ToolRegistry, def ToolDefinition, handler func(ctx context.Context, input T) (string, error))

RegisterFunc is a convenience method for registering a tool with a typed handler.

func RegisterStructuredFunc

func RegisterStructuredFunc[T any](r *ToolRegistry, def ToolDefinition, handler func(ctx context.Context, input T) (string, *ToolResultMetadata, error))

RegisterStructuredFunc is a convenience method for registering a structured tool with a typed handler.

func RegisterTodosTools

func RegisterTodosTools(registry *ToolRegistry, store *TodoStore)

RegisterTodosTools registers both write_todos and read_todos tools on the given registry, backed by the provided TodoStore.

func RegisterToolSearchTool

func RegisterToolSearchTool(registry *ToolRegistry, deferred *DeferredToolRegistry)

RegisterToolSearchTool registers a "ToolSearch" tool in the given registry that allows the model to discover and load deferred tools on demand.

func StreamAgentToSSE

func StreamAgentToSSE(events <-chan AgentEvent, sse *SSEWriter) error

StreamAgentToSSE connects an agent event channel to an SSE writer.

func StringParam

func StringParam(description string) map[string]any

StringParam creates a string parameter schema.

func WithTraceContext

func WithTraceContext(ctx context.Context, traceparent, tracestate string) context.Context

WithTraceContext returns a child context whose W3C trace headers are passed to the Claude CLI as TRACEPARENT and TRACESTATE. Explicit Options.Env values take precedence. This provides propagation without requiring an OpenTelemetry dependency in the SDK; callers can inject headers from their tracer.

Types

type APIAgent

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

APIAgent runs agentic loops using the Anthropic API directly. This is the pattern used by labs-service for custom tool flows.

func NewAPIAgent

func NewAPIAgent(cfg APIAgentConfig) *APIAgent

NewAPIAgent creates an agent that uses the Anthropic API (or a custom provider).

func (*APIAgent) Run

func (a *APIAgent) Run(ctx context.Context, prompt string) (<-chan AgentEvent, error)

Run executes the agent loop and streams events.

func (*APIAgent) RunSync

func (a *APIAgent) RunSync(ctx context.Context, prompt string) (string, error)

RunSync executes the agent and returns all text output.

func (*APIAgent) TodoStore

func (a *APIAgent) TodoStore() *TodoStore

TodoStore returns the agent's TodoStore, or nil if todos are not enabled.

type APIAgentConfig

type APIAgentConfig struct {
	// Anthropic API key (defaults to ANTHROPIC_API_KEY env var)
	APIKey string // #nosec G117 -- This is a config field, not a hardcoded secret

	// Model to use (defaults to claude-sonnet-4-20250514)
	Model string

	// System prompt
	SystemPrompt string

	// Custom tools
	Tools *ToolRegistry

	// Hooks for tool execution lifecycle
	Hooks *Hooks

	// Maximum turns before stopping (default: 10)
	MaxTurns int

	// MaxTokens is the maximum number of tokens the model can generate per turn.
	// Defaults to 4096.
	MaxTokens int

	// CanUseTool is called before tool execution to get permission.
	// It is invoked before hooks.
	CanUseTool CanUseToolFunc

	// Subagents configures child agent definitions for the Task tool.
	Subagents *SubagentConfig

	// Skills provides skill-based tool organization with semantic lookup.
	Skills *SkillRegistry

	// ContextBuilder controls dynamic per-turn tool selection.
	// If nil, all registered tools are sent every turn (current behavior).
	ContextBuilder *ContextBuilder

	// Metrics collects per-turn and per-tool execution metrics.
	// If nil, no metrics are gathered.
	Metrics *MetricsCollector

	// ParallelTools enables concurrent execution of independent tool calls within a turn.
	// When true, all tool calls returned by the LLM in a single turn run in parallel.
	// Only enable this for tools with no inter-dependencies or shared mutable state.
	ParallelTools bool

	// Retry configures automatic retry behavior for tool execution failures.
	// Per-tool RetryConfig on ToolDefinition takes precedence over this global setting.
	Retry *RetryConfig

	// Budget sets resource limits (tokens, time) for the session.
	// The session stops with BudgetExceededError when any limit is hit.
	// Note: MaxCostUSD is not populated for APIAgent (use MaxTokens instead).
	Budget *BudgetConfig

	// History controls conversation history compaction before each LLM call.
	History *HistoryConfig

	// SystemPromptBlocks provides structured system prompt blocks with cache
	// control directives. When set, SystemPrompt is ignored.
	// Each block can have CacheControl set to enable Anthropic prompt caching.
	SystemPromptBlocks []SystemPromptBlock

	// EnableTodos registers the write_todos tool, allowing the agent to
	// plan its work and track progress via a todo list. The host app
	// receives AgentEventTodosUpdated events when the list changes.
	EnableTodos bool

	// TodoStore is an optional pre-existing TodoStore to use. If nil and
	// EnableTodos is true, a new store is created automatically.
	TodoStore *TodoStore

	// MaxTokensRecovery, if non-nil, enables automatic retry with increased
	// max_tokens when output is truncated.
	MaxTokensRecovery *MaxTokensRecovery

	// FallbackModel configures automatic model switching on persistent API errors.
	// When set, the agent switches to the fallback model after consecutive errors.
	FallbackModel *FallbackModelConfig

	// Provider overrides the default AnthropicProvider.
	// When set, APIKey is ignored (the provider manages its own credentials).
	// When nil, an AnthropicProvider is created from APIKey.
	Provider LLMProvider
}

APIAgentConfig configures an API-based agent.

type Agent

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

Agent orchestrates Claude with custom tools in an agentic loop.

func NewAgent

func NewAgent(cfg AgentConfig) *Agent

NewAgent creates an Agent with the given configuration.

func (*Agent) Close

func (a *Agent) Close() error

Close gracefully shuts down the agent, sending SIGINT then SIGKILL after timeout.

func (*Agent) RewindFiles

func (a *Agent) RewindFiles(ctx context.Context, userMessageID string) error

RewindFiles rewinds file changes to a previous checkpoint. Requires EnableFileCheckpointing to be set in Options.

func (*Agent) Run

func (a *Agent) Run(ctx context.Context, prompt string) (<-chan AgentEvent, error)

Run executes the agent loop with the given prompt. Returns a channel of AgentEvents for real-time streaming.

func (*Agent) RunSync

func (a *Agent) RunSync(ctx context.Context, prompt string) (string, error)

RunSync executes the agent and collects all text output.

func (*Agent) Send

func (a *Agent) Send(ctx context.Context, message string) error

Send writes a follow-up message to the running agent's stdin. The ctx parameter is checked for cancellation before sending.

func (*Agent) Stop

func (a *Agent) Stop()

Stop cancels the running agent.

func (*Agent) TodoStore

func (a *Agent) TodoStore() *TodoStore

TodoStore returns the agent's TodoStore, or nil if todos are not enabled.

type AgentConfig

type AgentConfig struct {
	// Base client options
	Options Options

	// Custom tools
	Tools *ToolRegistry

	// Hooks for tool execution lifecycle
	Hooks *Hooks

	// Maximum turns (LLM calls) before stopping. 0 = unlimited.
	MaxTurns int

	// CanUseTool is called before tool execution to get permission.
	// It is invoked before hooks.
	CanUseTool CanUseToolFunc

	// Subagents configures child agent definitions for the Task tool.
	Subagents *SubagentConfig

	// Skills provides skill-based tool organization with semantic lookup.
	Skills *SkillRegistry

	// ContextBuilder controls dynamic per-turn tool selection.
	// If nil, all registered tools are sent every turn (current behavior).
	ContextBuilder *ContextBuilder

	// Metrics collects per-turn and per-tool execution metrics.
	// If nil, no metrics are gathered.
	Metrics *MetricsCollector

	// ParallelTools enables concurrent execution of independent tool calls within a turn.
	// When true, all tool calls returned by the LLM in a single turn run in parallel.
	// Only enable this for tools with no inter-dependencies or shared mutable state.
	ParallelTools bool

	// Retry configures automatic retry behavior for tool execution failures.
	// Per-tool RetryConfig on ToolDefinition takes precedence over this global setting.
	Retry *RetryConfig

	// Budget sets resource limits (tokens, cost, time) for the session.
	// The session stops with BudgetExceededError when any limit is hit.
	Budget *BudgetConfig

	// History controls conversation history compaction before each LLM call,
	// preventing unbounded context growth in long sessions.
	History *HistoryConfig

	// EnableTodos registers the write_todos tool, allowing the agent to
	// plan its work and track progress via a todo list. The host app
	// receives AgentEventTodosUpdated events when the list changes.
	EnableTodos bool

	// TodoStore is an optional pre-existing TodoStore to use. If nil and
	// EnableTodos is true, a new store is created automatically.
	// Sharing a store across agents gives the parent visibility into child progress.
	TodoStore *TodoStore
}

AgentConfig configures an Agent.

type AgentDefinition

type AgentDefinition struct {
	// Name uniquely identifies this subagent.
	Name string
	// Description explains what this subagent does (shown to Claude).
	Description string
	// Prompt is the system prompt for the subagent.
	Prompt string
	// Tools is the tool registry for the subagent.
	Tools *ToolRegistry
	// Model specifies the model to use ("sonnet", "opus", "haiku", or "inherit").
	// "inherit" or empty uses the parent agent's model.
	Model string
	// MaxTurns limits the number of turns for the subagent. 0 = use default.
	MaxTurns int
	// Hooks configures lifecycle hooks for the subagent.
	Hooks *Hooks
}

AgentDefinition describes a named subagent that can be invoked via the Task tool.

type AgentEvent

type AgentEvent struct {
	Type    AgentEventType
	Content string

	// For tool events
	ToolCall     *ToolCall
	ToolResponse *ToolResponse

	// For message events
	Message *AssistantMessage

	// For completion
	Result *ResultMessage
	Error  error

	// For subagent events - links to the parent's tool invocation
	ParentToolUseID string
	// SubagentName identifies which subagent produced this event
	SubagentName string

	// For todos_updated events
	Todos []TodoItem

	// For turn_complete events - populated when a MetricsCollector is configured
	TurnMetrics *TurnMetrics
}

AgentEvent represents events emitted during agent execution.

type AgentEventType

type AgentEventType string

AgentEventType categorizes agent events.

const (
	AgentEventMessageStart   AgentEventType = "message_start"
	AgentEventContentDelta   AgentEventType = "content_delta"
	AgentEventMessageEnd     AgentEventType = "message_end"
	AgentEventToolUseStart   AgentEventType = "tool_use_start"
	AgentEventToolUseDelta   AgentEventType = "tool_use_delta"
	AgentEventToolUseEnd     AgentEventType = "tool_use_end"
	AgentEventToolResult     AgentEventType = "tool_result"
	AgentEventTurnComplete   AgentEventType = "turn_complete"
	AgentEventError          AgentEventType = "error"
	AgentEventComplete       AgentEventType = "complete"
	AgentEventSkillsSelected AgentEventType = "skills_selected"
	AgentEventTodosUpdated   AgentEventType = "todos_updated"
)

type AnthropicProvider

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

AnthropicProvider implements LLMProvider using the Anthropic Messages API. It supports prompt caching via SystemPromptBlocks, full streaming, and Anthropic-native token usage tracking.

func NewAnthropicProvider

func NewAnthropicProvider(cfg AnthropicProviderConfig) *AnthropicProvider

NewAnthropicProvider creates an Anthropic provider.

func (*AnthropicProvider) Complete

func (*AnthropicProvider) Name

func (p *AnthropicProvider) Name() string

Name returns "anthropic".

type AnthropicProviderConfig

type AnthropicProviderConfig struct {
	// APIKey is the Anthropic API key. Defaults to ANTHROPIC_API_KEY env var.
	APIKey string // #nosec G117 -- config field, not a hardcoded secret
}

AnthropicProviderConfig configures an Anthropic LLM provider.

type Artifact

type Artifact struct {
	ID        string       `json:"id"`
	Type      ArtifactType `json:"type"`
	Title     string       `json:"title"`
	Content   string       `json:"content"`
	CreatedAt time.Time    `json:"created_at"`
	UpdatedAt time.Time    `json:"updated_at"`
	Version   int          `json:"version"`
}

Artifact represents a generated content artifact.

type ArtifactRegistry

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

ArtifactRegistry manages artifacts and provides tools for agent use.

func NewArtifactRegistry

func NewArtifactRegistry() *ArtifactRegistry

NewArtifactRegistry creates a new artifact registry.

func (*ArtifactRegistry) All

func (r *ArtifactRegistry) All() []Artifact

All returns all artifacts in creation order.

func (*ArtifactRegistry) Count

func (r *ArtifactRegistry) Count() int

Count returns the number of artifacts.

func (*ArtifactRegistry) Get

func (r *ArtifactRegistry) Get(id string) (*Artifact, bool)

Get returns an artifact by ID.

func (*ArtifactRegistry) SystemPrompt

func (r *ArtifactRegistry) SystemPrompt() string

SystemPrompt returns a system prompt snippet that instructs the agent on artifact usage.

func (*ArtifactRegistry) Tools

func (r *ArtifactRegistry) Tools() *ToolRegistry

Tools returns a ToolRegistry with create_artifact and update_artifact tools. The registry is created once and cached — subsequent calls return the same instance.

type ArtifactType

type ArtifactType string

ArtifactType represents the kind of artifact content.

const (
	ArtifactHTML ArtifactType = "html"
	ArtifactJSX  ArtifactType = "jsx"
	ArtifactText ArtifactType = "text"
)

type AssistantMessage

type AssistantMessage struct {
	ID           string         `json:"id,omitempty"`
	Model        string         `json:"model,omitempty"`
	Content      []ContentBlock `json:"content"`
	StopReason   string         `json:"stop_reason,omitempty"`
	StopSequence string         `json:"stop_sequence,omitempty"`
}

AssistantMessage represents a message from Claude.

func (AssistantMessage) Role

func (*AssistantMessage) UnmarshalJSON

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

UnmarshalJSON decodes assistant message content blocks based on "type".

type BM25Index

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

BM25Index is a zero-dependency BM25 implementation for keyword search.

func NewBM25Index

func NewBM25Index() *BM25Index

NewBM25Index creates a new BM25 index with standard parameters.

func (*BM25Index) Index

func (idx *BM25Index) Index(id string, text string, tags []string) error

Index adds or updates a document in the index.

func (*BM25Index) Rebuild

func (idx *BM25Index) Rebuild() error

Rebuild clears and rebuilds the index. This is a no-op for BM25Index since re-indexing all docs would require external data. It recomputes internal statistics.

func (*BM25Index) Remove

func (idx *BM25Index) Remove(id string) error

Remove removes a document from the index.

func (*BM25Index) Search

func (idx *BM25Index) Search(query string, k int) []SearchResult

Search returns the top-k documents matching the query, sorted by score descending.

type BudgetConfig

type BudgetConfig struct {
	// MaxTokens stops the session once cumulative input+output tokens exceed
	// this value. Works for both Agent and APIAgent.
	MaxTokens int

	// MaxCostUSD stops the session once cumulative cost exceeds this value (USD).
	// Populated only for the CLI-based Agent via ResultMessage.Cost.
	MaxCostUSD float64

	// MaxDuration stops the session once wall-clock time since session start
	// exceeds this duration. Works for both Agent and APIAgent.
	MaxDuration time.Duration
}

BudgetConfig sets resource limits for a session. Any field left at its zero value is treated as unlimited.

type BudgetExceededError

type BudgetExceededError struct {
	Reason string
}

BudgetExceededError is returned as an AgentEventError when a budget limit is hit.

func (*BudgetExceededError) Error

func (e *BudgetExceededError) Error() string

type CacheControl

type CacheControl struct {
	Type string // "ephemeral"
}

CacheControl configures prompt caching for a system prompt block.

type CanUseToolFunc

type CanUseToolFunc func(ctx context.Context, toolName, toolUseID string, input json.RawMessage) PermissionDecision

CanUseToolFunc is a callback invoked before tool execution to get permission.

type ChatMessage

type ChatMessage struct {
	// Role of the message sender.
	Role ChatRole
	// Content is the text content of the message.
	Content string
	// ToolCalls are tool invocations requested by the assistant.
	// Only set when Role is ChatRoleAssistant.
	ToolCalls []ToolCall
	// ToolCallID links a tool result back to the tool call that produced it.
	// Only set when Role is ChatRoleTool.
	ToolCallID string
	// IsError indicates the tool result is an error.
	// Only set when Role is ChatRoleTool.
	IsError bool
}

ChatMessage is a provider-agnostic conversation message used by APIAgent. The agentic loop maintains a []ChatMessage history; providers convert to their native format.

Note: ConversationMessage (agent.go) serves the same purpose for the CLI-based Agent. Both types are intentionally separate — the CLI agent uses string Role; ChatMessage uses typed ChatRole.

type ChatRequest

type ChatRequest struct {
	// Model identifier (e.g., "claude-sonnet-4-20250514", "gpt-4o", "mistral-large-latest").
	Model string
	// Messages is the conversation history.
	Messages []ChatMessage
	// Tools available for the model to call.
	Tools []ToolDefinition
	// SystemPrompt is a plain text system prompt.
	SystemPrompt string
	// SystemBlocks provides structured system prompt blocks with cache control.
	// Anthropic-specific; other providers concatenate block text into a single system message.
	SystemBlocks []SystemPromptBlock
	// MaxTokens is the maximum number of tokens to generate.
	MaxTokens int
	// Temperature controls randomness. Nil uses the provider's default.
	Temperature *float64
}

ChatRequest is a provider-agnostic request to an LLM.

type ChatResponse

type ChatResponse struct {
	// Content is the text content of the assistant's response.
	Content string
	// ToolCalls are tool invocations requested by the assistant.
	ToolCalls []ToolCall
	// StopReason indicates why the model stopped generating.
	// Normalized to: "end_turn", "tool_use", "max_tokens".
	StopReason string
	// Usage contains token consumption metrics.
	Usage ChatUsage
}

ChatResponse is a provider-agnostic response from an LLM.

type ChatRole

type ChatRole string

ChatRole represents a message role in the chat completions format.

const (
	ChatRoleSystem    ChatRole = "system"
	ChatRoleUser      ChatRole = "user"
	ChatRoleAssistant ChatRole = "assistant"
	ChatRoleTool      ChatRole = "tool"
)

type ChatStreamCallback

type ChatStreamCallback func(event ChatStreamEvent)

ChatStreamCallback receives streaming events during LLM completion. Providers call this as deltas arrive. May be nil to skip streaming.

type ChatStreamEvent

type ChatStreamEvent struct {
	// Type identifies the event kind.
	Type ChatStreamEventType
	// Content carries text for ContentDelta and ToolUseDelta events.
	Content string
	// ToolCall carries tool information for ToolUseStart and ToolUseEnd events.
	// On ToolUseStart: ID and Name are set; Input is nil (not yet accumulated).
	// On ToolUseEnd: ID, Name, and fully-accumulated Input are all set.
	ToolCall *ToolCall
}

ChatStreamEvent carries a streaming delta from a provider.

type ChatStreamEventType

type ChatStreamEventType string

ChatStreamEventType identifies the kind of streaming event from a provider.

const (
	// ChatStreamContentDelta is a text chunk from the assistant.
	ChatStreamContentDelta ChatStreamEventType = "content_delta"
	// ChatStreamToolUseStart indicates the model is starting a tool call.
	ChatStreamToolUseStart ChatStreamEventType = "tool_use_start"
	// ChatStreamToolUseDelta is a partial JSON chunk of tool input.
	ChatStreamToolUseDelta ChatStreamEventType = "tool_use_delta"
	// ChatStreamToolUseEnd indicates the tool call input is complete.
	ChatStreamToolUseEnd ChatStreamEventType = "tool_use_end"
)

type ChatUsage

type ChatUsage struct {
	InputTokens  int
	OutputTokens int
	// CacheCreationInputTokens is Anthropic-specific; 0 for other providers.
	CacheCreationInputTokens int
	// CacheReadInputTokens is Anthropic-specific; 0 for other providers.
	CacheReadInputTokens int
}

ChatUsage contains token usage information from an LLM response.

type CheckpointManager

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

CheckpointManager handles file checkpointing and rewind operations. Requires the CLI to have been run with --enable-file-checkpointing.

func NewCheckpointManager

func NewCheckpointManager(sessionID, cliPath, cwd string) *CheckpointManager

NewCheckpointManager creates a new checkpoint manager.

func (*CheckpointManager) RewindFiles

func (cm *CheckpointManager) RewindFiles(ctx context.Context, userMessageID string) error

RewindFiles reverts file changes to the state at the given user message ID. This uses the Claude CLI's checkpoint rewind functionality.

type Client

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

Client provides a streaming interface to Claude Code CLI.

func NewClient

func NewClient(opts Options) *Client

NewClient creates a new Claude agent client.

func (*Client) Close

func (c *Client) Close() error

Close gracefully shuts down the running command. It sends SIGINT first, then SIGKILL after a 5-second timeout.

func (*Client) IsRunning

func (c *Client) IsRunning() bool

IsRunning returns whether a query is currently running.

func (*Client) Query

func (c *Client) Query(ctx context.Context, prompt string) (<-chan Event, error)

Query sends a prompt and returns a channel of streaming events.

func (*Client) QueryWithMessages

func (c *Client) QueryWithMessages(ctx context.Context, messages []Message) (<-chan Event, error)

QueryWithMessages sends messages and returns streaming events. Messages are formatted into a single prompt for the CLI. For proper multi-turn conversation support with external tool execution, use APIAgent which communicates directly with the Anthropic API.

func (*Client) Send

func (c *Client) Send(data string) error

Send writes data to the running process's stdin. This can be used to send follow-up messages to a running query.

func (*Client) Stop

func (c *Client) Stop() error

Stop terminates the running command immediately with SIGKILL.

type ContentBlock

type ContentBlock interface {
	Type() ContentBlockType
	// contains filtered or unexported methods
}

ContentBlock represents a block of content in a message.

type ContentBlockType

type ContentBlockType string

ContentBlockType represents the type of content block.

const (
	ContentTypeText       ContentBlockType = "text"
	ContentTypeToolUse    ContentBlockType = "tool_use"
	ContentTypeToolResult ContentBlockType = "tool_result"
)

type ContextBuilder

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

ContextBuilder provides dynamic per-turn tool selection using BM25 search.

func NewContextBuilder

func NewContextBuilder(store *Store, opts ...ContextOption) *ContextBuilder

NewContextBuilder creates a ContextBuilder with the given store and options.

func (*ContextBuilder) SelectSkills

func (cb *ContextBuilder) SelectSkills(_ context.Context, query string, k int) []*Skill

SelectSkills returns the most relevant skills for the query.

func (*ContextBuilder) SelectTools

func (cb *ContextBuilder) SelectTools(_ context.Context, query string) []ToolDefinition

SelectTools returns the tool definitions most relevant to the query. Falls back to all tools if no index is configured or the query is empty.

type ContextOption

type ContextOption func(*ContextBuilder)

ContextOption configures a ContextBuilder.

func WithIndex

func WithIndex(index SkillIndex) ContextOption

WithIndex sets the search index for semantic tool selection.

func WithMaxTools

func WithMaxTools(n int) ContextOption

WithMaxTools sets the maximum number of tools to return from SelectTools.

type ConversationMessage

type ConversationMessage struct {
	Role       string     `json:"role"`
	Content    string     `json:"content"`
	ToolCalls  []ToolCall `json:"tool_calls,omitempty"`
	ToolCallID string     `json:"tool_call_id,omitempty"`
}

ConversationMessage represents a message in the conversation history.

func InjectReminders

func InjectReminders(history []ConversationMessage, reminders []SystemReminder) []ConversationMessage

InjectReminders appends formatted reminders to the last user message in the history. If there are no user messages, the reminders are prepended as a new user message. Returns a new slice without mutating the input.

type ConversationResetMessage

type ConversationResetMessage struct {
	// NewConversationID is an opaque identifier for the fresh conversation, for
	// UIs to key an empty transcript on (and discard any cached session
	// title). This is NOT the SessionID of subsequent messages.
	NewConversationID string `json:"new_conversation_id,omitempty"`
	// UUID uniquely identifies this message.
	UUID string `json:"uuid,omitempty"`
	// SessionID is the ID of the session that was reset (the outgoing
	// session; messages after the reset carry a new session ID).
	SessionID string `json:"session_id,omitempty"`
}

ConversationResetMessage is emitted when the session's conversation is replaced without ending the connection — e.g. after "/clear" or any other flow that discards the transcript mid-session.

In streaming input mode a single connection can carry many user turns, and a reset clears the conversation history *and* zeroes the running totals reported on subsequent ResultMessages (e.g. Cost). If you accumulate those totals across a long-lived session, snapshot them when this message arrives.

type DeferredTool

type DeferredTool struct {
	Name        string
	Description string // Brief one-line description
	SearchHint  string // Keywords for search matching
}

DeferredTool represents a tool whose full definition is not loaded into the active registry until explicitly requested via ToolSearch.

type DeferredToolLoader

type DeferredToolLoader func(ctx context.Context, name string) (*ToolDefinition, ToolHandler, error)

DeferredToolLoader resolves a deferred tool name into its full definition and handler.

type DeferredToolRegistry

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

DeferredToolRegistry holds tools that are lazily loaded on demand.

func NewDeferredToolRegistry

func NewDeferredToolRegistry(loader DeferredToolLoader) *DeferredToolRegistry

NewDeferredToolRegistry creates a new DeferredToolRegistry with the given loader.

func (*DeferredToolRegistry) Add

func (d *DeferredToolRegistry) Add(tool DeferredTool)

Add registers a deferred tool for discovery.

func (*DeferredToolRegistry) All

All returns all registered deferred tools.

func (*DeferredToolRegistry) IsLoaded

func (d *DeferredToolRegistry) IsLoaded(name string) bool

IsLoaded returns true if the named tool has been loaded.

func (*DeferredToolRegistry) Load

func (d *DeferredToolRegistry) Load(ctx context.Context, name string, into *ToolRegistry) error

Load resolves a deferred tool and registers it in the target registry. Returns an error if the tool is not found or the loader fails.

func (*DeferredToolRegistry) Search

func (d *DeferredToolRegistry) Search(query string, maxResults int) []DeferredTool

Search finds deferred tools matching the query string. Uses simple keyword matching against Name, Description, and SearchHint. Returns up to maxResults matches, sorted by relevance.

type DeferredToolUse

type DeferredToolUse struct {
	ID    string          `json:"id"`
	Name  string          `json:"name"`
	Input json.RawMessage `json:"input"`
}

DeferredToolUse is a tool call deferred by a PreToolUse hook returning a "defer" decision.

type DockerBackend

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

DockerBackend runs code inside Docker containers for production-grade isolation.

func NewDockerBackend

func NewDockerBackend(cfg DockerBackendConfig) *DockerBackend

NewDockerBackend creates a new Docker-based sandbox backend.

func (*DockerBackend) Close

func (b *DockerBackend) Close() error

Close destroys all containers and cleans up.

func (*DockerBackend) CreateSession

func (b *DockerBackend) CreateSession(ctx context.Context, opts SessionOptions) (SandboxSession, error)

CreateSession creates a new Docker container as a sandbox session.

type DockerBackendConfig

type DockerBackendConfig struct {
	// Images maps languages to Docker image names. Defaults are provided for all
	// built-in languages if not specified.
	Images map[Language]string

	// NetworkMode is the Docker network mode. Defaults to "none" (no network access).
	NetworkMode string
}

DockerBackendConfig configures the Docker sandbox backend.

type EffortLevel

type EffortLevel string

EffortLevel controls how much extended-thinking effort Claude spends on a turn.

const (
	EffortLow    EffortLevel = "low"
	EffortMedium EffortLevel = "medium"
	EffortHigh   EffortLevel = "high"
	EffortXHigh  EffortLevel = "xhigh"
	EffortMax    EffortLevel = "max"
)

type Event

type Event struct {
	// Raw JSON line
	Raw string

	// Parsed event type
	Type StreamEventType

	// For text content deltas
	Text string

	// For tool input JSON deltas
	ToolUseDelta string

	// For tool use events
	ToolUse *ToolUseEvent

	// For tool results
	ToolResult *ToolResultEvent

	// For assistant messages
	AssistantMessage *AssistantMessage

	// For result/completion
	Result *ResultMessage

	// For mid-session conversation resets (e.g. "/clear")
	ConversationReset *ConversationResetMessage

	// Parsing error if any
	Error error
}

Event represents a parsed event from the stream.

type ExecResult

type ExecResult struct {
	ExitCode  int           `json:"exit_code"`
	Stdout    string        `json:"stdout"`
	Stderr    string        `json:"stderr"`
	Duration  time.Duration `json:"duration"`
	OOMKilled bool          `json:"oom_killed,omitempty"`
	TimedOut  bool          `json:"timed_out,omitempty"`
}

ExecResult holds the output of a code execution or command.

type Execution

type Execution struct {
	ID        string      `json:"id"`
	SessionID string      `json:"session_id"`
	Language  Language    `json:"language"`
	Code      string      `json:"code"`
	Command   string      `json:"command,omitempty"`
	Result    *ExecResult `json:"result"`
	CreatedAt time.Time   `json:"created_at"`
}

Execution records a single code execution for host app inspection.

type FallbackModelConfig

type FallbackModelConfig struct {
	// Model is the fallback model identifier (e.g., "claude-haiku-4-5-20251001").
	Model string
	// AfterErrors is the number of consecutive errors before switching to fallback.
	// Default: 3.
	AfterErrors int
	// RevertAfter is the duration after which to try the primary model again.
	// Zero means stay on fallback for the rest of the session.
	RevertAfter time.Duration
}

FallbackModelConfig configures automatic model switching on persistent API errors.

type GenericHookHandler

type GenericHookHandler func(ctx context.Context, data HookEventData)

GenericHookHandler is a function called for lifecycle events.

type HistoryConfig

type HistoryConfig struct {
	// MaxTurns keeps only the last N assistant+tool turns in the history sent
	// to the LLM. The initial user prompt is always preserved. 0 = unlimited.
	// A "turn" is one assistant response and all its tool result messages.
	MaxTurns int

	// DropToolResults replaces tool-result content from older turns with a
	// short placeholder, reducing token usage while preserving conversation
	// structure. Has no effect unless MaxTurns > 0 and older turns exist.
	// Not supported for APIAgent (use MaxTurns only).
	DropToolResults bool

	// Summarizer, if set, is called to produce a summary of turns that would
	// otherwise be dropped when MaxTurns is exceeded. The summary is prepended
	// as a system-context user message after the initial prompt.
	Summarizer HistorySummarizer

	// SummarizeThreshold is the number of excess turns before summarization
	// triggers. For example, if MaxTurns=10 and SummarizeThreshold=5, the
	// summarizer is called when history reaches 15 turns. Default: 0.
	SummarizeThreshold int
}

HistoryConfig controls conversation history compaction applied before each LLM call. This prevents the context window from growing unboundedly in long multi-turn sessions.

type HistorySummarizer

type HistorySummarizer func(ctx context.Context, messages []ConversationMessage) (string, error)

HistorySummarizer summarizes a slice of conversation messages into a single summary string. The caller provides the implementation (e.g., calling an LLM).

type HookContext

type HookContext struct {
	// ToolName is the name of the tool being called.
	ToolName string
	// ToolUseID is the unique identifier for this tool invocation.
	ToolUseID string
	// Input is the raw JSON input to the tool.
	Input json.RawMessage
}

HookContext provides context about the tool being executed.

type HookDecision

type HookDecision string

HookDecision represents the decision made by a hook.

const (
	// HookAllow allows the tool execution to proceed.
	HookAllow HookDecision = "allow"
	// HookDeny blocks the tool execution.
	HookDeny HookDecision = "deny"
	// HookModify allows execution with modified input.
	HookModify HookDecision = "modify"
)

type HookEvent

type HookEvent string

HookEvent represents the type of hook event.

const (
	// HookPreToolUse is called before a tool is executed.
	HookPreToolUse HookEvent = "PreToolUse"
	// HookPostToolUse is called after a tool is executed successfully.
	HookPostToolUse HookEvent = "PostToolUse"
	// HookPostToolUseFailure is called after a tool execution fails.
	HookPostToolUseFailure HookEvent = "PostToolUseFailure"
	// HookStop is called when the agent stops.
	HookStop HookEvent = "Stop"
	// HookSubagentStart is called when a subagent begins execution.
	HookSubagentStart HookEvent = "SubagentStart"
	// HookSubagentStop is called when a subagent finishes execution.
	HookSubagentStop HookEvent = "SubagentStop"
	// HookNotification is called for general notifications.
	HookNotification HookEvent = "Notification"
	// HookPermissionRequest is called when a tool call needs a permission
	// decision (i.e. a CanUseToolFunc is about to be invoked), before the
	// decision is known.
	HookPermissionRequest HookEvent = "PermissionRequest"
	// HookSessionStart is called when a session begins.
	HookSessionStart HookEvent = "SessionStart"
	// HookSessionEnd is called when a session ends.
	HookSessionEnd HookEvent = "SessionEnd"
)

type HookEventData

type HookEventData struct {
	// Event is the hook event type.
	Event HookEvent
	// SessionID is the current session identifier.
	SessionID string
	// SubagentName is the name of the subagent (for SubagentStart/Stop).
	SubagentName string
	// ToolName is the tool name (for tool-related events).
	ToolName string
	// ToolUseID is the tool invocation ID (for tool-related events).
	ToolUseID string
	// Error is the error message (for failure events).
	Error string
	// Message is a human-readable description of the event.
	Message string
}

HookEventData provides event-type-specific data for lifecycle hooks.

type HookResult

type HookResult struct {
	// Decision determines whether to allow, deny, or modify the tool call.
	Decision HookDecision
	// Reason explains why the decision was made (used for deny).
	Reason string
	// ModifiedInput is the new input to use (only for HookModify).
	ModifiedInput json.RawMessage
	// Output is additional data to include in tool result (for PostToolUse).
	Output string
	// AdditionalContext is injected into the conversation as additional context.
	AdditionalContext string
	// SystemMessage is a system-level instruction to inject.
	SystemMessage string
	// Continue indicates whether execution should continue after this hook.
	Continue bool
	// SuppressOutput hides the tool's stdout from the conversation.
	SuppressOutput bool
}

HookResult is the result returned by a hook handler.

func AllowHook

func AllowHook() HookResult

AllowHook returns a result that allows the tool execution.

func DenyHook

func DenyHook(reason string) HookResult

DenyHook returns a result that denies the tool execution.

func ModifyHook

func ModifyHook(newInput json.RawMessage) HookResult

ModifyHook returns a result that modifies the tool input.

type Hooks

type Hooks struct {

	// EventHandlers maps lifecycle events to generic handlers.
	// Kept as a direct map since event handlers are simple and don't need indexing.
	EventHandlers map[HookEvent][]GenericHookHandler
	// contains filtered or unexported fields
}

Hooks configures hook handlers for tool execution. Internally backed by a Store for indexed lookups and removal support.

func NewHooks

func NewHooks() *Hooks

NewHooks creates a new Hooks configuration.

func NewHooksWithStore

func NewHooksWithStore(store *Store) *Hooks

NewHooksWithStore creates a Hooks configuration sharing the given store.

func (*Hooks) AddPostHook

func (h *Hooks) AddPostHook(matcher string, hook PostToolUseHook)

AddPostHook adds a post-tool-use hook for the specified tool pattern.

func (*Hooks) AddPostHookWithOptions

func (h *Hooks) AddPostHookWithOptions(matcher string, isRegex bool, timeout time.Duration, hook PostToolUseHook)

AddPostHookWithOptions adds a post-hook with matcher options (regex, timeout).

func (*Hooks) AddPreHook

func (h *Hooks) AddPreHook(matcher string, hook PreToolUseHook)

AddPreHook adds a pre-tool-use hook for the specified tool pattern.

func (*Hooks) AddPreHookWithOptions

func (h *Hooks) AddPreHookWithOptions(matcher string, isRegex bool, timeout time.Duration, hook PreToolUseHook)

AddPreHookWithOptions adds a pre-hook with matcher options (regex, timeout).

func (*Hooks) EmitEvent

func (h *Hooks) EmitEvent(ctx context.Context, data HookEventData)

EmitEvent fires all handlers registered for the given event.

func (*Hooks) OnAllTools

func (h *Hooks) OnAllTools() *ToolHookBuilder

OnAllTools is a convenience method to add hooks for all tools.

func (*Hooks) OnEvent

func (h *Hooks) OnEvent(event HookEvent, handler GenericHookHandler)

OnEvent registers a handler for a lifecycle event.

func (*Hooks) OnTool

func (h *Hooks) OnTool(toolName string) *ToolHookBuilder

OnTool is a convenience method to add hooks for a specific tool.

func (*Hooks) OnToolRegex

func (h *Hooks) OnToolRegex(pattern string) *ToolHookBuilder

OnToolRegex is a convenience method to add hooks matching a regex pattern.

func (*Hooks) RemoveHook

func (h *Hooks) RemoveHook(id string)

RemoveHook removes a hook by its stored ID.

func (*Hooks) RunPostHooks

func (h *Hooks) RunPostHooks(ctx context.Context, hookCtx HookContext, toolResult string, isError bool) error

RunPostHooks executes all matching post-tool-use hooks.

func (*Hooks) RunPreHooks

func (h *Hooks) RunPreHooks(ctx context.Context, hookCtx HookContext) (HookResult, error)

RunPreHooks executes all matching pre-tool-use hooks. Returns the final decision and potentially modified input.

type JSONDecodeError

type JSONDecodeError struct {
	Line string
	Err  error
}

JSONDecodeError represents a JSON parsing error.

func (*JSONDecodeError) Error

func (e *JSONDecodeError) Error() string

func (*JSONDecodeError) Unwrap

func (e *JSONDecodeError) Unwrap() error

type LLMProvider

type LLMProvider interface {
	// Complete sends a chat request and returns the full response.
	// onEvent, if non-nil, is called with streaming deltas as they arrive.
	// Streaming providers call onEvent for each content/tool chunk as it arrives.
	// Non-streaming providers may ignore onEvent entirely; the ChatResponse is
	// always the authoritative result regardless of whether onEvent was called.
	Complete(ctx context.Context, req ChatRequest, onEvent ChatStreamCallback) (ChatResponse, error)

	// Name returns a human-readable provider name (e.g., "anthropic", "openai").
	Name() string
}

LLMProvider abstracts an LLM chat completions endpoint. Implementations handle message format conversion, streaming, and provider-specific features (e.g., prompt caching for Anthropic).

The APIAgent's agentic loop calls Complete on each turn, passing provider-agnostic ChatMessages and receiving a ChatResponse.

func DeepSeekProvider

func DeepSeekProvider(model string) LLMProvider

DeepSeekProvider returns an LLMProvider for DeepSeek's API. Uses DEEPSEEK_API_KEY environment variable.

agent := claude.NewAPIAgent(claude.APIAgentConfig{
    Provider: claude.DeepSeekProvider("deepseek-chat"),
})

func MistralProvider

func MistralProvider(model string) LLMProvider

MistralProvider returns an LLMProvider for Mistral AI's API. Uses MISTRAL_API_KEY environment variable.

agent := claude.NewAPIAgent(claude.APIAgentConfig{
    Provider: claude.MistralProvider("mistral-large-latest"),
})

func OpenAIProvider

func OpenAIProvider(model string) LLMProvider

OpenAIProvider returns an LLMProvider for OpenAI's API. Uses OPENAI_API_KEY environment variable.

agent := claude.NewAPIAgent(claude.APIAgentConfig{
    Provider: claude.OpenAIProvider("gpt-4o"),
})

func QwenProvider

func QwenProvider(model string) LLMProvider

QwenProvider returns an LLMProvider for Alibaba's Qwen models via DashScope. Uses DASHSCOPE_API_KEY environment variable.

agent := claude.NewAPIAgent(claude.APIAgentConfig{
    Provider: claude.QwenProvider("qwen-max"),
})

type Language

type Language string

Language represents a supported programming language for sandbox execution.

const (
	LangPython     Language = "python"
	LangJavaScript Language = "javascript"
	LangGo         Language = "go"
	LangBash       Language = "bash"
)

func AllLanguages

func AllLanguages() []Language

AllLanguages returns all built-in supported languages.

type LoopMetrics

type LoopMetrics struct {
	// SessionDuration is the total elapsed time for the session.
	SessionDuration time.Duration
	// Turns holds per-turn metrics, indexed by turn order.
	Turns []TurnMetrics
	// ToolStats maps tool name to aggregated call statistics.
	ToolStats map[string]*ToolStats
}

LoopMetrics is a point-in-time snapshot of session-level metrics.

type MCPContent

type MCPContent struct {
	Type string `json:"type"`
	Text string `json:"text,omitempty"`
}

MCPContent represents content in an MCP response.

func TextContent

func TextContent(text string) MCPContent

TextContent creates a text content block.

type MCPServer

type MCPServer interface {
	// Name returns the server name.
	Name() string
	// Version returns the server version.
	Version() string
	// ListTools returns available tools.
	ListTools() []MCPTool
	// CallTool executes a tool and returns the result.
	CallTool(ctx context.Context, name string, args json.RawMessage) (MCPToolResult, error)
}

MCPServer represents an MCP (Model Context Protocol) server.

type MCPServerConfig

type MCPServerConfig struct {
	// Type is the transport type ("stdio", "sse", etc.)
	Type string `json:"type"`
	// Command is the command to run for stdio servers.
	Command string `json:"command,omitempty"`
	// Args are arguments for the command.
	Args []string `json:"args,omitempty"`
	// URL is the URL for SSE/HTTP servers.
	URL string `json:"url,omitempty"`
	// Env is environment variables for the server.
	Env map[string]string `json:"env,omitempty"`
}

MCPServerConfig describes an external MCP server configuration.

type MCPServers

type MCPServers struct {
	// InProcess maps server names to SDK MCP servers.
	InProcess map[string]*SDKMCPServer
	// External maps server names to external server configs.
	External map[string]MCPServerConfig
}

MCPServers holds both in-process and external MCP servers.

func NewMCPServers

func NewMCPServers() *MCPServers

NewMCPServers creates a new MCP servers configuration.

func (*MCPServers) AddExternal

func (m *MCPServers) AddExternal(name string, config MCPServerConfig)

AddExternal adds an external MCP server configuration.

func (*MCPServers) AddInProcess

func (m *MCPServers) AddInProcess(name string, server *SDKMCPServer)

AddInProcess adds an in-process SDK MCP server.

type MCPTool

type MCPTool struct {
	Name        string              `json:"name"`
	Description string              `json:"description"`
	InputSchema map[string]any      `json:"inputSchema"`
	Annotations *MCPToolAnnotations `json:"annotations,omitempty"`
}

MCPTool describes a tool available on an MCP server.

type MCPToolAnnotations

type MCPToolAnnotations struct {
	// ReadOnlyHint indicates the tool only reads data and has no side effects.
	ReadOnlyHint bool `json:"readOnlyHint,omitempty"`
	// DestructiveHint indicates the tool may cause destructive/irreversible changes.
	DestructiveHint bool `json:"destructiveHint,omitempty"`
	// IdempotentHint indicates calling the tool multiple times with the same input has the same effect.
	IdempotentHint bool `json:"idempotentHint,omitempty"`
	// OpenWorldHint indicates the tool interacts with the external world (network, filesystem, etc.).
	OpenWorldHint bool `json:"openWorldHint,omitempty"`
}

MCPToolAnnotations provides hints about a tool's behavior.

type MCPToolHandler

type MCPToolHandler func(ctx context.Context, args json.RawMessage) (MCPToolResult, error)

MCPToolHandler is a function that handles MCP tool calls.

type MCPToolRegistry

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

MCPToolRegistry wraps MCP servers and provides a unified tool interface.

func NewMCPToolRegistry

func NewMCPToolRegistry(servers *MCPServers) *MCPToolRegistry

NewMCPToolRegistry creates a registry from MCP servers.

func (*MCPToolRegistry) ToToolRegistry

func (r *MCPToolRegistry) ToToolRegistry() *ToolRegistry

ToToolRegistry converts MCP servers to a standard ToolRegistry. Tool names are prefixed with "mcp__serverName__".

type MCPToolResult

type MCPToolResult struct {
	Content []MCPContent `json:"content"`
	IsError bool         `json:"isError,omitempty"`
}

MCPToolResult is the result of calling an MCP tool.

type MaxTokensRecovery

type MaxTokensRecovery struct {
	// ScaleFactor multiplies max_tokens on each retry. Default: 2.0.
	ScaleFactor float64
	// MaxRetries is the maximum number of recovery attempts. Default: 2.
	MaxRetries int
	// Ceiling is the absolute maximum for max_tokens. Default: 16384.
	Ceiling int
}

MaxTokensRecovery configures automatic retry when output is truncated due to max_tokens limits. Only applies when stop_reason is "max_tokens" and there are no tool calls or mid-tool-call errors.

type Message

type Message interface {
	Role() MessageRole
	// contains filtered or unexported methods
}

Message represents a conversation message.

type MessageOrigin

type MessageOrigin struct {
	// Kind discriminates the origin. See MessageOriginKind.
	Kind MessageOriginKind `json:"kind"`
	// Subkind further qualifies Kind (e.g. "scheduled-trigger" or
	// "peer-send-message" when Kind is "task-notification").
	Subkind string `json:"subkind,omitempty"`
	// Server is the MCP server name (Kind == "channel").
	Server string `json:"server,omitempty"`
	// From is the sender address (Kind == "peer" or "observer"). Sender-asserted —
	// use for reply routing/display, never as proof of identity.
	From string `json:"from,omitempty"`
	// Name is the sender's display name (Kind == "peer"), already sanitized by the CLI.
	Name string `json:"name,omitempty"`
	// FromSession is the sender's host-openable session id, if provided (Kind == "peer").
	FromSession string `json:"fromSession,omitempty"`
	// SenderTaskID is the task id of the in-process background subagent that sent
	// this message (Kind == "peer" or "observer"; absent for cross-session peers).
	SenderTaskID string `json:"senderTaskId,omitempty"`
	// Body is the decoded message body with the peer envelope stripped (Kind == "peer").
	Body string `json:"body,omitempty"`
}

MessageOrigin describes where an injected message came from — e.g. a background task notification, a peer session, or an MCP server channel.

type MessageOriginKind

type MessageOriginKind string

MessageOriginKind identifies the provenance of a message. Values other than the ones documented here may be emitted by newer CLI versions — treat anything unrecognized as "not human".

const (
	OriginHuman            MessageOriginKind = "human"
	OriginChannel          MessageOriginKind = "channel"
	OriginPeer             MessageOriginKind = "peer"
	OriginTaskNotification MessageOriginKind = "task-notification"
	OriginCoordinator      MessageOriginKind = "coordinator"
	OriginUnclassified     MessageOriginKind = "unclassified"
	OriginObserver         MessageOriginKind = "observer"
	OriginAutoContinuation MessageOriginKind = "auto-continuation"
	OriginObserverActivity MessageOriginKind = "observer-activity"
)

type MessageRole

type MessageRole string

MessageRole represents the role of a message sender.

const (
	RoleUser      MessageRole = "user"
	RoleAssistant MessageRole = "assistant"
)

type MetricsCollector

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

MetricsCollector gathers per-turn and per-tool metrics during agent execution. Configure it via AgentConfig.Metrics or APIAgentConfig.Metrics.

Example:

mc := claudeagent.NewMetricsCollector()
agent := claudeagent.NewAgent(claudeagent.AgentConfig{
    Metrics: mc,
    // ...
})
// After run completes:
summary := mc.Snapshot()

func NewMetricsCollector

func NewMetricsCollector() *MetricsCollector

NewMetricsCollector creates a ready-to-use metrics collector.

func (*MetricsCollector) Snapshot

func (m *MetricsCollector) Snapshot() LoopMetrics

Snapshot returns a copy of the current accumulated metrics. Safe to call concurrently with ongoing agent execution.

type ModelUsage

type ModelUsage struct {
	InputTokens              int     `json:"inputTokens,omitempty"`
	OutputTokens             int     `json:"outputTokens,omitempty"`
	CacheReadInputTokens     int     `json:"cacheReadInputTokens,omitempty"`
	CacheCreationInputTokens int     `json:"cacheCreationInputTokens,omitempty"`
	WebSearchRequests        int     `json:"webSearchRequests,omitempty"`
	CostUSD                  float64 `json:"costUSD,omitempty"`
	ContextWindow            int     `json:"contextWindow,omitempty"`
	MaxOutputTokens          int     `json:"maxOutputTokens,omitempty"`
	// CanonicalModel is the model id used for the pricing lookup (e.g.
	// "claude-opus-4-7"); may differ from the raw model string this entry is
	// keyed by (provider-specific ids, aliases).
	CanonicalModel string `json:"canonicalModel,omitempty"`
	// Provider is the API provider that served this model ("firstParty",
	// "bedrock", "vertex", "foundry", "anthropicAws", "anthropicGoogleCloud",
	// "mantle", "gateway").
	Provider string `json:"provider,omitempty"`
}

ModelUsage is a per-model token usage and cost breakdown reported on a ResultMessage. Field names mirror the CLI's own camelCase "modelUsage" shape.

type OpenAICompatConfig

type OpenAICompatConfig struct {
	// BaseURL is the API base URL (e.g., "https://api.openai.com/v1").
	BaseURL string
	// APIKey is the authentication key.
	APIKey string
	// Model is the model identifier (e.g., "gpt-4o", "mistral-large-latest").
	Model string
	// HTTPTimeout sets the HTTP client timeout. Defaults to 120 seconds.
	HTTPTimeout time.Duration
}

OpenAICompatConfig configures an OpenAI-compatible chat completions provider.

type OpenAICompatProvider

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

OpenAICompatProvider implements LLMProvider for any /v1/chat/completions endpoint. Supports OpenAI, Mistral, DeepSeek, Qwen, and other compatible APIs.

func NewOpenAICompatProvider

func NewOpenAICompatProvider(cfg OpenAICompatConfig) *OpenAICompatProvider

NewOpenAICompatProvider creates a provider for an OpenAI-compatible API.

func (*OpenAICompatProvider) Complete

Complete sends the request to the OpenAI-compatible chat completions endpoint.

func (*OpenAICompatProvider) Name

func (p *OpenAICompatProvider) Name() string

Name returns the provider name.

func (*OpenAICompatProvider) WithName

WithName returns a copy of the provider with a custom name (e.g., "mistral", "openai").

type Options

type Options struct {
	// Working directory for the agent
	Cwd string

	// Path to the Claude CLI executable (defaults to "claude" in PATH)
	CLIPath string

	// Env adds or overrides environment variables for the Claude CLI process.
	// Inherited variables remain available. Explicit TRACEPARENT/TRACESTATE
	// values take precedence over trace context propagated from Query's context.
	Env map[string]string

	// Model to use (e.g., "claude-sonnet-4-20250514")
	Model string

	// Permission mode for tool execution
	PermissionMode PermissionMode

	// Allowed tools (e.g., ["Read", "Write", "Bash"])
	AllowedTools []string

	// Disallowed tools
	DisallowedTools []string

	// Maximum turns before stopping
	MaxTurns int

	// System prompt override
	SystemPrompt string

	// Continue from a previous session
	SessionID string

	// Additional CLI arguments
	ExtraArgs []string

	// MCP servers for tool integration (in-process and external)
	MCPServers *MCPServers

	// Tools specifies which built-in tools are available (different from AllowedTools filter).
	Tools *ToolsConfig

	// CustomSessionID sets an explicit session ID instead of auto-generating one.
	CustomSessionID string

	// ForkSession creates a fork of the session specified by SessionID.
	ForkSession bool

	// Debug enables debug logging.
	Debug bool

	// DebugFile writes debug output to a file instead of stderr.
	DebugFile string

	// Betas enables beta features by name.
	Betas []string

	// AdditionalDirectories adds extra directories to the agent context.
	AdditionalDirectories []string

	// SettingSources specifies additional settings source files.
	SettingSources []string

	// Plugins configures plugins to load.
	Plugins []PluginConfig

	// EnableFileCheckpointing enables file checkpointing for session rewind.
	EnableFileCheckpointing bool

	// Effort controls how much extended-thinking effort Claude spends
	// (low, medium, high, xhigh, max). Maps to the CLI's --effort flag.
	Effort EffortLevel

	// ForwardSubagentText forwards subagent text and thinking blocks as
	// assistant/user messages with parent_tool_use_id set. Only takes effect
	// with the CLI's stream-json output format.
	ForwardSubagentText bool

	// IncludeHookEvents includes all hook lifecycle events in the CLI's
	// output stream (stream-json output format only).
	IncludeHookEvents bool

	// MaxBudgetUSD stops the CLI's own turn loop once cumulative API spend
	// exceeds this amount. Unlike BudgetConfig.MaxCostUSD (enforced client-side
	// across Query calls), this is enforced by the CLI itself within a single
	// --print invocation.
	MaxBudgetUSD float64

	// JSONSchema requests structured output validated against this JSON
	// Schema string; the validated result is returned on
	// ResultMessage.StructuredOutput.
	JSONSchema string
}

Options configures the Claude agent behavior.

func DefaultOptions

func DefaultOptions() Options

DefaultOptions returns sensible defaults.

type PermissionDecision

type PermissionDecision struct {
	// Allow indicates whether tool execution is permitted.
	Allow bool
	// Reason explains the decision.
	Reason string
	// ModifiedInput optionally replaces the tool input.
	ModifiedInput json.RawMessage
}

PermissionDecision represents the result of a canUseTool callback.

type PermissionMode

type PermissionMode string

PermissionMode controls how tool permissions are handled.

const (
	PermissionDefault     PermissionMode = "default"
	PermissionAcceptEdits PermissionMode = "acceptEdits"
	PermissionPlan        PermissionMode = "plan"
	PermissionBypassAll   PermissionMode = "bypassPermissions"
)

type PluginConfig

type PluginConfig struct {
	// Type is the plugin type (e.g., "file").
	Type string
	// Path is the file path for file-type plugins.
	Path string
}

PluginConfig describes a plugin to load.

type PostToolUseHook

type PostToolUseHook func(ctx context.Context, hookCtx HookContext, result string, isError bool) HookResult

PostToolUseHook is a function called after tool execution.

type PreToolUseHook

type PreToolUseHook func(ctx context.Context, hookCtx HookContext) HookResult

PreToolUseHook is a function called before tool execution.

type ProcessBackend

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

ProcessBackend runs code as local subprocesses. It does NOT provide true isolation — suitable for development and testing only.

func NewProcessBackend

func NewProcessBackend(cfg ProcessBackendConfig) *ProcessBackend

NewProcessBackend creates a new process-based sandbox backend.

func (*ProcessBackend) Close

func (b *ProcessBackend) Close() error

Close cleans up all sessions.

func (*ProcessBackend) CreateSession

func (b *ProcessBackend) CreateSession(ctx context.Context, opts SessionOptions) (SandboxSession, error)

CreateSession creates a new process-based sandbox session.

type ProcessBackendConfig

type ProcessBackendConfig struct {
	// TempDir is the base directory for sandbox working directories.
	// Defaults to os.TempDir().
	TempDir string
}

ProcessBackendConfig configures the local process sandbox backend.

type ProcessError

type ProcessError struct {
	ExitCode int
	Stderr   string
}

ProcessError represents an error from the CLI process.

func (*ProcessError) Error

func (e *ProcessError) Error() string

type RawContentBlock

type RawContentBlock struct {
	Type  ContentBlockType `json:"type"`
	ID    string           `json:"id,omitempty"`
	Name  string           `json:"name,omitempty"`
	Text  string           `json:"text,omitempty"`
	Input json.RawMessage  `json:"input,omitempty"`
}

RawContentBlock is used for parsing content blocks from JSON.

type ResourceLimits

type ResourceLimits struct {
	// MemoryMB is the maximum memory in megabytes. 0 uses the default (256MB).
	// Enforced by Docker backend via --memory flag.
	MemoryMB int `json:"memory_mb,omitempty"`
	// WallClockSec is the maximum wall-clock time in seconds. 0 uses the default (60s).
	// Enforced by both backends via context timeout.
	WallClockSec int `json:"wall_clock_sec,omitempty"`
	// MaxOutputBytes truncates stdout/stderr to this many bytes. 0 uses the default (1MB).
	MaxOutputBytes int `json:"max_output_bytes,omitempty"`
}

ResourceLimits defines execution constraints for sandbox sessions.

func DefaultResourceLimits

func DefaultResourceLimits() ResourceLimits

DefaultResourceLimits returns safe default resource limits.

type ResultError

type ResultError struct {
	// Subtype is the result subtype (e.g. "error_max_turns",
	// "error_during_execution", or "success" when the agent loop itself
	// completed but the last turn was an API error).
	Subtype string
	// Errors lists error strings reported by the CLI (may be empty).
	Errors []string
	// Result is the result text, if any. For API failures this holds the
	// "API Error: ..." prose.
	Result string
	// APIErrorStatus is the HTTP status of the failing API call, if any.
	APIErrorStatus *int
	// TerminalReason explains why the run ended (e.g. "api_error", "max_turns"),
	// if reported by the CLI.
	TerminalReason string
	// SessionID is the session the result belongs to, if reported.
	SessionID string
}

ResultError is returned when the CLI reports a terminal error result — a "result" message with IsError true (see ResultMessage). It carries the result's payload so callers can branch on why the run failed without string matching, e.g.:

if re, ok := err.(*ResultError); ok {
    if re.TerminalReason == "api_error" {
        retry()
    }
}

func NewResultError

func NewResultError(r *ResultMessage) *ResultError

NewResultError builds a ResultError from a terminal-error ResultMessage.

func (*ResultError) Error

func (e *ResultError) Error() string

type ResultMessage

type ResultMessage struct {
	Type         string       `json:"type"`
	Subtype      string       `json:"subtype,omitempty"`
	Cost         float64      `json:"total_cost_usd,omitempty"`
	Usage        *ResultUsage `json:"usage,omitempty"`
	InputTokens  int          `json:"-"` // Populated from Usage
	OutputTokens int          `json:"-"` // Populated from Usage
	Duration     float64      `json:"duration_ms,omitempty"`
	SessionID    string       `json:"session_id,omitempty"`
	IsError      bool         `json:"is_error,omitempty"`
	NumTurns     int          `json:"num_turns,omitempty"`
	Result       string       `json:"result,omitempty"`
	StopReason   string       `json:"stop_reason,omitempty"`

	// UUID uniquely identifies this result message.
	UUID string `json:"uuid,omitempty"`
	// TerminalReason explains why the query loop terminated (e.g. "completed",
	// "max_turns", "aborted_streaming", "aborted_tools"). Empty when the CLI
	// did not report one (older CLI versions, or a result that bypassed the
	// query loop such as a local slash command).
	TerminalReason string `json:"terminal_reason,omitempty"`
	// ModelUsage breaks down token usage and cost per model, keyed by the
	// model string the CLI billed against. Passed through verbatim from the
	// CLI's "modelUsage" field.
	ModelUsage map[string]ModelUsage `json:"modelUsage,omitempty"`
	// PermissionDenials lists tool calls that were denied during this turn.
	PermissionDenials []json.RawMessage `json:"permission_denials,omitempty"`
	// DeferredToolUse is set when a PreToolUse hook returned a "defer"
	// decision: the run stopped and this carries the deferred tool call so
	// the caller can inspect it and decide whether to resume.
	DeferredToolUse *DeferredToolUse `json:"deferred_tool_use,omitempty"`
	// Errors lists non-fatal error messages accumulated during the turn.
	Errors []string `json:"errors,omitempty"`
	// APIErrorStatus is the HTTP status code (e.g. 429, 500, 529) of the
	// failing API call when IsError is true and Subtype is "success"; nil
	// otherwise. Safe to log (no message content).
	APIErrorStatus *int `json:"api_error_status,omitempty"`
	// StructuredOutput holds the JSON result validated against Options.JSONSchema,
	// when one was configured.
	StructuredOutput json.RawMessage `json:"structured_output,omitempty"`
	// Origin describes the provenance of the user message that triggered this
	// turn — nil for a directly-sent prompt. Lets a streaming-input consumer
	// distinguish its own turns from injected ones (e.g. task notifications).
	Origin *MessageOrigin `json:"origin,omitempty"`
}

ResultMessage contains the final result of a query.

func QuerySync

func QuerySync(ctx context.Context, prompt string, opts ...Options) (string, *ResultMessage, error)

QuerySync sends a prompt and collects all text responses into a single string. This blocks until the query completes.

type ResultUsage

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

ResultUsage contains token usage information.

type RetryConfig

type RetryConfig struct {
	// MaxAttempts is the total number of execution attempts including the first.
	// 0 or 1 means no retry.
	MaxAttempts int

	// Backoff is the base wait duration before the first retry.
	// Each subsequent retry doubles the wait: Backoff, 2×Backoff, 4×Backoff, …
	Backoff time.Duration

	// RetryOn determines whether a given error should trigger a retry.
	// If nil, all errors are retried up to MaxAttempts.
	RetryOn func(err error) bool
}

RetryConfig configures automatic retry behavior for tool execution. Attach it globally via AgentConfig.Retry / APIAgentConfig.Retry, or per-tool via ToolDefinition.RetryConfig (per-tool takes precedence).

type SDKMCPServer

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

SDKMCPServer is an in-process MCP server implementation. This is the Go equivalent of Python's create_sdk_mcp_server.

func NewSDKMCPServer

func NewSDKMCPServer(name, version string) *SDKMCPServer

NewSDKMCPServer creates a new in-process MCP server.

func (*SDKMCPServer) AddTool

func (s *SDKMCPServer) AddTool(tool MCPTool, handler MCPToolHandler)

AddTool registers a tool with the server.

func (*SDKMCPServer) CallTool

func (s *SDKMCPServer) CallTool(ctx context.Context, name string, args json.RawMessage) (MCPToolResult, error)

CallTool executes the named tool.

func (*SDKMCPServer) HasTool

func (s *SDKMCPServer) HasTool(name string) bool

HasTool returns whether a tool with the given name is registered.

func (*SDKMCPServer) ListTools

func (s *SDKMCPServer) ListTools() []MCPTool

ListTools returns all registered tools.

func (*SDKMCPServer) Name

func (s *SDKMCPServer) Name() string

Name returns the server name.

func (*SDKMCPServer) ToolCount

func (s *SDKMCPServer) ToolCount() int

ToolCount returns the number of registered tools.

func (*SDKMCPServer) Version

func (s *SDKMCPServer) Version() string

Version returns the server version.

type SSEWriter

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

SSEWriter wraps an http.ResponseWriter for Server-Sent Events.

func NewSSEWriter

func NewSSEWriter(w http.ResponseWriter) (*SSEWriter, error)

NewSSEWriter creates an SSE writer from an HTTP response writer.

func (*SSEWriter) Close

func (s *SSEWriter) Close() error

Close sends a final close event.

func (*SSEWriter) WriteAgentEvent

func (s *SSEWriter) WriteAgentEvent(event AgentEvent) error

WriteAgentEvent writes an AgentEvent as an SSE event.

func (*SSEWriter) WriteEvent

func (s *SSEWriter) WriteEvent(eventType string, data any) error

WriteEvent writes an SSE event with the given type and data.

type SandboxBackend

type SandboxBackend interface {
	// CreateSession creates a new sandbox session.
	CreateSession(ctx context.Context, opts SessionOptions) (SandboxSession, error)

	// Close cleans up all backend resources.
	Close() error
}

SandboxBackend creates and manages isolated execution environments.

type SandboxConfig

type SandboxConfig struct {
	// Backend is the execution backend (required).
	Backend SandboxBackend

	// AllowedLanguages restricts which languages the agent can use.
	// Empty means all built-in languages are allowed.
	AllowedLanguages []Language

	// Limits sets resource constraints for all executions.
	// Zero values use defaults from DefaultResourceLimits().
	Limits ResourceLimits

	// EnableSessions allows the agent to create persistent sessions
	// that survive across multiple execute_code calls.
	EnableSessions bool

	// EnableFileIO exposes write_file, read_file, list_files tools.
	EnableFileIO bool

	// EnableCommands exposes the run_command tool.
	EnableCommands bool

	// WorkDir is the working directory inside the sandbox.
	// Defaults to "/workspace".
	WorkDir string
}

SandboxConfig configures the sandbox registry.

type SandboxFileInfo

type SandboxFileInfo struct {
	Path  string `json:"path"`
	Size  int64  `json:"size"`
	IsDir bool   `json:"is_dir"`
}

SandboxFileInfo describes a file inside a sandbox session.

type SandboxRegistry

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

SandboxRegistry manages sandbox sessions and provides tools for agent use.

func NewSandboxRegistry

func NewSandboxRegistry(cfg SandboxConfig) *SandboxRegistry

NewSandboxRegistry creates a new sandbox registry.

func (*SandboxRegistry) Close

func (r *SandboxRegistry) Close() error

Close destroys all sessions and releases backend resources.

func (*SandboxRegistry) ExecutionCount

func (r *SandboxRegistry) ExecutionCount() int

ExecutionCount returns the total number of executions.

func (*SandboxRegistry) Executions

func (r *SandboxRegistry) Executions() []Execution

Executions returns all executions in chronological order.

func (*SandboxRegistry) GetExecution

func (r *SandboxRegistry) GetExecution(id string) (*Execution, bool)

GetExecution returns a specific execution by ID.

func (*SandboxRegistry) SessionIDs

func (r *SandboxRegistry) SessionIDs() []string

SessionIDs returns all active session IDs.

func (*SandboxRegistry) SystemPrompt

func (r *SandboxRegistry) SystemPrompt() string

SystemPrompt returns a system prompt snippet for sandbox usage.

func (*SandboxRegistry) Tools

func (r *SandboxRegistry) Tools() *ToolRegistry

Tools returns a ToolRegistry with sandbox tools. The registry is created once and cached.

type SandboxSession

type SandboxSession interface {
	// ID returns the unique session identifier.
	ID() string

	// Execute runs code and returns the result.
	Execute(ctx context.Context, code string) (*ExecResult, error)

	// RunCommand runs a shell command and returns the result.
	RunCommand(ctx context.Context, command string) (*ExecResult, error)

	// WriteFile writes content to a file inside the sandbox.
	WriteFile(ctx context.Context, path string, content []byte) error

	// ReadFile reads a file from the sandbox.
	ReadFile(ctx context.Context, path string) ([]byte, error)

	// ListFiles lists files in a directory inside the sandbox.
	ListFiles(ctx context.Context, dir string) ([]SandboxFileInfo, error)

	// Destroy tears down the session and releases resources.
	Destroy(ctx context.Context) error
}

SandboxSession represents an active sandbox environment.

type SearchResult

type SearchResult struct {
	ID    string
	Score float64
}

SearchResult holds a document ID and its relevance score.

type SessionInfo

type SessionInfo struct {
	SessionID    string `json:"session_id"`
	Summary      string `json:"summary"`
	LastModified int64  `json:"last_modified"`
	FileSize     int64  `json:"file_size,omitempty"`
	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"`
}

SessionInfo contains display metadata for a persisted Claude Code session.

func ListSessions

func ListSessions(opts SessionListOptions) ([]SessionInfo, error)

ListSessions returns persisted sessions sorted by last-modified time, newest first.

func ListSessionsFromStore

func ListSessionsFromStore(ctx context.Context, store SessionStore, projectKey string, opts SessionListOptions) ([]SessionInfo, error)

ListSessionsFromStore returns store-backed sessions sorted newest first.

type SessionKey

type SessionKey struct {
	ProjectKey string `json:"project_key"`
	SessionID  string `json:"session_id"`
	Subpath    string `json:"subpath,omitempty"`
}

SessionKey identifies a main transcript or one of its subagent transcripts.

type SessionListOptions

type SessionListOptions struct {
	// Directory restricts discovery to the Claude Code project directory for
	// this path. Empty searches every project under the configured projects root.
	Directory string
	// ConfigDir overrides CLAUDE_CONFIG_DIR. Empty checks CLAUDE_CONFIG_DIR and
	// then defaults to ~/.claude.
	ConfigDir string
	Limit     int
	Offset    int
}

SessionListOptions configures session discovery and pagination.

type SessionMessage

type SessionMessage struct {
	Type            MessageRole     `json:"type"`
	UUID            string          `json:"uuid"`
	SessionID       string          `json:"session_id"`
	Message         json.RawMessage `json:"message"`
	ParentToolUseID string          `json:"parent_tool_use_id,omitempty"`
	ParentAgentID   string          `json:"parent_agent_id,omitempty"`
}

SessionMessage is a visible user or assistant message reconstructed from a persisted JSONL transcript. Message contains the raw Anthropic API message.

func GetSessionMessages

func GetSessionMessages(sessionID string, opts SessionMessageOptions) ([]SessionMessage, error)

GetSessionMessages reconstructs the active user/assistant chain from a transcript.

func GetSessionMessagesFromStore

func GetSessionMessagesFromStore(ctx context.Context, store SessionStore, key SessionKey, opts SessionMessageOptions) ([]SessionMessage, error)

GetSessionMessagesFromStore reconstructs a visible conversation from a SessionStore.

type SessionMessageOptions

type SessionMessageOptions struct {
	Directory string
	ConfigDir string
	Limit     int
	Offset    int
}

SessionMessageOptions configures transcript lookup and pagination.

type SessionOptions

type SessionOptions struct {
	Language Language
	Limits   ResourceLimits
	WorkDir  string
}

SessionOptions configures a new sandbox session.

type SessionStore

SessionStore is the persistence adapter used by the store-backed helpers. Implementations should treat transcript entries as opaque JSON objects.

type SessionStoreEntry

type SessionStoreEntry map[string]any

SessionStoreEntry is one opaque CLI transcript record. Stores must preserve each JSON object but need not preserve JSON key order or whitespace.

type SessionStoreListEntry

type SessionStoreListEntry struct {
	SessionID string `json:"session_id"`
	MTime     int64  `json:"mtime"`
}

SessionStoreListEntry identifies a main transcript and its last-modified time.

type Skill

type Skill struct {
	Name         string
	Description  string
	Tags         []string
	Category     string
	Dependencies []string
	Examples     []SkillExample
	Priority     int
	Metadata     map[string]string
}

Skill represents a composable capability bundle with rich metadata.

type SkillExample

type SkillExample struct {
	Query       string
	ToolsUsed   []string
	Description string
}

SkillExample describes an example query that a skill can handle.

type SkillIndex

type SkillIndex interface {
	// Index adds a document (skill or tool description) to the index.
	Index(id string, text string, tags []string) error
	// Remove removes a document from the index.
	Remove(id string) error
	// Search returns top-k matching document IDs with scores.
	Search(query string, k int) []SearchResult
	// Rebuild re-indexes everything from scratch.
	Rebuild() error
}

SkillIndex provides semantic/keyword lookup over skills and tools.

type SkillRegistry

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

SkillRegistry manages skill registration, resolution, and querying.

func NewSkillRegistry

func NewSkillRegistry(store *Store) *SkillRegistry

NewSkillRegistry creates a new SkillRegistry backed by the given store.

func (*SkillRegistry) All

func (sr *SkillRegistry) All() ([]*Skill, error)

All returns all registered skills.

func (*SkillRegistry) ByCategory

func (sr *SkillRegistry) ByCategory(category string) ([]*Skill, error)

ByCategory returns skills in the given category.

func (*SkillRegistry) ByTag

func (sr *SkillRegistry) ByTag(tag string) ([]*Skill, error)

ByTag returns skills matching the given tag.

func (*SkillRegistry) Get

func (sr *SkillRegistry) Get(name string) (*Skill, error)

Get returns a skill by name, or nil if not found.

func (*SkillRegistry) Register

func (sr *SkillRegistry) Register(skill Skill, tools *ToolRegistry) error

Register adds a skill and its tools to the store. Each tool from the ToolRegistry is stored with Source="skill:<name>" and inherits the skill's tags.

func (*SkillRegistry) Remove

func (sr *SkillRegistry) Remove(name string) error

Remove removes a skill and its associated tools from the store.

func (*SkillRegistry) Resolve

func (sr *SkillRegistry) Resolve(skillNames ...string) (*ToolRegistry, error)

Resolve returns a ToolRegistry containing tools from the named skills and their transitive dependencies.

type Store

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

Store provides a unified memdb-backed storage for tools, skills, and hooks.

func NewStore

func NewStore() *Store

NewStore creates a new Store backed by go-memdb.

func (*Store) DeleteHook

func (s *Store) DeleteHook(id string) error

DeleteHook removes a hook by ID.

func (*Store) DeleteSkill

func (s *Store) DeleteSkill(name string) error

DeleteSkill removes a skill by name.

func (*Store) DeleteTool

func (s *Store) DeleteTool(name string) error

DeleteTool removes a tool by name.

func (*Store) GetHook

func (s *Store) GetHook(id string) (*StoredHook, error)

GetHook retrieves a hook by ID.

func (*Store) GetSkill

func (s *Store) GetSkill(name string) (*StoredSkill, error)

GetSkill retrieves a skill by name.

func (*Store) GetTool

func (s *Store) GetTool(name string) (*StoredTool, error)

GetTool retrieves a tool by name.

func (*Store) InsertHook

func (s *Store) InsertHook(hook *StoredHook) error

InsertHook adds a hook to the store. If ID is empty, one is auto-generated on a copy so the caller's struct is not mutated.

func (*Store) InsertSkill

func (s *Store) InsertSkill(skill *StoredSkill) error

InsertSkill adds or replaces a skill in the store.

func (*Store) InsertTool

func (s *Store) InsertTool(tool *StoredTool) error

InsertTool adds or replaces a tool in the store.

func (*Store) ListHooks

func (s *Store) ListHooks() ([]*StoredHook, error)

ListHooks returns all stored hooks.

func (*Store) ListHooksByPattern

func (s *Store) ListHooksByPattern(pattern string) ([]*StoredHook, error)

ListHooksByPattern returns hooks matching a specific pattern.

func (*Store) ListSkills

func (s *Store) ListSkills() ([]*StoredSkill, error)

ListSkills returns all stored skills.

func (*Store) ListSkillsByCategory

func (s *Store) ListSkillsByCategory(category string) ([]*StoredSkill, error)

ListSkillsByCategory returns skills in the given category.

func (*Store) ListSkillsByTag

func (s *Store) ListSkillsByTag(tag string) ([]*StoredSkill, error)

ListSkillsByTag returns skills matching the given tag.

func (*Store) ListTools

func (s *Store) ListTools() ([]*StoredTool, error)

ListTools returns all stored tools.

func (*Store) ListToolsBySource

func (s *Store) ListToolsBySource(source string) ([]*StoredTool, error)

ListToolsBySource returns tools matching the given source.

func (*Store) ListToolsByTag

func (s *Store) ListToolsByTag(tag string) ([]*StoredTool, error)

ListToolsByTag returns tools matching the given tag.

func (*Store) Snapshot

func (s *Store) Snapshot() *StoreSnapshot

Snapshot returns a read-only point-in-time view of the store.

type StoreSnapshot

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

StoreSnapshot provides read-only access to a consistent store state. Call Close when done to release the read transaction.

func (*StoreSnapshot) Close

func (ss *StoreSnapshot) Close()

Close releases the snapshot's read transaction.

func (*StoreSnapshot) Skills

func (ss *StoreSnapshot) Skills() ([]*StoredSkill, error)

Skills returns all skills in the snapshot.

func (*StoreSnapshot) SkillsByCategory

func (ss *StoreSnapshot) SkillsByCategory(category string) ([]*StoredSkill, error)

SkillsByCategory returns skills in the given category.

func (*StoreSnapshot) Tools

func (ss *StoreSnapshot) Tools() ([]*StoredTool, error)

Tools returns all tools in the snapshot.

func (*StoreSnapshot) ToolsBySource

func (ss *StoreSnapshot) ToolsBySource(source string) ([]*StoredTool, error)

ToolsBySource returns tools matching the given source.

func (*StoreSnapshot) ToolsByTag

func (ss *StoreSnapshot) ToolsByTag(tag string) ([]*StoredTool, error)

ToolsByTag returns tools matching the given tag.

type StoredHook

type StoredHook struct {
	ID        string
	Pattern   string
	IsRegex   bool
	Timeout   time.Duration
	PreHooks  []PreToolUseHook
	PostHooks []PostToolUseHook
}

StoredHook wraps hook data with an ID for indexing.

type StoredSkill

type StoredSkill struct {
	Name         string
	Description  string
	Tags         []string
	Category     string
	Tools        []ToolDefinition
	Handlers     map[string]ToolHandler
	Dependencies []string
	Examples     []SkillExample
	Priority     int
	Metadata     map[string]string
}

StoredSkill is the skill record in memdb.

type StoredTool

type StoredTool struct {
	ToolDefinition           // embedded
	Source            string // "native", "mcp:<server>", "skill:<name>"
	Tags              []string
	Handler           ToolHandler           // not indexed
	StructuredHandler StructuredToolHandler // if set, Handler wraps this
}

StoredTool wraps a ToolDefinition with storage metadata.

type StreamCallback

type StreamCallback func(event Event) error

StreamCallback is a function called for each streaming event.

type StreamDelta

type StreamDelta struct {
	Type         string `json:"type,omitempty"`
	Text         string `json:"text,omitempty"`
	PartialJSON  string `json:"partial_json,omitempty"`
	StopReason   string `json:"stop_reason,omitempty"`
	StopSequence string `json:"stop_sequence,omitempty"`
}

StreamDelta represents delta content in a stream event.

type StreamEvent

type StreamEvent struct {
	Type  StreamEventType `json:"type"`
	Index int             `json:"index,omitempty"`

	// For message_start
	Message *AssistantMessage `json:"message,omitempty"`

	// For content_block_start/delta
	ContentBlock *RawContentBlock `json:"content_block,omitempty"`
	Delta        *StreamDelta     `json:"delta,omitempty"`
}

StreamEvent represents a streaming event from Claude.

type StreamEventType

type StreamEventType string

StreamEventType represents the type of streaming event.

const (
	EventMessageStart      StreamEventType = "message_start"
	EventContentBlockStart StreamEventType = "content_block_start"
	EventContentBlockDelta StreamEventType = "content_block_delta"
	EventContentBlockStop  StreamEventType = "content_block_stop"
	EventMessageDelta      StreamEventType = "message_delta"
	EventMessageStop       StreamEventType = "message_stop"
	EventToolUseStart      StreamEventType = "tool_use_start"
	EventToolUseDelta      StreamEventType = "tool_use_delta"
	EventToolUseEnd        StreamEventType = "tool_use_end"
	EventToolResult        StreamEventType = "tool_result"
	EventResult            StreamEventType = "result"
	EventAssistant         StreamEventType = "assistant"
	EventSystem            StreamEventType = "system"
	EventConversationReset StreamEventType = "conversation_reset"
)

type StructuredToolHandler

type StructuredToolHandler func(ctx context.Context, input json.RawMessage) (string, *ToolResultMetadata, error)

StructuredToolHandler returns content + optional metadata alongside the result.

type SubagentConfig

type SubagentConfig struct {
	// Agents maps subagent names to their definitions.
	Agents map[string]*AgentDefinition
}

SubagentConfig holds the set of available subagent definitions.

func NewSubagentConfig

func NewSubagentConfig() *SubagentConfig

NewSubagentConfig creates a new subagent configuration.

func (*SubagentConfig) Add

func (sc *SubagentConfig) Add(def *AgentDefinition)

Add registers an agent definition.

type SystemPromptBlock

type SystemPromptBlock struct {
	// Text is the content of this system prompt section.
	Text string
	// CacheControl, when non-nil, enables Anthropic prompt caching for this block.
	// Set to &CacheControl{Type: "ephemeral"} for standard caching behavior.
	CacheControl *CacheControl
}

SystemPromptBlock is a section of the system prompt with optional cache control.

type SystemReminder

type SystemReminder struct {
	Content string
}

SystemReminder represents mid-conversation context to inject via XML tags.

type TextBlock

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

TextBlock represents a text content block.

func (TextBlock) Type

func (TextBlock) Type() ContentBlockType

type TodoItem

type TodoItem struct {
	ID          string       `json:"id"`
	Description string       `json:"description"`
	Status      TodoStatus   `json:"status"`
	Priority    TodoPriority `json:"priority"`
	ParentID    string       `json:"parent_id,omitempty"`
}

TodoItem represents a single tracked task the agent is working on.

type TodoPriority

type TodoPriority string

TodoPriority represents the urgency of a todo item.

const (
	TodoPriorityHigh   TodoPriority = "high"
	TodoPriorityMedium TodoPriority = "medium"
	TodoPriorityLow    TodoPriority = "low"
)

type TodoStatus

type TodoStatus string

TodoStatus represents the state of a todo item.

const (
	TodoStatusPending    TodoStatus = "pending"
	TodoStatusInProgress TodoStatus = "in_progress"
	TodoStatusCompleted  TodoStatus = "completed"
)

type TodoStore

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

TodoStore provides thread-safe storage for todo items. It is intentionally separate from the memdb Store since todos are a simple ordered list managed atomically via write_todos.

func NewTodoStore

func NewTodoStore() *TodoStore

NewTodoStore creates an empty TodoStore.

func (*TodoStore) List

func (s *TodoStore) List() []TodoItem

List returns a snapshot of all todos.

func (*TodoStore) Write

func (s *TodoStore) Write(items []TodoItem)

Write replaces all todos atomically.

type ToolAnnotations

type ToolAnnotations struct {
	// ReadOnly indicates the tool does not modify any state.
	ReadOnly bool `json:"read_only,omitempty"`
	// Destructive indicates the tool makes hard-to-reverse changes.
	Destructive bool `json:"destructive,omitempty"`
	// ConcurrencySafe indicates the tool can run in parallel with other
	// concurrency-safe tools. Tools without this annotation (or with it
	// set to false) are assumed unsafe for parallel execution.
	ConcurrencySafe bool `json:"concurrency_safe,omitempty"`
	// SearchHint is a short keyword phrase (3-10 words) that describes
	// the tool's capabilities for deferred tool discovery via ToolSearch.
	SearchHint string `json:"search_hint,omitempty"`
}

ToolAnnotations provides safety and behavior metadata for a tool. These annotations inform the agent harness about tool properties without changing the tool's execution. They enable per-tool concurrency decisions, deferred loading, and richer permission policies.

type ToolCall

type ToolCall struct {
	ID    string          `json:"id"`
	Name  string          `json:"name"`
	Input json.RawMessage `json:"input"`
}

ToolCall represents a tool invocation from Claude.

type ToolDefinition

type ToolDefinition struct {
	Name        string         `json:"name"`
	Description string         `json:"description"`
	InputSchema map[string]any `json:"input_schema"`

	// Annotations provides optional safety and behavior metadata.
	// If nil, the tool has no annotations and defaults apply.
	Annotations *ToolAnnotations `json:"annotations,omitempty"`

	// ValidateInput performs input validation before execution.
	// Called after pre-hooks, before the handler. If nil, no validation is performed.
	ValidateInput ToolValidator `json:"-"`

	// CheckPermissions performs tool-specific permission checks.
	// Called after pre-hooks, before ValidateInput. If nil, no check is performed.
	CheckPermissions ToolPermissionCheck `json:"-"`

	// RetryConfig overrides the agent-level retry policy for this specific tool.
	// If nil, the agent's global RetryConfig is used.
	RetryConfig *RetryConfig `json:"-"`
}

ToolDefinition describes a tool that can be called by Claude.

func ReadTodosToolDefinition

func ReadTodosToolDefinition() ToolDefinition

ReadTodosToolDefinition returns the ToolDefinition for the read_todos tool.

func TodosToolDefinition

func TodosToolDefinition() ToolDefinition

TodosToolDefinition returns the ToolDefinition for the write_todos tool.

type ToolHandler

type ToolHandler func(ctx context.Context, input json.RawMessage) (string, error)

ToolHandler is a function that executes a tool and returns a result.

type ToolHookBuilder

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

ToolHookBuilder provides a fluent API for adding hooks.

func (*ToolHookBuilder) After

After adds a post-tool-use hook.

func (*ToolHookBuilder) Before

Before adds a pre-tool-use hook.

func (*ToolHookBuilder) WithTimeout

func (b *ToolHookBuilder) WithTimeout(d time.Duration) *ToolHookBuilder

WithTimeout sets the timeout for hooks added by this builder.

type ToolNotFoundError

type ToolNotFoundError struct {
	Name string
}

ToolNotFoundError indicates a tool was not found in the registry.

func (*ToolNotFoundError) Error

func (e *ToolNotFoundError) Error() string

type ToolPermissionCheck

type ToolPermissionCheck func(ctx context.Context, input json.RawMessage) error

ToolPermissionCheck performs tool-specific permission checks. Return nil to allow, or an error to deny.

type ToolRegistry

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

ToolRegistry maps tool names to their handlers. Internally backed by a Store for indexed lookups and thread-safe access.

func MergeToolRegistries

func MergeToolRegistries(registries ...*ToolRegistry) *ToolRegistry

MergeToolRegistries combines multiple tool registries into one.

func NewToolRegistry

func NewToolRegistry() *ToolRegistry

NewToolRegistry creates a new tool registry.

func NewToolRegistryWithStore

func NewToolRegistryWithStore(store *Store) *ToolRegistry

NewToolRegistryWithStore creates a tool registry sharing the given store.

func (*ToolRegistry) Definitions

func (r *ToolRegistry) Definitions() []ToolDefinition

Definitions returns all registered tool definitions.

func (*ToolRegistry) Execute

func (r *ToolRegistry) Execute(ctx context.Context, name string, input json.RawMessage) (string, error)

Execute runs a tool by name with the given input.

func (*ToolRegistry) ExecuteStructured

func (r *ToolRegistry) ExecuteStructured(ctx context.Context, name string, input json.RawMessage) (string, *ToolResultMetadata, error)

ExecuteStructured runs a tool and returns both the result string and any metadata. If the tool uses a regular (non-structured) handler, metadata is nil.

func (*ToolRegistry) GetHandler

func (r *ToolRegistry) GetHandler(name string) (ToolHandler, bool)

GetHandler returns the handler for the given tool name.

func (*ToolRegistry) GetToolDef

func (r *ToolRegistry) GetToolDef(name string) *ToolDefinition

GetToolDef returns the full ToolDefinition for the named tool, or nil.

func (*ToolRegistry) Has

func (r *ToolRegistry) Has(name string) bool

Has checks if a tool is registered.

func (*ToolRegistry) IsConcurrencySafe

func (r *ToolRegistry) IsConcurrencySafe(name string) bool

IsConcurrencySafe returns true if the named tool has ConcurrencySafe annotation.

func (*ToolRegistry) Merge

func (r *ToolRegistry) Merge(other *ToolRegistry)

Merge adds all tools from another registry.

func (*ToolRegistry) Register

func (r *ToolRegistry) Register(def ToolDefinition, handler ToolHandler)

Register adds a tool to the registry with Source="native".

func (*ToolRegistry) RegisterStructured

func (r *ToolRegistry) RegisterStructured(def ToolDefinition, handler StructuredToolHandler)

RegisterStructured registers a tool with a handler that returns metadata.

func (*ToolRegistry) RegisterWithSource

func (r *ToolRegistry) RegisterWithSource(def ToolDefinition, handler ToolHandler, source string, tags []string)

RegisterWithSource adds a tool with an explicit source and tags.

func (*ToolRegistry) Remove

func (r *ToolRegistry) Remove(name string)

Remove deletes a tool from the registry by name.

func (*ToolRegistry) Store

func (r *ToolRegistry) Store() *Store

Store returns the underlying store for cross-component queries.

func (*ToolRegistry) ToolAnnotations

func (r *ToolRegistry) ToolAnnotations(name string) *ToolAnnotations

ToolAnnotations returns the annotations for the named tool, or nil.

func (*ToolRegistry) ToolRetryConfig

func (r *ToolRegistry) ToolRetryConfig(name string) *RetryConfig

ToolRetryConfig returns the per-tool RetryConfig for the given name, or nil if the tool has no override. The agent-level RetryConfig is used as fallback.

func (*ToolRegistry) ToolsByTag

func (r *ToolRegistry) ToolsByTag(tag string) []ToolDefinition

ToolsByTag returns tool definitions matching the given tag.

type ToolResponse

type ToolResponse struct {
	ToolUseID string              `json:"tool_use_id"`
	Content   string              `json:"content"`
	IsError   bool                `json:"is_error,omitempty"`
	Metadata  *ToolResultMetadata `json:"-"` // not serialized
}

ToolResponse is the result of executing a tool.

type ToolResultBlock

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

ToolResultBlock represents a tool result content block.

func (ToolResultBlock) Type

type ToolResultEvent

type ToolResultEvent struct {
	ToolUseID string
	Content   string
	IsError   bool
}

ToolResultEvent represents the result of a tool invocation.

type ToolResultMetadata

type ToolResultMetadata struct {
	// InjectMessages are additional conversation messages to append to history
	// after this tool result. Useful for tools that need to provide extra context.
	InjectMessages []ConversationMessage
	// SystemContext is additional context to include in the next system reminder.
	SystemContext string
	// SuggestFollowUp is a hint for the agent about what to do next.
	SuggestFollowUp string
}

ToolResultMetadata carries optional side-channel information from tool execution back to the agent loop.

type ToolStats

type ToolStats struct {
	// Name is the tool name.
	Name string
	// Calls is the total number of invocations.
	Calls int
	// Failures is the number of invocations that returned an error.
	Failures int
	// TotalTime is the cumulative execution time across all calls.
	TotalTime time.Duration
}

ToolStats accumulates statistics for a single tool across all invocations in a session.

func (*ToolStats) AvgTime

func (s *ToolStats) AvgTime() time.Duration

AvgTime returns the average execution time per call.

type ToolUseBlock

type ToolUseBlock struct {
	ID    string          `json:"id"`
	Name  string          `json:"name"`
	Input json.RawMessage `json:"input"`
}

ToolUseBlock represents a tool use content block.

func (ToolUseBlock) Type

type ToolUseEvent

type ToolUseEvent struct {
	ID    string
	Name  string
	Input json.RawMessage
}

ToolUseEvent represents a tool being invoked.

type ToolValidator

type ToolValidator func(ctx context.Context, input json.RawMessage) error

ToolValidator validates tool input before execution. Return nil to allow, or an error to reject.

type ToolsConfig

type ToolsConfig struct {
	// Preset is a named tool preset (e.g., "default", "code", "all").
	Preset string
	// Names lists specific tool names to enable.
	Names []string
}

ToolsConfig specifies which built-in tools are available.

type TurnMetrics

type TurnMetrics struct {
	// TurnIndex is the zero-based index of this turn within the session.
	TurnIndex int
	// LLMLatency is the wall-clock time spent waiting for the LLM to respond.
	LLMLatency time.Duration
	// ToolsInvoked lists the names of tools called during this turn (in invocation order).
	ToolsInvoked []string
}

TurnMetrics captures timing and tool data for a single LLM turn.

type UserMessage

type UserMessage struct {
	Content []ContentBlock `json:"content"`
	// Origin describes the provenance of this message (nil for a message the
	// caller sent directly). Populated for injected turns such as background
	// task notifications or peer/channel messages.
	Origin *MessageOrigin `json:"origin,omitempty"`
}

UserMessage represents a message from the user.

func (UserMessage) Role

func (UserMessage) Role() MessageRole

func (*UserMessage) UnmarshalJSON

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

UnmarshalJSON decodes user message content blocks based on "type".

Directories

Path Synopsis
examples
artifacts command
Artifacts example showing how to generate HTML/JSX/text content with an API agent.
Artifacts example showing how to generate HTML/JSX/text content with an API agent.
generation command
Generation example showing agentic flows for image/video generation.
Generation example showing agentic flows for image/video generation.
hooks command
metrics command
Metrics example showing per-turn latency and per-tool execution stats, combined with parallel tool execution for faster multi-tool turns.
Metrics example showing per-turn latency and per-tool execution stats, combined with parallel tool execution for faster multi-tool turns.
providers command
Providers example showing how to run the same agent with Anthropic or OpenAI.
Providers example showing how to run the same agent with Anthropic or OpenAI.
resilience command
Resilience example demonstrating retry logic, budget controls, and history compaction working together in a long-running agent session.
Resilience example demonstrating retry logic, budget controls, and history compaction working together in a long-running agent session.
sandbox command
Sandbox example showing how to give an API agent code execution capabilities.
Sandbox example showing how to give an API agent code execution capabilities.
simple command
Simple example showing basic query usage.
Simple example showing basic query usage.
skills command
Skills example demonstrating skill-based tool organization with semantic lookup.
Skills example demonstrating skill-based tool organization with semantic lookup.
streaming command
Streaming example showing real-time event handling.
Streaming example showing real-time event handling.
subagents command
todos command
Todos example showing how to enable the write_todos tool so the agent can plan and track its own work.
Todos example showing how to enable the write_todos tool so the agent can plan and track its own work.
tools command
Tools example showing how to handle tool calls and results.
Tools example showing how to handle tool calls and results.

Jump to

Keyboard shortcuts

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