agent

package
v0.3.15 Latest Latest
Warning

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

Go to latest
Published: Dec 28, 2025 License: MIT Imports: 17 Imported by: 0

Documentation

Overview

Package agent implements a hierarchical multi-agent system for orchestrating Claude API interactions with support for child agents, state management, and tool execution.

Index

Constants

View Source
const (
	ModelSonnet = "sonnet"
	ModelHaiku  = "haiku"
	ModelOpus   = "opus"
)

Valid model names for agent configuration

View Source
const (
	RoleOrchestrator = "orchestrator"
	RoleReviewer     = "reviewer"
	RoleWorker       = "worker"
	RoleVoter        = "voter"
)

Valid role names for agent configuration

Variables

This section is empty.

Functions

func IsRetryable

func IsRetryable(err error) bool

IsRetryable determines if an error is worth retrying. Transient errors (network, timeout, rate limit) should be retried. Permanent errors (invalid input, auth failure) should not.

func Retry

func Retry(ctx context.Context, config RetryConfig, fn RetryableFunc) error

Retry executes a function with exponential backoff retry logic. Returns nil if the function eventually succeeds, or the last error if all retries fail.

Types

type Agent

type Agent struct {
	// ID is the hierarchical identifier (e.g., "session.1.2")
	ID string

	// ParentID is the ID of the parent agent (empty for root)
	ParentID string

	// Model specifies which Claude model to use ("sonnet", "haiku", "opus")
	Model string

	// Role describes the agent's purpose ("orchestrator", "reviewer", "worker", "voter")
	Role string

	// State tracks the current execution state
	State State

	// Messages contains the conversation history
	Messages []Message

	// Client is the Claude API client
	Client *core.Client

	// Tools is the tool registry available to this agent
	Tools *tools.Registry

	// Executor handles tool execution
	Executor *tools.Executor

	// Permissions defines what operations this agent can perform
	Permissions []string

	// Children maps child agent IDs to their instances
	Children map[string]*Agent

	// TotalCost tracks cumulative API cost for this agent
	TotalCost float64

	// MaxIterations is the maximum number of think-act loops
	MaxIterations int

	// MaxTokens is the maximum tokens per API request
	MaxTokens int

	// MaxMissionLength is the maximum mission length in characters
	MaxMissionLength int

	// MaxMessageHistory is the maximum number of messages to keep
	MaxMessageHistory int
	// contains filtered or unexported fields
}

Agent represents a single agent in the multi-agent system. Agents can spawn child agents, forming a hierarchy identified by dot-notation IDs. Thread-safe for concurrent access to state and children.

func NewAgent

func NewAgent(cfg Config) (*Agent, error)

NewAgent creates a new agent with the given configuration. It validates all required fields and returns an error if validation fails. The agent is initialized with clean state (Idle), empty message history, a new tool registry, executor, and Claude API client.

func RetryAgentSpawn

func RetryAgentSpawn(ctx context.Context, parent *Agent, config SubAgentConfig) (*Agent, error)

RetryAgentSpawn wraps agent spawning with retry logic for transient failures.

func (*Agent) AppendMessage

func (a *Agent) AppendMessage(msg Message)

AppendMessage adds a message to the history with proper synchronization.

func (*Agent) GetMessageCount

func (a *Agent) GetMessageCount() int

GetMessageCount returns the current message count without copying.

func (*Agent) GetMessages

func (a *Agent) GetMessages() []Message

GetMessages returns a thread-safe copy of the message history. The returned slice is a copy and safe to modify.

func (*Agent) GetState

func (a *Agent) GetState() State

GetState returns the current state of the agent. This method is thread-safe.

func (*Agent) Run

func (a *Agent) Run(ctx context.Context, mission string) (*Result, error)

Run executes a mission and returns the result. Algorithm:

  1. Add mission as user message
  2. Loop: a. Set state to Thinking b. Call client.CreateMessage() with messages and tool definitions c. If no tool calls, return final response d. Set state to ToolExecution e. Execute tools via executor f. Add tool results to messages g. Repeat
  3. Track total cost
  4. Respect context cancellation
  5. Handle errors gracefully

