core

package
v0.0.0-...-2869b66 Latest Latest
Warning

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

Go to latest
Published: Dec 9, 2025 License: MIT Imports: 16 Imported by: 0

Documentation

Index

Constants

View Source
const (
	DefaultMaxIterations      = 20
	DefaultCheckpointInterval = 5 * time.Minute
	DefaultMinTestCoverage    = 0.8
	// DefaultConfidenceThreshold is the default confidence threshold for initial observations
	DefaultConfidenceThreshold = 0.5
	// PercentageScale is used to convert scores to percentage (0-1 range)
	PercentageScale = 100.0
)

Default agent configuration constants

View Source
const (
	// CheckpointDirPerm is the permission for checkpoint directories (rwxr-xr-x)
	CheckpointDirPerm = 0755
	// CheckpointFilePerm is the permission for checkpoint files (rw-r--r--)
	CheckpointFilePerm = 0644
)

Checkpoint file system permissions

View Source
const (
	// DefaultMaxRetries is the default maximum number of retry attempts
	DefaultMaxRetries = 3
	// DefaultInitialDelay is the default initial delay before first retry
	DefaultInitialDelay = 1 * time.Second
	// DefaultMaxDelay is the default maximum delay between retries
	DefaultMaxDelay = 30 * time.Second
	// DefaultBackoffFactor is the default exponential backoff multiplier
	DefaultBackoffFactor = 2.0
	// DefaultJitterFactor is the default jitter factor for randomizing delays
	DefaultJitterFactor = 0.25
	// DefaultTokenCheckInterval is the default interval for checking rate limit tokens
	DefaultTokenCheckInterval = 100 * time.Millisecond
	// SecondsPerMinute is used for rate limit calculations
	SecondsPerMinute = 60.0
)

Default retry configuration constants

Variables

This section is empty.

Functions

func NewAgent

func NewAgent(toolRegistry tools.ToolRegistry, config *Config) agent.Agent

NewAgent creates a new core agent

Types

type Checkpoint

type Checkpoint struct {
	ID             string                 `json:"id"`
	Timestamp      time.Time              `json:"timestamp"`
	State          agent.AgentState       `json:"state"`
	Goal           agent.Goal             `json:"goal"`
	CurrentPlan    []agent.Task           `json:"current_plan"`
	Decisions      []agent.Decision       `json:"decisions"`
	CompletedTasks []agent.TaskResult     `json:"completed_tasks"`
	Iteration      int                    `json:"iteration"`
	Metadata       map[string]interface{} `json:"metadata"`
}

Checkpoint represents a saved agent state

type CheckpointManager

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

CheckpointManager handles saving and restoring agent state

func NewCheckpointManager

func NewCheckpointManager(checkpointDir string, autoSave bool, saveInterval time.Duration, logger *slog.Logger) *CheckpointManager

NewCheckpointManager creates a new checkpoint manager

func (*CheckpointManager) Delete

func (cm *CheckpointManager) Delete(checkpointID string) error

Delete removes a checkpoint

func (*CheckpointManager) List

func (cm *CheckpointManager) List() ([]Checkpoint, error)

List returns all available checkpoints

func (*CheckpointManager) Restore

func (cm *CheckpointManager) Restore(ctx context.Context, checkpointID string, agent *CoreAgent) error

Restore loads a checkpoint and restores agent state

func (*CheckpointManager) Save

func (cm *CheckpointManager) Save(ctx context.Context, agent *CoreAgent) (*Checkpoint, error)

Save creates a checkpoint of the current agent state

func (*CheckpointManager) StartAutoSave

func (cm *CheckpointManager) StartAutoSave(ctx context.Context, agent *CoreAgent)

StartAutoSave begins automatic checkpoint creation

type CircuitBreaker

type CircuitBreaker struct {
	MaxFailures     int
	ResetTimeout    time.Duration
	HalfOpenTimeout time.Duration
	// contains filtered or unexported fields
}

CircuitBreaker prevents cascading failures

func NewCircuitBreaker

func NewCircuitBreaker(maxFailures int, resetTimeout time.Duration, logger *slog.Logger) *CircuitBreaker

NewCircuitBreaker creates a new circuit breaker

func (*CircuitBreaker) AllowRequest

func (cb *CircuitBreaker) AllowRequest() bool

AllowRequest checks if the circuit breaker allows a request

func (*CircuitBreaker) Execute

func (cb *CircuitBreaker) Execute(ctx context.Context, operation RetryableOperation, name string) error

Execute runs an operation through the circuit breaker

func (*CircuitBreaker) GetState

func (cb *CircuitBreaker) GetState() CircuitState

GetState returns the current circuit state

func (*CircuitBreaker) RecordFailure

func (cb *CircuitBreaker) RecordFailure()

RecordFailure records a failed operation

func (*CircuitBreaker) RecordSuccess

func (cb *CircuitBreaker) RecordSuccess()

