Documentation
¶
Overview ¶
Package claudeagent provides a Go SDK for interacting with Claude Code CLI.
Index ¶
- Constants
- Variables
- func AddToolFunc[T any](s *SDKMCPServer, tool MCPTool, ...)
- func AgentHTTPHandler(agent *Agent) http.HandlerFunc
- func BoolParam(description string) map[string]any
- func CollectText(events <-chan Event) (string, error)
- func DefaultDockerImages() map[Language]string
- func DeleteSession(sessionID, directory, configDir string) error
- func DeleteSessionFromStore(ctx context.Context, store SessionStore, projectKey, sessionID string) error
- func EnumParam(description string, values ...string) map[string]any
- func FormatReminder(r SystemReminder) string
- func FormatReminders(reminders []SystemReminder) string
- func GetToolName(serverName, toolName string) string
- func IntParam(description string) map[string]any
- func MarshalToolInput(v any) json.RawMessage
- func ObjectSchema(properties map[string]any, required ...string) map[string]any
- func ProjectKeyForDirectory(directory string) (string, error)
- func Query(ctx context.Context, prompt string, opts ...Options) (<-chan Event, error)
- func QueryWithCallback(ctx context.Context, prompt string, callback StreamCallback, opts ...Options) error
- func RegisterFunc[T any](r *ToolRegistry, def ToolDefinition, ...)
- func RegisterStructuredFunc[T any](r *ToolRegistry, def ToolDefinition, ...)
- func RegisterTodosTools(registry *ToolRegistry, store *TodoStore)
- func RegisterToolSearchTool(registry *ToolRegistry, deferred *DeferredToolRegistry)
- func StreamAgentToSSE(events <-chan AgentEvent, sse *SSEWriter) error
- func StringParam(description string) map[string]any
- func WithTraceContext(ctx context.Context, traceparent, tracestate string) context.Context
- type APIAgent
- type APIAgentConfig
- type Agent
- func (a *Agent) Close() error
- func (a *Agent) RewindFiles(ctx context.Context, userMessageID string) error
- func (a *Agent) Run(ctx context.Context, prompt string) (<-chan AgentEvent, error)
- func (a *Agent) RunSync(ctx context.Context, prompt string) (string, error)
- func (a *Agent) Send(ctx context.Context, message string) error
- func (a *Agent) Stop()
- func (a *Agent) TodoStore() *TodoStore
- type AgentConfig
- type AgentDefinition
- type AgentEvent
- type AgentEventType
- type AnthropicProvider
- type AnthropicProviderConfig
- type Artifact
- type ArtifactRegistry
- type ArtifactType
- type AssistantMessage
- type BM25Index
- type BudgetConfig
- type BudgetExceededError
- type CacheControl
- type CanUseToolFunc
- type ChatMessage
- type ChatRequest
- type ChatResponse
- type ChatRole
- type ChatStreamCallback
- type ChatStreamEvent
- type ChatStreamEventType
- type ChatUsage
- type CheckpointManager
- type Client
- func (c *Client) Close() error
- func (c *Client) IsRunning() bool
- func (c *Client) Query(ctx context.Context, prompt string) (<-chan Event, error)
- func (c *Client) QueryWithMessages(ctx context.Context, messages []Message) (<-chan Event, error)
- func (c *Client) Send(data string) error
- func (c *Client) Stop() error
- type ContentBlock
- type ContentBlockType
- type ContextBuilder
- type ContextOption
- type ConversationMessage
- type ConversationResetMessage
- type DeferredTool
- type DeferredToolLoader
- type DeferredToolRegistry
- func (d *DeferredToolRegistry) Add(tool DeferredTool)
- func (d *DeferredToolRegistry) All() []DeferredTool
- func (d *DeferredToolRegistry) IsLoaded(name string) bool
- func (d *DeferredToolRegistry) Load(ctx context.Context, name string, into *ToolRegistry) error
- func (d *DeferredToolRegistry) Search(query string, maxResults int) []DeferredTool
- type DeferredToolUse
- type DockerBackend
- type DockerBackendConfig
- type EffortLevel
- type Event
- type ExecResult
- type Execution
- type FallbackModelConfig
- type GenericHookHandler
- type HistoryConfig
- type HistorySummarizer
- type HookContext
- type HookDecision
- type HookEvent
- type HookEventData
- type HookResult
- type Hooks
- func (h *Hooks) AddPostHook(matcher string, hook PostToolUseHook)
- func (h *Hooks) AddPostHookWithOptions(matcher string, isRegex bool, timeout time.Duration, hook PostToolUseHook)
- func (h *Hooks) AddPreHook(matcher string, hook PreToolUseHook)
- func (h *Hooks) AddPreHookWithOptions(matcher string, isRegex bool, timeout time.Duration, hook PreToolUseHook)
- func (h *Hooks) EmitEvent(ctx context.Context, data HookEventData)
- func (h *Hooks) OnAllTools() *ToolHookBuilder
- func (h *Hooks) OnEvent(event HookEvent, handler GenericHookHandler)
- func (h *Hooks) OnTool(toolName string) *ToolHookBuilder
- func (h *Hooks) OnToolRegex(pattern string) *ToolHookBuilder
- func (h *Hooks) RemoveHook(id string)
- func (h *Hooks) RunPostHooks(ctx context.Context, hookCtx HookContext, toolResult string, isError bool) error
- func (h *Hooks) RunPreHooks(ctx context.Context, hookCtx HookContext) (HookResult, error)
- type JSONDecodeError
- type LLMProvider
- type Language
- type LoopMetrics
- type MCPContent
- type MCPServer
- type MCPServerConfig
- type MCPServers
- type MCPTool
- type MCPToolAnnotations
- type MCPToolHandler
- type MCPToolRegistry
- type MCPToolResult
- type MaxTokensRecovery
- type Message
- type MessageOrigin
- type MessageOriginKind
- type MessageRole
- type MetricsCollector
- type ModelUsage
- type OpenAICompatConfig
- type OpenAICompatProvider
- type Options
- type PermissionDecision
- type PermissionMode
- type PluginConfig
- type PostToolUseHook
- type PreToolUseHook
- type ProcessBackend
- type ProcessBackendConfig
- type ProcessError
- type RawContentBlock
- type ResourceLimits
- type ResultError
- type ResultMessage
- type ResultUsage
- type RetryConfig
- type SDKMCPServer
- func (s *SDKMCPServer) AddTool(tool MCPTool, handler MCPToolHandler)
- func (s *SDKMCPServer) CallTool(ctx context.Context, name string, args json.RawMessage) (MCPToolResult, error)
- func (s *SDKMCPServer) HasTool(name string) bool
- func (s *SDKMCPServer) ListTools() []MCPTool
- func (s *SDKMCPServer) Name() string
- func (s *SDKMCPServer) ToolCount() int
- func (s *SDKMCPServer) Version() string
- type SSEWriter
- type SandboxBackend
- type SandboxConfig
- type SandboxFileInfo
- type SandboxRegistry
- func (r *SandboxRegistry) Close() error
- func (r *SandboxRegistry) ExecutionCount() int
- func (r *SandboxRegistry) Executions() []Execution
- func (r *SandboxRegistry) GetExecution(id string) (*Execution, bool)
- func (r *SandboxRegistry) SessionIDs() []string
- func (r *SandboxRegistry) SystemPrompt() string
- func (r *SandboxRegistry) Tools() *ToolRegistry
- type SandboxSession
- type SearchResult
- type SessionInfo
- type SessionKey
- type SessionListOptions
- type SessionMessage
- type SessionMessageOptions
- type SessionOptions
- type SessionStore
- type SessionStoreEntry
- type SessionStoreListEntry
- type Skill
- type SkillExample
- type SkillIndex
- type SkillRegistry
- func (sr *SkillRegistry) All() ([]*Skill, error)
- func (sr *SkillRegistry) ByCategory(category string) ([]*Skill, error)
- func (sr *SkillRegistry) ByTag(tag string) ([]*Skill, error)
- func (sr *SkillRegistry) Get(name string) (*Skill, error)
- func (sr *SkillRegistry) Register(skill Skill, tools *ToolRegistry) error
- func (sr *SkillRegistry) Remove(name string) error
- func (sr *SkillRegistry) Resolve(skillNames ...string) (*ToolRegistry, error)
- type Store
- func (s *Store) DeleteHook(id string) error
- func (s *Store) DeleteSkill(name string) error
- func (s *Store) DeleteTool(name string) error
- func (s *Store) GetHook(id string) (*StoredHook, error)
- func (s *Store) GetSkill(name string) (*StoredSkill, error)
- func (s *Store) GetTool(name string) (*StoredTool, error)
- func (s *Store) InsertHook(hook *StoredHook) error
- func (s *Store) InsertSkill(skill *StoredSkill) error
- func (s *Store) InsertTool(tool *StoredTool) error
- func (s *Store) ListHooks() ([]*StoredHook, error)
- func (s *Store) ListHooksByPattern(pattern string) ([]*StoredHook, error)
- func (s *Store) ListSkills() ([]*StoredSkill, error)
- func (s *Store) ListSkillsByCategory(category string) ([]*StoredSkill, error)
- func (s *Store) ListSkillsByTag(tag string) ([]*StoredSkill, error)
- func (s *Store) ListTools() ([]*StoredTool, error)
- func (s *Store) ListToolsBySource(source string) ([]*StoredTool, error)
- func (s *Store) ListToolsByTag(tag string) ([]*StoredTool, error)
- func (s *Store) Snapshot() *StoreSnapshot
- type StoreSnapshot
- func (ss *StoreSnapshot) Close()
- func (ss *StoreSnapshot) Skills() ([]*StoredSkill, error)
- func (ss *StoreSnapshot) SkillsByCategory(category string) ([]*StoredSkill, error)
- func (ss *StoreSnapshot) Tools() ([]*StoredTool, error)
- func (ss *StoreSnapshot) ToolsBySource(source string) ([]*StoredTool, error)
- func (ss *StoreSnapshot) ToolsByTag(tag string) ([]*StoredTool, error)
- type StoredHook
- type StoredSkill
- type StoredTool
- type StreamCallback
- type StreamDelta
- type StreamEvent
- type StreamEventType
- type StructuredToolHandler
- type SubagentConfig
- type SystemPromptBlock
- type SystemReminder
- type TextBlock
- type TodoItem
- type TodoPriority
- type TodoStatus
- type TodoStore
- type ToolAnnotations
- type ToolCall
- type ToolDefinition
- type ToolHandler
- type ToolHookBuilder
- type ToolNotFoundError
- type ToolPermissionCheck
- type ToolRegistry
- func (r *ToolRegistry) Definitions() []ToolDefinition
- func (r *ToolRegistry) Execute(ctx context.Context, name string, input json.RawMessage) (string, error)
- func (r *ToolRegistry) ExecuteStructured(ctx context.Context, name string, input json.RawMessage) (string, *ToolResultMetadata, error)
- func (r *ToolRegistry) GetHandler(name string) (ToolHandler, bool)
- func (r *ToolRegistry) GetToolDef(name string) *ToolDefinition
- func (r *ToolRegistry) Has(name string) bool
- func (r *ToolRegistry) IsConcurrencySafe(name string) bool
- func (r *ToolRegistry) Merge(other *ToolRegistry)
- func (r *ToolRegistry) Register(def ToolDefinition, handler ToolHandler)
- func (r *ToolRegistry) RegisterStructured(def ToolDefinition, handler StructuredToolHandler)
- func (r *ToolRegistry) RegisterWithSource(def ToolDefinition, handler ToolHandler, source string, tags []string)
- func (r *ToolRegistry) Remove(name string)
- func (r *ToolRegistry) Store() *Store
- func (r *ToolRegistry) ToolAnnotations(name string) *ToolAnnotations
- func (r *ToolRegistry) ToolRetryConfig(name string) *RetryConfig
- func (r *ToolRegistry) ToolsByTag(tag string) []ToolDefinition
- type ToolResponse
- type ToolResultBlock
- type ToolResultEvent
- type ToolResultMetadata
- type ToolStats
- type ToolUseBlock
- type ToolUseEvent
- type ToolValidator
- type ToolsConfig
- type TurnMetrics
- type UserMessage
Constants ¶
const ReadTodosToolName = "read_todos"
ReadTodosToolName is the registered name of the read_todos tool.
const TodoToolName = "write_todos"
TodoToolName is the registered name of the write_todos tool.
Variables ¶
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 CollectText ¶
CollectText is a helper that extracts all text from a stream of events.
func DefaultDockerImages ¶
DefaultDockerImages returns the default Docker images for each language.
func DeleteSession ¶
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 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 ¶
GetToolName returns the full tool name for an MCP tool (mcp__serverName__toolName).
func MarshalToolInput ¶
func MarshalToolInput(v any) json.RawMessage
MarshalToolInput is a helper to marshal tool input to JSON.
func ObjectSchema ¶
ObjectSchema creates an object schema for tool input.
func ProjectKeyForDirectory ¶
ProjectKeyForDirectory derives the SessionStore project key used by Claude Code for directory-backed transcripts.
func Query ¶
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 ¶
StringParam creates a string parameter schema.
func WithTraceContext ¶
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).
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 ¶
Close gracefully shuts down the agent, sending SIGINT then SIGKILL after timeout.
func (*Agent) RewindFiles ¶
RewindFiles rewinds file changes to a previous checkpoint. Requires EnableFileCheckpointing to be set in Options.
func (*Agent) Run ¶
Run executes the agent loop with the given prompt. Returns a channel of AgentEvents for real-time streaming.
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 (p *AnthropicProvider) Complete(ctx context.Context, req ChatRequest, onEvent ChatStreamCallback) (ChatResponse, error)
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) Role() MessageRole
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) Rebuild ¶
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.
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.
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 (*Client) Close ¶
Close gracefully shuts down the running command. It sends SIGINT first, then SIGKILL after a 5-second timeout.
func (*Client) QueryWithMessages ¶
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.
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 ¶
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 ¶
func (d *DeferredToolRegistry) All() []DeferredTool
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 NewHooksWithStore ¶
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 ¶
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 ¶
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.
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 ¶
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 ¶
func (p *OpenAICompatProvider) Complete(ctx context.Context, req ChatRequest, onEvent ChatStreamCallback) (ChatResponse, error)
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 ¶
func (p *OpenAICompatProvider) WithName(name string) *OpenAICompatProvider
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.
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) 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 ¶
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.
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) 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) WriteAgentEvent ¶
func (s *SSEWriter) WriteAgentEvent(event AgentEvent) error
WriteAgentEvent writes an AgentEvent as an SSE event.
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 ¶
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 ¶
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 ¶
type SessionStore interface {
Append(context.Context, SessionKey, []SessionStoreEntry) error
Load(context.Context, SessionKey) ([]SessionStoreEntry, error)
ListSessions(context.Context, string) ([]SessionStoreListEntry, error)
Delete(context.Context, SessionKey) error
}
SessionStore is the persistence adapter used by the store-backed helpers. Implementations should treat transcript entries as opaque JSON objects.
type SessionStoreEntry ¶
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 ¶
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 (*Store) DeleteHook ¶
DeleteHook removes a hook by ID.
func (*Store) DeleteSkill ¶
DeleteSkill removes a skill by name.
func (*Store) DeleteTool ¶
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 ¶
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.
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 ¶
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 ¶
func (b *ToolHookBuilder) After(hook PostToolUseHook) *ToolHookBuilder
After adds a post-tool-use hook.
func (*ToolHookBuilder) Before ¶
func (b *ToolHookBuilder) Before(hook PreToolUseHook) *ToolHookBuilder
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 ¶
func (ToolResultBlock) Type() ContentBlockType
type ToolResultEvent ¶
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.
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 ¶
func (ToolUseBlock) Type() ContentBlockType
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".
Source Files
¶
- agent.go
- api_agent.go
- artifacts.go
- budget.go
- chat_anthropic.go
- chat_openai.go
- chat_provider.go
- chat_types.go
- checkpoint.go
- client.go
- context.go
- deferred.go
- errors.go
- execute.go
- history.go
- hooks.go
- mcp.go
- metrics.go
- providers.go
- query.go
- reminder.go
- retry.go
- sandbox.go
- sandbox_backend.go
- sandbox_docker.go
- sandbox_process.go
- search.go
- sessions.go
- skill.go
- sse.go
- store.go
- subagent.go
- todos.go
- tools.go
- types.go
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. |