func (*Agent) SetState

func (a *Agent) SetState(state State) error

SetState transitions the agent to a new state. It validates the state transition and returns an error if the transition is invalid. This method is thread-safe.

func (*Agent) SpawnSubAgent

func (a *Agent) SpawnSubAgent(cfg SubAgentConfig) (*Agent, error)

SpawnSubAgent creates a new child agent with the given configuration. The child agent inherits the parent's API client and can optionally have a subset of the parent's permissions and tools. Permission escalation is prevented - a child cannot have permissions that its parent doesn't have.

The child is assigned a hierarchical ID (parentID + "." + childIndex) and is added to the parent's children map in a thread-safe manner.

Returns an error if: - The child would have permissions the parent doesn't have (escalation) - The model or role is invalid - Thread-safe child ID generation or map update fails

func (*Agent) Stop

func (a *Agent) Stop() error

Stop stops the agent and all its children in a cascading manner. Algorithm: 1. Check if already stopped (idempotent) 2. Stop all children in parallel 3. Wait for all children to stop 4. Set self state to Stopped 5. Release resources (when coordinator is implemented)

This method is thread-safe and idempotent.

type CachedResult

type CachedResult struct {
	// Result is the cached result
	Result *Result
	// ExpiresAt is when the cache entry expires
	ExpiresAt time.Time
}

CachedResult stores an operation result with expiration.

type Checkpoint

type Checkpoint struct {
	// TaskID is a unique identifier for this checkpoint
	TaskID string

	// Subtask is the task that was completed
	Subtask ComplexTask

	// Result is the output from completing the subtask
	Result *Result

	// Timestamp is when the checkpoint was created
	Timestamp time.Time
}

Checkpoint represents a saved subtask result for recovery

type ComplexTask

type ComplexTask struct {
	// Description is the task description
	Description string

	// Constraints are validation rules for the result
	// Supported: "non-empty", "contains:X", "max-length:N", "format:json"
	Constraints []string

	// Metadata stores additional task information
	Metadata map[string]interface{}
}

ComplexTask represents a task that may be decomposed into subtasks

type Config

type Config struct {
	// ID is the hierarchical identifier for this agent (required)
	ID string

	// ParentID is the ID of the parent agent (empty for root agents)
	ParentID string

	// Model specifies which Claude model to use (required: "sonnet", "haiku", "opus")
	Model string

	// Role describes the agent's purpose (required: "orchestrator", "reviewer", "worker", "voter")
	Role string

	// Permissions defines what operations this agent can perform (optional)
	Permissions []string

	// APIKey is the Anthropic API key for Claude client (required)
	APIKey string

	// ApprovalFunc is called when tools need user approval (optional)
	ApprovalFunc tools.ApprovalFunc

	// MaxIterations is the maximum number of think-act loops before stopping (optional, default: 10)
	MaxIterations int

	// MaxTokens is the maximum tokens per API request (optional, default: 4096)
	MaxTokens int

	// MaxMissionLength is the maximum mission length in characters (optional, default: 100000)
	MaxMissionLength int

	// MaxMessageHistory is the maximum number of messages to keep in history (optional, default: 100, -1 = unlimited)
	// When exceeded, oldest messages are truncated to prevent memory leaks
	MaxMessageHistory int
}

Config contains configuration parameters for creating a new agent

type GracefulDegradation

type GracefulDegradation struct {
	// MinimumSuccess is the minimum number of successful operations required
	MinimumSuccess int
	// TotalAttempts is the total number of operations attempted
	TotalAttempts int
	// SuccessCount tracks successful operations
	SuccessCount int
	// FailureCount tracks failed operations
	FailureCount int
}

GracefulDegradation attempts to continue with partial results when some operations fail.

func NewGracefulDegradation

func NewGracefulDegradation(totalAttempts, minimumSuccess int) *GracefulDegradation

NewGracefulDegradation creates a degradation tracker.

func (*GracefulDegradation) CanContinue