RecordSuccess records a successful operation

type CircuitState

type CircuitState string

CircuitState represents the state of a circuit breaker

const (
	CircuitStateClosed   CircuitState = "CLOSED"    // Normal operation
	CircuitStateOpen     CircuitState = "OPEN"      // Failing, reject requests
	CircuitStateHalfOpen CircuitState = "HALF_OPEN" // Testing if recovered
)

type Config

type Config struct {
	MaxIterations   int
	DryRun          bool
	ReviewConfig    *review.Config
	Logger          *slog.Logger
	GeminiClient    *gemini.Client
	CheckpointDir   string
	AutoSave        bool
	SaveInterval    time.Duration
	RetryConfig     *RetryStrategy
	EnableTelemetry bool
}

Config holds agent configuration

func DefaultConfig

func DefaultConfig() *Config

DefaultConfig returns default configuration

type Constraint

type Constraint struct {
	Type        ConstraintType
	Description string
	Validator   func(action agent.Action) error
}

Constraint represents a limitation on what the agent can do

type ConstraintType

type ConstraintType string

ConstraintType categorizes constraints

const (
	ConstraintTypeAPI          ConstraintType = "API"          // No API changes
	ConstraintTypeArchitecture ConstraintType = "ARCHITECTURE" // Must follow pattern
	ConstraintTypeSecurity     ConstraintType = "SECURITY"     // Security requirements
	ConstraintTypePerformance  ConstraintType = "PERFORMANCE"  // Performance limits
	ConstraintTypeTesting      ConstraintType = "TESTING"      // Testing requirements
)

type ConstraintValidator

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

ConstraintValidator validates that agent actions respect goal constraints

func NewConstraintValidator

func NewConstraintValidator(goalConstraints []string) *ConstraintValidator

NewConstraintValidator creates a validator for goal constraints

func (*ConstraintValidator) Validate

func (cv *ConstraintValidator) Validate(action agent.Action) error

Validate checks if an action violates any constraints

func (*ConstraintValidator) ValidateChanges

func (cv *ConstraintValidator) ValidateChanges(changes []agent.Change) error

ValidateChanges validates that changes respect constraints

type CoreAgent

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

CoreAgent implements the main agent loop

func (*CoreAgent) Execute

func (a *CoreAgent) Execute(ctx context.Context, goal agent.Goal) (*agent.Result, error)

Execute implements the main agent loop: Perceive → Plan → Act → Review → Reflect

func (*CoreAgent) GetCheckpoints

func (a *CoreAgent) GetCheckpoints() ([]Checkpoint, error)

GetCheckpoints returns available checkpoints

func (*CoreAgent) GetHistory

func (a *CoreAgent) GetHistory() []agent.Decision

func (*CoreAgent) GetProgress

func (a *CoreAgent) GetProgress() *agent.Progress

func (*CoreAgent) GetState

func (a *CoreAgent) GetState() agent.AgentState

func (*CoreAgent) GetTelemetrySummary

func (a *CoreAgent) GetTelemetrySummary() map[string]interface{}

GetTelemetrySummary returns telemetry metrics summary

func (*CoreAgent) Pause

func (a *CoreAgent) Pause() error

func (*CoreAgent) ProvideFeedback

func (a *CoreAgent) ProvideFeedback(feedback agent.Feedback) error

func (*CoreAgent) RestoreFromCheckpoint

func (a *CoreAgent) RestoreFromCheckpoint(ctx context.Context, checkpointID string) error

RestoreFromCheckpoint restores agent state from a checkpoint

func (*CoreAgent) Resume

func (a *CoreAgent) Resume() error

func (*CoreAgent) SetConstraints

func (a *CoreAgent) SetConstraints(constraints []string)

SetConstraints updates the agent's constraint validator

func (*CoreAgent) Stop

func (a *CoreAgent) Stop() error

type Metrics

type Metrics struct {
	// Execution metrics
	TotalExecutions      int64
	SuccessfulExecutions int64
	FailedExecutions     int64

	// Decision metrics
	DecisionsMade   map[agent.DecisionType]int64
	DecisionLatency map[agent.DecisionType][]time.Duration

	// Tool metrics
	ToolInvocations    map[string]int64
	ToolSuccessRate    map[string]float64
	ToolAverageLatency map[string]time.Duration

	// State metrics
	TimeInState      map[agent.AgentState]time.Duration
	StateTransitions map[string]int64 // "FROM->TO" format

	// Task metrics
	TasksCreated        int64
	TasksCompleted      int64
	TasksFailed         int64
	AverageTaskDuration time.Duration

	// Review metrics
	ReviewsPerformed   int64
	ReviewsApproved    int64
	ReviewsRejected    int64
	AverageReviewScore float64

	// Learning metrics
	LearningsStored    int64
	LearningsApplied   int64
	LearningConfidence []float64
	// contains filtered or unexported fields
}

Metrics tracks agent performance metrics

func NewMetrics