func (gd *GracefulDegradation) CanContinue() bool

CanContinue checks if we can proceed with partial results.

func (*GracefulDegradation) RecordFailure

func (gd *GracefulDegradation) RecordFailure()

RecordFailure increments the failure counter.

func (*GracefulDegradation) RecordSuccess

func (gd *GracefulDegradation) RecordSuccess()

RecordSuccess increments the success counter.

func (*GracefulDegradation) ShouldAbort

func (gd *GracefulDegradation) ShouldAbort() bool

ShouldAbort checks if we should stop early (impossible to reach minimum).

type LogLevel

type LogLevel int

LogLevel defines logging verbosity levels.

const (
	// LogLevelDebug shows all messages including detailed traces
	LogLevelDebug LogLevel = iota
	// LogLevelInfo shows informational messages
	LogLevelInfo
	// LogLevelWarn shows warnings and errors
	LogLevelWarn
	// LogLevelError shows only errors
	LogLevelError
)

type Logger

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

Logger provides structured logging for agent operations. In production, this integrates with Jeff's logging system.

func NewLogger

func NewLogger(level LogLevel) *Logger

NewLogger creates a new logger with the specified level.

func (*Logger) LogAgentSpawn

func (l *Logger) LogAgentSpawn(agentID, parentID, model, role string)

LogAgentSpawn logs agent creation.

func (*Logger) LogAgentStart

func (l *Logger) LogAgentStart(agentID, mission string)

LogAgentStart logs agent run initiation.

func (*Logger) LogAgentStop

func (l *Logger) LogAgentStop(agentID string, cost float64)

LogAgentStop logs agent shutdown.

func (*Logger) LogCacheHit

func (l *Logger) LogCacheHit(key string)

LogCacheHit logs cache hit.

func (*Logger) LogCacheMiss

func (l *Logger) LogCacheMiss(key string)

LogCacheMiss logs cache miss.

func (*Logger) LogCheckpointLoad

func (l *Logger) LogCheckpointLoad(taskID string)

LogCheckpointLoad logs checkpoint restoration.

func (*Logger) LogCheckpointSave

func (l *Logger) LogCheckpointSave(taskID string)

LogCheckpointSave logs checkpoint persistence.

func (*Logger) LogDecompositionAtomic

func (l *Logger) LogDecompositionAtomic(agentID string, task string)

LogDecompositionAtomic logs detection of atomic task.

func (*Logger) LogDecompositionComplete

func (l *Logger) LogDecompositionComplete(agentID string, depth int, cost float64)

LogDecompositionComplete logs completion of decomposition.

func (*Logger) LogDecompositionStart

func (l *Logger) LogDecompositionStart(agentID string, depth int, task string)

LogDecompositionStart logs task decomposition initiation.

func (*Logger) LogDecompositionSubtasks

func (l *Logger) LogDecompositionSubtasks(agentID string, numSubtasks int)

LogDecompositionSubtasks logs discovered subtasks.

func (*Logger) LogError

func (l *Logger) LogError(agentID, operation string, err error)

LogError logs error messages.

func (*Logger) LogMetrics

func (l *Logger) LogMetrics(metrics *Metrics)

LogMetrics logs current system metrics.

func (*Logger) LogOrphanCleanup

func (l *Logger) LogOrphanCleanup(agentID string)

LogOrphanCleanup logs orphan cleanup completion.

func (*Logger) LogOrphanDetected

func (l *Logger) LogOrphanDetected(agentID, parentID string)

LogOrphanDetected logs orphaned agent detection.

func (*Logger) LogRateLimitWait

func (l *Logger) LogRateLimitWait(agentID string, tokens float64)

LogRateLimitWait logs when rate limiting causes a wait.

func (*Logger) LogResourceConflict

func (l *Logger) LogResourceConflict(agentID, resourceID, ownerID string)

LogResourceConflict logs lock acquisition failure.

func (*Logger) LogResourceLock

func (l *Logger) LogResourceLock(agentID, resourceID string)

LogResourceLock logs resource lock acquisition.

func (*Logger) LogResourceRelease

func (l *Logger) LogResourceRelease(agentID, resourceID string)

LogResourceRelease logs resource lock release.

func (*Logger) LogStateTransition

func (l *Logger) LogStateTransition(agentID string, from, to State)

LogStateTransition logs agent state changes.

func (*Logger) LogToolCall

func (l *Logger) LogToolCall(agentID, toolName string, params map[string]interface{})

LogToolCall logs tool execution.

func (*Logger) LogToolResult

func (l *Logger) LogToolResult(agentID, toolName string, success bool, duration time.Duration)

LogToolResult logs tool execution result.

func (*Logger) LogValidationFailure

func (l *Logger) LogValidationFailure(agentID string, constraint string)

LogValidationFailure logs constraint validation failure.

func (*Logger) LogVotingAgentResult

func (l *Logger) LogVotingAgentResult(agentID string, output string, cost float64)

LogVotingAgentResult logs individual voting agent result.

func (*Logger) LogVotingResult

func (l *Logger) LogVotingResult(orchestratorID string, consensusPercent float64, reached bool, votes map[string]int)

LogVotingResult logs voting consensus result.

func (*Logger) LogVotingStart

func (l *Logger) LogVotingStart(orchestratorID string, numAgents int, task string)

LogVotingStart logs the beginning of a voting round.

type Message

type Message = core.Message

Message represents a message in the agent's conversation history. This is a type alias for core.Message to provide agent-specific interface.

type Metrics

type Metrics struct {
	// TotalAgentsSpawned is the total number of agents created
	TotalAgentsSpawned int
	// ActiveAgents is the current number of active agents
	ActiveAgents int
	// TotalCost is the cumulative API cost across all agents
	TotalCost float64
	// ToolCallsByAgent maps agent IDs to their tool call counts
	ToolCallsByAgent map[string]int
	// VotingConsensusRate is the percentage of voting rounds that reached consensus
	VotingConsensusRate float64
	// TotalVotingRounds is the total number of voting executions
	TotalVotingRounds int
	// ConsensusReached is the number of times consensus was reached
	ConsensusReached int
	// AverageAgentsPerVote is the average number of agents in voting rounds
	AverageAgentsPerVote float64
	// DecompositionDepthMax is the deepest decomposition level reached
	DecompositionDepthMax int
	// StartTime is when metrics collection started
	StartTime time.Time
}

Metrics tracks performance and usage metrics across the agent hierarchy.

func GetAgentHierarchyMetrics

func GetAgentHierarchyMetrics(agent *Agent) *Metrics

GetAgentHierarchyMetrics recursively collects metrics from an agent and all its children.

type MetricsCollector

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

MetricsCollector collects and aggregates metrics from the agent hierarchy.

func NewMetricsCollector

func NewMetricsCollector() *MetricsCollector

NewMetricsCollector creates a new metrics collector.

func (*MetricsCollector) GetMetrics

func (mc *MetricsCollector) GetMetrics() *Metrics

GetMetrics returns a pointer to a copy of the current metrics.

func (*MetricsCollector) RecordAgentSpawn

func (mc *MetricsCollector) RecordAgentSpawn()

RecordAgentSpawn records that a new agent was created.

func (*MetricsCollector) RecordAgentStop

func (mc *MetricsCollector) RecordAgentStop()

RecordAgentStop records that an agent was stopped.

func (*MetricsCollector) RecordCost

func (mc *MetricsCollector) RecordCost(cost float64)

RecordCost adds to the total cost.

func (*MetricsCollector) RecordDecompositionDepth

func (mc *MetricsCollector) RecordDecompositionDepth(depth int)

RecordDecompositionDepth records the depth of a decomposition.

func (*MetricsCollector) RecordToolCall

func (mc *MetricsCollector) RecordToolCall(agentID string)

RecordToolCall records a tool execution by an agent.

func (*MetricsCollector) RecordVotingRound

func (mc *MetricsCollector) RecordVotingRound(reached bool, numAgents int)