func NewMetrics() *Metrics

NewMetrics creates a new metrics tracker

func (*Metrics) GetAverageLearningConfidence

func (m *Metrics) GetAverageLearningConfidence() float64

GetAverageLearningConfidence returns average confidence of learnings

func (*Metrics) GetSuccessRate

func (m *Metrics) GetSuccessRate() float64

GetSuccessRate returns the overall success rate

func (*Metrics) RecordDecision

func (m *Metrics) RecordDecision(decisionType agent.DecisionType, latency time.Duration)

RecordDecision records a decision made by the agent

func (*Metrics) RecordExecution

func (m *Metrics) RecordExecution(success bool, duration time.Duration)

RecordExecution records an execution attempt

func (*Metrics) RecordLearning

func (m *Metrics) RecordLearning(stored bool, applied bool, confidence float64)

RecordLearning records learning metrics

func (*Metrics) RecordReview

func (m *Metrics) RecordReview(decision agent.ReviewDecision, score float64)

RecordReview records review metrics

func (*Metrics) RecordStateTransition

func (m *Metrics) RecordStateTransition(from, to agent.AgentState, duration time.Duration)

RecordStateTransition records a state change

func (*Metrics) RecordTask

func (m *Metrics) RecordTask(created bool, completed bool, failed bool, duration time.Duration)

RecordTask records task metrics

func (*Metrics) RecordToolInvocation

func (m *Metrics) RecordToolInvocation(toolName string, success bool, latency time.Duration)

RecordToolInvocation records a tool being used

func (*Metrics) Summary

func (m *Metrics) Summary() map[string]interface{}

Summary returns a summary of all metrics

type Planner

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

Planner generates execution plans using AI

func NewPlanner

func NewPlanner(geminiClient *gemini.Client, logger *slog.Logger) *Planner

NewPlanner creates a new AI-powered planner

func (*Planner) AdaptPlan

func (p *Planner) AdaptPlan(ctx context.Context, currentPlan []agent.Task, adaptReason string, feedback string) ([]agent.Task, error)

AdaptPlan modifies an existing plan based on new information

func (*Planner) GeneratePlan

func (p *Planner) GeneratePlan(ctx context.Context, goal agent.Goal, codebaseContext string, projectContext *analyzer.ProjectContext) ([]agent.Task, *agent.Reasoning, error)

GeneratePlan creates a multi-step execution plan using chain-of-thought reasoning

type RateLimiter

type RateLimiter struct {
	RequestsPerMinute int
	BurstSize         int
	// contains filtered or unexported fields
}

RateLimiter prevents overwhelming external services

func NewRateLimiter

func NewRateLimiter(requestsPerMinute int, burstSize int, logger *slog.Logger) *RateLimiter

NewRateLimiter creates a new rate limiter

func (*RateLimiter) Allow

func (rl *RateLimiter) Allow() bool

Allow checks if a request is allowed under rate limits

func (*RateLimiter) Wait

func (rl *RateLimiter) Wait(ctx context.Context) error

Wait waits until a request is allowed

type RetryStrategy

type RetryStrategy struct {
	MaxRetries      int
	InitialDelay    time.Duration
	MaxDelay        time.Duration
	BackoffFactor   float64
	RetryableErrors []string
	Logger          *slog.Logger
}

RetryStrategy defines how retries should be performed

func DefaultRetryStrategy

func DefaultRetryStrategy() *RetryStrategy

DefaultRetryStrategy returns a sensible retry strategy

func (*RetryStrategy) Execute

func (rs *RetryStrategy) Execute(ctx context.Context, operation RetryableOperation, operationName string) error

Execute runs an operation with retry logic and exponential backoff

func (*RetryStrategy) ExecuteWithResult

func (rs *RetryStrategy) ExecuteWithResult(
	ctx context.Context,
	operation func(ctx context.Context, attempt int) (interface{}, error),
	operationName string,
) (interface{}, error)

ExecuteWithResult runs an operation with retry logic and returns a result

type RetryableOperation

type RetryableOperation func(ctx context.Context, attempt int) error

RetryableOperation represents an operation that can be retried

type TraceSpan

type TraceSpan struct {
	Name      string
	StartTime time.Time
	EndTime   time.Time
	Duration  time.Duration
	Metadata  map[string]interface{}
	Error     error
}

TraceSpan represents a traced operation

type Tracer

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

Tracer provides distributed tracing capabilities

func NewTracer

func NewTracer() *Tracer

NewTracer creates a new tracer

func (*Tracer) EndSpan

func (t *Tracer) EndSpan(span *TraceSpan)

EndSpan completes a trace span

func (*Tracer) GetSpans

func (t *Tracer) GetSpans() []TraceSpan

GetSpans returns all recorded spans

func (*Tracer) StartSpan

func (t *Tracer) StartSpan(name string) *TraceSpan

StartSpan begins a new trace span

Jump to

Keyboard shortcuts

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