RecordVotingRound records a voting execution result.

func (*MetricsCollector) Reset

func (mc *MetricsCollector) Reset()

Reset clears all metrics.

type Monitor

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

Monitor runs background tasks to maintain agent system health. Detects orphaned agents and cleans up resources.

func NewMonitor

func NewMonitor(coordinator *ResourceCoordinator, interval time.Duration) *Monitor

NewMonitor creates a new agent monitor. interval: how often to check for orphans (default 30 seconds)

func (*Monitor) GetActiveAgentCount

func (m *Monitor) GetActiveAgentCount() int

GetActiveAgentCount returns the number of active agents.

func (*Monitor) GetOrphanCount

func (m *Monitor) GetOrphanCount() int

GetOrphanCount returns the current number of orphaned agents detected. This is a snapshot - orphans are cleaned up automatically.

func (*Monitor) Heartbeat

func (m *Monitor) Heartbeat(agentID string)

Heartbeat updates an agent's last heartbeat time. Logs a warning if the agent is not registered.

func (*Monitor) RegisterAgent

func (m *Monitor) RegisterAgent(agent *Agent)

RegisterAgent adds an agent to the monitor's registry.

func (*Monitor) Start

func (m *Monitor) Start()

Start begins the monitoring background goroutine.

func (*Monitor) Stop

func (m *Monitor) Stop()

Stop halts the monitoring goroutine. Safe to call multiple times (idempotent).

func (*Monitor) UnregisterAgent

func (m *Monitor) UnregisterAgent(agentID string)

UnregisterAgent removes an agent from the monitor's registry.

type ResourceCoordinator

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

ResourceCoordinator manages shared resources across the agent hierarchy. Provides locking, rate limiting, and caching to prevent race conditions and API quota exhaustion. Thread-safe for concurrent access by multiple agents.

func NewResourceCoordinator

func NewResourceCoordinator() *ResourceCoordinator

NewResourceCoordinator creates a new resource coordinator with default configuration. Default rate limit: 100 requests per second with burst capacity of 200.

func (*ResourceCoordinator) Acquire

func (rc *ResourceCoordinator) Acquire(ctx context.Context, agentID, resourceID string) error

Acquire attempts to acquire a lock on a resource for the given agent. Returns nil if successful, or an error if the resource is locked by another agent. Idempotent: if the agent already owns the lock, returns nil.

func (*ResourceCoordinator) CleanupExpiredCache

func (rc *ResourceCoordinator) CleanupExpiredCache()

CleanupExpiredCache removes all expired cache entries. This should be called periodically in a background goroutine to prevent expired entries from accumulating.

func (*ResourceCoordinator) ClearCache

func (rc *ResourceCoordinator) ClearCache()

ClearCache removes all cache entries.

func (*ResourceCoordinator) GetCached

func (rc *ResourceCoordinator) GetCached(key string) (*Result, bool)

GetCached retrieves a cached result if it exists and hasn't expired. Returns (result, true) if cache hit, (nil, false) if cache miss. Note: Expired entries are returned as cache miss; cleanup happens in background.

func (*ResourceCoordinator) InvalidateCache

func (rc *ResourceCoordinator) InvalidateCache(key string)

InvalidateCache removes a specific cache entry.

func (*ResourceCoordinator) Release

func (rc *ResourceCoordinator) Release(agentID, resourceID string) error

Release releases a lock on a resource. Returns an error if the agent does not own the lock.

func (*ResourceCoordinator) ReleaseAll

func (rc *ResourceCoordinator) ReleaseAll(agentID string)

ReleaseAll releases all locks held by the given agent. Used during agent cleanup to prevent resource leaks.

func (*ResourceCoordinator) SetCached

func (rc *ResourceCoordinator) SetCached(key string, result *Result, ttl time.Duration)

SetCached stores a result in the cache with the specified TTL.

type ResourceLock

type ResourceLock struct {
	// ResourceID is the identifier of the locked resource
	ResourceID string
	// OwnerID is the ID of the agent holding the lock
	OwnerID string
	// AcquiredAt is when the lock was acquired
	AcquiredAt time.Time
}

ResourceLock represents a lock on a shared resource. Only one agent can hold a lock on a resource at a time.

type Result

type Result struct {
	// AgentID is the ID of the agent that produced this result
	AgentID string

	// Output is the final text output from the agent
	Output string

	// Cost is the total API cost for this execution
	Cost float64

	// ToolCalls is the list of tools called during execution
	ToolCalls []ToolCall

	// Errors is a list of non-fatal errors that occurred
	Errors []error
}

Result represents the result of an agent execution

func RetryDecomposition

func RetryDecomposition(ctx context.Context, decomposer *TaskDecomposer, task ComplexTask, depth int) (*Result, error)

RetryDecomposition wraps task decomposition with retry logic.

type RetryConfig

type RetryConfig struct {
	// MaxRetries is the maximum number of retry attempts
	MaxRetries int
	// InitialDelay is the delay before the first retry
	InitialDelay time.Duration
	// MaxDelay is the maximum delay between retries
	MaxDelay time.Duration
	// Multiplier is the backoff multiplier (typically 2.0 for exponential)
	Multiplier float64
	// Jitter adds randomness to prevent thundering herd
	Jitter bool
}

RetryConfig configures retry behavior for operations.

func DefaultRetryConfig

func DefaultRetryConfig() RetryConfig

DefaultRetryConfig returns a sensible default retry configuration.

type RetryableFunc

type RetryableFunc func() error

RetryableFunc is a function that can be retried.

type State

type State string

State represents the current state of an agent

const (
	// StateIdle indicates the agent is idle and ready to accept work
	StateIdle State = "Idle"

	// StateThinking indicates the agent is generating a response
	StateThinking State = "Thinking"

	// StateStreaming indicates the agent is streaming a response
	StateStreaming State = "Streaming"

	// StateToolExecution indicates the agent is executing tools
	StateToolExecution State = "ToolExecution"

	// StateStopped indicates the agent has been stopped
	StateStopped State = "Stopped"
)

type Status

type Status struct {
	Agent         *Agent
	LastHeartbeat time.Time
	ParentAlive   bool
}

Status tracks an agent's health status.

type SubAgentConfig

type SubAgentConfig struct {
	// Model specifies which Claude model to use (optional, defaults to parent's model)
	// Must be one of: "sonnet", "haiku", "opus"
	Model string

	// Role describes the agent's purpose (optional, defaults to "worker")
	// Must be one of: "orchestrator", "reviewer", "worker", "voter"
	Role string

	// Permissions defines what operations this agent can perform (optional, defaults to parent's permissions)
	// Child cannot have more permissions than parent (escalation is rejected)
	Permissions []string

	// Tools is an optional subset of tool names to make available to this agent
	// If not specified, child inherits parent's tools
	Tools []string

	// MaxIterations overrides the maximum think-act loops (nil = inherit from parent)
	MaxIterations *int

	// MaxTokens overrides the maximum tokens per API request (nil = inherit from parent)
	MaxTokens *int

	// MaxMissionLength overrides the maximum mission length (nil = inherit from parent)
	MaxMissionLength *int

	// MaxMessageHistory overrides the maximum message history (nil = inherit from parent)
	MaxMessageHistory *int
}

SubAgentConfig contains configuration parameters for spawning a sub-agent

type TaskDecomposer

type TaskDecomposer struct {
	// Orchestrator is the agent that performs decomposition
	Orchestrator *Agent

	// MaxDepth is the maximum recursion depth (default: 3)
	MaxDepth int

	// VotingConfig is used for atomic task execution
	VotingConfig VotingConfig

	// DB is the SQLite database for checkpointing (optional)
	DB *sql.DB
}

TaskDecomposer manages decomposition of complex tasks into subtasks

func NewTaskDecomposer

func NewTaskDecomposer(orchestrator *Agent, maxDepth int, votingConfig VotingConfig, db *sql.DB) *TaskDecomposer

NewTaskDecomposer creates a new task decomposer

func (*TaskDecomposer) DecomposeAndExecute

func (td *TaskDecomposer) DecomposeAndExecute(ctx context.Context, task ComplexTask, depth int) (*Result, error)

DecomposeAndExecute recursively decomposes and executes a complex task Algorithm:

  1. Check depth limit (error if exceeded)
  2. Decompose task into subtasks using LLM
  3. If no subtasks (atomic): a. Execute with voting b. Validate result c. Return result
  4. If has subtasks (recursive): a. For each subtask: - Recursively call DecomposeAndExecute (depth + 1) - Validate result - If validation fails, retry with voting - Save checkpoint b. Combine results c. Return combined result

type TokenBucket

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

TokenBucket implements token bucket rate limiting algorithm. Allows bursts up to capacity while maintaining average rate.

func NewTokenBucket

func NewTokenBucket(capacity, refillRate float64) *TokenBucket

NewTokenBucket creates a new token bucket rate limiter. capacity: maximum number of tokens (burst size) refillRate: tokens added per second (average rate)

func (*TokenBucket) Take

func (tb *TokenBucket) Take(ctx context.Context, tokens float64) error

Take attempts to consume the specified number of tokens. Blocks until tokens are available or context is cancelled. Returns an error if context is cancelled before tokens are available.

type ToolCall

type ToolCall struct {
	// ID is the unique identifier for this tool call
	ID string

	// Name is the name of the tool that was called
	Name string

	// Input is the parameters passed to the tool
	Input map[string]interface{}

	// Result is the output from the tool execution
	Result string

	// Error is any error that occurred during tool execution
	Error error
}

ToolCall represents a tool invocation during agent execution

type VotingConfig

type VotingConfig struct {
	// NumAgents is the number of voting agents to spawn (default: 5)
	NumAgents int

	// ConsensusPercent is the minimum percentage required for consensus (default: 0.6)
	// Value should be between 0.0 and 1.0 (e.g., 0.6 = 60%)
	ConsensusPercent float64

	// Model specifies which Claude model voting agents should use (default: "haiku")
	Model string

	// Timeout is the maximum time in seconds to wait for voting (default: 120)
	Timeout int
}

VotingConfig defines configuration for voting execution

type VotingCoordinator

type VotingCoordinator struct {
	// Orchestrator is the parent agent that spawns voting agents
	Orchestrator *Agent
}

VotingCoordinator manages voting execution

func NewVotingCoordinator

func NewVotingCoordinator(orchestrator *Agent) *VotingCoordinator

NewVotingCoordinator creates a new voting coordinator

func (*VotingCoordinator) ExecuteWithVoting

func (vc *VotingCoordinator) ExecuteWithVoting(ctx context.Context, task string, cfg VotingConfig) (*VotingResult, error)

ExecuteWithVoting executes a task with N voting agents and computes consensus Algorithm: 1. Apply default config values 2. Spawn N identical voting agents (fan-out) 3. Execute all agents in parallel with same task 4. Compute consensus from results (fan-in) 5. Cleanup all voting agents 6. Return consensus result

type VotingResult

type VotingResult struct {
	// Output is the consensus output (majority answer)
	Output string

	// ConsensusPercent is the percentage of agents that agreed (0.0 to 1.0)
	ConsensusPercent float64

	// ConsensusReached indicates if the consensus threshold was met
	ConsensusReached bool

	// VotingAgents is the number of agents that successfully completed
	VotingAgents int

	// FailedAgents is the number of agents that failed
	FailedAgents int

	// TotalCost is the aggregate cost across all voting agents
	TotalCost float64

	// Votes maps normalized outputs to vote counts (for debugging)
	Votes map[string]int
}

VotingResult contains the result of a voting execution

func RetryVoting

func RetryVoting(ctx context.Context, orchestrator *Agent, task string, config VotingConfig) (*VotingResult, error)

RetryVoting wraps voting execution with retry and graceful degradation. If some agents fail, it continues with successful ones if minimum threshold is met.

Jump to

Keyboard shortcuts

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