Documentation
¶
Overview ¶
Package autonomous - Task 29: Audit Log for all autonomous operations
Package autonomous provides a "Computer Use" style autonomous agent loop. It implements a Plan → Execute → Verify → Retry cycle for autonomous coding tasks.
Package autonomous - Task 28: Command Approval Workflow for risky operations
Package autonomous - Task 4: Agent Confidence Score for autonomous decision-making
Package autonomous - Task 26: Danger Level assessment for commands
Package autonomous - Task 17: Agent Debug Mode for transparency in autonomous mode
Package autonomous - Task 20: Learning from Autonomous Failures
Package autonomous - Task 10: Goal State tracking for complex multi-file changes
Package autonomous provides autonomous agent capabilities ¶
Package autonomous - Task 3: Multi-step planning engine with dependency graph
Package autonomous - Task 16: Agent Playbooks for common task patterns
Package autonomous - Task 13: Progress Dashboard for long-running tasks
Package autonomous - Task 27: Protected Paths configuration
Package autonomous - Task 12: Timeout and resource limits for autonomous operations
Package autonomous - Task 34: Resource Limits (CPU, Memory, Execution Time) for sandboxes
Package autonomous - Task 33: Restricted Commands list configuration
Package autonomous - Task 6: Review Checkpoint system for destructive operations
Package autonomous - Task 9: Rollback Stack for safe autonomous experimentation
Package autonomous - Task 32: Safety Profile system (strict/balanced/permissive)
Package autonomous - Task 21: Docker-based sandboxed command execution
Package autonomous - Task 24: File system isolation for sandbox mode
Package autonomous - Task 25: Network isolation options for sandbox
Package autonomous - Task 23: Sandbox container templates for common languages
Package autonomous - Task 11: Smart Retry with error pattern recognition
Package autonomous - Task 30: Snapshot capability before destructive changes
Package autonomous - Task 5: Interrupt/Resume capability for long-running tasks
Package autonomous - Task 19: Success Criteria validation before task completion
Package autonomous - Task 8: Task Queue for parallel autonomous operations
Package autonomous - Task 2: Autonomous test-running with failure analysis and auto-fix
Index ¶
- Variables
- func ApplyNetworkProfile(config *SandboxConfig, profileName string) error
- func CheckDockerAvailable() bool
- func CompareProfiles(p1, p2 *SafetyProfile) map[string]interface{}
- func DefaultStrategies() map[string]RetryStrategy
- func DetectSandboxTemplate(repoPath string) string
- func IsCommandSafe(command string) bool
- func ListImages(ctx context.Context) ([]string, error)
- func ListNetworkProfiles() []string
- func NeedsApproval(command string) bool
- func SandboxTemplateNames() []string
- func ValidateSandboxLimits(limits *SandboxLimits) error
- type Action
- type ActionContext
- type ApprovalCallback
- type ApprovalDecision
- type ApprovalMode
- type ApprovalPolicy
- type ApprovalProfileSettings
- type ApprovalRequest
- type ApprovalStats
- type ApprovalStatus
- type AuditConfig
- type AuditEvent
- type AuditEventType
- type AuditFilter
- type AuditLogger
- func (al *AuditLogger) Clear()
- func (al *AuditLogger) Export() ([]byte, error)
- func (al *AuditLogger) GetEvents(filter AuditFilter) []AuditEvent
- func (al *AuditLogger) GetRecentEvents(n int) []AuditEvent
- func (al *AuditLogger) GetStats() AuditStats
- func (al *AuditLogger) Log(eventType AuditEventType, severity AuditSeverity, message string, ...)
- func (al *AuditLogger) LogApproval(requestID, command string, approved bool, approvedBy, reason string)
- func (al *AuditLogger) LogCommand(command string, args []string, result string, duration time.Duration, ...)
- func (al *AuditLogger) LogError(operation, message string, err error)
- func (al *AuditLogger) LogFileOperation(operation, path string, result string, err error)
- func (al *AuditLogger) LogSecurity(event, details string, severity AuditSeverity)
- func (al *AuditLogger) LogSnapshot(operation, snapshotID string, err error)
- func (al *AuditLogger) SetSessionID(sessionID string)
- type AuditOption
- func WithActor(actor string) AuditOption
- func WithApprovalID(id string) AuditOption
- func WithApproved(approved bool) AuditOption
- func WithDangerLevel(level DangerLevel) AuditOption
- func WithDuration(d time.Duration) AuditOption
- func WithError(err error) AuditOption
- func WithMetadata(key string, value interface{}) AuditOption
- func WithOperation(operation string) AuditOption
- func WithResult(result string) AuditOption
- func WithStepID(stepID string) AuditOption
- func WithTarget(target string) AuditOption
- type AuditSafetySettings
- type AuditSeverity
- type AuditStats
- type Checkpoint
- type ChecksumMismatch
- type CommandApprovalManager
- func (cam *CommandApprovalManager) Approve(requestID string, approvedBy string) error
- func (cam *CommandApprovalManager) Cancel(requestID string) error
- func (cam *CommandApprovalManager) Deny(requestID string, reason string) error
- func (cam *CommandApprovalManager) ExpirePending() int
- func (cam *CommandApprovalManager) ExportRequests() ([]byte, error)
- func (cam *CommandApprovalManager) GetPending() []*ApprovalRequest
- func (cam *CommandApprovalManager) GetPolicy() ApprovalPolicy
- func (cam *CommandApprovalManager) GetRequest(requestID string) (*ApprovalRequest, bool)
- func (cam *CommandApprovalManager) GetStats() ApprovalStats
- func (cam *CommandApprovalManager) IsApproved(requestID string) bool
- func (cam *CommandApprovalManager) RequestAndWait(ctx context.Context, command string, args []string, workingDir string) (*ApprovalRequest, error)
- func (cam *CommandApprovalManager) RequestApproval(ctx context.Context, command string, args []string, workingDir string) (*ApprovalRequest, error)
- func (cam *CommandApprovalManager) SetCallback(callback ApprovalCallback)
- func (cam *CommandApprovalManager) SetPolicy(policy ApprovalPolicy)
- func (cam *CommandApprovalManager) WaitForApproval(ctx context.Context, requestID string) (*ApprovalRequest, error)
- type CommandCategory
- type ConfidenceEngine
- func (ce *ConfidenceEngine) ApplyLearningFromFile(learnings map[string]float64)
- func (ce *ConfidenceEngine) CalculateConfidence(action PlanStep, context ActionContext) ConfidenceScore
- func (ce *ConfidenceEngine) ExportLearnings() map[string]float64
- func (ce *ConfidenceEngine) GetConfidenceStats() ConfidenceStats
- func (ce *ConfidenceEngine) GetThresholds() ConfidenceThresholds
- func (ce *ConfidenceEngine) RecordOutcome(action string, confidence float64, outcome string)
- func (ce *ConfidenceEngine) SetThresholds(thresholds ConfidenceThresholds)
- func (ce *ConfidenceEngine) ShouldProceed(score ConfidenceScore) Decision
- type ConfidenceRecord
- type ConfidenceScore
- type ConfidenceStats
- type ConfidenceThresholds
- type Config
- type ContainerUsage
- type ContainerViolation
- type CriterionBuilder
- func (b *CriterionBuilder) Build() *SuccessCriterion
- func (b *CriterionBuilder) Negate() *CriterionBuilder
- func (b *CriterionBuilder) Optional() *CriterionBuilder
- func (b *CriterionBuilder) WithDescription(desc string) *CriterionBuilder
- func (b *CriterionBuilder) WithExpected(expected string) *CriterionBuilder
- func (b *CriterionBuilder) WithMetadata(key string, value any) *CriterionBuilder
- func (b *CriterionBuilder) WithName(name string) *CriterionBuilder
- func (b *CriterionBuilder) WithPattern(pattern string) *CriterionBuilder
- func (b *CriterionBuilder) WithRetries(count int, delay time.Duration) *CriterionBuilder
- func (b *CriterionBuilder) WithTimeout(timeout time.Duration) *CriterionBuilder
- func (b *CriterionBuilder) WithWeight(weight float64) *CriterionBuilder
- type CriterionChecker
- type CriterionStatus
- type CriterionType
- type CustomSafetyRule
- type DNSConfig
- type DangerAssessment
- type DangerAssessmentBuilder
- func (b *DangerAssessmentBuilder) Build() *DangerAssessment
- func (b *DangerAssessmentBuilder) Destructive() *DangerAssessmentBuilder
- func (b *DangerAssessmentBuilder) WithAffectedPath(path string) *DangerAssessmentBuilder
- func (b *DangerAssessmentBuilder) WithCategory(category DangerCategory) *DangerAssessmentBuilder
- func (b *DangerAssessmentBuilder) WithLevel(level DangerLevel) *DangerAssessmentBuilder
- func (b *DangerAssessmentBuilder) WithMitigation(mitigation string) *DangerAssessmentBuilder
- func (b *DangerAssessmentBuilder) WithReason(reason string) *DangerAssessmentBuilder
- type DangerAssessor
- func (da *DangerAssessor) AddCustomRule(rule DangerRule) error
- func (da *DangerAssessor) AddProtectedPath(path string)
- func (da *DangerAssessor) AssessCommand(command string) *DangerAssessment
- func (da *DangerAssessor) GetProtectedPaths() []string
- func (da *DangerAssessor) RemoveCustomRule(name string) bool
- func (da *DangerAssessor) RemoveProtectedPath(path string) bool
- type DangerCategory
- type DangerLevel
- type DangerPattern
- type DangerRule
- type DangerThresholdSettings
- type DashboardConfig
- type DashboardStats
- type DashboardStatus
- type DebugCategory
- type DebugConfig
- type DebugEvent
- type DebugLevel
- type DebugMode
- func (dm *DebugMode) Disable()
- func (dm *DebugMode) Enable()
- func (dm *DebugMode) EndSession(status string)
- func (dm *DebugMode) ExportJSON() string
- func (dm *DebugMode) GenerateReport() string
- func (dm *DebugMode) GetErrors() []DebugEvent
- func (dm *DebugMode) GetEvents() []DebugEvent
- func (dm *DebugMode) GetEventsByCategory(category DebugCategory) []DebugEvent
- func (dm *DebugMode) GetEventsByLevel(level DebugLevel) []DebugEvent
- func (dm *DebugMode) GetSession() *DebugSession
- func (dm *DebugMode) GetSlowOperations() []DebugEvent
- func (dm *DebugMode) GetWarnings() []DebugEvent
- func (dm *DebugMode) IsEnabled() bool
- func (dm *DebugMode) Log(level DebugLevel, category DebugCategory, message string, ...)
- func (dm *DebugMode) LogContext(operation string, tokens int, files []string)
- func (dm *DebugMode) LogExecution(stepID, action string, duration time.Duration, err error)
- func (dm *DebugMode) LogPlanning(message string, plan interface{})
- func (dm *DebugMode) LogRetry(iteration int, reason string, willRetry bool)
- func (dm *DebugMode) LogState(from, to string, details map[string]any)
- func (dm *DebugMode) LogVerification(stepID string, passed bool, details map[string]any)
- func (dm *DebugMode) Pause()
- func (dm *DebugMode) Resume()
- func (dm *DebugMode) SetCategories(categories []DebugCategory)
- func (dm *DebugMode) SetLevel(level DebugLevel)
- func (dm *DebugMode) StartSession(task string) *DebugSession
- type DebugModeBuilder
- func (b *DebugModeBuilder) Build() *DebugMode
- func (b *DebugModeBuilder) BuildConfig() DebugConfig
- func (b *DebugModeBuilder) WithCategories(categories ...DebugCategory) *DebugModeBuilder
- func (b *DebugModeBuilder) WithEnabled(enabled bool) *DebugModeBuilder
- func (b *DebugModeBuilder) WithIncludeStack(include bool) *DebugModeBuilder
- func (b *DebugModeBuilder) WithLevel(level DebugLevel) *DebugModeBuilder
- func (b *DebugModeBuilder) WithLogFile(path string) *DebugModeBuilder
- func (b *DebugModeBuilder) WithMaxEvents(max int) *DebugModeBuilder
- func (b *DebugModeBuilder) WithOutputFormat(format string) *DebugModeBuilder
- func (b *DebugModeBuilder) WithPauseOnError(pause bool) *DebugModeBuilder
- func (b *DebugModeBuilder) WithRealTimeOutput(realtime bool) *DebugModeBuilder
- func (b *DebugModeBuilder) WithSlowThreshold(threshold time.Duration) *DebugModeBuilder
- type DebugSession
- type Decision
- type DecisionOption
- type DecisionRequest
- type DecisionResponse
- type DecisionType
- type DependencyGraph
- type EmergencyStopConfig
- type EmergencyStopHandler
- type EmergencyStopManager
- func (m *EmergencyStopManager) AlertChan() <-chan EmergencyStopTrigger
- func (m *EmergencyStopManager) AttemptRecovery(ctx context.Context) error
- func (m *EmergencyStopManager) CheckResourceUsage(memoryMB int64, cpuPercent float64, goroutineCount int)
- func (m *EmergencyStopManager) ClearErrorCount()
- func (m *EmergencyStopManager) GetStatus() map[string]interface{}
- func (m *EmergencyStopManager) GetTrigger() *EmergencyStopTrigger
- func (m *EmergencyStopManager) IsStopped() bool
- func (m *EmergencyStopManager) RecordAction(action string)
- func (m *EmergencyStopManager) RecordError(err error, isCritical bool)
- func (m *EmergencyStopManager) Reset()
- func (m *EmergencyStopManager) SetAuditLogger(logger *AuditLogger)
- func (m *EmergencyStopManager) SetEngine(engine *Engine)
- func (m *EmergencyStopManager) SetNotifyCallback(callback func(trigger EmergencyStopTrigger))
- func (m *EmergencyStopManager) StopChan() <-chan struct{}
- func (m *EmergencyStopManager) Trigger(reason EmergencyStopReason, severity EmergencyStopSeverity, ...) error
- func (m *EmergencyStopManager) TriggerSafetyViolation(violation, details string)
- type EmergencyStopReason
- type EmergencyStopSeverity
- type EmergencyStopTrigger
- type Engine
- type ErrorCategory
- type ExecutionResult
- type FailureAnalysis
- type FailureLearner
- func (fl *FailureLearner) ApplyLearning(rec *FailureRecommendation) bool
- func (fl *FailureLearner) Clear()
- func (fl *FailureLearner) ExportLearnings() (string, error)
- func (fl *FailureLearner) GenerateReport() string
- func (fl *FailureLearner) GetPatterns() []LearnedPattern
- func (fl *FailureLearner) GetRecentLearnings(limit int) []*FailureLearning
- func (fl *FailureLearner) GetRecommendation(errorMsg string) *FailureRecommendation
- func (fl *FailureLearner) GetStats() LearnerStats
- func (fl *FailureLearner) GetUnverifiedLearnings() []*FailureLearning
- func (fl *FailureLearner) RecordFailure(taskType, taskID, errorMsg string, context map[string]any) *FailureLearning
- func (fl *FailureLearner) RecordSolution(learningID, solution string, actions []LearningAction)
- func (fl *FailureLearner) Save() error
- func (fl *FailureLearner) VerifyLearning(learningID string)
- type FailureLearnerBuilder
- func (b *FailureLearnerBuilder) Build() *FailureLearner
- func (b *FailureLearnerBuilder) WithEnabled(enabled bool) *FailureLearnerBuilder
- func (b *FailureLearnerBuilder) WithMaxLearnings(max int) *FailureLearnerBuilder
- func (b *FailureLearnerBuilder) WithSmartRetry(sr *SmartRetry) *FailureLearnerBuilder
- func (b *FailureLearnerBuilder) WithStoragePath(path string) *FailureLearnerBuilder
- type FailureLearnerConfig
- type FailureLearning
- type FailurePattern
- type FailureRecommendation
- type FileOperation
- type FileSystemIsolation
- func (fsi *FileSystemIsolation) AddAllowedPath(path string)
- func (fsi *FileSystemIsolation) AddDeniedPattern(pattern string)
- func (fsi *FileSystemIsolation) AddReadOnlyPath(path string)
- func (fsi *FileSystemIsolation) ClearAuditLog()
- func (fsi *FileSystemIsolation) DeleteFile(ctx context.Context, path string) error
- func (fsi *FileSystemIsolation) GetAuditLog() []FileOperation
- func (fsi *FileSystemIsolation) ListDir(ctx context.Context, path string) ([]string, error)
- func (fsi *FileSystemIsolation) MkDir(ctx context.Context, path string) error
- func (fsi *FileSystemIsolation) ReadFile(ctx context.Context, path string) ([]byte, error)
- func (fsi *FileSystemIsolation) Stat(ctx context.Context, path string) (map[string]interface{}, error)
- func (fsi *FileSystemIsolation) ValidatePath(path string, op string) error
- func (fsi *FileSystemIsolation) WriteFile(ctx context.Context, path string, content []byte) error
- type FixAction
- type FixActionType
- type GoalPriority
- type GoalState
- type GoalStats
- type GoalStatus
- type GoalTracker
- func (gt *GoalTracker) AbandonGoal(goalID string, reason string) error
- func (gt *GoalTracker) AddFailureCondition(goalID string, condition string) error
- func (gt *GoalTracker) AddMilestone(goalID string, name string, description string) (*Milestone, error)
- func (gt *GoalTracker) AddSubGoal(parentID string, subGoal *GoalState) error
- func (gt *GoalTracker) AddSuccessCriterion(goalID string, criterion string) error
- func (gt *GoalTracker) CanStart(goalID string) (bool, error)
- func (gt *GoalTracker) CheckFailureConditions(goalID string, evaluator func(condition string) (bool, error)) (bool, error)
- func (gt *GoalTracker) CheckSuccessCriteria(goalID string, evaluator func(criterion string) (bool, error)) (bool, error)
- func (gt *GoalTracker) CompleteGoal(goalID string) error
- func (gt *GoalTracker) CompleteMilestone(goalID string, milestoneID string) error
- func (gt *GoalTracker) CreateGoal(name string, description string, priority GoalPriority) *GoalState
- func (gt *GoalTracker) FailGoal(goalID string, reason string) error
- func (gt *GoalTracker) GetActiveGoal() *GoalState
- func (gt *GoalTracker) GetAllGoals() []*GoalState
- func (gt *GoalTracker) GetGoal(goalID string) *GoalState
- func (gt *GoalTracker) GetHistory() []*GoalState
- func (gt *GoalTracker) GetInProgressGoals() []*GoalState
- func (gt *GoalTracker) GetPendingGoals() []*GoalState
- func (gt *GoalTracker) GetStats() GoalStats
- func (gt *GoalTracker) RecordCommand(goalID string, command string) error
- func (gt *GoalTracker) RecordError(goalID string, errMsg string) error
- func (gt *GoalTracker) RecordFileModification(goalID string, filePath string) error
- func (gt *GoalTracker) SetActiveGoal(goalID string) error
- func (gt *GoalTracker) SetDependency(goalID string, dependsOnGoalID string) error
- func (gt *GoalTracker) SetProgress(goalID string, progress float64) error
- func (gt *GoalTracker) SetTargetState(goalID string, key string, value any) error
- type GoalTrackerConfig
- type HumanInLoopConfig
- type HumanInLoopManager
- func (m *HumanInLoopManager) AddTrigger(trigger *HumanInLoopTrigger)
- func (m *HumanInLoopManager) EnableTrigger(id string, enabled bool) bool
- func (m *HumanInLoopManager) GetHistory() []*DecisionResponse
- func (m *HumanInLoopManager) GetPendingRequests() []*DecisionRequest
- func (m *HumanInLoopManager) GetStats() map[string]any
- func (m *HumanInLoopManager) GetTriggers() []*HumanInLoopTrigger
- func (m *HumanInLoopManager) RemoveTrigger(id string) bool
- func (m *HumanInLoopManager) RequestDecision(ctx context.Context, request *DecisionRequest) (*DecisionResponse, error)
- func (m *HumanInLoopManager) RespondToDecision(response *DecisionResponse) error
- func (m *HumanInLoopManager) SetConfidenceCheck(fn func(confidence float64, context map[string]any) bool)
- func (m *HumanInLoopManager) ShouldTrigger(decisionType DecisionType, confidence float64, context map[string]any) bool
- type HumanInLoopTrigger
- type InstanceStatus
- type InterruptContext
- func (ic *InterruptContext) GetCheckpoint() *Checkpoint
- func (ic *InterruptContext) Interrupt(reason string)
- func (ic *InterruptContext) IsInterrupted() bool
- func (ic *InterruptContext) Reason() string
- func (ic *InterruptContext) SetCancelFunc(cancel context.CancelFunc)
- func (ic *InterruptContext) SetCheckpoint(cp *Checkpoint)
- type IsolationConfig
- type LearnedPattern
- type LearnerStats
- type LearningAction
- type LimitEnforcer
- func (le *LimitEnforcer) AddCost(cost float64) *LimitViolation
- func (le *LimitEnforcer) AddTokens(count int64) *LimitViolation
- func (le *LimitEnforcer) CanPerform(opType string) bool
- func (le *LimitEnforcer) CheckAll() []*LimitViolation
- func (le *LimitEnforcer) CheckDuration() *LimitViolation
- func (le *LimitEnforcer) CheckIdle() *LimitViolation
- func (le *LimitEnforcer) CheckMemory() *LimitViolation
- func (le *LimitEnforcer) CheckTurnLimit() *LimitViolation
- func (le *LimitEnforcer) Context(parent context.Context) (context.Context, context.CancelFunc)
- func (le *LimitEnforcer) GetLimits() ResourceLimits
- func (le *LimitEnforcer) GetRemaining() ResourceLimits
- func (le *LimitEnforcer) GetUsage() ResourceUsage
- func (le *LimitEnforcer) GetViolation() *LimitViolation
- func (le *LimitEnforcer) IncrementAPICall() *LimitViolation
- func (le *LimitEnforcer) IncrementCommand() *LimitViolation
- func (le *LimitEnforcer) IncrementFileRead() *LimitViolation
- func (le *LimitEnforcer) IncrementFileWrite() *LimitViolation
- func (le *LimitEnforcer) IncrementRetry() *LimitViolation
- func (le *LimitEnforcer) IncrementTurn() *LimitViolation
- func (le *LimitEnforcer) IsViolated() bool
- func (le *LimitEnforcer) PercentUsed() map[string]float64
- func (le *LimitEnforcer) Reset()
- func (le *LimitEnforcer) SetLimits(limits ResourceLimits)
- func (le *LimitEnforcer) SetLogger(logger interface{ ... })
- func (le *LimitEnforcer) SetOnViolation(callback func(*LimitViolation))
- func (le *LimitEnforcer) SetOnWarning(callback func(string))
- func (le *LimitEnforcer) Summary() string
- func (le *LimitEnforcer) TurnContext(parent context.Context) (context.Context, context.CancelFunc)
- func (le *LimitEnforcer) UpdateActivity()
- type LimitViolation
- type Milestone
- type NetworkIsolation
- func (ni *NetworkIsolation) AddPortMapping(mapping PortMapping)
- func (ni *NetworkIsolation) BuildDockerArgs() []string
- func (ni *NetworkIsolation) CreateInternalNetwork(ctx context.Context, name string) error
- func (ni *NetworkIsolation) GetMode() NetworkMode
- func (ni *NetworkIsolation) GetNetworkStats(ctx context.Context, containerID string) (map[string]interface{}, error)
- func (ni *NetworkIsolation) GetPolicy() NetworkPolicy
- func (ni *NetworkIsolation) GetPortMappings() []PortMapping
- func (ni *NetworkIsolation) RemoveNetwork(ctx context.Context) error
- func (ni *NetworkIsolation) RemovePortMapping(hostPort int)
- func (ni *NetworkIsolation) SetDNSConfig(config *DNSConfig)
- func (ni *NetworkIsolation) SetMode(mode NetworkMode)
- func (ni *NetworkIsolation) SetPolicy(policy NetworkPolicy)
- func (ni *NetworkIsolation) TestConnectivity(ctx context.Context, sandbox *Sandbox, host string, port int) (bool, error)
- func (ni *NetworkIsolation) ValidateConnection(host string, port int) error
- type NetworkIsolationBuilder
- func (b *NetworkIsolationBuilder) Build() *NetworkIsolation
- func (b *NetworkIsolationBuilder) BuildConfig() NetworkIsolationConfig
- func (b *NetworkIsolationBuilder) WithCustomNetwork(network string) *NetworkIsolationBuilder
- func (b *NetworkIsolationBuilder) WithDNS(servers []string) *NetworkIsolationBuilder
- func (b *NetworkIsolationBuilder) WithMode(mode NetworkMode) *NetworkIsolationBuilder
- func (b *NetworkIsolationBuilder) WithPolicy(policy NetworkPolicy) *NetworkIsolationBuilder
- func (b *NetworkIsolationBuilder) WithPortMapping(hostPort, containerPort int, protocol string) *NetworkIsolationBuilder
- func (b *NetworkIsolationBuilder) WithProfile(profileName string) *NetworkIsolationBuilder
- type NetworkIsolationConfig
- type NetworkMode
- type NetworkPolicy
- type NetworkProfile
- type NetworkSafetySettings
- type NodeStatus
- type OperationType
- type PatternStats
- type PermissionError
- type Plan
- type PlanNode
- type PlanStats
- type PlanStatus
- type PlanStep
- type Planner
- func (p *Planner) AddStep(step PlanStep, dependencies []int) (int, error)
- func (p *Planner) BuildPlanFromSteps(steps []PlanStep) error
- func (p *Planner) ExecutePlan(ctx context.Context, executor func(step PlanStep) error) error
- func (p *Planner) GetExecutionOrder() ([]int, error)
- func (p *Planner) GetParallelGroups() ([][]int, error)
- func (p *Planner) GetReadySteps() []*PlanNode
- func (p *Planner) GetStats() PlanStats
- func (p *Planner) GetStatus() PlanStatus
- func (p *Planner) MarkStepStatus(stepID int, status NodeStatus) error
- type Playbook
- type PlaybookBuilder
- func (b *PlaybookBuilder) AddStep(stepType, action, target string, required bool) *PlaybookBuilder
- func (b *PlaybookBuilder) AddSuccessCriteria(criteria string) *PlaybookBuilder
- func (b *PlaybookBuilder) AddTag(tag string) *PlaybookBuilder
- func (b *PlaybookBuilder) AddTriggerKeywords(keywords ...string) *PlaybookBuilder
- func (b *PlaybookBuilder) AddTriggerPatterns(patterns ...string) *PlaybookBuilder
- func (b *PlaybookBuilder) AddVariable(key, value string) *PlaybookBuilder
- func (b *PlaybookBuilder) Build() *Playbook
- func (b *PlaybookBuilder) SetEnabled(enabled bool) *PlaybookBuilder
- func (b *PlaybookBuilder) SetTriggerPriority(priority int) *PlaybookBuilder
- func (b *PlaybookBuilder) WithAuthor(author string) *PlaybookBuilder
- func (b *PlaybookBuilder) WithDescription(desc string) *PlaybookBuilder
- func (b *PlaybookBuilder) WithVersion(version string) *PlaybookBuilder
- type PlaybookInstance
- func (pi *PlaybookInstance) AdvanceStep() bool
- func (pi *PlaybookInstance) GetCurrentStep() *ResolvedStep
- func (pi *PlaybookInstance) GetProgress() float64
- func (pi *PlaybookInstance) GetSummary() string
- func (pi *PlaybookInstance) IsComplete() bool
- func (pi *PlaybookInstance) IsFailed() bool
- func (pi *PlaybookInstance) MarkStepCompleted(output string)
- func (pi *PlaybookInstance) MarkStepFailed(err error)
- func (pi *PlaybookInstance) MarkStepSkipped(reason string)
- func (pi *PlaybookInstance) Start()
- type PlaybookRegistry
- func (r *PlaybookRegistry) Disable(id string) error
- func (r *PlaybookRegistry) Enable(id string) error
- func (r *PlaybookRegistry) Get(id string) (*Playbook, error)
- func (r *PlaybookRegistry) GetByType(playbookType PlaybookType) []*Playbook
- func (r *PlaybookRegistry) GetStats() map[string]any
- func (r *PlaybookRegistry) InstantiatePlaybook(ctx context.Context, playbookID string, variables map[string]string) (*PlaybookInstance, error)
- func (r *PlaybookRegistry) List() []*Playbook
- func (r *PlaybookRegistry) ListEnabled() []*Playbook
- func (r *PlaybookRegistry) Match(taskDescription string) *Playbook
- func (r *PlaybookRegistry) MatchAll(taskDescription string) []*Playbook
- func (r *PlaybookRegistry) Register(playbook *Playbook) error
- func (r *PlaybookRegistry) SetLogger(logger interface{ ... })
- func (r *PlaybookRegistry) Unregister(id string)
- type PlaybookStep
- type PlaybookStepStatus
- type PlaybookTrigger
- type PlaybookType
- type PortMapping
- type ProfileCustomization
- func WithApprovalMode(mode ApprovalMode) ProfileCustomization
- func WithAutoSnapshot(enabled bool, minDangerLevel DangerLevel) ProfileCustomization
- func WithDangerThreshold(approvalRequired, confirmationRequired DangerLevel) ProfileCustomization
- func WithNetworkEnabled(enabled bool) ProfileCustomization
- func WithProtectionEnabled(enabled bool) ProfileCustomization
- type ProgressDashboard
- func (d *ProgressDashboard) AddStep(id, name, description string) *ProgressStep
- func (d *ProgressDashboard) AddSubStep(parentID, id, name string) *ProgressStep
- func (d *ProgressDashboard) Cancel()
- func (d *ProgressDashboard) Complete()
- func (d *ProgressDashboard) CompleteStep(id string)
- func (d *ProgressDashboard) ExportJSON() string
- func (d *ProgressDashboard) Fail(errMsg string)
- func (d *ProgressDashboard) FailStep(id, errMsg string)
- func (d *ProgressDashboard) GetStats() DashboardStats
- func (d *ProgressDashboard) IncrementRetries()
- func (d *ProgressDashboard) Render()
- func (d *ProgressDashboard) RetryStep(id string)
- func (d *ProgressDashboard) SetCost(cost float64)
- func (d *ProgressDashboard) SetProgress(progress float64)
- func (d *ProgressDashboard) SetStatus(status DashboardStatus)
- func (d *ProgressDashboard) SetTokens(tokens int64)
- func (d *ProgressDashboard) SkipStep(id string)
- func (d *ProgressDashboard) Start()
- func (d *ProgressDashboard) StartStep(id string)
- func (d *ProgressDashboard) Stop()
- func (d *ProgressDashboard) UpdateStepProgress(id string, progress float64)
- type ProgressStep
- type ProtectedPath
- type ProtectedPathAccess
- type ProtectedPathAction
- type ProtectedPathConfig
- type ProtectedPathType
- type ProtectedPathsBuilder
- func (b *ProtectedPathsBuilder) AddExactPath(path string, action ProtectedPathAction, description string) *ProtectedPathsBuilder
- func (b *ProtectedPathsBuilder) AddGlobPath(pattern string, action ProtectedPathAction, description string) *ProtectedPathsBuilder
- func (b *ProtectedPathsBuilder) AddPrefixPath(prefix string, action ProtectedPathAction, description string) *ProtectedPathsBuilder
- func (b *ProtectedPathsBuilder) AddRegexPath(pattern string, action ProtectedPathAction, description string) *ProtectedPathsBuilder
- func (b *ProtectedPathsBuilder) Build() *ProtectedPathsManager
- func (b *ProtectedPathsBuilder) BuildConfig() ProtectedPathConfig
- func (b *ProtectedPathsBuilder) WithAuditEnabled(enabled bool) *ProtectedPathsBuilder
- func (b *ProtectedPathsBuilder) WithDefaultAction(action ProtectedPathAction) *ProtectedPathsBuilder
- func (b *ProtectedPathsBuilder) WithPriority(priority int) *ProtectedPathsBuilder
- type ProtectedPathsManager
- func (ppm *ProtectedPathsManager) AddProtectedPath(rule ProtectedPath)
- func (ppm *ProtectedPathsManager) CheckPath(path, operation string) (ProtectedPathAction, *ProtectedPath)
- func (ppm *ProtectedPathsManager) ClearAuditLog()
- func (ppm *ProtectedPathsManager) ExportConfig() ([]byte, error)
- func (ppm *ProtectedPathsManager) GetAuditLog() []ProtectedPathAccess
- func (ppm *ProtectedPathsManager) GetProtectedPaths() []ProtectedPath
- func (ppm *ProtectedPathsManager) GetStats() map[string]interface{}
- func (ppm *ProtectedPathsManager) ImportConfig(data []byte) error
- func (ppm *ProtectedPathsManager) IsAccessAllowed(path, operation string) bool
- func (ppm *ProtectedPathsManager) LoadConfigFromFile(path string) error
- func (ppm *ProtectedPathsManager) RemoveProtectedPath(path string) bool
- func (ppm *ProtectedPathsManager) SaveConfigToFile(path string) error
- func (ppm *ProtectedPathsManager) ShouldWarn(path, operation string) bool
- func (ppm *ProtectedPathsManager) UpdateProtectedPath(path string, updates ProtectedPath) bool
- func (ppm *ProtectedPathsManager) ValidatePath(path, operation string) error
- type ProtectionSettings
- type QueueStats
- type QueuedTask
- type ResolvedStep
- type ResourceLimits
- type ResourceSafetySettings
- type ResourceUsage
- type RestoreConfig
- type RestoreOption
- type RestrictedCommand
- type RestrictedCommandsConfig
- type RestrictedCommandsManager
- func (mgr *RestrictedCommandsManager) AddCommand(cmd RestrictedCommand) error
- func (mgr *RestrictedCommandsManager) CheckCommand(command string) *RestrictionResult
- func (mgr *RestrictedCommandsManager) DisableCommand(id string) error
- func (mgr *RestrictedCommandsManager) EnableCommand(id string) error
- func (mgr *RestrictedCommandsManager) Export() ([]byte, error)
- func (mgr *RestrictedCommandsManager) GetCommand(id string) (*RestrictedCommand, bool)
- func (mgr *RestrictedCommandsManager) GetStats() RestrictionStats
- func (mgr *RestrictedCommandsManager) Import(data []byte) error
- func (mgr *RestrictedCommandsManager) ListByCategory(category CommandCategory) []*RestrictedCommand
- func (mgr *RestrictedCommandsManager) ListByRestriction(level RestrictionLevel) []*RestrictedCommand
- func (mgr *RestrictedCommandsManager) ListCommands() []*RestrictedCommand
- func (mgr *RestrictedCommandsManager) RemoveCommand(id string) error
- func (mgr *RestrictedCommandsManager) Reset()
- func (mgr *RestrictedCommandsManager) SetAuditLogger(logger *AuditLogger)
- func (mgr *RestrictedCommandsManager) SetGlobalRestriction(level RestrictionLevel)
- func (mgr *RestrictedCommandsManager) SetRestrictionLevel(id string, level RestrictionLevel) error
- func (mgr *RestrictedCommandsManager) UpdateCommand(cmd RestrictedCommand) error
- type RestrictionLevel
- type RestrictionResult
- type RestrictionStats
- type Result
- type ResumableEngine
- type RetryAttempt
- type RetryConfig
- type RetryHistory
- type RetryPattern
- type RetryResult
- type RetryStats
- type RetryStrategy
- type ReviewCheckpoint
- func (rc *ReviewCheckpoint) AddHook(hook ReviewHook)
- func (rc *ReviewCheckpoint) Approve(requestID string, reason string) error
- func (rc *ReviewCheckpoint) GetPendingReviews() []*ReviewRequest
- func (rc *ReviewCheckpoint) Reject(requestID string, reason string) error
- func (rc *ReviewCheckpoint) RequestReview(ctx context.Context, op OperationType, target string, description string, ...) (*ReviewRequest, error)
- func (rc *ReviewCheckpoint) SubmitResponse(requestID string, decision ReviewDecision, reason string, respondedBy string) (*ReviewResponse, error)
- func (rc *ReviewCheckpoint) WaitForReview(ctx context.Context, requestID string) (*ReviewResponse, error)
- type ReviewDecision
- type ReviewHook
- type ReviewPolicy
- type ReviewRequest
- type ReviewResponse
- type RiskLevel
- type RollbackConfig
- type RollbackEntry
- type RollbackOp
- type RollbackSnapshot
- type RollbackStack
- func (rs *RollbackStack) CanRollback() bool
- func (rs *RollbackStack) Clear()
- func (rs *RollbackStack) CreateSnapshot(name string) (*RollbackSnapshot, error)
- func (rs *RollbackStack) GetEntries() []*RollbackEntry
- func (rs *RollbackStack) GetEntry(id string) *RollbackEntry
- func (rs *RollbackStack) GetLastOfType(rollbackType RollbackType) *RollbackEntry
- func (rs *RollbackStack) Peek() *RollbackEntry
- func (rs *RollbackStack) Pop() *RollbackEntry
- func (rs *RollbackStack) PushFileCreate(path string, content string) *RollbackEntry
- func (rs *RollbackStack) PushFileDelete(path string, content string) *RollbackEntry
- func (rs *RollbackStack) PushFileEdit(path string, originalContent string) *RollbackEntry
- func (rs *RollbackStack) PushGitCommit(commitHash string) *RollbackEntry
- func (rs *RollbackStack) Rollback() error
- func (rs *RollbackStack) RollbackAll() error
- func (rs *RollbackStack) RollbackTo(entryID string) error
- func (rs *RollbackStack) Size() int
- type RollbackType
- type SafetyMode
- type SafetyProfile
- type SafetyProfileManager
- func (mgr *SafetyProfileManager) AddCustomRule(rule CustomSafetyRule) error
- func (mgr *SafetyProfileManager) CreateCustomProfile(base SafetyProfileName, customizations ...ProfileCustomization) (*SafetyProfile, error)
- func (mgr *SafetyProfileManager) EvaluateCustomRules(operation string) (string, *DangerLevel, string)
- func (mgr *SafetyProfileManager) ExportProfile(name SafetyProfileName) ([]byte, error)
- func (mgr *SafetyProfileManager) GetActiveProfile() *SafetyProfile
- func (mgr *SafetyProfileManager) GetActiveProfileName() SafetyProfileName
- func (mgr *SafetyProfileManager) GetProfile(name SafetyProfileName) (*SafetyProfile, bool)
- func (mgr *SafetyProfileManager) ImportProfile(data []byte) error
- func (mgr *SafetyProfileManager) IsNetworkAllowed(host string, port int) (bool, string)
- func (mgr *SafetyProfileManager) IsPathProtected(path string) (bool, string)
- func (mgr *SafetyProfileManager) ListProfiles() []SafetyProfileName
- func (mgr *SafetyProfileManager) RemoveCustomRule(ruleID string) error
- func (mgr *SafetyProfileManager) ResetProfile(name SafetyProfileName) error
- func (mgr *SafetyProfileManager) SetActiveProfile(name SafetyProfileName) error
- func (mgr *SafetyProfileManager) ShouldApprove(dangerLevel DangerLevel) bool
- func (mgr *SafetyProfileManager) ShouldConfirm(dangerLevel DangerLevel) bool
- func (mgr *SafetyProfileManager) ShouldSnapshot(dangerLevel DangerLevel, operation string) bool
- func (mgr *SafetyProfileManager) UpdateProfile(name SafetyProfileName, customizations ...ProfileCustomization) error
- type SafetyProfileName
- type Sandbox
- func (s *Sandbox) AddVolumeMount(hostPath, containerPath string, readOnly bool)
- func (s *Sandbox) CopyFrom(ctx context.Context, containerPath, hostPath string) error
- func (s *Sandbox) CopyTo(ctx context.Context, hostPath, containerPath string) error
- func (s *Sandbox) Execute(ctx context.Context, command string, args ...string) *SandboxResult
- func (s *Sandbox) ExecuteWithOutput(ctx context.Context, command string, args ...string) *SandboxResult
- func (s *Sandbox) GetContainerID() string
- func (s *Sandbox) GetContainerStats(ctx context.Context) (map[string]any, error)
- func (s *Sandbox) IsRunning() bool
- func (s *Sandbox) SetEnvVar(key, value string)
- func (s *Sandbox) Start(ctx context.Context) error
- func (s *Sandbox) Stop(ctx context.Context) error
- type SandboxBuilder
- func (b *SandboxBuilder) Build() *Sandbox
- func (b *SandboxBuilder) BuildConfig() SandboxConfig
- func (b *SandboxBuilder) WithCPUShares(shares int64) *SandboxBuilder
- func (b *SandboxBuilder) WithCleanupOnExit(cleanup bool) *SandboxBuilder
- func (b *SandboxBuilder) WithEnvVar(key, value string) *SandboxBuilder
- func (b *SandboxBuilder) WithImage(image string) *SandboxBuilder
- func (b *SandboxBuilder) WithMemoryLimit(mb int64) *SandboxBuilder
- func (b *SandboxBuilder) WithNetwork(enabled bool) *SandboxBuilder
- func (b *SandboxBuilder) WithOutputCallback(callback func(string)) *SandboxBuilder
- func (b *SandboxBuilder) WithPullImage(pull bool) *SandboxBuilder
- func (b *SandboxBuilder) WithTimeout(timeout time.Duration) *SandboxBuilder
- func (b *SandboxBuilder) WithVolumeMount(hostPath, containerPath string, readOnly bool) *SandboxBuilder
- func (b *SandboxBuilder) WithWorkDir(dir string) *SandboxBuilder
- type SandboxConfig
- type SandboxLimits
- type SandboxLimitsConfig
- type SandboxLimitsManager
- func (mgr *SandboxLimitsManager) AddCustomProfile(profile SandboxLimits) error
- func (mgr *SandboxLimitsManager) AssignLimits(containerID string, limits *SandboxLimits)
- func (mgr *SandboxLimitsManager) AssignProfile(containerID string, profile SandboxLimitsProfile) error
- func (mgr *SandboxLimitsManager) CheckViolation(containerID string, usage *ContainerUsage) *ContainerViolation
- func (mgr *SandboxLimitsManager) CreateLimitsFromProfile(profile SandboxLimitsProfile, overrides map[string]interface{}) *SandboxLimits
- func (mgr *SandboxLimitsManager) Export() ([]byte, error)
- func (mgr *SandboxLimitsManager) GetCustomProfile(id string) *SandboxLimits
- func (mgr *SandboxLimitsManager) GetDefaultLimits() *SandboxLimits
- func (mgr *SandboxLimitsManager) GetLimits(containerID string) *SandboxLimits
- func (mgr *SandboxLimitsManager) GetProfile(profile SandboxLimitsProfile) *SandboxLimits
- func (mgr *SandboxLimitsManager) GetStats() SandboxResourceStats
- func (mgr *SandboxLimitsManager) GetUsageHistory(containerID string) []ContainerUsage
- func (mgr *SandboxLimitsManager) GetViolations() []ContainerViolation
- func (mgr *SandboxLimitsManager) ListProfiles() []*SandboxLimits
- func (mgr *SandboxLimitsManager) RecordUsage(containerID string, usage *ContainerUsage)
- func (mgr *SandboxLimitsManager) RemoveContainer(containerID string)
- func (mgr *SandboxLimitsManager) RemoveCustomProfile(id string) error
- func (mgr *SandboxLimitsManager) Reset()
- type SandboxLimitsProfile
- type SandboxResourceLimits
- type SandboxResourceStats
- type SandboxResult
- type SandboxTemplate
- type SessionState
- type SessionStatus
- type SmartRetry
- func (sr *SmartRetry) AddPattern(pattern *RetryPattern)
- func (sr *SmartRetry) AnalyzeFailure(errorMsg string) *FailureAnalysis
- func (sr *SmartRetry) ExecuteWithRetry(ctx context.Context, taskID string, fn func() error) *RetryResult
- func (sr *SmartRetry) GetBestFixHint(errorMsg string) string
- func (sr *SmartRetry) GetHistory() []RetryAttempt
- func (sr *SmartRetry) GetPatternStats(patternID string) *PatternStats
- func (sr *SmartRetry) GetStats() RetryStats
- func (sr *SmartRetry) LearnFromHistory()
- func (sr *SmartRetry) Reset()
- func (sr *SmartRetry) SetLogger(logger interface{ ... })
- type SnapshotConfig
- type SnapshotFile
- type SnapshotManager
- func (sm *SnapshotManager) AutoSnapshot(operation, path string, paths []string) (*SnapshotMetadata, error)
- func (sm *SnapshotManager) CreateSnapshot(name string, snapshotType SnapshotType, paths []string, opts ...SnapshotOption) (*SnapshotMetadata, error)
- func (sm *SnapshotManager) DeleteSnapshot(snapshotID string) error
- func (sm *SnapshotManager) ExpireSnapshots() int
- func (sm *SnapshotManager) ExportMetadata(snapshotID string) ([]byte, error)
- func (sm *SnapshotManager) GetSnapshot(snapshotID string) (*SnapshotMetadata, bool)
- func (sm *SnapshotManager) GetSnapshotsByType(snapshotType SnapshotType) []*SnapshotMetadata
- func (sm *SnapshotManager) GetStats() SnapshotStats
- func (sm *SnapshotManager) ListSnapshots() []*SnapshotMetadata
- func (sm *SnapshotManager) RestoreSnapshot(snapshotID string, opts ...RestoreOption) error
- func (sm *SnapshotManager) SetAuditLogger(logger *AuditLogger)
- func (sm *SnapshotManager) VerifyAndRepair(snapshotID string) (*VerifyResult, error)
- func (sm *SnapshotManager) VerifyRestore(snapshotID string) (*VerifyResult, error)
- func (sm *SnapshotManager) VerifySnapshotIntegrity(snapshotID string) error
- type SnapshotMetadata
- type SnapshotOption
- type SnapshotSafetySettings
- type SnapshotStats
- type SnapshotStatus
- type SnapshotType
- type StateManager
- func (sm *StateManager) CreateCheckpoint(phase string, iteration int, task string, plan *Plan, ...) (*Checkpoint, error)
- func (sm *StateManager) DeleteSession(sessionID string) error
- func (sm *StateManager) GetLatestCheckpoint() *Checkpoint
- func (sm *StateManager) ListSessions() ([]SessionState, error)
- func (sm *StateManager) RestoreFromCheckpoint(checkpointID string) (*Checkpoint, error)
- func (sm *StateManager) ResumeSession(sessionID string) (*SessionState, error)
- func (sm *StateManager) SaveSession(task string, status SessionStatus, phase string, iteration int, ...) error
- type Status
- type StepStatus
- type SuccessCriteriaConfig
- type SuccessCriteriaValidator
- func (v *SuccessCriteriaValidator) GetStats() map[string]any
- func (v *SuccessCriteriaValidator) QuickValidate(ctx context.Context, criterion *SuccessCriterion) (*ValidationResult, error)
- func (v *SuccessCriteriaValidator) RegisterChecker(criterionType CriterionType, checker CriterionChecker)
- func (v *SuccessCriteriaValidator) SetLogger(logger interface{ ... })
- func (v *SuccessCriteriaValidator) Validate(ctx context.Context, criteria []*SuccessCriterion) *ValidationReport
- type SuccessCriterion
- type TaskExecutor
- type TaskPriority
- type TaskQueue
- func (tq *TaskQueue) AddTask(name string, description string, priority TaskPriority, dependencies []string) *QueuedTask
- func (tq *TaskQueue) Cancel(taskID string) error
- func (tq *TaskQueue) CancelAll()
- func (tq *TaskQueue) GetCompleted() []*QueuedTask
- func (tq *TaskQueue) GetPending() []*QueuedTask
- func (tq *TaskQueue) GetRunning() []*QueuedTask
- func (tq *TaskQueue) GetStats() QueueStats
- func (tq *TaskQueue) GetTask(id string) *QueuedTask
- func (tq *TaskQueue) SetTaskMetadata(taskID string, key string, value any) error
- func (tq *TaskQueue) Start(ctx context.Context)
- func (tq *TaskQueue) Stop()
- func (tq *TaskQueue) WaitForCompletion(ctx context.Context) error
- func (tq *TaskQueue) WaitForTask(ctx context.Context, taskID string) (*QueuedTask, error)
- type TaskQueueConfig
- type TaskStatus
- type TestFailure
- type TestResult
- type TestRunner
- func (tr *TestRunner) DetectFlakyTests(ctx context.Context, iterations int) ([]string, error)
- func (tr *TestRunner) RunBenchmarks(ctx context.Context) (*TestResult, error)
- func (tr *TestRunner) RunSpecificTests(ctx context.Context, testNames []string) (*TestResult, error)
- func (tr *TestRunner) RunTestsWithAnalysis(ctx context.Context) (*TestResult, error)
- func (tr *TestRunner) RunTestsWithAutoFix(ctx context.Context) (*TestResult, error)
- type TestSummary
- type TimeRestriction
- type TriggerAction
- type TriggerCondition
- type UrgencyLevel
- type ValidationReport
- type ValidationResult
- type VerificationResult
- type VerifyResult
- type VolumeMount
Constants ¶
This section is empty.
Variables ¶
var NetworkProfiles = map[string]NetworkProfile{ "strict": { Name: "strict", Description: "No network access - maximum security", Mode: NetworkModeNone, Policy: StrictNetworkPolicy(), }, "secure": { Name: "secure", Description: "HTTPS only with DNS", Mode: NetworkModeBridge, Policy: DefaultNetworkPolicy(), }, "development": { Name: "development", Description: "Permissive for development", Mode: NetworkModeBridge, Policy: DevelopmentNetworkPolicy(), }, "isolated": { Name: "isolated", Description: "Internal network only", Mode: NetworkModeInternal, Policy: StrictNetworkPolicy(), }, "full": { Name: "full", Description: "Full network access", Mode: NetworkModeHost, Policy: PermissiveNetworkPolicy(), }, }
Predefined network profiles
Functions ¶
func ApplyNetworkProfile ¶
func ApplyNetworkProfile(config *SandboxConfig, profileName string) error
ApplyNetworkProfile applies a predefined profile to the sandbox config.
func CheckDockerAvailable ¶
func CheckDockerAvailable() bool
CheckDockerAvailable checks if Docker is available on the system.
func CompareProfiles ¶
func CompareProfiles(p1, p2 *SafetyProfile) map[string]interface{}
CompareProfiles compares two profiles and returns the differences.
func DefaultStrategies ¶
func DefaultStrategies() map[string]RetryStrategy
DefaultStrategies returns built-in retry strategies.
func DetectSandboxTemplate ¶
DetectSandboxTemplate attempts to detect the appropriate sandbox template based on files present in the repository.
func IsCommandSafe ¶
IsCommandSafe returns true if a command is safe to execute automatically.
func ListImages ¶
ListImages lists available Docker images.
func ListNetworkProfiles ¶
func ListNetworkProfiles() []string
ListNetworkProfiles lists all available network profiles.
func NeedsApproval ¶
NeedsApproval returns true if a command needs approval before execution.
func SandboxTemplateNames ¶
func SandboxTemplateNames() []string
SandboxTemplateNames returns the names of all available templates.
func ValidateSandboxLimits ¶
func ValidateSandboxLimits(limits *SandboxLimits) error
ValidateSandboxLimits validates resource limits for consistency.
Types ¶
type ActionContext ¶
type ActionContext struct {
FileExists bool
HasTests bool
IsGitRepo bool
HasUncommittedChanges bool
DependencyCount int
RecentFailures int
RecentSuccesses int
TokensUsed int
MaxTokens int
PreviousActions []string
TargetFiles []string
}
ActionContext provides context for confidence assessment.
type ApprovalCallback ¶
type ApprovalCallback func(request *ApprovalRequest) (*ApprovalDecision, error)
ApprovalCallback is called when a decision is needed.
type ApprovalDecision ¶
type ApprovalDecision struct {
// RequestID is the request being decided
RequestID string `json:"request_id"`
// Approved indicates if the request is approved
Approved bool `json:"approved"`
// Reason for the decision
Reason string `json:"reason,omitempty"`
// ApprovedBy is who made the decision
ApprovedBy string `json:"approved_by,omitempty"`
// Timestamp of the decision
Timestamp time.Time `json:"timestamp"`
}
ApprovalDecision represents a decision on an approval request.
type ApprovalMode ¶
type ApprovalMode string
ApprovalMode determines how approvals are handled.
const ( // ApprovalModeStrict - All operations require approval ApprovalModeStrict ApprovalMode = "strict" // ApprovalModeBalanced - Only risky operations require approval (default) ApprovalModeBalanced ApprovalMode = "balanced" // ApprovalModePermissive - Only critical operations require approval ApprovalModePermissive ApprovalMode = "permissive" // ApprovalModeAuto - Auto-approve everything (dangerous!) ApprovalModeAuto ApprovalMode = "auto" )
type ApprovalPolicy ¶
type ApprovalPolicy struct {
// Mode is the approval mode
Mode ApprovalMode `json:"mode"`
// AutoApproveSafe auto-approves safe operations
AutoApproveSafe bool `json:"auto_approve_safe"`
// AutoApproveLow auto-approves low-risk operations
AutoApproveLow bool `json:"auto_approve_low"`
// RequireApprovalMedium requires approval for medium risk
RequireApprovalMedium bool `json:"require_approval_medium"`
// RequireApprovalHigh requires approval for high risk
RequireApprovalHigh bool `json:"require_approval_high"`
// RequireApprovalCritical requires approval for critical risk
RequireApprovalCritical bool `json:"require_approval_critical"`
// Timeout is the default approval timeout
Timeout time.Duration `json:"timeout"`
// MaxPendingRequests is the maximum pending requests allowed
MaxPendingRequests int `json:"max_pending_requests"`
// AllowedApprovers is a list of who can approve (empty = anyone)
AllowedApprovers []string `json:"allowed_approvers,omitempty"`
// Blocklist are commands that always require approval
Blocklist []string `json:"blocklist,omitempty"`
// Allowlist are commands that can be auto-approved
Allowlist []string `json:"allowlist,omitempty"`
}
ApprovalPolicy defines rules for automatic approval decisions.
func DefaultApprovalPolicy ¶
func DefaultApprovalPolicy() ApprovalPolicy
DefaultApprovalPolicy returns the default approval policy.
type ApprovalProfileSettings ¶
type ApprovalProfileSettings struct {
// Mode is the approval mode
Mode ApprovalMode `json:"mode"`
// AutoApproveSafe automatically approves safe operations
AutoApproveSafe bool `json:"auto_approve_safe"`
// AutoApproveLow automatically approves low-risk operations
AutoApproveLow bool `json:"auto_approve_low"`
// RequireReason requires a reason for approval
RequireReason bool `json:"require_reason"`
// Timeout is how long to wait for approval
Timeout time.Duration `json:"timeout"`
// MaxPendingRequests is the maximum pending approvals
MaxPendingRequests int `json:"max_pending_requests"`
// NotifyOnRequest sends notification on approval request
NotifyOnRequest bool `json:"notify_on_request"`
}
ApprovalProfileSettings controls approval behavior.
type ApprovalRequest ¶
type ApprovalRequest struct {
// ID is the unique request identifier
ID string `json:"id"`
// Command is the command to be executed
Command string `json:"command"`
// Args are the command arguments
Args []string `json:"args,omitempty"`
// WorkingDir is the working directory
WorkingDir string `json:"working_dir,omitempty"`
// Assessment is the danger assessment
Assessment *DangerAssessment `json:"assessment"`
// Status is the current approval status
Status ApprovalStatus `json:"status"`
// CreatedAt is when the request was created
CreatedAt time.Time `json:"created_at"`
// ExpiresAt is when the request expires
ExpiresAt time.Time `json:"expires_at"`
// DecidedAt is when a decision was made
DecidedAt *time.Time `json:"decided_at,omitempty"`
// ApprovedBy is who approved (if applicable)
ApprovedBy string `json:"approved_by,omitempty"`
// DenialReason is why it was denied (if applicable)
DenialReason string `json:"denial_reason,omitempty"`
// Metadata contains additional context
Metadata map[string]interface{} `json:"metadata,omitempty"`
// Checksum for request integrity
Checksum string `json:"checksum"`
}
ApprovalRequest represents a request for operation approval.
type ApprovalStats ¶
type ApprovalStats struct {
TotalRequests int `json:"total_requests"`
PendingRequests int `json:"pending_requests"`
ApprovedRequests int `json:"approved_requests"`
DeniedRequests int `json:"denied_requests"`
ExpiredRequests int `json:"expired_requests"`
AutoApproved int `json:"auto_approved"`
AverageWaitTime time.Duration `json:"average_wait_time"`
ApprovalRate float64 `json:"approval_rate"`
ByDangerLevel map[string]int `json:"by_danger_level"`
LastRequestTime *time.Time `json:"last_request_time,omitempty"`
}
ApprovalStats tracks approval workflow statistics.
type ApprovalStatus ¶
type ApprovalStatus string
ApprovalStatus represents the status of an approval request.
const ( // ApprovalStatusPending - Request is awaiting approval ApprovalStatusPending ApprovalStatus = "pending" // ApprovalStatusApproved - Request has been approved ApprovalStatusApproved ApprovalStatus = "approved" // ApprovalStatusDenied - Request has been denied ApprovalStatusDenied ApprovalStatus = "denied" // ApprovalStatusExpired - Request has expired without decision ApprovalStatusExpired ApprovalStatus = "expired" // ApprovalStatusCancelled - Request was cancelled ApprovalStatusCancelled ApprovalStatus = "cancelled" // ApprovalStatusAutoApproved - Request was auto-approved (safe operation) ApprovalStatusAutoApproved ApprovalStatus = "auto_approved" )
type AuditConfig ¶
type AuditConfig struct {
// Enabled turns audit logging on/off
Enabled bool `json:"enabled"`
// MaxEvents is the maximum events to keep in memory
MaxEvents int `json:"max_events"`
// PersistToFile saves audit logs to disk
PersistToFile bool `json:"persist_to_file"`
// LogPath is the directory for audit log files
LogPath string `json:"log_path"`
// RotateSize is the max size before rotating (bytes)
RotateSize int64 `json:"rotate_size"`
// IncludeMetadata includes full metadata in logs
IncludeMetadata bool `json:"include_metadata"`
// SeverityFilter only logs events at or above this severity
SeverityFilter AuditSeverity `json:"severity_filter"`
// EventTypes filters which event types to log (empty = all)
EventTypes []AuditEventType `json:"event_types,omitempty"`
}
AuditConfig configures the audit log behavior.
func DefaultAuditConfig ¶
func DefaultAuditConfig() AuditConfig
DefaultAuditConfig returns the default audit configuration.
type AuditEvent ¶
type AuditEvent struct {
// ID is the unique event identifier
ID string `json:"id"`
// Timestamp is when the event occurred
Timestamp time.Time `json:"timestamp"`
// Type is the event type
Type AuditEventType `json:"type"`
// Severity is the event severity
Severity AuditSeverity `json:"severity"`
// Message is a human-readable description
Message string `json:"message"`
// SessionID is the session this event belongs to
SessionID string `json:"session_id,omitempty"`
// StepID is the step this event relates to
StepID string `json:"step_id,omitempty"`
// Operation is the specific operation performed
Operation string `json:"operation,omitempty"`
// Target is what was operated on (file path, command, etc.)
Target string `json:"target,omitempty"`
// Actor is who/what initiated the operation
Actor string `json:"actor,omitempty"`
// Result is the outcome (success/failure)
Result string `json:"result,omitempty"`
// Error contains error details if applicable
Error string `json:"error,omitempty"`
// DangerLevel is the assessed danger level (if applicable)
DangerLevel string `json:"danger_level,omitempty"`
// Approved indicates if this was approved
Approved *bool `json:"approved,omitempty"`
// ApprovalID references the approval request
ApprovalID string `json:"approval_id,omitempty"`
// Duration is how long the operation took
Duration time.Duration `json:"duration,omitempty"`
// Metadata contains additional context
Metadata map[string]interface{} `json:"metadata,omitempty"`
// Checksum for event integrity
Checksum string `json:"checksum"`
}
AuditEvent represents a single audit log entry.
type AuditEventType ¶
type AuditEventType string
AuditEventType represents the type of audit event.
const ( // AuditEventCommand - Command execution AuditEventCommand AuditEventType = "command" // AuditEventFileRead - File read operation AuditEventFileRead AuditEventType = "file_read" // AuditEventFileWrite - File write operation AuditEventFileWrite AuditEventType = "file_write" // AuditEventFileDelete - File delete operation AuditEventFileDelete AuditEventType = "file_delete" // AuditEventApproval - Approval request/decision AuditEventApproval AuditEventType = "approval" // AuditEventSnapshot - Snapshot created/restored AuditEventSnapshot AuditEventType = "snapshot" // AuditEventRollback - Rollback operation AuditEventRollback AuditEventType = "rollback" // AuditEventError - Error occurred AuditEventError AuditEventType = "error" // AuditEventSecurity - Security-related event AuditEventSecurity AuditEventType = "security" // AuditEventSandbox - Sandbox operation AuditEventSandbox AuditEventType = "sandbox" // AuditEventNetwork - Network operation AuditEventNetwork AuditEventType = "network" // AuditEventPlan - Plan created/modified AuditEventPlan AuditEventType = "plan" // AuditEventStep - Step execution AuditEventStep AuditEventType = "step" )
type AuditFilter ¶
type AuditFilter struct {
Types []AuditEventType
Severity AuditSeverity
SessionID string
StepID string
Result string
StartTime *time.Time
EndTime *time.Time
}
AuditFilter filters audit events.
func (AuditFilter) Matches ¶
func (f AuditFilter) Matches(event AuditEvent) bool
Matches checks if an event matches the filter.
type AuditLogger ¶
type AuditLogger struct {
// contains filtered or unexported fields
}
AuditLogger manages audit logging for autonomous operations.
func NewAuditLogger ¶
func NewAuditLogger(config AuditConfig) *AuditLogger
NewAuditLogger creates a new audit logger.
func (*AuditLogger) Export ¶
func (al *AuditLogger) Export() ([]byte, error)
Export exports all events to JSON.
func (*AuditLogger) GetEvents ¶
func (al *AuditLogger) GetEvents(filter AuditFilter) []AuditEvent
GetEvents returns all events matching the filter.
func (*AuditLogger) GetRecentEvents ¶
func (al *AuditLogger) GetRecentEvents(n int) []AuditEvent
GetRecentEvents returns the most recent n events.
func (*AuditLogger) GetStats ¶
func (al *AuditLogger) GetStats() AuditStats
GetStats returns audit statistics.
func (*AuditLogger) Log ¶
func (al *AuditLogger) Log(eventType AuditEventType, severity AuditSeverity, message string, opts ...AuditOption)
Log records a new audit event.
func (*AuditLogger) LogApproval ¶
func (al *AuditLogger) LogApproval(requestID, command string, approved bool, approvedBy, reason string)
LogApproval logs an approval event.
func (*AuditLogger) LogCommand ¶
func (al *AuditLogger) LogCommand(command string, args []string, result string, duration time.Duration, err error)
LogCommand logs a command execution.
func (*AuditLogger) LogError ¶
func (al *AuditLogger) LogError(operation, message string, err error)
LogError logs an error event.
func (*AuditLogger) LogFileOperation ¶
func (al *AuditLogger) LogFileOperation(operation, path string, result string, err error)
LogFileOperation logs a file operation.
func (*AuditLogger) LogSecurity ¶
func (al *AuditLogger) LogSecurity(event, details string, severity AuditSeverity)
LogSecurity logs a security-related event.
func (*AuditLogger) LogSnapshot ¶
func (al *AuditLogger) LogSnapshot(operation, snapshotID string, err error)
LogSnapshot logs a snapshot operation.
func (*AuditLogger) SetSessionID ¶
func (al *AuditLogger) SetSessionID(sessionID string)
SetSessionID sets the current session identifier.
type AuditOption ¶
type AuditOption func(*AuditEvent)
AuditOption is a functional option for audit events.
func WithApprovalID ¶
func WithApprovalID(id string) AuditOption
WithApprovalID sets the approval ID.
func WithApproved ¶
func WithApproved(approved bool) AuditOption
WithApproved sets the approved status.
func WithDangerLevel ¶
func WithDangerLevel(level DangerLevel) AuditOption
WithDangerLevel sets the danger level.
func WithMetadata ¶
func WithMetadata(key string, value interface{}) AuditOption
WithMetadata sets metadata.
func WithOperation ¶
func WithOperation(operation string) AuditOption
WithOperation sets the operation.
type AuditSafetySettings ¶
type AuditSafetySettings struct {
// Enabled turns on audit logging
Enabled bool `json:"enabled"`
// LogAllOperations logs all operations
LogAllOperations bool `json:"log_all_operations"`
// LogApprovals logs approval decisions
LogApprovals bool `json:"log_approvals"`
// LogRejections logs rejections
LogRejections bool `json:"log_rejections"`
// LogSnapshots logs snapshot operations
LogSnapshots bool `json:"log_snapshots"`
// LogNetwork logs network operations
LogNetwork bool `json:"log_network"`
// RetentionDays is how long to keep logs
RetentionDays int `json:"retention_days"`
// IncludeContent includes file content in logs
IncludeContent bool `json:"include_content"`
}
AuditSafetySettings controls audit logging.
type AuditSeverity ¶
type AuditSeverity string
AuditSeverity represents the severity level of an audit event.
const ( // AuditSeverityInfo - Informational event AuditSeverityInfo AuditSeverity = "info" // AuditSeverityWarning - Warning event AuditSeverityWarning AuditSeverity = "warning" // AuditSeverityError - Error event AuditSeverityError AuditSeverity = "error" // AuditSeverityCritical - Critical security event AuditSeverityCritical AuditSeverity = "critical" )
type AuditStats ¶
type AuditStats struct {
TotalEvents int `json:"total_events"`
EventsByType map[string]int `json:"events_by_type"`
EventsByResult map[string]int `json:"events_by_result"`
FirstEvent *time.Time `json:"first_event,omitempty"`
LastEvent *time.Time `json:"last_event,omitempty"`
ErrorsLogged int `json:"errors_logged"`
CriticalEvents int `json:"critical_events"`
}
AuditStats tracks audit log statistics.
type Checkpoint ¶
type Checkpoint struct {
ID string `json:"id"`
Timestamp int64 `json:"timestamp"`
Phase string `json:"phase"`
Iteration int `json:"iteration"`
Task string `json:"task"`
Plan *Plan `json:"plan,omitempty"`
CompletedSteps []int `json:"completed_steps"`
PendingSteps []int `json:"pending_steps"`
Result *Result `json:"result,omitempty"`
Metadata map[string]any `json:"metadata,omitempty"`
}
Checkpoint represents a saved state of an autonomous session.
type ChecksumMismatch ¶
type ChecksumMismatch struct {
Path string `json:"path"`
ExpectedHash string `json:"expected_hash"`
ActualHash string `json:"actual_hash"`
}
ChecksumMismatch represents a checksum verification failure.
type CommandApprovalManager ¶
type CommandApprovalManager struct {
// contains filtered or unexported fields
}
CommandApprovalManager manages the approval workflow for commands.
func NewCommandApprovalManager ¶
func NewCommandApprovalManager(assessor *DangerAssessor) *CommandApprovalManager
NewCommandApprovalManager creates a new approval manager.
func (*CommandApprovalManager) Approve ¶
func (cam *CommandApprovalManager) Approve(requestID string, approvedBy string) error
Approve approves a pending request.
func (*CommandApprovalManager) Cancel ¶
func (cam *CommandApprovalManager) Cancel(requestID string) error
Cancel cancels a pending request.
func (*CommandApprovalManager) Deny ¶
func (cam *CommandApprovalManager) Deny(requestID string, reason string) error
Deny denies a pending request.
func (*CommandApprovalManager) ExpirePending ¶
func (cam *CommandApprovalManager) ExpirePending() int
ExpirePending expires all pending requests that have timed out.
func (*CommandApprovalManager) ExportRequests ¶
func (cam *CommandApprovalManager) ExportRequests() ([]byte, error)
ExportRequests exports all requests for audit.
func (*CommandApprovalManager) GetPending ¶
func (cam *CommandApprovalManager) GetPending() []*ApprovalRequest
GetPending returns all pending requests.
func (*CommandApprovalManager) GetPolicy ¶
func (cam *CommandApprovalManager) GetPolicy() ApprovalPolicy
GetPolicy returns the current policy.
func (*CommandApprovalManager) GetRequest ¶
func (cam *CommandApprovalManager) GetRequest(requestID string) (*ApprovalRequest, bool)
GetRequest retrieves a specific request.
func (*CommandApprovalManager) GetStats ¶
func (cam *CommandApprovalManager) GetStats() ApprovalStats
GetStats returns approval statistics.
func (*CommandApprovalManager) IsApproved ¶
func (cam *CommandApprovalManager) IsApproved(requestID string) bool
IsApproved checks if a request is approved (including auto-approved).
func (*CommandApprovalManager) RequestAndWait ¶
func (cam *CommandApprovalManager) RequestAndWait(ctx context.Context, command string, args []string, workingDir string) (*ApprovalRequest, error)
RequestAndWait requests approval and waits for the decision.
func (*CommandApprovalManager) RequestApproval ¶
func (cam *CommandApprovalManager) RequestApproval(ctx context.Context, command string, args []string, workingDir string) (*ApprovalRequest, error)
RequestApproval creates a new approval request.
func (*CommandApprovalManager) SetCallback ¶
func (cam *CommandApprovalManager) SetCallback(callback ApprovalCallback)
SetCallback sets the approval callback.
func (*CommandApprovalManager) SetPolicy ¶
func (cam *CommandApprovalManager) SetPolicy(policy ApprovalPolicy)
SetPolicy sets the approval policy.
func (*CommandApprovalManager) WaitForApproval ¶
func (cam *CommandApprovalManager) WaitForApproval(ctx context.Context, requestID string) (*ApprovalRequest, error)
WaitForApproval waits for a decision on a request.
type CommandCategory ¶
type CommandCategory string
CommandCategory represents a category of commands.
const ( CommandCategoryFileSystem CommandCategory = "filesystem" CommandCategoryNetwork CommandCategory = "network" CommandCategoryProcess CommandCategory = "process" CommandCategorySystem CommandCategory = "system" CommandCategoryPackage CommandCategory = "package" CommandCategoryGit CommandCategory = "git" CommandCategoryDatabase CommandCategory = "database" CommandCategoryCloud CommandCategory = "cloud" CommandCategoryContainer CommandCategory = "container" CommandCategoryCustom CommandCategory = "custom" )
type ConfidenceEngine ¶
type ConfidenceEngine struct {
// contains filtered or unexported fields
}
ConfidenceEngine calculates and manages confidence scores.
func NewConfidenceEngine ¶
func NewConfidenceEngine() *ConfidenceEngine
NewConfidenceEngine creates a new confidence engine.
func (*ConfidenceEngine) ApplyLearningFromFile ¶
func (ce *ConfidenceEngine) ApplyLearningFromFile(learnings map[string]float64)
ApplyLearningFromFile applies pre-trained learnings from a file.
func (*ConfidenceEngine) CalculateConfidence ¶
func (ce *ConfidenceEngine) CalculateConfidence(action PlanStep, context ActionContext) ConfidenceScore
CalculateConfidence computes confidence score for an action.
func (*ConfidenceEngine) ExportLearnings ¶
func (ce *ConfidenceEngine) ExportLearnings() map[string]float64
ExportLearnings returns current learnings for persistence.
func (*ConfidenceEngine) GetConfidenceStats ¶
func (ce *ConfidenceEngine) GetConfidenceStats() ConfidenceStats
GetConfidenceStats returns statistics about confidence decisions.
func (*ConfidenceEngine) GetThresholds ¶
func (ce *ConfidenceEngine) GetThresholds() ConfidenceThresholds
GetThresholds returns current confidence thresholds.
func (*ConfidenceEngine) RecordOutcome ¶
func (ce *ConfidenceEngine) RecordOutcome(action string, confidence float64, outcome string)
RecordOutcome records the outcome of a confidence-based decision for learning.
func (*ConfidenceEngine) SetThresholds ¶
func (ce *ConfidenceEngine) SetThresholds(thresholds ConfidenceThresholds)
SetThresholds allows customizing confidence thresholds.
func (*ConfidenceEngine) ShouldProceed ¶
func (ce *ConfidenceEngine) ShouldProceed(score ConfidenceScore) Decision
ShouldProceed determines if the agent should proceed with an action.
type ConfidenceRecord ¶
type ConfidenceRecord struct {
Action string
Confidence float64
Outcome string // "success", "failure", "partial"
Timestamp int64
}
ConfidenceRecord tracks past confidence decisions for learning.
type ConfidenceScore ¶
type ConfidenceScore struct {
Overall float64 `json:"overall"`
Components map[string]float64 `json:"components"`
Reasoning string `json:"reasoning"`
ShouldAsk bool `json:"should_ask_human"`
RiskLevel RiskLevel `json:"risk_level"`
}
ConfidenceScore represents the agent's confidence in a decision or action. Range: 0.0 (no confidence) to 1.0 (absolute confidence)
type ConfidenceStats ¶
type ConfidenceStats struct {
TotalDecisions int
AverageConfidence float64
SuccessRate float64
LearningCount int
LearningsActive bool
}
ConfidenceStats contains statistics about the confidence engine.
type ConfidenceThresholds ¶
type ConfidenceThresholds struct {
AutoProceed float64 // Confidence above this = proceed automatically
AskHuman float64 // Confidence below this = ask human
RefuseAction float64 // Confidence below this = refuse action
}
ConfidenceThresholds defines when to ask for human input.
func DefaultConfidenceThresholds ¶
func DefaultConfidenceThresholds() ConfidenceThresholds
DefaultConfidenceThresholds returns sensible defaults.
type Config ¶
type Config struct {
MaxIterations int // Maximum iterations before stopping (default: 20)
MaxCost float64 // Maximum cost in USD before stopping (default: 5.0)
MaxDuration time.Duration // Maximum duration before stopping (default: 30min)
VerificationRetry int // Number of retries on verification failure (default: 3)
SafetyMode SafetyMode // Safety level for operations
Interruptible bool // Allow Ctrl+C to interrupt (default: true)
ProgressCallback func(status Status)
}
Config holds configuration for the autonomous engine.
type ContainerUsage ¶
type ContainerUsage struct {
// ContainerID is the container identifier
ContainerID string `json:"container_id"`
// CPU usage
CPUPercent float64 `json:"cpu_percent"`
CPUUsageNanos int64 `json:"cpu_usage_nanos"`
// Memory usage
MemoryMB int64 `json:"memory_mb"`
MemoryLimitMB int64 `json:"memory_limit_mb"`
MemoryPercent float64 `json:"memory_percent"`
// Network I/O
NetworkRxBytes int64 `json:"network_rx_bytes"`
NetworkTxBytes int64 `json:"network_tx_bytes"`
// Block I/O
BlockReadBytes int64 `json:"block_read_bytes"`
BlockWriteBytes int64 `json:"block_write_bytes"`
// Process count
PidsCurrent int64 `json:"pids_current"`
// Timestamp
Timestamp time.Time `json:"timestamp"`
}
ContainerUsage represents current resource usage for a container.
func ParseDockerStats ¶
func ParseDockerStats(output string) (*ContainerUsage, error)
ParseDockerStats parses docker stats output into ContainerUsage.
type ContainerViolation ¶
type ContainerViolation struct {
// ContainerID is the container identifier
ContainerID string `json:"container_id"`
// Type of violation
Type string `json:"type"`
// Current value
Current interface{} `json:"current"`
// Limit value
Limit interface{} `json:"limit"`
// Severity of violation
Severity string `json:"severity"`
// Message describing the violation
Message string `json:"message"`
// Timestamp
Timestamp time.Time `json:"timestamp"`
// Action taken
Action string `json:"action"`
}
ContainerViolation represents a resource limit violation for a container.
type CriterionBuilder ¶
type CriterionBuilder struct {
// contains filtered or unexported fields
}
CriterionBuilder helps build success criteria
func NewCriterionBuilder ¶
func NewCriterionBuilder(criterionType CriterionType, target string) *CriterionBuilder
NewCriterionBuilder creates a new criterion builder
func (*CriterionBuilder) Build ¶
func (b *CriterionBuilder) Build() *SuccessCriterion
Build returns the built criterion
func (*CriterionBuilder) Negate ¶
func (b *CriterionBuilder) Negate() *CriterionBuilder
Negate negates the result
func (*CriterionBuilder) Optional ¶
func (b *CriterionBuilder) Optional() *CriterionBuilder
Optional marks the criterion as optional
func (*CriterionBuilder) WithDescription ¶
func (b *CriterionBuilder) WithDescription(desc string) *CriterionBuilder
WithDescription sets the criterion description
func (*CriterionBuilder) WithExpected ¶
func (b *CriterionBuilder) WithExpected(expected string) *CriterionBuilder
WithExpected sets the expected value
func (*CriterionBuilder) WithMetadata ¶
func (b *CriterionBuilder) WithMetadata(key string, value any) *CriterionBuilder
WithMetadata adds metadata
func (*CriterionBuilder) WithName ¶
func (b *CriterionBuilder) WithName(name string) *CriterionBuilder
WithName sets the criterion name
func (*CriterionBuilder) WithPattern ¶
func (b *CriterionBuilder) WithPattern(pattern string) *CriterionBuilder
WithPattern sets the pattern for matching
func (*CriterionBuilder) WithRetries ¶
func (b *CriterionBuilder) WithRetries(count int, delay time.Duration) *CriterionBuilder
WithRetries sets the retry count and delay
func (*CriterionBuilder) WithTimeout ¶
func (b *CriterionBuilder) WithTimeout(timeout time.Duration) *CriterionBuilder
WithTimeout sets the timeout
func (*CriterionBuilder) WithWeight ¶
func (b *CriterionBuilder) WithWeight(weight float64) *CriterionBuilder
WithWeight sets the weight for scoring
type CriterionChecker ¶
type CriterionChecker func(ctx context.Context, criterion *SuccessCriterion) (*ValidationResult, error)
CriterionChecker is a function that checks a criterion
type CriterionStatus ¶
type CriterionStatus string
CriterionStatus represents the status of a criterion check
const ( CriterionStatusPending CriterionStatus = "pending" CriterionStatusPassed CriterionStatus = "passed" CriterionStatusFailed CriterionStatus = "failed" CriterionStatusSkipped CriterionStatus = "skipped" CriterionStatusError CriterionStatus = "error" )
type CriterionType ¶
type CriterionType string
CriterionType represents the type of success criterion
const ( CriterionTypeFileExists CriterionType = "file_exists" CriterionTypeFileNotExists CriterionType = "file_not_exists" CriterionTypeFileContains CriterionType = "file_contains" CriterionTypeFileMatches CriterionType = "file_matches" CriterionTypeCommandSuccess CriterionType = "command_success" CriterionTypeCommandOutput CriterionType = "command_output" CriterionTypeTestPasses CriterionType = "test_passes" CriterionTypeBuildSuccess CriterionType = "build_success" CriterionTypeLintPasses CriterionType = "lint_passes" CriterionTypeCustom CriterionType = "custom" )
type CustomSafetyRule ¶
type CustomSafetyRule struct {
// ID is the unique rule identifier
ID string `json:"id"`
// Name is the rule name
Name string `json:"name"`
// Description explains the rule
Description string `json:"description"`
// Enabled turns the rule on/off
Enabled bool `json:"enabled"`
// Pattern is the command/operation pattern to match
Pattern string `json:"pattern"`
// Action is what to do when matched (allow, deny, require_approval, warn)
Action string `json:"action"`
// Priority is the rule priority (higher = checked first)
Priority int `json:"priority"`
// DangerLevelOverride overrides the danger level for matched operations
DangerLevelOverride *DangerLevel `json:"danger_level_override,omitempty"`
// Message is shown when the rule is triggered
Message string `json:"message,omitempty"`
}
CustomSafetyRule defines a user-defined safety rule.
type DNSConfig ¶
type DNSConfig struct {
Servers []string `json:"servers"`
Search []string `json:"search"`
Options []string `json:"options"`
}
DNSConfig defines DNS configuration for the sandbox.
type DangerAssessment ¶
type DangerAssessment struct {
// Level is the overall danger level
Level DangerLevel `json:"level"`
// Category is the primary danger category
Category DangerCategory `json:"category"`
// Score is a numeric risk score (0-100)
Score int `json:"score"`
// Confidence is the confidence in the assessment (0-1)
Confidence float64 `json:"confidence"`
// Reasons are the factors that contributed to the assessment
Reasons []string `json:"reasons"`
// Mitigations are suggested mitigations for the risks
Mitigations []string `json:"mitigations"`
// AffectedPaths are file paths that would be affected
AffectedPaths []string `json:"affected_paths"`
// IsDestructive indicates if the operation is destructive
IsDestructive bool `json:"is_destructive"`
// IsReversible indicates if the operation can be undone
IsReversible bool `json:"is_reversible"`
// RequiresSandbox indicates if sandboxing is recommended
RequiresSandbox bool `json:"requires_sandbox"`
// ApprovalMessage is a message to show when requesting approval
ApprovalMessage string `json:"approval_message"`
}
DangerAssessment contains the result of a danger assessment.
type DangerAssessmentBuilder ¶
type DangerAssessmentBuilder struct {
// contains filtered or unexported fields
}
DangerAssessmentBuilder helps create danger assessments for custom scenarios.
func NewDangerAssessmentBuilder ¶
func NewDangerAssessmentBuilder() *DangerAssessmentBuilder
NewDangerAssessmentBuilder creates a new builder.
func (*DangerAssessmentBuilder) Build ¶
func (b *DangerAssessmentBuilder) Build() *DangerAssessment
Build returns the assessment.
func (*DangerAssessmentBuilder) Destructive ¶
func (b *DangerAssessmentBuilder) Destructive() *DangerAssessmentBuilder
Destructive marks the assessment as destructive.
func (*DangerAssessmentBuilder) WithAffectedPath ¶
func (b *DangerAssessmentBuilder) WithAffectedPath(path string) *DangerAssessmentBuilder
WithAffectedPath adds an affected path.
func (*DangerAssessmentBuilder) WithCategory ¶
func (b *DangerAssessmentBuilder) WithCategory(category DangerCategory) *DangerAssessmentBuilder
WithCategory sets the category.
func (*DangerAssessmentBuilder) WithLevel ¶
func (b *DangerAssessmentBuilder) WithLevel(level DangerLevel) *DangerAssessmentBuilder
WithLevel sets the danger level.
func (*DangerAssessmentBuilder) WithMitigation ¶
func (b *DangerAssessmentBuilder) WithMitigation(mitigation string) *DangerAssessmentBuilder
WithMitigation adds a mitigation.
func (*DangerAssessmentBuilder) WithReason ¶
func (b *DangerAssessmentBuilder) WithReason(reason string) *DangerAssessmentBuilder
WithReason adds a reason.
type DangerAssessor ¶
type DangerAssessor struct {
// contains filtered or unexported fields
}
DangerAssessor assesses the danger level of commands and operations.
func NewDangerAssessor ¶
func NewDangerAssessor() *DangerAssessor
NewDangerAssessor creates a new danger assessor.
func (*DangerAssessor) AddCustomRule ¶
func (da *DangerAssessor) AddCustomRule(rule DangerRule) error
AddCustomRule adds a custom danger rule.
func (*DangerAssessor) AddProtectedPath ¶
func (da *DangerAssessor) AddProtectedPath(path string)
AddProtectedPath adds a path to the protected list.
func (*DangerAssessor) AssessCommand ¶
func (da *DangerAssessor) AssessCommand(command string) *DangerAssessment
AssessCommand evaluates a command and returns a danger assessment.
func (*DangerAssessor) GetProtectedPaths ¶
func (da *DangerAssessor) GetProtectedPaths() []string
GetProtectedPaths returns the list of protected paths.
func (*DangerAssessor) RemoveCustomRule ¶
func (da *DangerAssessor) RemoveCustomRule(name string) bool
RemoveCustomRule removes a custom rule by name.
func (*DangerAssessor) RemoveProtectedPath ¶
func (da *DangerAssessor) RemoveProtectedPath(path string) bool
RemoveProtectedPath removes a path from the protected list.
type DangerCategory ¶
type DangerCategory string
DangerCategory represents a category of dangerous operations.
const ( DangerCategoryFileSystem DangerCategory = "filesystem" DangerCategoryNetwork DangerCategory = "network" DangerCategoryProcess DangerCategory = "process" DangerCategorySystem DangerCategory = "system" DangerCategorySecurity DangerCategory = "security" DangerCategoryData DangerCategory = "data" DangerCategoryGit DangerCategory = "git" DangerCategoryPackage DangerCategory = "package" DangerCategoryConfig DangerCategory = "config" DangerCategoryUnknown DangerCategory = "unknown" )
type DangerLevel ¶
type DangerLevel int
DangerLevel represents the risk level of a command or operation.
const ( // DangerLevelSafe - No risk, safe to execute automatically DangerLevelSafe DangerLevel = iota // DangerLevelLow - Minimal risk, standard operations DangerLevelLow // DangerLevelMedium - Moderate risk, may need review DangerLevelMedium // DangerLevelHigh - Significant risk, requires approval DangerLevelHigh // DangerLevelCritical - Maximum risk, requires explicit approval DangerLevelCritical )
func AssessDangerLevel ¶
func AssessDangerLevel(op OperationType, target string, details map[string]any) DangerLevel
AssessDangerLevel determines the danger level of an operation.
func QuickAssess ¶
func QuickAssess(command string) DangerLevel
QuickAssess provides a quick danger level for a command.
func (DangerLevel) MarshalText ¶
func (d DangerLevel) MarshalText() ([]byte, error)
MarshalText implements encoding.TextMarshaler.
func (DangerLevel) NeedsApproval ¶
func (d DangerLevel) NeedsApproval() bool
NeedsApproval returns true if this danger level requires approval.
func (DangerLevel) RequiresConfirmation ¶
func (d DangerLevel) RequiresConfirmation() bool
RequiresConfirmation returns true if this level needs user confirmation.
func (DangerLevel) String ¶
func (d DangerLevel) String() string
String returns the string representation of the danger level.
func (*DangerLevel) UnmarshalText ¶
func (d *DangerLevel) UnmarshalText(text []byte) error
UnmarshalText implements encoding.TextUnmarshaler.
type DangerPattern ¶
type DangerPattern struct {
// Pattern is the regex pattern to match
Pattern *regexp.Regexp `json:"-"`
// PatternStr is the string representation of the pattern
PatternStr string `json:"pattern"`
// Category is the danger category
Category DangerCategory `json:"category"`
// Level is the base danger level
Level DangerLevel `json:"level"`
// IsDestructive indicates if the matched command is destructive
IsDestructive bool `json:"is_destructive"`
// Reason describes why this pattern is dangerous
Reason string `json:"reason"`
// Mitigation suggests how to reduce risk
Mitigation string `json:"mitigation"`
}
DangerPattern matches commands and assigns danger levels.
type DangerRule ¶
type DangerRule struct {
Name string `json:"name"`
Pattern string `json:"pattern"`
Level DangerLevel `json:"level"`
Category DangerCategory `json:"category"`
Enabled bool `json:"enabled"`
Priority int `json:"priority"`
}
DangerRule is a custom rule for danger assessment.
type DangerThresholdSettings ¶
type DangerThresholdSettings struct {
// ApprovalRequired is the minimum danger level requiring approval
ApprovalRequired DangerLevel `json:"approval_required"`
// ConfirmationRequired is the minimum level requiring confirmation
ConfirmationRequired DangerLevel `json:"confirmation_required"`
// AutoReject is the level at which operations are auto-rejected
AutoReject DangerLevel `json:"auto_reject"`
// WarningLevel is the level at which warnings are shown
WarningLevel DangerLevel `json:"warning_level"`
// BlockLevel is the level at which operations are blocked
BlockLevel DangerLevel `json:"block_level"`
}
DangerThresholdSettings defines danger level thresholds.
type DashboardConfig ¶
type DashboardConfig struct {
TaskName string
Output io.Writer
RefreshRate time.Duration
ShowTimestamps bool
Compact bool
}
DashboardConfig configures the dashboard.
type DashboardStats ¶
type DashboardStats struct {
TaskName string
Duration time.Duration
Status DashboardStatus
Progress float64
TotalOps int
CompletedOps int
FailedOps int
Retries int
TokensUsed int64
Cost float64
StepsCompleted int
StepsTotal int
}
DashboardStats holds dashboard statistics.
type DashboardStatus ¶
type DashboardStatus string
DashboardStatus represents the overall status.
const ( DashboardStatusRunning DashboardStatus = "running" DashboardStatusPaused DashboardStatus = "paused" DashboardStatusCompleted DashboardStatus = "completed" DashboardStatusFailed DashboardStatus = "failed" DashboardStatusCancelled DashboardStatus = "cancelled" )
type DebugCategory ¶
type DebugCategory string
DebugCategory represents a category of debug output
const ( DebugCategoryPlanning DebugCategory = "planning" DebugCategoryExecution DebugCategory = "execution" DebugCategoryVerification DebugCategory = "verification" DebugCategoryRetry DebugCategory = "retry" DebugCategoryState DebugCategory = "state" DebugCategoryContext DebugCategory = "context" DebugCategoryAll DebugCategory = "all" )
type DebugConfig ¶
type DebugConfig struct {
Enabled bool `json:"enabled"`
Level DebugLevel `json:"level"`
Categories []DebugCategory `json:"categories"`
OutputFormat string `json:"output_format"` // "text", "json", "markdown"
IncludeStack bool `json:"include_stack"`
MaxEvents int `json:"max_events"`
SlowThreshold time.Duration `json:"slow_threshold"`
PauseOnError bool `json:"pause_on_error"`
LogFile string `json:"log_file"`
RealTimeOutput bool `json:"real_time_output"`
}
DebugConfig configures the debug mode
func DefaultDebugConfig ¶
func DefaultDebugConfig() DebugConfig
DefaultDebugConfig returns default debug configuration
type DebugEvent ¶
type DebugEvent struct {
Timestamp time.Time `json:"timestamp"`
Level DebugLevel `json:"level"`
Category DebugCategory `json:"category"`
Message string `json:"message"`
Details map[string]any `json:"details,omitempty"`
Duration time.Duration `json:"duration,omitempty"`
StackTrace string `json:"stack_trace,omitempty"`
TaskID string `json:"task_id,omitempty"`
StepID string `json:"step_id,omitempty"`
Iteration int `json:"iteration,omitempty"`
}
DebugEvent represents a single debug event
type DebugLevel ¶
type DebugLevel int
DebugLevel represents the verbosity level of debug output
const ( DebugLevelNone DebugLevel = 0 DebugLevelError DebugLevel = 1 DebugLevelWarn DebugLevel = 2 DebugLevelInfo DebugLevel = 3 DebugLevelDebug DebugLevel = 4 DebugLevelTrace DebugLevel = 5 )
type DebugMode ¶
type DebugMode struct {
// contains filtered or unexported fields
}
DebugMode provides transparency for autonomous agent operations
func NewDebugMode ¶
func NewDebugMode(config DebugConfig) *DebugMode
NewDebugMode creates a new debug mode instance
func (*DebugMode) EndSession ¶
EndSession ends the current debug session
func (*DebugMode) ExportJSON ¶
ExportJSON exports the session as JSON
func (*DebugMode) GenerateReport ¶
GenerateReport generates a debug report for the session
func (*DebugMode) GetErrors ¶
func (dm *DebugMode) GetErrors() []DebugEvent
GetErrors returns all error-level events
func (*DebugMode) GetEvents ¶
func (dm *DebugMode) GetEvents() []DebugEvent
GetEvents returns all events from the current session
func (*DebugMode) GetEventsByCategory ¶
func (dm *DebugMode) GetEventsByCategory(category DebugCategory) []DebugEvent
GetEventsByCategory returns events filtered by category
func (*DebugMode) GetEventsByLevel ¶
func (dm *DebugMode) GetEventsByLevel(level DebugLevel) []DebugEvent
GetEventsByLevel returns events filtered by level
func (*DebugMode) GetSession ¶
func (dm *DebugMode) GetSession() *DebugSession
GetSession returns the current session
func (*DebugMode) GetSlowOperations ¶
func (dm *DebugMode) GetSlowOperations() []DebugEvent
GetSlowOperations returns events that exceeded the slow threshold
func (*DebugMode) GetWarnings ¶
func (dm *DebugMode) GetWarnings() []DebugEvent
GetWarnings returns all warning-level events
func (*DebugMode) Log ¶
func (dm *DebugMode) Log(level DebugLevel, category DebugCategory, message string, details map[string]any)
Log logs a debug event
func (*DebugMode) LogContext ¶
LogContext logs a context-related event
func (*DebugMode) LogExecution ¶
LogExecution logs an execution phase event
func (*DebugMode) LogPlanning ¶
LogPlanning logs a planning phase event
func (*DebugMode) LogVerification ¶
LogVerification logs a verification phase event
func (*DebugMode) Pause ¶
func (dm *DebugMode) Pause()
Pause pauses the debug session (for interactive debugging)
func (*DebugMode) SetCategories ¶
func (dm *DebugMode) SetCategories(categories []DebugCategory)
SetCategories sets the debug categories
func (*DebugMode) SetLevel ¶
func (dm *DebugMode) SetLevel(level DebugLevel)
SetLevel sets the debug level
func (*DebugMode) StartSession ¶
func (dm *DebugMode) StartSession(task string) *DebugSession
StartSession starts a new debug session
type DebugModeBuilder ¶
type DebugModeBuilder struct {
// contains filtered or unexported fields
}
DebugModeBuilder helps create debug configurations
func NewDebugModeBuilder ¶
func NewDebugModeBuilder() *DebugModeBuilder
NewDebugModeBuilder creates a new debug mode builder
func (*DebugModeBuilder) Build ¶
func (b *DebugModeBuilder) Build() *DebugMode
Build returns the configured DebugMode
func (*DebugModeBuilder) BuildConfig ¶
func (b *DebugModeBuilder) BuildConfig() DebugConfig
BuildConfig returns the configuration
func (*DebugModeBuilder) WithCategories ¶
func (b *DebugModeBuilder) WithCategories(categories ...DebugCategory) *DebugModeBuilder
WithCategories sets the debug categories
func (*DebugModeBuilder) WithEnabled ¶
func (b *DebugModeBuilder) WithEnabled(enabled bool) *DebugModeBuilder
WithEnabled sets whether debug is enabled
func (*DebugModeBuilder) WithIncludeStack ¶
func (b *DebugModeBuilder) WithIncludeStack(include bool) *DebugModeBuilder
WithIncludeStack sets whether to include stack traces
func (*DebugModeBuilder) WithLevel ¶
func (b *DebugModeBuilder) WithLevel(level DebugLevel) *DebugModeBuilder
WithLevel sets the debug level
func (*DebugModeBuilder) WithLogFile ¶
func (b *DebugModeBuilder) WithLogFile(path string) *DebugModeBuilder
WithLogFile sets the log file path
func (*DebugModeBuilder) WithMaxEvents ¶
func (b *DebugModeBuilder) WithMaxEvents(max int) *DebugModeBuilder
WithMaxEvents sets the maximum number of events
func (*DebugModeBuilder) WithOutputFormat ¶
func (b *DebugModeBuilder) WithOutputFormat(format string) *DebugModeBuilder
WithOutputFormat sets the output format
func (*DebugModeBuilder) WithPauseOnError ¶
func (b *DebugModeBuilder) WithPauseOnError(pause bool) *DebugModeBuilder
WithPauseOnError sets whether to pause on errors
func (*DebugModeBuilder) WithRealTimeOutput ¶
func (b *DebugModeBuilder) WithRealTimeOutput(realtime bool) *DebugModeBuilder
WithRealTimeOutput sets whether to output in real-time
func (*DebugModeBuilder) WithSlowThreshold ¶
func (b *DebugModeBuilder) WithSlowThreshold(threshold time.Duration) *DebugModeBuilder
WithSlowThreshold sets the slow operation threshold
type DebugSession ¶
type DebugSession struct {
ID string `json:"id"`
StartedAt time.Time `json:"started_at"`
EndedAt time.Time `json:"ended_at,omitempty"`
Task string `json:"task"`
Events []DebugEvent `json:"events"`
Status string `json:"status"`
Config DebugConfig `json:"config"`
// contains filtered or unexported fields
}
DebugSession represents a debug session for an autonomous run
type DecisionOption ¶
type DecisionOption struct {
ID string `json:"id"`
Label string `json:"label"`
Description string `json:"description"`
Risk string `json:"risk"` // Risk level: low/medium/high
Recommended bool `json:"recommended"` // Is this the agent's recommendation?
Confidence float64 `json:"confidence"` // Agent confidence in this option
Metadata map[string]any `json:"metadata,omitempty"`
}
DecisionOption represents a possible choice for the human
type DecisionRequest ¶
type DecisionRequest struct {
ID string `json:"id"`
Type DecisionType `json:"type"`
Urgency UrgencyLevel `json:"urgency"`
Title string `json:"title"`
Description string `json:"description"`
Context string `json:"context"` // Additional context
Options []DecisionOption `json:"options"`
Confidence float64 `json:"confidence"` // Agent's overall confidence
CreatedAt time.Time `json:"created_at"`
ExpiresAt *time.Time `json:"expires_at,omitempty"`
SourceStep string `json:"source_step"` // Which step triggered this
Metadata map[string]any `json:"metadata,omitempty"`
}
DecisionRequest represents a request for human input
type DecisionResponse ¶
type DecisionResponse struct {
RequestID string `json:"request_id"`
SelectedID string `json:"selected_id"` // Which option was chosen
CustomInput string `json:"custom_input,omitempty"` // Free-form input if allowed
Reasoning string `json:"reasoning,omitempty"` // Why this choice
RespondedAt time.Time `json:"responded_at"`
RespondedBy string `json:"responded_by"` // User identifier
}
DecisionResponse represents a human's decision
type DecisionType ¶
type DecisionType string
DecisionType represents the type of decision requiring human input
const ( DecisionTypeAmbiguous DecisionType = "ambiguous" // Multiple valid options DecisionTypeDestructive DecisionType = "destructive" // Potentially harmful operation DecisionTypeUncertain DecisionType = "uncertain" // Low confidence score DecisionTypeConflict DecisionType = "conflict" // Conflicting information DecisionTypeSecurity DecisionType = "security" // Security-sensitive operation DecisionTypeCost DecisionType = "cost" // High cost operation DecisionTypeExternal DecisionType = "external" // External service interaction DecisionTypeApproval DecisionType = "approval" // Needs explicit approval )
type DependencyGraph ¶
type DependencyGraph struct {
// contains filtered or unexported fields
}
DependencyGraph represents the dependency relationships between plan steps.
type EmergencyStopConfig ¶
type EmergencyStopConfig struct {
Enabled bool // Enable emergency stop system
AutoRecovery bool // Attempt automatic recovery
MaxConsecutiveErrors int // Errors before triggering stop (default: 5)
MaxRepeatedActions int // Same action repeated before stop (default: 3)
LoopDetectionWindow time.Duration // Window for loop detection (default: 30s)
LoopDetectionThreshold int // Max identical actions in window (default: 5)
GracefulTimeout time.Duration // Time for graceful shutdown (default: 5s)
RollbackOnStop bool // Rollback to last snapshot on stop
NotifyOnStop bool // Send notification on emergency stop
}
EmergencyStopConfig holds configuration for emergency stop behavior.
func DefaultEmergencyStopConfig ¶
func DefaultEmergencyStopConfig() EmergencyStopConfig
DefaultEmergencyStopConfig returns the default configuration.
type EmergencyStopHandler ¶
type EmergencyStopHandler struct {
// contains filtered or unexported fields
}
EmergencyStopHandler provides HTTP/WebSocket handler support.
func NewEmergencyStopHandler ¶
func NewEmergencyStopHandler(manager *EmergencyStopManager, logger *slog.Logger) *EmergencyStopHandler
NewEmergencyStopHandler creates a new handler.
func (*EmergencyStopHandler) HandleReset ¶
func (h *EmergencyStopHandler) HandleReset() error
HandleReset handles reset requests.
func (*EmergencyStopHandler) HandleStatus ¶
func (h *EmergencyStopHandler) HandleStatus() map[string]interface{}
HandleStatus returns status for external monitoring.
func (*EmergencyStopHandler) HandleTrigger ¶
func (h *EmergencyStopHandler) HandleTrigger(reason, message, source string) error
HandleTrigger handles an external trigger request.
type EmergencyStopManager ¶
type EmergencyStopManager struct {
// contains filtered or unexported fields
}
EmergencyStopManager manages emergency stop functionality.
func NewEmergencyStopManager ¶
func NewEmergencyStopManager(config EmergencyStopConfig, logger *slog.Logger) *EmergencyStopManager
NewEmergencyStopManager creates a new emergency stop manager.
func (*EmergencyStopManager) AlertChan ¶
func (m *EmergencyStopManager) AlertChan() <-chan EmergencyStopTrigger
AlertChan returns the alert channel for notifications.
func (*EmergencyStopManager) AttemptRecovery ¶
func (m *EmergencyStopManager) AttemptRecovery(ctx context.Context) error
AttemptRecovery attempts to recover from an emergency stop.
func (*EmergencyStopManager) CheckResourceUsage ¶
func (m *EmergencyStopManager) CheckResourceUsage(memoryMB int64, cpuPercent float64, goroutineCount int)
CheckResourceUsage checks resource usage against limits.
func (*EmergencyStopManager) ClearErrorCount ¶
func (m *EmergencyStopManager) ClearErrorCount()
ClearErrorCount resets the error counter after a successful operation.
func (*EmergencyStopManager) GetStatus ¶
func (m *EmergencyStopManager) GetStatus() map[string]interface{}
GetStatus returns the current status of the emergency stop manager.
func (*EmergencyStopManager) GetTrigger ¶
func (m *EmergencyStopManager) GetTrigger() *EmergencyStopTrigger
GetTrigger returns the emergency stop trigger details.
func (*EmergencyStopManager) IsStopped ¶
func (m *EmergencyStopManager) IsStopped() bool
IsStopped returns whether an emergency stop has been triggered.
func (*EmergencyStopManager) RecordAction ¶
func (m *EmergencyStopManager) RecordAction(action string)
RecordAction records an action for loop detection.
func (*EmergencyStopManager) RecordError ¶
func (m *EmergencyStopManager) RecordError(err error, isCritical bool)
RecordError records an error and checks for error threshold.
func (*EmergencyStopManager) Reset ¶
func (m *EmergencyStopManager) Reset()
Reset clears the emergency stop state for a new session.
func (*EmergencyStopManager) SetAuditLogger ¶
func (m *EmergencyStopManager) SetAuditLogger(logger *AuditLogger)
SetAuditLogger sets the audit logger for emergency events.
func (*EmergencyStopManager) SetEngine ¶
func (m *EmergencyStopManager) SetEngine(engine *Engine)
SetEngine links the manager to an autonomous engine.
func (*EmergencyStopManager) SetNotifyCallback ¶
func (m *EmergencyStopManager) SetNotifyCallback(callback func(trigger EmergencyStopTrigger))
SetNotifyCallback sets a callback for emergency stop notifications.
func (*EmergencyStopManager) StopChan ¶
func (m *EmergencyStopManager) StopChan() <-chan struct{}
StopChan returns the stop channel for listening.
func (*EmergencyStopManager) Trigger ¶
func (m *EmergencyStopManager) Trigger(reason EmergencyStopReason, severity EmergencyStopSeverity, message, source string, context map[string]interface{}) error
Trigger initiates an emergency stop.
func (*EmergencyStopManager) TriggerSafetyViolation ¶
func (m *EmergencyStopManager) TriggerSafetyViolation(violation, details string)
TriggerSafetyViolation triggers a stop due to safety policy breach.
type EmergencyStopReason ¶
type EmergencyStopReason string
EmergencyStopReason defines why an emergency stop was triggered.
const ( EmergencyStopManual EmergencyStopReason = "manual" // User-triggered EmergencyStopInfiniteLoop EmergencyStopReason = "infinite_loop" // Loop detection EmergencyStopResourceExhaust EmergencyStopReason = "resource_exhaust" // Memory/CPU limits EmergencyStopCriticalError EmergencyStopReason = "critical_error" // Unrecoverable error EmergencyStopTimeout EmergencyStopReason = "timeout" // Execution timeout EmergencyStopUserAbort EmergencyStopReason = "user_abort" // User requested abort EmergencyStopSafetyViolation EmergencyStopReason = "safety_violation" // Safety policy breach EmergencyStopExternalSignal EmergencyStopReason = "external_signal" // External monitoring trigger )
type EmergencyStopSeverity ¶
type EmergencyStopSeverity int
EmergencyStopSeverity defines the severity level of the stop.
const ( SeverityWarning EmergencyStopSeverity = iota // Can continue with caution SeverityCritical // Must stop immediately SeverityFatal // System-level issue, full halt )
type EmergencyStopTrigger ¶
type EmergencyStopTrigger struct {
Reason EmergencyStopReason
Severity EmergencyStopSeverity
Message string
Source string // "user", "system", "monitor", "engine"
Timestamp time.Time
Context map[string]interface{} // Additional context
Recovered bool // Whether recovery was attempted
Stacktrace string // Optional stack trace
}
EmergencyStopTrigger represents what triggered the stop.
type Engine ¶
type Engine struct {
// contains filtered or unexported fields
}
Engine represents the autonomous agent engine.
func NewEngine ¶
func NewEngine(repoPath string, agent *iteragent.Agent, tools []iteragent.Tool, logger *slog.Logger, config Config) *Engine
NewEngine creates a new autonomous engine.
type ErrorCategory ¶
type ErrorCategory string
ErrorCategory categorizes error types for strategy selection.
const ( CategoryBuildError ErrorCategory = "build_error" CategoryTestFailure ErrorCategory = "test_failure" CategoryRaceCondition ErrorCategory = "race_condition" CategoryTimeout ErrorCategory = "timeout" CategoryNetworkError ErrorCategory = "network_error" CategoryResourceError ErrorCategory = "resource_error" CategorySyntaxError ErrorCategory = "syntax_error" CategoryImportError ErrorCategory = "import_error" CategoryRuntimeError ErrorCategory = "runtime_error" CategoryUnknown ErrorCategory = "unknown" )
type ExecutionResult ¶
type FailureAnalysis ¶
type FailureAnalysis struct {
OriginalError string
Category ErrorCategory
PatternID string
Fixable bool
Confidence float64
HistoricalFixRate float64
Suggestions []string
RelatedFiles []string
}
FailureAnalysis contains structured failure information.
type FailureLearner ¶
type FailureLearner struct {
// contains filtered or unexported fields
}
FailureLearner learns from autonomous failures to improve future operations. It extends SmartRetry (Task 11) with persistent learning across sessions.
func NewFailureLearner ¶
func NewFailureLearner(config FailureLearnerConfig) *FailureLearner
NewFailureLearner creates a new failure learner.
func (*FailureLearner) ApplyLearning ¶
func (fl *FailureLearner) ApplyLearning(rec *FailureRecommendation) bool
ApplyLearning applies a learned solution to a new failure.
func (*FailureLearner) ExportLearnings ¶
func (fl *FailureLearner) ExportLearnings() (string, error)
ExportLearnings exports learnings to JSON.
func (*FailureLearner) GenerateReport ¶
func (fl *FailureLearner) GenerateReport() string
GenerateReport generates a learning report.
func (*FailureLearner) GetPatterns ¶
func (fl *FailureLearner) GetPatterns() []LearnedPattern
GetPatterns returns all learned patterns.
func (*FailureLearner) GetRecentLearnings ¶
func (fl *FailureLearner) GetRecentLearnings(limit int) []*FailureLearning
GetRecentLearnings returns the most recent learnings.
func (*FailureLearner) GetRecommendation ¶
func (fl *FailureLearner) GetRecommendation(errorMsg string) *FailureRecommendation
GetRecommendation returns recommendations based on learned failures.
func (*FailureLearner) GetStats ¶
func (fl *FailureLearner) GetStats() LearnerStats
GetStats returns learning statistics.
func (*FailureLearner) GetUnverifiedLearnings ¶
func (fl *FailureLearner) GetUnverifiedLearnings() []*FailureLearning
GetUnverifiedLearnings returns learnings that haven't been verified.
func (*FailureLearner) RecordFailure ¶
func (fl *FailureLearner) RecordFailure(taskType, taskID, errorMsg string, context map[string]any) *FailureLearning
RecordFailure records a failure for learning.
func (*FailureLearner) RecordSolution ¶
func (fl *FailureLearner) RecordSolution(learningID, solution string, actions []LearningAction)
RecordSolution records a solution for a failure.
func (*FailureLearner) Save ¶
func (fl *FailureLearner) Save() error
Save persists learnings to storage.
func (*FailureLearner) VerifyLearning ¶
func (fl *FailureLearner) VerifyLearning(learningID string)
VerifyLearning marks a learning as verified.
type FailureLearnerBuilder ¶
type FailureLearnerBuilder struct {
// contains filtered or unexported fields
}
FailureLearnerBuilder helps create FailureLearner configurations.
func NewFailureLearnerBuilder ¶
func NewFailureLearnerBuilder() *FailureLearnerBuilder
NewFailureLearnerBuilder creates a new builder.
func (*FailureLearnerBuilder) Build ¶
func (b *FailureLearnerBuilder) Build() *FailureLearner
Build creates the FailureLearner.
func (*FailureLearnerBuilder) WithEnabled ¶
func (b *FailureLearnerBuilder) WithEnabled(enabled bool) *FailureLearnerBuilder
WithEnabled sets whether learning is enabled.
func (*FailureLearnerBuilder) WithMaxLearnings ¶
func (b *FailureLearnerBuilder) WithMaxLearnings(max int) *FailureLearnerBuilder
WithMaxLearnings sets the maximum number of learnings.
func (*FailureLearnerBuilder) WithSmartRetry ¶
func (b *FailureLearnerBuilder) WithSmartRetry(sr *SmartRetry) *FailureLearnerBuilder
WithSmartRetry sets the SmartRetry integration.
func (*FailureLearnerBuilder) WithStoragePath ¶
func (b *FailureLearnerBuilder) WithStoragePath(path string) *FailureLearnerBuilder
WithStoragePath sets the storage path.
type FailureLearnerConfig ¶
type FailureLearnerConfig struct {
StoragePath string
Enabled bool
MaxLearnings int
SmartRetry *SmartRetry
}
FailureLearnerConfig configures the failure learner.
type FailureLearning ¶
type FailureLearning struct {
ID string `json:"id"`
Timestamp time.Time `json:"timestamp"`
TaskType string `json:"task_type"`
TaskID string `json:"task_id"`
ErrorMessage string `json:"error_message"`
ErrorHash string `json:"error_hash"`
Category ErrorCategory `json:"category"`
Context map[string]any `json:"context,omitempty"`
Solution string `json:"solution"`
SuccessRate float64 `json:"success_rate"`
Attempts int `json:"attempts"`
FilePatterns []string `json:"file_patterns,omitempty"`
Actions []LearningAction `json:"actions,omitempty"`
Verified bool `json:"verified"`
VerifiedAt time.Time `json:"verified_at,omitempty"`
}
FailureLearning represents a learned lesson from a failure.
type FailurePattern ¶
type FailurePattern struct {
Pattern string // Regex pattern to match in test output
Category string // "build_error", "test_failure", "race_condition", "timeout", "import_error"
FixHint string // Hint for the agent on how to fix
AutoFixable bool // Whether this can be auto-fixed
}
FailurePattern represents a known failure pattern and its fix suggestion.
func DefaultFailurePatterns ¶
func DefaultFailurePatterns() []FailurePattern
DefaultFailurePatterns returns the built-in failure pattern detection rules.
type FailureRecommendation ¶
type FailureRecommendation struct {
ErrorHash string
Category ErrorCategory
PatternID string
Confidence float64
AutoFixable bool
FixTemplate string
Suggestions []string
Actions []LearningAction
SimilarCases []*FailureLearning
}
FailureRecommendation contains recommendations for handling a failure.
type FileOperation ¶
type FileOperation struct {
Op string `json:"op"`
Path string `json:"path"`
Success bool `json:"success"`
Timestamp int64 `json:"timestamp"`
Error string `json:"error,omitempty"`
}
FileOperation records a file system operation.
type FileSystemIsolation ¶
type FileSystemIsolation struct {
// contains filtered or unexported fields
}
FileSystemIsolation provides controlled file system access through sandbox.
func NewFileSystemIsolation ¶
func NewFileSystemIsolation(sandbox *Sandbox, workspaceRoot string, config IsolationConfig) *FileSystemIsolation
NewFileSystemIsolation creates a new file system isolation manager.
func (*FileSystemIsolation) AddAllowedPath ¶
func (fsi *FileSystemIsolation) AddAllowedPath(path string)
AddAllowedPath adds a path to the allowed list.
func (*FileSystemIsolation) AddDeniedPattern ¶
func (fsi *FileSystemIsolation) AddDeniedPattern(pattern string)
AddDeniedPattern adds a pattern to the denied list.
func (*FileSystemIsolation) AddReadOnlyPath ¶
func (fsi *FileSystemIsolation) AddReadOnlyPath(path string)
AddReadOnlyPath adds a path to the read-only list.
func (*FileSystemIsolation) ClearAuditLog ¶
func (fsi *FileSystemIsolation) ClearAuditLog()
ClearAuditLog clears the audit log.
func (*FileSystemIsolation) DeleteFile ¶
func (fsi *FileSystemIsolation) DeleteFile(ctx context.Context, path string) error
DeleteFile deletes a file through the sandbox.
func (*FileSystemIsolation) GetAuditLog ¶
func (fsi *FileSystemIsolation) GetAuditLog() []FileOperation
GetAuditLog returns the audit log.
func (*FileSystemIsolation) MkDir ¶
func (fsi *FileSystemIsolation) MkDir(ctx context.Context, path string) error
MkDir creates a directory through the sandbox.
func (*FileSystemIsolation) Stat ¶
func (fsi *FileSystemIsolation) Stat(ctx context.Context, path string) (map[string]interface{}, error)
Stat returns file information through the sandbox.
func (*FileSystemIsolation) ValidatePath ¶
func (fsi *FileSystemIsolation) ValidatePath(path string, op string) error
ValidatePath checks if a path is allowed for the given operation.
type FixAction ¶
type FixAction struct {
Type FixActionType
Description string
Command string
FilePattern string
Template string
}
FixAction represents a potential fix to try.
type FixActionType ¶
type FixActionType string
FixActionType defines types of automated fixes.
const ( FixTypeImport FixActionType = "import" FixTypeFormat FixActionType = "format" FixTypeLint FixActionType = "lint" FixTypeRebuild FixActionType = "rebuild" FixTypeClean FixActionType = "clean" FixTypeWait FixActionType = "wait" FixTypeAlternative FixActionType = "alternative" )
type GoalPriority ¶
type GoalPriority int
GoalPriority represents the priority of a goal.
const ( GoalPriorityLow GoalPriority = iota GoalPriorityNormal GoalPriorityHigh GoalPriorityCritical )
type GoalState ¶
type GoalState struct {
ID string `json:"id"`
Name string `json:"name"`
Description string `json:"description"`
Priority GoalPriority `json:"priority"`
Status GoalStatus `json:"status"`
CreatedAt int64 `json:"created_at"`
UpdatedAt int64 `json:"updated_at"`
CompletedAt int64 `json:"completed_at,omitempty"`
// Goal definition
TargetState map[string]any `json:"target_state,omitempty"` // Desired state
SuccessCriteria []string `json:"success_criteria"` // Conditions for success
FailureConditions []string `json:"failure_conditions,omitempty"` // Conditions for failure
// Progress tracking
SubGoals []*GoalState `json:"sub_goals,omitempty"`
Progress float64 `json:"progress"` // 0.0 - 1.0
Milestones []Milestone `json:"milestones,omitempty"`
// Execution tracking
FilesModified []string `json:"files_modified,omitempty"`
CommandsRun []string `json:"commands_run,omitempty"`
Errors []string `json:"errors,omitempty"`
RetryCount int `json:"retry_count"`
MaxRetries int `json:"max_retries"`
// Dependencies
Dependencies []string `json:"dependencies,omitempty"` // Goal IDs this depends on
Blocks []string `json:"blocks,omitempty"` // Goal IDs that depend on this
// Metadata
Tags []string `json:"tags,omitempty"`
Metadata map[string]any `json:"metadata,omitempty"`
}
GoalState represents a desired end state for the autonomous agent.
type GoalStats ¶
type GoalStats struct {
Total int `json:"total"`
Pending int `json:"pending"`
InProgress int `json:"in_progress"`
Completed int `json:"completed"`
Failed int `json:"failed"`
Abandoned int `json:"abandoned"`
TotalProgress float64 `json:"total_progress"`
AverageProgress float64 `json:"average_progress"`
}
GoalStats holds statistics about goals.
type GoalStatus ¶
type GoalStatus string
GoalStatus represents the status of a goal.
const ( GoalStatusPending GoalStatus = "pending" GoalStatusInProgress GoalStatus = "in_progress" GoalStatusCompleted GoalStatus = "completed" GoalStatusFailed GoalStatus = "failed" GoalStatusAbandoned GoalStatus = "abandoned" )
type GoalTracker ¶
type GoalTracker struct {
// contains filtered or unexported fields
}
GoalTracker manages goal states for autonomous operations.
func NewGoalTracker ¶
func NewGoalTracker(config GoalTrackerConfig) *GoalTracker
NewGoalTracker creates a new goal tracker.
func (*GoalTracker) AbandonGoal ¶
func (gt *GoalTracker) AbandonGoal(goalID string, reason string) error
AbandonGoal marks a goal as abandoned.
func (*GoalTracker) AddFailureCondition ¶
func (gt *GoalTracker) AddFailureCondition(goalID string, condition string) error
AddFailureCondition adds a failure condition to a goal.
func (*GoalTracker) AddMilestone ¶
func (gt *GoalTracker) AddMilestone(goalID string, name string, description string) (*Milestone, error)
AddMilestone adds a milestone to a goal.
func (*GoalTracker) AddSubGoal ¶
func (gt *GoalTracker) AddSubGoal(parentID string, subGoal *GoalState) error
AddSubGoal adds a sub-goal to a parent goal.
func (*GoalTracker) AddSuccessCriterion ¶
func (gt *GoalTracker) AddSuccessCriterion(goalID string, criterion string) error
AddSuccessCriterion adds a success criterion to a goal.
func (*GoalTracker) CanStart ¶
func (gt *GoalTracker) CanStart(goalID string) (bool, error)
CanStart checks if a goal can be started (all dependencies completed).
func (*GoalTracker) CheckFailureConditions ¶
func (gt *GoalTracker) CheckFailureConditions(goalID string, evaluator func(condition string) (bool, error)) (bool, error)
CheckFailureConditions evaluates if any failure conditions are met.
func (*GoalTracker) CheckSuccessCriteria ¶
func (gt *GoalTracker) CheckSuccessCriteria(goalID string, evaluator func(criterion string) (bool, error)) (bool, error)
CheckSuccessCriteria evaluates if all success criteria are met.
func (*GoalTracker) CompleteGoal ¶
func (gt *GoalTracker) CompleteGoal(goalID string) error
CompleteGoal marks a goal as completed.
func (*GoalTracker) CompleteMilestone ¶
func (gt *GoalTracker) CompleteMilestone(goalID string, milestoneID string) error
CompleteMilestone marks a milestone as completed.
func (*GoalTracker) CreateGoal ¶
func (gt *GoalTracker) CreateGoal(name string, description string, priority GoalPriority) *GoalState
CreateGoal creates a new goal.
func (*GoalTracker) FailGoal ¶
func (gt *GoalTracker) FailGoal(goalID string, reason string) error
FailGoal marks a goal as failed.
func (*GoalTracker) GetActiveGoal ¶
func (gt *GoalTracker) GetActiveGoal() *GoalState
GetActiveGoal returns the current active goal.
func (*GoalTracker) GetAllGoals ¶
func (gt *GoalTracker) GetAllGoals() []*GoalState
GetAllGoals returns all goals.
func (*GoalTracker) GetGoal ¶
func (gt *GoalTracker) GetGoal(goalID string) *GoalState
GetGoal returns a goal by ID.
func (*GoalTracker) GetHistory ¶
func (gt *GoalTracker) GetHistory() []*GoalState
GetHistory returns the goal history.
func (*GoalTracker) GetInProgressGoals ¶
func (gt *GoalTracker) GetInProgressGoals() []*GoalState
GetInProgressGoals returns all in-progress goals.
func (*GoalTracker) GetPendingGoals ¶
func (gt *GoalTracker) GetPendingGoals() []*GoalState
GetPendingGoals returns all pending goals.
func (*GoalTracker) GetStats ¶
func (gt *GoalTracker) GetStats() GoalStats
GetStats returns goal statistics.
func (*GoalTracker) RecordCommand ¶
func (gt *GoalTracker) RecordCommand(goalID string, command string) error
RecordCommand records a command execution for a goal.
func (*GoalTracker) RecordError ¶
func (gt *GoalTracker) RecordError(goalID string, errMsg string) error
RecordError records an error for a goal.
func (*GoalTracker) RecordFileModification ¶
func (gt *GoalTracker) RecordFileModification(goalID string, filePath string) error
RecordFileModification records a file modification for a goal.
func (*GoalTracker) SetActiveGoal ¶
func (gt *GoalTracker) SetActiveGoal(goalID string) error
SetActiveGoal sets the current active goal.
func (*GoalTracker) SetDependency ¶
func (gt *GoalTracker) SetDependency(goalID string, dependsOnGoalID string) error
SetDependency sets a dependency between goals.
func (*GoalTracker) SetProgress ¶
func (gt *GoalTracker) SetProgress(goalID string, progress float64) error
SetProgress manually sets the progress of a goal.
func (*GoalTracker) SetTargetState ¶
func (gt *GoalTracker) SetTargetState(goalID string, key string, value any) error
SetTargetState sets the target state for a goal.
type GoalTrackerConfig ¶
type GoalTrackerConfig struct {
MaxRetries int `json:"max_retries"`
}
GoalTrackerConfig holds configuration for the goal tracker.
func DefaultGoalTrackerConfig ¶
func DefaultGoalTrackerConfig() GoalTrackerConfig
DefaultGoalTrackerConfig returns sensible defaults.
type HumanInLoopConfig ¶
type HumanInLoopConfig struct {
Enabled bool `json:"enabled"`
DefaultTimeout time.Duration `json:"default_timeout"`
MaxPendingRequests int `json:"max_pending_requests"`
AutoApproveLowRisk bool `json:"auto_approve_low_risk"`
LowRiskThreshold float64 `json:"low_risk_threshold"`
NotifyOnRequest bool `json:"notify_on_request"`
NotificationChannels []string `json:"notification_channels"`
}
HumanInLoopConfig holds configuration for the human-in-loop system
func DefaultHumanInLoopConfig ¶
func DefaultHumanInLoopConfig() HumanInLoopConfig
DefaultHumanInLoopConfig returns default configuration
type HumanInLoopManager ¶
type HumanInLoopManager struct {
// contains filtered or unexported fields
}
HumanInLoopManager manages human-in-loop interactions
func NewHumanInLoopManager ¶
func NewHumanInLoopManager(config HumanInLoopConfig) *HumanInLoopManager
NewHumanInLoopManager creates a new human-in-loop manager
func (*HumanInLoopManager) AddTrigger ¶
func (m *HumanInLoopManager) AddTrigger(trigger *HumanInLoopTrigger)
AddTrigger adds a new trigger to the manager
func (*HumanInLoopManager) EnableTrigger ¶
func (m *HumanInLoopManager) EnableTrigger(id string, enabled bool) bool
EnableTrigger enables or disables a trigger by ID
func (*HumanInLoopManager) GetHistory ¶
func (m *HumanInLoopManager) GetHistory() []*DecisionResponse
GetHistory returns the decision response history
func (*HumanInLoopManager) GetPendingRequests ¶
func (m *HumanInLoopManager) GetPendingRequests() []*DecisionRequest
GetPendingRequests returns all pending decision requests
func (*HumanInLoopManager) GetStats ¶
func (m *HumanInLoopManager) GetStats() map[string]any
GetStats returns statistics about the human-in-loop system
func (*HumanInLoopManager) GetTriggers ¶
func (m *HumanInLoopManager) GetTriggers() []*HumanInLoopTrigger
GetTriggers returns all configured triggers
func (*HumanInLoopManager) RemoveTrigger ¶
func (m *HumanInLoopManager) RemoveTrigger(id string) bool
RemoveTrigger removes a trigger by ID
func (*HumanInLoopManager) RequestDecision ¶
func (m *HumanInLoopManager) RequestDecision(ctx context.Context, request *DecisionRequest) (*DecisionResponse, error)
RequestDecision creates a new decision request and waits for response
func (*HumanInLoopManager) RespondToDecision ¶
func (m *HumanInLoopManager) RespondToDecision(response *DecisionResponse) error
RespondToDecision submits a decision response
func (*HumanInLoopManager) SetConfidenceCheck ¶
func (m *HumanInLoopManager) SetConfidenceCheck(fn func(confidence float64, context map[string]any) bool)
SetConfidenceCheck sets a custom confidence check function
func (*HumanInLoopManager) ShouldTrigger ¶
func (m *HumanInLoopManager) ShouldTrigger(decisionType DecisionType, confidence float64, context map[string]any) bool
ShouldTrigger checks if a decision should trigger human input
type HumanInLoopTrigger ¶
type HumanInLoopTrigger struct {
ID string `json:"id"`
Name string `json:"name"`
Enabled bool `json:"enabled"`
Condition TriggerCondition `json:"condition"`
Action TriggerAction `json:"action"`
Priority int `json:"priority"` // Higher = checked first
CreatedAt time.Time `json:"created_at"`
UpdatedAt time.Time `json:"updated_at"`
}
HumanInLoopTrigger represents a configured trigger
type InstanceStatus ¶
type InstanceStatus string
InstanceStatus represents the status of a playbook instance
const ( InstanceStatusPending InstanceStatus = "pending" InstanceStatusRunning InstanceStatus = "running" InstanceStatusCompleted InstanceStatus = "completed" InstanceStatusFailed InstanceStatus = "failed" InstanceStatusCancelled InstanceStatus = "cancelled" )
type InterruptContext ¶
type InterruptContext struct {
// contains filtered or unexported fields
}
InterruptContext provides interrupt handling for autonomous operations.
func NewInterruptContext ¶
func NewInterruptContext() *InterruptContext
NewInterruptContext creates a new interrupt context.
func (*InterruptContext) GetCheckpoint ¶
func (ic *InterruptContext) GetCheckpoint() *Checkpoint
GetCheckpoint returns the saved checkpoint.
func (*InterruptContext) Interrupt ¶
func (ic *InterruptContext) Interrupt(reason string)
Interrupt signals an interruption request.
func (*InterruptContext) IsInterrupted ¶
func (ic *InterruptContext) IsInterrupted() bool
IsInterrupted checks if an interruption was requested.
func (*InterruptContext) Reason ¶
func (ic *InterruptContext) Reason() string
Reason returns the interruption reason.
func (*InterruptContext) SetCancelFunc ¶
func (ic *InterruptContext) SetCancelFunc(cancel context.CancelFunc)
SetCancelFunc sets the context cancel function.
func (*InterruptContext) SetCheckpoint ¶
func (ic *InterruptContext) SetCheckpoint(cp *Checkpoint)
SetCheckpoint saves a checkpoint during interruption.
type IsolationConfig ¶
type IsolationConfig struct {
AllowedPaths []string `json:"allowed_paths"`
ReadOnlyPaths []string `json:"read_only_paths"`
DeniedPatterns []string `json:"denied_patterns"`
EnableAudit bool `json:"enable_audit"`
}
IsolationConfig configures file system isolation.
func DefaultIsolationConfig ¶
func DefaultIsolationConfig() IsolationConfig
DefaultIsolationConfig returns a secure default configuration.
type LearnedPattern ¶
type LearnedPattern struct {
ID string `json:"id"`
Pattern string `json:"pattern"` // Regex pattern
Description string `json:"description"`
Category ErrorCategory `json:"category"`
OccurrenceCount int `json:"occurrence_count"`
SuccessActions []string `json:"success_actions"` // Actions that worked
FailActions []string `json:"fail_actions"` // Actions that didn't work
AutoFixable bool `json:"auto_fixable"`
FixTemplate string `json:"fix_template,omitempty"`
Confidence float64 `json:"confidence"`
LastSeen time.Time `json:"last_seen"`
}
LearnedPattern represents a pattern extracted from multiple failures.
type LearnerStats ¶
type LearnerStats struct {
TotalFailures int `json:"total_failures"`
TotalLearnings int `json:"total_learnings"`
PatternsLearned int `json:"patterns_learned"`
SuccessfulApplies int `json:"successful_applies"`
FailedApplies int `json:"failed_applies"`
ByCategory map[ErrorCategory]int `json:"by_category"`
ByTaskType map[string]int `json:"by_task_type"`
LastLearning time.Time `json:"last_learning"`
}
LearnerStats tracks overall learning statistics.
type LearningAction ¶
type LearningAction struct {
Type string `json:"type"` // "code_change", "config_change", "retry", "skip", "alternative"
Description string `json:"description"`
Command string `json:"command,omitempty"`
File string `json:"file,omitempty"`
Success bool `json:"success"`
}
LearningAction represents an action taken to resolve a failure.
type LimitEnforcer ¶
type LimitEnforcer struct {
// contains filtered or unexported fields
}
LimitEnforcer enforces resource limits during operations.
func NewLimitEnforcer ¶
func NewLimitEnforcer(limits ResourceLimits) *LimitEnforcer
NewLimitEnforcer creates a new limit enforcer.
func (*LimitEnforcer) AddCost ¶
func (le *LimitEnforcer) AddCost(cost float64) *LimitViolation
AddCost adds to the total cost.
func (*LimitEnforcer) AddTokens ¶
func (le *LimitEnforcer) AddTokens(count int64) *LimitViolation
AddTokens adds to the token counter.
func (*LimitEnforcer) CanPerform ¶
func (le *LimitEnforcer) CanPerform(opType string) bool
CanPerform checks if an operation can be performed without violating limits.
func (*LimitEnforcer) CheckAll ¶
func (le *LimitEnforcer) CheckAll() []*LimitViolation
CheckAll performs all limit checks.
func (*LimitEnforcer) CheckDuration ¶
func (le *LimitEnforcer) CheckDuration() *LimitViolation
CheckDuration checks if total duration limit has been exceeded.
func (*LimitEnforcer) CheckIdle ¶
func (le *LimitEnforcer) CheckIdle() *LimitViolation
CheckIdle checks if the operation has been idle too long.
func (*LimitEnforcer) CheckMemory ¶
func (le *LimitEnforcer) CheckMemory() *LimitViolation
CheckMemory checks current memory usage against limits.
func (*LimitEnforcer) CheckTurnLimit ¶
func (le *LimitEnforcer) CheckTurnLimit() *LimitViolation
CheckTurnLimit checks if the turn limit has been reached.
func (*LimitEnforcer) Context ¶
func (le *LimitEnforcer) Context(parent context.Context) (context.Context, context.CancelFunc)
Context creates a context with timeout based on limits.
func (*LimitEnforcer) GetLimits ¶
func (le *LimitEnforcer) GetLimits() ResourceLimits
GetLimits returns current limits.
func (*LimitEnforcer) GetRemaining ¶
func (le *LimitEnforcer) GetRemaining() ResourceLimits
GetRemaining returns remaining resources.
func (*LimitEnforcer) GetUsage ¶
func (le *LimitEnforcer) GetUsage() ResourceUsage
GetUsage returns current resource usage.
func (*LimitEnforcer) GetViolation ¶
func (le *LimitEnforcer) GetViolation() *LimitViolation
GetViolation returns the most recent violation.
func (*LimitEnforcer) IncrementAPICall ¶
func (le *LimitEnforcer) IncrementAPICall() *LimitViolation
IncrementAPICall increments the API call counter.
func (*LimitEnforcer) IncrementCommand ¶
func (le *LimitEnforcer) IncrementCommand() *LimitViolation
IncrementCommand increments the command counter.
func (*LimitEnforcer) IncrementFileRead ¶
func (le *LimitEnforcer) IncrementFileRead() *LimitViolation
IncrementFileRead increments the file read counter.
func (*LimitEnforcer) IncrementFileWrite ¶
func (le *LimitEnforcer) IncrementFileWrite() *LimitViolation
IncrementFileWrite increments the file write counter.
func (*LimitEnforcer) IncrementRetry ¶
func (le *LimitEnforcer) IncrementRetry() *LimitViolation
IncrementRetry increments the retry counter and checks limits.
func (*LimitEnforcer) IncrementTurn ¶
func (le *LimitEnforcer) IncrementTurn() *LimitViolation
IncrementTurn increments the turn counter and checks limits.
func (*LimitEnforcer) IsViolated ¶
func (le *LimitEnforcer) IsViolated() bool
IsViolated returns true if any limit has been violated.
func (*LimitEnforcer) PercentUsed ¶
func (le *LimitEnforcer) PercentUsed() map[string]float64
PercentUsed returns the percentage of each resource used.
func (*LimitEnforcer) SetLimits ¶
func (le *LimitEnforcer) SetLimits(limits ResourceLimits)
SetLimits updates the limits.
func (*LimitEnforcer) SetLogger ¶
func (le *LimitEnforcer) SetLogger(logger interface { Info(msg string, args ...any) Warn(msg string, args ...any) })
SetLogger sets the logger for the enforcer.
func (*LimitEnforcer) SetOnViolation ¶
func (le *LimitEnforcer) SetOnViolation(callback func(*LimitViolation))
SetOnViolation sets the callback for limit violations.
func (*LimitEnforcer) SetOnWarning ¶
func (le *LimitEnforcer) SetOnWarning(callback func(string))
SetOnWarning sets the callback for warnings.
func (*LimitEnforcer) Summary ¶
func (le *LimitEnforcer) Summary() string
Summary returns a human-readable summary of resource usage.
func (*LimitEnforcer) TurnContext ¶
func (le *LimitEnforcer) TurnContext(parent context.Context) (context.Context, context.CancelFunc)
TurnContext creates a context for a single turn.
func (*LimitEnforcer) UpdateActivity ¶
func (le *LimitEnforcer) UpdateActivity()
UpdateActivity updates the last activity timestamp.
type LimitViolation ¶
type LimitViolation struct {
Type string // "timeout", "turns", "memory", "tokens", "cost", etc.
Limit interface{} // The limit that was exceeded
Actual interface{} // The actual value
Message string // Human-readable message
Timestamp time.Time // When it occurred
Recoverable bool // Whether operation can continue
}
LimitViolation represents a limit breach.
type Milestone ¶
type Milestone struct {
ID string `json:"id"`
Name string `json:"name"`
Description string `json:"description"`
Completed bool `json:"completed"`
CompletedAt int64 `json:"completed_at,omitempty"`
}
Milestone represents a checkpoint in goal progress.
type NetworkIsolation ¶
type NetworkIsolation struct {
// contains filtered or unexported fields
}
NetworkIsolation manages network settings for the sandbox.
func NewNetworkIsolation ¶
func NewNetworkIsolation(config NetworkIsolationConfig) *NetworkIsolation
NewNetworkIsolation creates a new network isolation manager.
func (*NetworkIsolation) AddPortMapping ¶
func (ni *NetworkIsolation) AddPortMapping(mapping PortMapping)
AddPortMapping adds a port mapping.
func (*NetworkIsolation) BuildDockerArgs ¶
func (ni *NetworkIsolation) BuildDockerArgs() []string
BuildDockerArgs builds Docker arguments for network configuration.
func (*NetworkIsolation) CreateInternalNetwork ¶
func (ni *NetworkIsolation) CreateInternalNetwork(ctx context.Context, name string) error
CreateInternalNetwork creates a Docker internal network.
func (*NetworkIsolation) GetMode ¶
func (ni *NetworkIsolation) GetMode() NetworkMode
GetMode returns the current network mode.
func (*NetworkIsolation) GetNetworkStats ¶
func (ni *NetworkIsolation) GetNetworkStats(ctx context.Context, containerID string) (map[string]interface{}, error)
GetNetworkStats returns network statistics.
func (*NetworkIsolation) GetPolicy ¶
func (ni *NetworkIsolation) GetPolicy() NetworkPolicy
GetPolicy returns the current network policy.
func (*NetworkIsolation) GetPortMappings ¶
func (ni *NetworkIsolation) GetPortMappings() []PortMapping
GetPortMappings returns all port mappings.
func (*NetworkIsolation) RemoveNetwork ¶
func (ni *NetworkIsolation) RemoveNetwork(ctx context.Context) error
RemoveNetwork removes a Docker network.
func (*NetworkIsolation) RemovePortMapping ¶
func (ni *NetworkIsolation) RemovePortMapping(hostPort int)
RemovePortMapping removes a port mapping.
func (*NetworkIsolation) SetDNSConfig ¶
func (ni *NetworkIsolation) SetDNSConfig(config *DNSConfig)
SetDNSConfig sets the DNS configuration.
func (*NetworkIsolation) SetMode ¶
func (ni *NetworkIsolation) SetMode(mode NetworkMode)
SetMode sets the network mode.
func (*NetworkIsolation) SetPolicy ¶
func (ni *NetworkIsolation) SetPolicy(policy NetworkPolicy)
SetPolicy sets the network policy.
func (*NetworkIsolation) TestConnectivity ¶
func (ni *NetworkIsolation) TestConnectivity(ctx context.Context, sandbox *Sandbox, host string, port int) (bool, error)
TestConnectivity tests network connectivity from inside the sandbox.
func (*NetworkIsolation) ValidateConnection ¶
func (ni *NetworkIsolation) ValidateConnection(host string, port int) error
ValidateConnection checks if a connection is allowed by the policy.
type NetworkIsolationBuilder ¶
type NetworkIsolationBuilder struct {
// contains filtered or unexported fields
}
NetworkIsolationBuilder helps create NetworkIsolation configurations.
func NewNetworkIsolationBuilder ¶
func NewNetworkIsolationBuilder() *NetworkIsolationBuilder
NewNetworkIsolationBuilder creates a new builder.
func (*NetworkIsolationBuilder) Build ¶
func (b *NetworkIsolationBuilder) Build() *NetworkIsolation
Build creates the NetworkIsolation.
func (*NetworkIsolationBuilder) BuildConfig ¶
func (b *NetworkIsolationBuilder) BuildConfig() NetworkIsolationConfig
BuildConfig returns the configuration.
func (*NetworkIsolationBuilder) WithCustomNetwork ¶
func (b *NetworkIsolationBuilder) WithCustomNetwork(network string) *NetworkIsolationBuilder
WithCustomNetwork sets a custom Docker network.
func (*NetworkIsolationBuilder) WithDNS ¶
func (b *NetworkIsolationBuilder) WithDNS(servers []string) *NetworkIsolationBuilder
WithDNS sets DNS servers.
func (*NetworkIsolationBuilder) WithMode ¶
func (b *NetworkIsolationBuilder) WithMode(mode NetworkMode) *NetworkIsolationBuilder
WithMode sets the network mode.
func (*NetworkIsolationBuilder) WithPolicy ¶
func (b *NetworkIsolationBuilder) WithPolicy(policy NetworkPolicy) *NetworkIsolationBuilder
WithPolicy sets the network policy.
func (*NetworkIsolationBuilder) WithPortMapping ¶
func (b *NetworkIsolationBuilder) WithPortMapping(hostPort, containerPort int, protocol string) *NetworkIsolationBuilder
WithPortMapping adds a port mapping.
func (*NetworkIsolationBuilder) WithProfile ¶
func (b *NetworkIsolationBuilder) WithProfile(profileName string) *NetworkIsolationBuilder
WithProfile applies a predefined profile.
type NetworkIsolationConfig ¶
type NetworkIsolationConfig struct {
Mode NetworkMode `json:"mode"`
Policy NetworkPolicy `json:"policy"`
PortMappings []PortMapping `json:"port_mappings"`
DNSConfig *DNSConfig `json:"dns_config"`
CustomNetwork string `json:"custom_network"`
}
NetworkIsolationConfig configures network isolation.
type NetworkMode ¶
type NetworkMode string
NetworkMode defines the network isolation level for the sandbox.
const ( // NetworkModeNone - No network access (most secure) NetworkModeNone NetworkMode = "none" // NetworkModeInternal - Internal network only (can communicate with other containers) NetworkModeInternal NetworkMode = "internal" // NetworkModeBridge - Bridge network with controlled outbound access NetworkModeBridge NetworkMode = "bridge" // NetworkModeHost - Full host network access (least secure) NetworkModeHost NetworkMode = "host" )
type NetworkPolicy ¶
type NetworkPolicy struct {
// AllowedHosts is a list of hosts that can be accessed
AllowedHosts []string `json:"allowed_hosts"`
// BlockedHosts is a list of hosts that are explicitly blocked
BlockedHosts []string `json:"blocked_hosts"`
// AllowedPorts is a list of ports that can be accessed
AllowedPorts []int `json:"allowed_ports"`
// BlockedPorts is a list of ports that are explicitly blocked
BlockedPorts []int `json:"blocked_ports"`
// AllowDNS allows DNS resolution
AllowDNS bool `json:"allow_dns"`
// AllowHTTP allows HTTP (port 80)
AllowHTTP bool `json:"allow_http"`
// AllowHTTPS allows HTTPS (port 443)
AllowHTTPS bool `json:"allow_https"`
// AllowOutbound allows all outbound traffic
AllowOutbound bool `json:"allow_outbound"`
// AllowInbound allows inbound connections
AllowInbound bool `json:"allow_inbound"`
}
NetworkPolicy defines traffic rules for the sandbox.
func DefaultNetworkPolicy ¶
func DefaultNetworkPolicy() NetworkPolicy
DefaultNetworkPolicy returns a secure default network policy.
func DevelopmentNetworkPolicy ¶
func DevelopmentNetworkPolicy() NetworkPolicy
DevelopmentNetworkPolicy returns a policy suitable for development.
func PermissiveNetworkPolicy ¶
func PermissiveNetworkPolicy() NetworkPolicy
PermissiveNetworkPolicy returns a permissive network policy.
func StrictNetworkPolicy ¶
func StrictNetworkPolicy() NetworkPolicy
StrictNetworkPolicy returns a strict network policy (no network access).
type NetworkProfile ¶
type NetworkProfile struct {
Name string `json:"name"`
Description string `json:"description"`
Mode NetworkMode `json:"mode"`
Policy NetworkPolicy `json:"policy"`
}
NetworkProfile represents a predefined network configuration.
func GetNetworkProfile ¶
func GetNetworkProfile(name string) (NetworkProfile, bool)
GetNetworkProfile returns a predefined network profile.
type NetworkSafetySettings ¶
type NetworkSafetySettings struct {
// Enabled allows network operations
Enabled bool `json:"enabled"`
// AllowedHosts are hosts that can be accessed
AllowedHosts []string `json:"allowed_hosts"`
// BlockedHosts are hosts that cannot be accessed
BlockedHosts []string `json:"blocked_hosts"`
// AllowedPorts are ports that can be used
AllowedPorts []int `json:"allowed_ports"`
// RequireApprovalForExternal requires approval for external network access
RequireApprovalForExternal bool `json:"require_approval_for_external"`
// MaxConnections is the maximum concurrent connections
MaxConnections int `json:"max_connections"`
// Timeout is the network operation timeout
Timeout time.Duration `json:"timeout"`
}
NetworkSafetySettings controls network access.
type NodeStatus ¶
type NodeStatus string
NodeStatus represents the execution status of a plan node.
const ( StatusPending NodeStatus = "pending" StatusReady NodeStatus = "ready" // All dependencies met StatusRunning NodeStatus = "running" StatusCompleted NodeStatus = "completed" StatusFailed NodeStatus = "failed" StatusSkipped NodeStatus = "skipped" StatusBlocked NodeStatus = "blocked" // Dependencies failed )
type OperationType ¶
type OperationType string
OperationType represents the type of operation being reviewed.
const ( OperationFileDelete OperationType = "file_delete" OperationFileOverwrite OperationType = "file_overwrite" OperationGitForcePush OperationType = "git_force_push" OperationGitResetHard OperationType = "git_reset_hard" OperationDatabaseDrop OperationType = "database_drop" OperationDatabaseTruncate OperationType = "database_truncate" OperationSystemCommand OperationType = "system_command" OperationNetworkRequest OperationType = "network_request" OperationConfigChange OperationType = "config_change" OperationDependencyChange OperationType = "dependency_change" )
type PatternStats ¶
type PatternStats struct {
PatternID string
TotalSeen int
TotalFixed int
TotalFailed int
AvgAttempts float64
LastFixed time.Time
FixActions map[string]int // fix description -> success count
}
PatternStats tracks statistics for a pattern.
type PermissionError ¶
type PermissionError struct {
Path string `json:"path"`
ExpectedMode uint32 `json:"expected_mode"`
ActualMode uint32 `json:"actual_mode"`
}
PermissionError represents a permission verification failure.
type PlanNode ¶
type PlanNode struct {
Step PlanStep
ID int
Dependencies []int
Status NodeStatus
Priority int
}
PlanNode wraps a PlanStep with dependency and status information.
type PlanStatus ¶
type PlanStatus string
PlanStatus represents the overall status of a plan.
const ( PlanStatusEmpty PlanStatus = "empty" PlanStatusPending PlanStatus = "pending" PlanStatusRunning PlanStatus = "running" PlanStatusCompleted PlanStatus = "completed" PlanStatusFailed PlanStatus = "failed" PlanStatusPartialFailure PlanStatus = "partial_failure" )
type Planner ¶
type Planner struct {
// contains filtered or unexported fields
}
Planner manages multi-step plans with dependency resolution.
func NewPlanner ¶
NewPlanner creates a new planner instance.
func (*Planner) BuildPlanFromSteps ¶
BuildPlanFromSteps creates a plan with dependency analysis from steps.
func (*Planner) ExecutePlan ¶
ExecutePlan executes all steps respecting dependencies.
func (*Planner) GetExecutionOrder ¶
GetExecutionOrder returns steps in topological order (dependencies first).
func (*Planner) GetParallelGroups ¶
GetParallelGroups returns groups of steps that can be executed in parallel.
func (*Planner) GetReadySteps ¶
GetReadySteps returns all steps that are ready to execute (dependencies met).
func (*Planner) GetStatus ¶
func (p *Planner) GetStatus() PlanStatus
GetStatus returns the overall status of the plan.
func (*Planner) MarkStepStatus ¶
func (p *Planner) MarkStepStatus(stepID int, status NodeStatus) error
MarkStepStatus updates the status of a step and handles cascading effects.
type Playbook ¶
type Playbook struct {
ID string `json:"id"`
Name string `json:"name"`
Type PlaybookType `json:"type"`
Description string `json:"description"`
Version string `json:"version"`
Author string `json:"author"`
CreatedAt time.Time `json:"created_at"`
UpdatedAt time.Time `json:"updated_at"`
Steps []PlaybookStep `json:"steps"`
SuccessCriteria []string `json:"success_criteria"`
Triggers PlaybookTrigger `json:"triggers"`
Variables map[string]string `json:"variables"` // Default variable values
Metadata map[string]any `json:"metadata"`
Tags []string `json:"tags"`
Enabled bool `json:"enabled"`
}
Playbook represents a reusable task template
type PlaybookBuilder ¶
type PlaybookBuilder struct {
// contains filtered or unexported fields
}
PlaybookBuilder helps create custom playbooks
func NewPlaybookBuilder ¶
func NewPlaybookBuilder(id, name string, playbookType PlaybookType) *PlaybookBuilder
NewPlaybookBuilder creates a new playbook builder
func (*PlaybookBuilder) AddStep ¶
func (b *PlaybookBuilder) AddStep(stepType, action, target string, required bool) *PlaybookBuilder
AddStep adds a step to the playbook
func (*PlaybookBuilder) AddSuccessCriteria ¶
func (b *PlaybookBuilder) AddSuccessCriteria(criteria string) *PlaybookBuilder
AddSuccessCriteria adds success criteria
func (*PlaybookBuilder) AddTag ¶
func (b *PlaybookBuilder) AddTag(tag string) *PlaybookBuilder
AddTag adds a tag
func (*PlaybookBuilder) AddTriggerKeywords ¶
func (b *PlaybookBuilder) AddTriggerKeywords(keywords ...string) *PlaybookBuilder
AddTriggerKeywords adds trigger keywords
func (*PlaybookBuilder) AddTriggerPatterns ¶
func (b *PlaybookBuilder) AddTriggerPatterns(patterns ...string) *PlaybookBuilder
AddTriggerPatterns adds trigger regex patterns
func (*PlaybookBuilder) AddVariable ¶
func (b *PlaybookBuilder) AddVariable(key, value string) *PlaybookBuilder
AddVariable adds a default variable
func (*PlaybookBuilder) Build ¶
func (b *PlaybookBuilder) Build() *Playbook
Build returns the built playbook
func (*PlaybookBuilder) SetEnabled ¶
func (b *PlaybookBuilder) SetEnabled(enabled bool) *PlaybookBuilder
SetEnabled sets the enabled status
func (*PlaybookBuilder) SetTriggerPriority ¶
func (b *PlaybookBuilder) SetTriggerPriority(priority int) *PlaybookBuilder
SetTriggerPriority sets the trigger priority
func (*PlaybookBuilder) WithAuthor ¶
func (b *PlaybookBuilder) WithAuthor(author string) *PlaybookBuilder
WithAuthor sets the author
func (*PlaybookBuilder) WithDescription ¶
func (b *PlaybookBuilder) WithDescription(desc string) *PlaybookBuilder
WithDescription sets the description
func (*PlaybookBuilder) WithVersion ¶
func (b *PlaybookBuilder) WithVersion(version string) *PlaybookBuilder
WithVersion sets the version
type PlaybookInstance ¶
type PlaybookInstance struct {
Playbook *Playbook
Variables map[string]string
Steps []ResolvedStep
CreatedAt time.Time
Status InstanceStatus
CurrentStep int
}
PlaybookInstance represents a concrete instance of a playbook with resolved variables
func NewPlaybookInstance ¶
func NewPlaybookInstance(playbook *Playbook, variables map[string]string) *PlaybookInstance
NewPlaybookInstance creates a new instance from a playbook
func (*PlaybookInstance) AdvanceStep ¶
func (pi *PlaybookInstance) AdvanceStep() bool
AdvanceStep moves to the next step
func (*PlaybookInstance) GetCurrentStep ¶
func (pi *PlaybookInstance) GetCurrentStep() *ResolvedStep
GetCurrentStep returns the current step
func (*PlaybookInstance) GetProgress ¶
func (pi *PlaybookInstance) GetProgress() float64
GetProgress returns the completion percentage
func (*PlaybookInstance) GetSummary ¶
func (pi *PlaybookInstance) GetSummary() string
GetSummary returns a summary of the instance execution
func (*PlaybookInstance) IsComplete ¶
func (pi *PlaybookInstance) IsComplete() bool
IsComplete returns true if the instance has completed all steps
func (*PlaybookInstance) IsFailed ¶
func (pi *PlaybookInstance) IsFailed() bool
IsFailed returns true if the instance has failed
func (*PlaybookInstance) MarkStepCompleted ¶
func (pi *PlaybookInstance) MarkStepCompleted(output string)
MarkStepCompleted marks the current step as completed
func (*PlaybookInstance) MarkStepFailed ¶
func (pi *PlaybookInstance) MarkStepFailed(err error)
MarkStepFailed marks the current step as failed
func (*PlaybookInstance) MarkStepSkipped ¶
func (pi *PlaybookInstance) MarkStepSkipped(reason string)
MarkStepSkipped marks the current step as skipped
func (*PlaybookInstance) Start ¶
func (pi *PlaybookInstance) Start()
Start begins execution of the playbook instance
type PlaybookRegistry ¶
type PlaybookRegistry struct {
// contains filtered or unexported fields
}
PlaybookRegistry manages all available playbooks
func NewPlaybookRegistry ¶
func NewPlaybookRegistry() *PlaybookRegistry
NewPlaybookRegistry creates a new playbook registry
func (*PlaybookRegistry) Disable ¶
func (r *PlaybookRegistry) Disable(id string) error
Disable disables a playbook
func (*PlaybookRegistry) Enable ¶
func (r *PlaybookRegistry) Enable(id string) error
Enable enables a playbook
func (*PlaybookRegistry) Get ¶
func (r *PlaybookRegistry) Get(id string) (*Playbook, error)
Get retrieves a playbook by ID
func (*PlaybookRegistry) GetByType ¶
func (r *PlaybookRegistry) GetByType(playbookType PlaybookType) []*Playbook
GetByType retrieves all playbooks of a given type
func (*PlaybookRegistry) GetStats ¶
func (r *PlaybookRegistry) GetStats() map[string]any
GetStats returns statistics about the registry
func (*PlaybookRegistry) InstantiatePlaybook ¶
func (r *PlaybookRegistry) InstantiatePlaybook(ctx context.Context, playbookID string, variables map[string]string) (*PlaybookInstance, error)
InstantiatePlaybook creates a concrete execution plan from a playbook
func (*PlaybookRegistry) List ¶
func (r *PlaybookRegistry) List() []*Playbook
List returns all registered playbooks
func (*PlaybookRegistry) ListEnabled ¶
func (r *PlaybookRegistry) ListEnabled() []*Playbook
ListEnabled returns all enabled playbooks
func (*PlaybookRegistry) Match ¶
func (r *PlaybookRegistry) Match(taskDescription string) *Playbook
Match finds the best matching playbook for a task description
func (*PlaybookRegistry) MatchAll ¶
func (r *PlaybookRegistry) MatchAll(taskDescription string) []*Playbook
MatchAll returns all matching playbooks sorted by relevance
func (*PlaybookRegistry) Register ¶
func (r *PlaybookRegistry) Register(playbook *Playbook) error
Register adds a playbook to the registry
func (*PlaybookRegistry) SetLogger ¶
func (r *PlaybookRegistry) SetLogger(logger interface { Info(msg string, args ...any) Warn(msg string, args ...any) Error(msg string, args ...any) })
SetLogger sets the logger for the registry
func (*PlaybookRegistry) Unregister ¶
func (r *PlaybookRegistry) Unregister(id string)
Unregister removes a playbook from the registry
type PlaybookStep ¶
type PlaybookStep struct {
ID string `json:"id"`
Order int `json:"order"`
Type string `json:"type"` // "read", "write", "test", "build", "command"
Action string `json:"action"` // Action description template
Target string `json:"target"` // Target template (file, command, etc.)
Required bool `json:"required"` // Must succeed for playbook success
Timeout time.Duration `json:"timeout"`
RetryCount int `json:"retry_count"`
Variables map[string]string `json:"variables"` // Variables to substitute
Conditions []string `json:"conditions"` // Conditions to execute this step
OnFailure string `json:"on_failure"` // "abort", "skip", "retry", "continue"
}
PlaybookStep represents a single step in a playbook
type PlaybookStepStatus ¶
type PlaybookStepStatus string
PlaybookStepStatus represents the status of a step
const ( PlaybookStepStatusPending PlaybookStepStatus = "pending" PlaybookStepStatusRunning PlaybookStepStatus = "running" PlaybookStepStatusCompleted PlaybookStepStatus = "completed" PlaybookStepStatusFailed PlaybookStepStatus = "failed" PlaybookStepStatusSkipped PlaybookStepStatus = "skipped" )
type PlaybookTrigger ¶
type PlaybookTrigger struct {
Keywords []string `json:"keywords"` // Keywords in task description
Patterns []string `json:"patterns"` // Regex patterns to match
FileTypes []string `json:"file_types"` // Relevant file extensions
Priority int `json:"priority"` // Higher = more relevant
}
PlaybookTrigger defines when a playbook should be suggested
type PlaybookType ¶
type PlaybookType string
PlaybookType represents the category of playbook
const ( PlaybookTypeRefactor PlaybookType = "refactor" PlaybookTypeAddTest PlaybookType = "add_test" PlaybookTypeFixBug PlaybookType = "fix_bug" PlaybookTypeAddFeature PlaybookType = "add_feature" PlaybookTypeOptimize PlaybookType = "optimize" PlaybookTypeDocument PlaybookType = "document" PlaybookTypeMigrate PlaybookType = "migrate" PlaybookTypeSecurity PlaybookType = "security" PlaybookTypeCustom PlaybookType = "custom" )
type PortMapping ¶
type PortMapping struct {
HostPort int `json:"host_port"`
ContainerPort int `json:"container_port"`
Protocol string `json:"protocol"` // tcp, udp
HostIP string `json:"host_ip"`
}
PortMapping defines a port mapping between host and container.
type ProfileCustomization ¶
type ProfileCustomization func(*SafetyProfile)
ProfileCustomization is a function that customizes a profile.
func WithApprovalMode ¶
func WithApprovalMode(mode ApprovalMode) ProfileCustomization
WithApprovalMode sets the approval mode.
func WithAutoSnapshot ¶
func WithAutoSnapshot(enabled bool, minDangerLevel DangerLevel) ProfileCustomization
WithAutoSnapshot sets auto-snapshot behavior.
func WithDangerThreshold ¶
func WithDangerThreshold(approvalRequired, confirmationRequired DangerLevel) ProfileCustomization
WithDangerThreshold sets danger thresholds.
func WithNetworkEnabled ¶
func WithNetworkEnabled(enabled bool) ProfileCustomization
WithNetworkEnabled sets network access.
func WithProtectionEnabled ¶
func WithProtectionEnabled(enabled bool) ProfileCustomization
WithProtectionEnabled sets protection behavior.
type ProgressDashboard ¶
type ProgressDashboard struct {
// contains filtered or unexported fields
}
ProgressDashboard provides real-time progress tracking for autonomous operations.
func NewProgressDashboard ¶
func NewProgressDashboard(config DashboardConfig) *ProgressDashboard
NewProgressDashboard creates a new progress dashboard.
func (*ProgressDashboard) AddStep ¶
func (d *ProgressDashboard) AddStep(id, name, description string) *ProgressStep
AddStep adds a new step to track.
func (*ProgressDashboard) AddSubStep ¶
func (d *ProgressDashboard) AddSubStep(parentID, id, name string) *ProgressStep
AddSubStep adds a sub-step to an existing step.
func (*ProgressDashboard) Cancel ¶
func (d *ProgressDashboard) Cancel()
Cancel marks the dashboard as cancelled.
func (*ProgressDashboard) Complete ¶
func (d *ProgressDashboard) Complete()
Complete marks the dashboard as completed and renders final state.
func (*ProgressDashboard) CompleteStep ¶
func (d *ProgressDashboard) CompleteStep(id string)
CompleteStep marks a step as completed.
func (*ProgressDashboard) ExportJSON ¶
func (d *ProgressDashboard) ExportJSON() string
ExportJSON exports dashboard state as JSON-like string.
func (*ProgressDashboard) Fail ¶
func (d *ProgressDashboard) Fail(errMsg string)
Fail marks the dashboard as failed.
func (*ProgressDashboard) FailStep ¶
func (d *ProgressDashboard) FailStep(id, errMsg string)
FailStep marks a step as failed.
func (*ProgressDashboard) GetStats ¶
func (d *ProgressDashboard) GetStats() DashboardStats
GetStats returns current dashboard statistics.
func (*ProgressDashboard) IncrementRetries ¶
func (d *ProgressDashboard) IncrementRetries()
IncrementRetries increments the retry counter.
func (*ProgressDashboard) Render ¶
func (d *ProgressDashboard) Render()
Render renders the dashboard to the output.
func (*ProgressDashboard) RetryStep ¶
func (d *ProgressDashboard) RetryStep(id string)
RetryStep marks a step as retrying.
func (*ProgressDashboard) SetCost ¶
func (d *ProgressDashboard) SetCost(cost float64)
SetCost updates cost.
func (*ProgressDashboard) SetProgress ¶
func (d *ProgressDashboard) SetProgress(progress float64)
SetProgress sets the overall progress.
func (*ProgressDashboard) SetStatus ¶
func (d *ProgressDashboard) SetStatus(status DashboardStatus)
SetStatus sets the dashboard status.
func (*ProgressDashboard) SetTokens ¶
func (d *ProgressDashboard) SetTokens(tokens int64)
SetTokens updates token usage.
func (*ProgressDashboard) SkipStep ¶
func (d *ProgressDashboard) SkipStep(id string)
SkipStep marks a step as skipped.
func (*ProgressDashboard) StartStep ¶
func (d *ProgressDashboard) StartStep(id string)
StartStep marks a step as running.
func (*ProgressDashboard) UpdateStepProgress ¶
func (d *ProgressDashboard) UpdateStepProgress(id string, progress float64)
UpdateStepProgress updates the progress of a step.
type ProgressStep ¶
type ProgressStep struct {
ID string
Name string
Description string
Status StepStatus
StartedAt time.Time
CompletedAt time.Time
Duration time.Duration
Progress float64 // 0.0 - 1.0
SubSteps []*ProgressStep
Error string
Metadata map[string]any
}
ProgressStep represents a single step in the operation.
type ProtectedPath ¶
type ProtectedPath struct {
// Path is the path or pattern to protect
Path string `json:"path"`
// Type is the matching type
Type ProtectedPathType `json:"type"`
// Action is the action to take on access
Action ProtectedPathAction `json:"action"`
// Description explains why this path is protected
Description string `json:"description"`
// Operations restricts protection to specific operations (empty = all)
Operations []string `json:"operations,omitempty"`
// Enabled toggles the rule
Enabled bool `json:"enabled"`
// Priority for rule ordering (higher = checked first)
Priority int `json:"priority"`
// contains filtered or unexported fields
}
ProtectedPath defines a single protected path rule.
type ProtectedPathAccess ¶
type ProtectedPathAccess struct {
Path string `json:"path"`
Operation string `json:"operation"`
Action ProtectedPathAction `json:"action"`
MatchedRule string `json:"matched_rule,omitempty"`
Timestamp int64 `json:"timestamp"`
Allowed bool `json:"allowed"`
UserID string `json:"user_id,omitempty"`
SessionID string `json:"session_id,omitempty"`
}
ProtectedPathAccess records an access attempt.
type ProtectedPathAction ¶
type ProtectedPathAction string
ProtectedPathAction defines what action to take when a protected path is accessed.
const ( // ActionBlock blocks access completely ActionBlock ProtectedPathAction = "block" // ActionWarn warns but allows access ActionWarn ProtectedPathAction = "warn" // ActionLog logs access without warning ActionLog ProtectedPathAction = "log" // ActionAllow allows access with tracking ActionAllow ProtectedPathAction = "allow" )
type ProtectedPathConfig ¶
type ProtectedPathConfig struct {
// Paths is the list of protected path rules
Paths []ProtectedPath `json:"paths"`
// DefaultAction is the action for unmatched sensitive paths
DefaultAction ProtectedPathAction `json:"default_action"`
// EnableAudit enables audit logging
EnableAudit bool `json:"enable_audit"`
// AuditFile is the path to the audit log file
AuditFile string `json:"audit_file"`
}
ProtectedPathConfig holds the configuration for protected paths.
func DefaultProtectedPathConfig ¶
func DefaultProtectedPathConfig() ProtectedPathConfig
DefaultProtectedPathConfig returns the default configuration.
type ProtectedPathType ¶
type ProtectedPathType string
ProtectedPathType defines the type of protection.
const ( // TypeExact matches exact path TypeExact ProtectedPathType = "exact" // TypePrefix matches path prefix TypePrefix ProtectedPathType = "prefix" // TypeGlob matches glob pattern TypeGlob ProtectedPathType = "glob" // TypeRegex matches regex pattern TypeRegex ProtectedPathType = "regex" )
type ProtectedPathsBuilder ¶
type ProtectedPathsBuilder struct {
// contains filtered or unexported fields
}
ProtectedPathsBuilder helps create protected path configurations.
func NewProtectedPathsBuilder ¶
func NewProtectedPathsBuilder() *ProtectedPathsBuilder
NewProtectedPathsBuilder creates a new builder.
func (*ProtectedPathsBuilder) AddExactPath ¶
func (b *ProtectedPathsBuilder) AddExactPath(path string, action ProtectedPathAction, description string) *ProtectedPathsBuilder
AddExactPath adds an exact path rule.
func (*ProtectedPathsBuilder) AddGlobPath ¶
func (b *ProtectedPathsBuilder) AddGlobPath(pattern string, action ProtectedPathAction, description string) *ProtectedPathsBuilder
AddGlobPath adds a glob pattern rule.
func (*ProtectedPathsBuilder) AddPrefixPath ¶
func (b *ProtectedPathsBuilder) AddPrefixPath(prefix string, action ProtectedPathAction, description string) *ProtectedPathsBuilder
AddPrefixPath adds a prefix path rule.
func (*ProtectedPathsBuilder) AddRegexPath ¶
func (b *ProtectedPathsBuilder) AddRegexPath(pattern string, action ProtectedPathAction, description string) *ProtectedPathsBuilder
AddRegexPath adds a regex pattern rule.
func (*ProtectedPathsBuilder) Build ¶
func (b *ProtectedPathsBuilder) Build() *ProtectedPathsManager
Build creates the ProtectedPathsManager.
func (*ProtectedPathsBuilder) BuildConfig ¶
func (b *ProtectedPathsBuilder) BuildConfig() ProtectedPathConfig
BuildConfig returns the configuration.
func (*ProtectedPathsBuilder) WithAuditEnabled ¶
func (b *ProtectedPathsBuilder) WithAuditEnabled(enabled bool) *ProtectedPathsBuilder
WithAuditEnabled enables/disables audit.
func (*ProtectedPathsBuilder) WithDefaultAction ¶
func (b *ProtectedPathsBuilder) WithDefaultAction(action ProtectedPathAction) *ProtectedPathsBuilder
WithDefaultAction sets the default action.
func (*ProtectedPathsBuilder) WithPriority ¶
func (b *ProtectedPathsBuilder) WithPriority(priority int) *ProtectedPathsBuilder
WithPriority sets the priority for the next Add* call. After an Add* call, priority resets to 0 (default 50).
type ProtectedPathsManager ¶
type ProtectedPathsManager struct {
// contains filtered or unexported fields
}
ProtectedPathsManager manages protected path rules.
func NewDefaultProtectedPathsManager ¶
func NewDefaultProtectedPathsManager() *ProtectedPathsManager
NewDefaultProtectedPathsManager creates a manager with default configuration.
func NewProtectedPathsManager ¶
func NewProtectedPathsManager(config ProtectedPathConfig) *ProtectedPathsManager
NewProtectedPathsManager creates a new manager.
func (*ProtectedPathsManager) AddProtectedPath ¶
func (ppm *ProtectedPathsManager) AddProtectedPath(rule ProtectedPath)
AddProtectedPath adds a new protected path rule.
func (*ProtectedPathsManager) CheckPath ¶
func (ppm *ProtectedPathsManager) CheckPath(path, operation string) (ProtectedPathAction, *ProtectedPath)
CheckPath checks if a path is protected and returns the appropriate action.
func (*ProtectedPathsManager) ClearAuditLog ¶
func (ppm *ProtectedPathsManager) ClearAuditLog()
ClearAuditLog clears the audit log.
func (*ProtectedPathsManager) ExportConfig ¶
func (ppm *ProtectedPathsManager) ExportConfig() ([]byte, error)
ExportConfig exports the configuration as JSON.
func (*ProtectedPathsManager) GetAuditLog ¶
func (ppm *ProtectedPathsManager) GetAuditLog() []ProtectedPathAccess
GetAuditLog returns the audit log.
func (*ProtectedPathsManager) GetProtectedPaths ¶
func (ppm *ProtectedPathsManager) GetProtectedPaths() []ProtectedPath
GetProtectedPaths returns all protected path rules.
func (*ProtectedPathsManager) GetStats ¶
func (ppm *ProtectedPathsManager) GetStats() map[string]interface{}
GetStats returns statistics about protected paths.
func (*ProtectedPathsManager) ImportConfig ¶
func (ppm *ProtectedPathsManager) ImportConfig(data []byte) error
ImportConfig imports configuration from JSON.
func (*ProtectedPathsManager) IsAccessAllowed ¶
func (ppm *ProtectedPathsManager) IsAccessAllowed(path, operation string) bool
IsAccessAllowed checks if access to a path is allowed.
func (*ProtectedPathsManager) LoadConfigFromFile ¶
func (ppm *ProtectedPathsManager) LoadConfigFromFile(path string) error
LoadConfigFromFile loads configuration from a file.
func (*ProtectedPathsManager) RemoveProtectedPath ¶
func (ppm *ProtectedPathsManager) RemoveProtectedPath(path string) bool
RemoveProtectedPath removes a protected path rule.
func (*ProtectedPathsManager) SaveConfigToFile ¶
func (ppm *ProtectedPathsManager) SaveConfigToFile(path string) error
SaveConfigToFile saves configuration to a file.
func (*ProtectedPathsManager) ShouldWarn ¶
func (ppm *ProtectedPathsManager) ShouldWarn(path, operation string) bool
ShouldWarn checks if access should trigger a warning.
func (*ProtectedPathsManager) UpdateProtectedPath ¶
func (ppm *ProtectedPathsManager) UpdateProtectedPath(path string, updates ProtectedPath) bool
UpdateProtectedPath updates an existing rule.
func (*ProtectedPathsManager) ValidatePath ¶
func (ppm *ProtectedPathsManager) ValidatePath(path, operation string) error
ValidatePath validates that a path is safe to access.
type ProtectionSettings ¶
type ProtectionSettings struct {
// Enabled turns on path protection
Enabled bool `json:"enabled"`
// ProtectedPaths are paths that cannot be modified
ProtectedPaths []string `json:"protected_paths"`
// ProtectedPatterns are glob patterns for protected paths
ProtectedPatterns []string `json:"protected_patterns"`
// AllowOverride allows overriding protection with explicit approval
AllowOverride bool `json:"allow_override"`
// ProtectGit protects .git directories
ProtectGit bool `json:"protect_git"`
// ProtectEnv protects .env files
ProtectEnv bool `json:"protect_env"`
// ProtectConfig protects config files
ProtectConfig bool `json:"protect_config"`
// ProtectHome protects home directory
ProtectHome bool `json:"protect_home"`
// ProtectSystem protects system directories
ProtectSystem bool `json:"protect_system"`
}
ProtectionSettings controls file and path protection.
type QueueStats ¶
type QueueStats struct {
Total int `json:"total"`
Pending int `json:"pending"`
Running int `json:"running"`
Completed int `json:"completed"`
Success int `json:"success"`
Failed int `json:"failed"`
}
QueueStats holds queue statistics.
type QueuedTask ¶
type QueuedTask struct {
ID string `json:"id"`
Name string `json:"name"`
Description string `json:"description"`
Priority TaskPriority `json:"priority"`
Status TaskStatus `json:"status"`
Dependencies []string `json:"dependencies,omitempty"`
CreatedAt int64 `json:"created_at"`
StartedAt int64 `json:"started_at,omitempty"`
CompletedAt int64 `json:"completed_at,omitempty"`
Result *Result `json:"result,omitempty"`
Error string `json:"error,omitempty"`
RetryCount int `json:"retry_count"`
MaxRetries int `json:"max_retries"`
Timeout time.Duration `json:"timeout"`
Metadata map[string]any `json:"metadata,omitempty"`
// contains filtered or unexported fields
}
QueuedTask represents a task in the queue.
func (*QueuedTask) GetStatus ¶
func (t *QueuedTask) GetStatus() TaskStatus
GetStatus returns the current task status with proper locking.
func (*QueuedTask) SetStatus ¶
func (t *QueuedTask) SetStatus(status TaskStatus)
SetStatus sets the task status with proper locking.
type ResolvedStep ¶
type ResolvedStep struct {
PlaybookStep
ResolvedAction string
ResolvedTarget string
Status PlaybookStepStatus
Output string
Error error
}
ResolvedStep is a playbook step with variables resolved
type ResourceLimits ¶
type ResourceLimits struct {
// Time constraints
MaxDuration time.Duration // Maximum total operation time
MaxTurnDuration time.Duration // Maximum time per turn/step
MaxIdleTime time.Duration // Maximum idle time before timeout
// Operation counts
MaxTurns int // Maximum number of turns/steps
MaxRetries int // Maximum retries per operation
MaxFileReads int // Maximum file reads
MaxFileWrites int // Maximum file writes
MaxCommands int // Maximum shell commands
MaxAPICalls int // Maximum API calls
// Memory constraints
MaxMemoryMB int64 // Maximum memory usage in MB
WarnMemoryMB int64 // Warning threshold for memory
// Token/Cost constraints
MaxTokens int64 // Maximum tokens (input + output)
MaxCost float64 // Maximum cost in dollars
// Concurrency constraints
MaxConcurrentOps int // Maximum concurrent operations
MaxGoroutines int // Maximum goroutines
}
ResourceLimits defines constraints for autonomous operations.
func DefaultResourceLimits ¶
func DefaultResourceLimits() ResourceLimits
DefaultResourceLimits returns sensible default limits.
func RelaxedResourceLimits ¶
func RelaxedResourceLimits() ResourceLimits
RelaxedResourceLimits returns relaxed limits for trusted operations.
func StrictResourceLimits ¶
func StrictResourceLimits() ResourceLimits
StrictResourceLimits returns strict limits for untrusted operations.
type ResourceSafetySettings ¶
type ResourceSafetySettings struct {
// MaxCPU is the maximum CPU percentage (0-100)
MaxCPU int `json:"max_cpu"`
// MaxMemoryMB is the maximum memory in MB
MaxMemoryMB int `json:"max_memory_mb"`
// MaxFileSize is the maximum file size in bytes
MaxFileSize int64 `json:"max_file_size"`
// MaxExecutionTime is the maximum operation duration
MaxExecutionTime time.Duration `json:"max_execution_time"`
// MaxFileOperations is the max file operations per session
MaxFileOperations int `json:"max_file_operations"`
// MaxNetworkBytes is the max network transfer in bytes
MaxNetworkBytes int64 `json:"max_network_bytes"`
}
ResourceSafetySettings controls resource limits.
type ResourceUsage ¶
type ResourceUsage struct {
Duration time.Duration
Turns int64
Retries int64
FileReads int64
FileWrites int64
Commands int64
APICalls int64
Tokens int64
MemoryMB int64
Cost float64
ConcurrentOps int
Goroutines int
}
ResourceUsage represents current resource consumption.
type RestoreConfig ¶
RestoreConfig configures restore behavior.
type RestoreOption ¶
type RestoreOption func(*RestoreConfig)
RestoreOption is a functional option for restoring snapshots.
func WithOverwrite ¶
func WithOverwrite(overwrite bool) RestoreOption
WithOverwrite sets whether to overwrite existing files.
type RestrictedCommand ¶
type RestrictedCommand struct {
// ID is the unique identifier
ID string `json:"id"`
// Name is the command name
Name string `json:"name"`
// Pattern is the regex or glob pattern to match
Pattern string `json:"pattern"`
// Description explains why it's restricted
Description string `json:"description"`
// Category is the command category
Category CommandCategory `json:"category"`
// Restriction is the restriction level
Restriction RestrictionLevel `json:"restriction"`
// Enabled turns the restriction on/off
Enabled bool `json:"enabled"`
// Message shown when the command is restricted
Message string `json:"message,omitempty"`
// AllowWithFlag allows the command with specific flags
AllowWithFlag []string `json:"allow_with_flag,omitempty"`
// BlockWithFlag blocks the command with specific flags
BlockWithFlag []string `json:"block_with_flag,omitempty"`
// RequireFlag requires these flags to be present
RequireFlag []string `json:"require_flag,omitempty"`
// DangerLevelOverride overrides the danger level
DangerLevelOverride *DangerLevel `json:"danger_level_override,omitempty"`
// TimeRestriction restricts when the command can run
TimeRestriction *TimeRestriction `json:"time_restriction,omitempty"`
// CreatedAt is when this was created
CreatedAt time.Time `json:"created_at"`
// ModifiedAt is when this was last modified
ModifiedAt time.Time `json:"modified_at"`
}
RestrictedCommand represents a restricted command configuration.
type RestrictedCommandsConfig ¶
type RestrictedCommandsConfig struct {
// Enabled turns on restriction checking
Enabled bool `json:"enabled"`
// ConfigPath is where to load/save restrictions
ConfigPath string `json:"config_path"`
// DefaultRestriction is the default level for unknown commands
DefaultRestriction RestrictionLevel `json:"default_restriction"`
// EnforceStrict enforces strict mode for all restrictions
EnforceStrict bool `json:"enforce_strict"`
// LogRestrictions logs all restriction checks
LogRestrictions bool `json:"log_restrictions"`
}
RestrictedCommandsConfig configures the restricted commands manager.
func DefaultRestrictedCommandsConfig ¶
func DefaultRestrictedCommandsConfig() RestrictedCommandsConfig
DefaultRestrictedCommandsConfig returns the default configuration.
type RestrictedCommandsManager ¶
type RestrictedCommandsManager struct {
// contains filtered or unexported fields
}
RestrictedCommandsManager manages the restricted commands list.
func NewRestrictedCommandsManager ¶
func NewRestrictedCommandsManager(config RestrictedCommandsConfig) *RestrictedCommandsManager
NewRestrictedCommandsManager creates a new restricted commands manager.
func (*RestrictedCommandsManager) AddCommand ¶
func (mgr *RestrictedCommandsManager) AddCommand(cmd RestrictedCommand) error
AddCommand adds a new restricted command.
func (*RestrictedCommandsManager) CheckCommand ¶
func (mgr *RestrictedCommandsManager) CheckCommand(command string) *RestrictionResult
CheckCommand checks if a command is restricted.
func (*RestrictedCommandsManager) DisableCommand ¶
func (mgr *RestrictedCommandsManager) DisableCommand(id string) error
DisableCommand disables a restricted command.
func (*RestrictedCommandsManager) EnableCommand ¶
func (mgr *RestrictedCommandsManager) EnableCommand(id string) error
EnableCommand enables a restricted command.
func (*RestrictedCommandsManager) Export ¶
func (mgr *RestrictedCommandsManager) Export() ([]byte, error)
Export exports all restricted commands to JSON.
func (*RestrictedCommandsManager) GetCommand ¶
func (mgr *RestrictedCommandsManager) GetCommand(id string) (*RestrictedCommand, bool)
GetCommand retrieves a restricted command by ID.
func (*RestrictedCommandsManager) GetStats ¶
func (mgr *RestrictedCommandsManager) GetStats() RestrictionStats
GetStats returns restriction statistics.
func (*RestrictedCommandsManager) Import ¶
func (mgr *RestrictedCommandsManager) Import(data []byte) error
Import imports restricted commands from JSON.
func (*RestrictedCommandsManager) ListByCategory ¶
func (mgr *RestrictedCommandsManager) ListByCategory(category CommandCategory) []*RestrictedCommand
ListByCategory lists commands by category.
func (*RestrictedCommandsManager) ListByRestriction ¶
func (mgr *RestrictedCommandsManager) ListByRestriction(level RestrictionLevel) []*RestrictedCommand
ListByRestriction lists commands by restriction level.
func (*RestrictedCommandsManager) ListCommands ¶
func (mgr *RestrictedCommandsManager) ListCommands() []*RestrictedCommand
ListCommands lists all restricted commands.
func (*RestrictedCommandsManager) RemoveCommand ¶
func (mgr *RestrictedCommandsManager) RemoveCommand(id string) error
RemoveCommand removes a restricted command.
func (*RestrictedCommandsManager) Reset ¶
func (mgr *RestrictedCommandsManager) Reset()
Reset resets all commands to defaults.
func (*RestrictedCommandsManager) SetAuditLogger ¶
func (mgr *RestrictedCommandsManager) SetAuditLogger(logger *AuditLogger)
SetAuditLogger sets the audit logger.
func (*RestrictedCommandsManager) SetGlobalRestriction ¶
func (mgr *RestrictedCommandsManager) SetGlobalRestriction(level RestrictionLevel)
SetGlobalRestriction sets the default restriction level.
func (*RestrictedCommandsManager) SetRestrictionLevel ¶
func (mgr *RestrictedCommandsManager) SetRestrictionLevel(id string, level RestrictionLevel) error
SetRestrictionLevel sets the restriction level for a command.
func (*RestrictedCommandsManager) UpdateCommand ¶
func (mgr *RestrictedCommandsManager) UpdateCommand(cmd RestrictedCommand) error
UpdateCommand updates an existing restricted command.
type RestrictionLevel ¶
type RestrictionLevel string
RestrictionLevel represents the level of restriction for a command.
const ( // RestrictionLevelNone - No restriction RestrictionLevelNone RestrictionLevel = "none" // RestrictionLevelWarn - Warning only, command can proceed RestrictionLevelWarn RestrictionLevel = "warn" // RestrictionLevelConfirm - Requires user confirmation RestrictionLevelConfirm RestrictionLevel = "confirm" // RestrictionLevelApproval - Requires explicit approval RestrictionLevelApproval RestrictionLevel = "approval" // RestrictionLevelBlock - Command is blocked completely RestrictionLevelBlock RestrictionLevel = "block" )
type RestrictionResult ¶
type RestrictionResult struct {
// Restricted indicates if the command is restricted
Restricted bool `json:"restricted"`
// Restriction is the restriction level
Restriction RestrictionLevel `json:"restriction"`
// Command is the matched command config
Command *RestrictedCommand `json:"command,omitempty"`
// Message explains why it's restricted
Message string `json:"message"`
// MatchedPattern is the pattern that matched
MatchedPattern string `json:"matched_pattern,omitempty"`
// Suggestion for alternative commands
Suggestion string `json:"suggestion,omitempty"`
}
RestrictionResult contains the result of a restriction check.
type RestrictionStats ¶
type RestrictionStats struct {
TotalCommands int `json:"total_commands"`
TotalChecks int `json:"total_checks"`
TotalBlocked int `json:"total_blocked"`
TotalWarned int `json:"total_warned"`
TotalApproved int `json:"total_approved"`
ByCategory map[string]int `json:"by_category"`
ByRestriction map[string]int `json:"by_restriction"`
MostBlockedCount int `json:"most_blocked_count"`
MostBlockedCmd string `json:"most_blocked_cmd"`
}
RestrictionStats tracks restriction statistics.
type Result ¶
type Result struct {
Success bool
Status string
Iterations int
FilesModified []string
CommandsRun []string
TotalCost float64
Duration time.Duration
FinalMessage string
Learnings []string // lessons learned during execution
Error error
}
Result holds the final result of an autonomous run.
type ResumableEngine ¶
type ResumableEngine struct {
// contains filtered or unexported fields
}
ResumableEngine wraps Engine with interrupt/resume capability.
func NewResumableEngine ¶
func NewResumableEngine(engine *Engine, stateDir string) *ResumableEngine
NewResumableEngine creates a resumable engine wrapper.
func (*ResumableEngine) Interrupt ¶
func (re *ResumableEngine) Interrupt(reason string)
Interrupt signals the engine to stop and save state.
func (*ResumableEngine) ListResumableSessions ¶
func (re *ResumableEngine) ListResumableSessions() ([]SessionState, error)
ListResumableSessions returns sessions that can be resumed.
type RetryAttempt ¶
type RetryAttempt struct {
Timestamp time.Time
TaskID string
Error string
Category ErrorCategory
AttemptNum int
Success bool
FixApplied string
Duration time.Duration
NextDelay time.Duration
}
RetryAttempt records a single retry attempt.
type RetryConfig ¶
type RetryConfig struct {
MaxAttempts int
BaseBackoff time.Duration
MaxBackoff time.Duration
LearningEnabled bool
}
RetryConfig configures the SmartRetry behavior.
type RetryHistory ¶
type RetryHistory struct {
// contains filtered or unexported fields
}
RetryHistory tracks retry attempts across sessions.
func NewRetryHistory ¶
func NewRetryHistory() *RetryHistory
NewRetryHistory creates a new retry history tracker.
type RetryPattern ¶
type RetryPattern struct {
ID string
RegexPattern string
Category ErrorCategory
AutoFixable bool
FixHints []string
SuccessRate float64
AttemptCount int
LastSeen time.Time
PreferredStrategy string
}
RetryPattern represents a learned error pattern with retry metadata.
func DefaultRetryPatterns ¶
func DefaultRetryPatterns() []*RetryPattern
DefaultRetryPatterns returns built-in retry patterns.
type RetryResult ¶
type RetryResult struct {
Success bool
Attempts int
TotalTime time.Duration
FinalError string
FixesApplied []string
Patterns []string
Learned bool
}
RetryResult holds the outcome of a smart retry operation.
type RetryStats ¶
type RetryStats struct {
TotalAttempts int
SuccessfulRetries int
SuccessRate float64
ByCategory map[ErrorCategory]int
}
RetryStats holds aggregate retry statistics.
type RetryStrategy ¶
type RetryStrategy struct {
Name string
MaxAttempts int
BackoffFactor float64
JitterEnabled bool
FixActions []FixAction
}
RetryStrategy defines how retries should be attempted.
type ReviewCheckpoint ¶
type ReviewCheckpoint struct {
// contains filtered or unexported fields
}
ReviewCheckpoint manages the review process for destructive operations.
func NewReviewCheckpoint ¶
func NewReviewCheckpoint(policy *ReviewPolicy, stateManager *StateManager) *ReviewCheckpoint
NewReviewCheckpoint creates a new review checkpoint system.
func (*ReviewCheckpoint) AddHook ¶
func (rc *ReviewCheckpoint) AddHook(hook ReviewHook)
AddHook adds a review hook.
func (*ReviewCheckpoint) Approve ¶
func (rc *ReviewCheckpoint) Approve(requestID string, reason string) error
Approve approves a pending review.
func (*ReviewCheckpoint) GetPendingReviews ¶
func (rc *ReviewCheckpoint) GetPendingReviews() []*ReviewRequest
GetPendingReviews returns all pending review requests.
func (*ReviewCheckpoint) Reject ¶
func (rc *ReviewCheckpoint) Reject(requestID string, reason string) error
Reject rejects a pending review.
func (*ReviewCheckpoint) RequestReview ¶
func (rc *ReviewCheckpoint) RequestReview(ctx context.Context, op OperationType, target string, description string, details map[string]any) (*ReviewRequest, error)
RequestReview creates a review request for an operation.
func (*ReviewCheckpoint) SubmitResponse ¶
func (rc *ReviewCheckpoint) SubmitResponse(requestID string, decision ReviewDecision, reason string, respondedBy string) (*ReviewResponse, error)
SubmitResponse submits a review decision.
func (*ReviewCheckpoint) WaitForReview ¶
func (rc *ReviewCheckpoint) WaitForReview(ctx context.Context, requestID string) (*ReviewResponse, error)
WaitForReview blocks until a review decision is made.
type ReviewDecision ¶
type ReviewDecision string
ReviewDecision represents the user's decision on a review request.
const ( DecisionApproved ReviewDecision = "approved" DecisionRejected ReviewDecision = "rejected" DecisionModified ReviewDecision = "modified" // Approved with modifications DecisionEscalated ReviewDecision = "escalated" // Needs higher approval DecisionDeferred ReviewDecision = "deferred" // Ask again later )
type ReviewHook ¶
type ReviewHook interface {
BeforeReview(req *ReviewRequest) error
AfterReview(req *ReviewRequest, resp *ReviewResponse) error
}
ReviewHook is called before/after review decisions.
type ReviewPolicy ¶
type ReviewPolicy struct {
// contains filtered or unexported fields
}
ReviewPolicy defines when reviews are required.
func DefaultReviewPolicy ¶
func DefaultReviewPolicy() *ReviewPolicy
DefaultReviewPolicy returns a sensible default policy.
func (*ReviewPolicy) AddProtectedBranch ¶
func (p *ReviewPolicy) AddProtectedBranch(branch string)
AddProtectedBranch adds a branch to the protected list.
func (*ReviewPolicy) AddProtectedPath ¶
func (p *ReviewPolicy) AddProtectedPath(pattern string)
AddProtectedPath adds a path to the protected list.
func (*ReviewPolicy) NeedsReview ¶
func (p *ReviewPolicy) NeedsReview(req *ReviewRequest) bool
NeedsReview determines if an operation requires review.
func (*ReviewPolicy) SetRequireReviewAboveLevel ¶
func (p *ReviewPolicy) SetRequireReviewAboveLevel(level DangerLevel)
SetRequireReviewAboveLevel sets the danger level threshold for reviews.
type ReviewRequest ¶
type ReviewRequest struct {
ID string `json:"id"`
Timestamp int64 `json:"timestamp"`
Operation OperationType `json:"operation"`
DangerLevel DangerLevel `json:"danger_level"`
Target string `json:"target"`
Description string `json:"description"`
Details map[string]any `json:"details,omitempty"`
AutoApprove bool `json:"auto_approve"`
Timeout time.Duration `json:"timeout"`
}
ReviewRequest represents a pending review for a destructive operation.
type ReviewResponse ¶
type ReviewResponse struct {
RequestID string `json:"request_id"`
Decision ReviewDecision `json:"decision"`
Reason string `json:"reason,omitempty"`
ModifiedOp *ReviewRequest `json:"modified_operation,omitempty"`
RespondedBy string `json:"responded_by,omitempty"`
Timestamp int64 `json:"timestamp"`
}
ReviewResponse represents the response to a review request.
type RollbackConfig ¶
type RollbackConfig struct {
MaxEntries int // Maximum entries in stack (default: 50)
BaseDir string // Base directory for backups
}
RollbackConfig holds configuration for the rollback stack.
func DefaultRollbackConfig ¶
func DefaultRollbackConfig() RollbackConfig
DefaultRollbackConfig returns sensible defaults.
type RollbackEntry ¶
type RollbackEntry struct {
ID string `json:"id"`
Type RollbackType `json:"type"`
Timestamp int64 `json:"timestamp"`
Path string `json:"path,omitempty"`
Original string `json:"original,omitempty"` // Original content for edits
Checksum string `json:"checksum,omitempty"` // Content checksum
CommitHash string `json:"commit_hash,omitempty"` // For git rollbacks
BranchName string `json:"branch_name,omitempty"`
Applied bool `json:"applied"`
Metadata map[string]any `json:"metadata,omitempty"`
}
RollbackEntry represents a single rollback operation.
type RollbackOp ¶
type RollbackOp struct {
Type string // "file_edit", "file_create", "file_delete", "git_commit"
Path string // file path affected
Original string // original content (for edits/creates)
Timestamp time.Time // when the operation occurred
CommitHash string // for git commits
}
RollbackOp represents an operation that can be rolled back.
type RollbackSnapshot ¶
type RollbackSnapshot struct {
Name string `json:"name"`
Timestamp int64 `json:"timestamp"`
Entries []RollbackEntry `json:"entries"`
}
RollbackSnapshot represents a saved state of the rollback stack.
type RollbackStack ¶
type RollbackStack struct {
// contains filtered or unexported fields
}
RollbackStack manages a stack of rollback operations.
func NewRollbackStack ¶
func NewRollbackStack(config RollbackConfig) *RollbackStack
NewRollbackStack creates a new rollback stack.
func (*RollbackStack) CanRollback ¶
func (rs *RollbackStack) CanRollback() bool
CanRollback checks if a rollback is possible.
func (*RollbackStack) Clear ¶
func (rs *RollbackStack) Clear()
Clear removes all entries without performing rollbacks.
func (*RollbackStack) CreateSnapshot ¶
func (rs *RollbackStack) CreateSnapshot(name string) (*RollbackSnapshot, error)
CreateSnapshot creates a named snapshot of the current stack.
func (*RollbackStack) GetEntries ¶
func (rs *RollbackStack) GetEntries() []*RollbackEntry
GetEntries returns all entries.
func (*RollbackStack) GetEntry ¶
func (rs *RollbackStack) GetEntry(id string) *RollbackEntry
GetEntry returns a specific entry by ID.
func (*RollbackStack) GetLastOfType ¶
func (rs *RollbackStack) GetLastOfType(rollbackType RollbackType) *RollbackEntry
GetLastOfType returns the most recent entry of a specific type.
func (*RollbackStack) Peek ¶
func (rs *RollbackStack) Peek() *RollbackEntry
Peek returns the most recent entry without removing it.
func (*RollbackStack) Pop ¶
func (rs *RollbackStack) Pop() *RollbackEntry
Pop removes and returns the most recent entry.
func (*RollbackStack) PushFileCreate ¶
func (rs *RollbackStack) PushFileCreate(path string, content string) *RollbackEntry
PushFileCreate records a file creation for potential rollback.
func (*RollbackStack) PushFileDelete ¶
func (rs *RollbackStack) PushFileDelete(path string, content string) *RollbackEntry
PushFileDelete records a file deletion for potential rollback.
func (*RollbackStack) PushFileEdit ¶
func (rs *RollbackStack) PushFileEdit(path string, originalContent string) *RollbackEntry
PushFileEdit records a file edit for potential rollback.
func (*RollbackStack) PushGitCommit ¶
func (rs *RollbackStack) PushGitCommit(commitHash string) *RollbackEntry
PushGitCommit records a git commit for potential rollback.
func (*RollbackStack) Rollback ¶
func (rs *RollbackStack) Rollback() error
Rollback performs the most recent rollback operation.
func (*RollbackStack) RollbackAll ¶
func (rs *RollbackStack) RollbackAll() error
RollbackAll rolls back all entries.
func (*RollbackStack) RollbackTo ¶
func (rs *RollbackStack) RollbackTo(entryID string) error
RollbackTo rolls back to a specific entry (inclusive).
func (*RollbackStack) Size ¶
func (rs *RollbackStack) Size() int
Size returns the number of entries in the stack.
type RollbackType ¶
type RollbackType string
RollbackType represents the type of rollback operation.
const ( RollbackTypeFileEdit RollbackType = "file_edit" RollbackTypeFileCreate RollbackType = "file_create" RollbackTypeFileDelete RollbackType = "file_delete" RollbackTypeGitCommit RollbackType = "git_commit" RollbackTypeGitBranch RollbackType = "git_branch" )
type SafetyMode ¶
type SafetyMode int
SafetyMode defines how cautious the agent should be.
const ( SafetyStrict SafetyMode = iota // Requires approval for all file changes SafetyBalanced // Auto-approves safe operations, asks for risky ones SafetyPermissive // Auto-approves most operations )
type SafetyProfile ¶
type SafetyProfile struct {
// Name is the profile name
Name SafetyProfileName `json:"name"`
// DisplayName is a human-readable name
DisplayName string `json:"display_name"`
// Description explains the profile
Description string `json:"description"`
// Approval settings
Approval ApprovalProfileSettings `json:"approval"`
// DangerThresholds defines when actions are triggered
DangerThresholds DangerThresholdSettings `json:"danger_thresholds"`
// Protection settings
Protection ProtectionSettings `json:"protection"`
// Network settings
Network NetworkSafetySettings `json:"network"`
// Snapshot settings
Snapshot SnapshotSafetySettings `json:"snapshot"`
// Resource limits
Resources ResourceSafetySettings `json:"resources"`
// Audit settings
Audit AuditSafetySettings `json:"audit"`
// CustomRules are user-defined rules
CustomRules []CustomSafetyRule `json:"custom_rules,omitempty"`
// CreatedAt is when the profile was created
CreatedAt time.Time `json:"created_at"`
// ModifiedAt is when the profile was last modified
ModifiedAt time.Time `json:"modified_at"`
}
SafetyProfile contains all safety-related configuration.
type SafetyProfileManager ¶
type SafetyProfileManager struct {
// contains filtered or unexported fields
}
SafetyProfileManager manages safety profiles.
func NewSafetyProfileManager ¶
func NewSafetyProfileManager(configPath string) *SafetyProfileManager
NewSafetyProfileManager creates a new safety profile manager.
func (*SafetyProfileManager) AddCustomRule ¶
func (mgr *SafetyProfileManager) AddCustomRule(rule CustomSafetyRule) error
AddCustomRule adds a custom safety rule.
func (*SafetyProfileManager) CreateCustomProfile ¶
func (mgr *SafetyProfileManager) CreateCustomProfile(base SafetyProfileName, customizations ...ProfileCustomization) (*SafetyProfile, error)
CreateCustomProfile creates a new custom profile based on an existing one.
func (*SafetyProfileManager) EvaluateCustomRules ¶
func (mgr *SafetyProfileManager) EvaluateCustomRules(operation string) (string, *DangerLevel, string)
EvaluateCustomRules evaluates custom rules for an operation.
func (*SafetyProfileManager) ExportProfile ¶
func (mgr *SafetyProfileManager) ExportProfile(name SafetyProfileName) ([]byte, error)
ExportProfile exports a profile to JSON.
func (*SafetyProfileManager) GetActiveProfile ¶
func (mgr *SafetyProfileManager) GetActiveProfile() *SafetyProfile
GetActiveProfile returns the currently active profile.
func (*SafetyProfileManager) GetActiveProfileName ¶
func (mgr *SafetyProfileManager) GetActiveProfileName() SafetyProfileName
GetActiveProfileName returns the name of the active profile.
func (*SafetyProfileManager) GetProfile ¶
func (mgr *SafetyProfileManager) GetProfile(name SafetyProfileName) (*SafetyProfile, bool)
GetProfile returns a safety profile by name.
func (*SafetyProfileManager) ImportProfile ¶
func (mgr *SafetyProfileManager) ImportProfile(data []byte) error
ImportProfile imports a profile from JSON.
func (*SafetyProfileManager) IsNetworkAllowed ¶
func (mgr *SafetyProfileManager) IsNetworkAllowed(host string, port int) (bool, string)
IsNetworkAllowed determines if network access is allowed.
func (*SafetyProfileManager) IsPathProtected ¶
func (mgr *SafetyProfileManager) IsPathProtected(path string) (bool, string)
IsPathProtected determines if a path is protected.
func (*SafetyProfileManager) ListProfiles ¶
func (mgr *SafetyProfileManager) ListProfiles() []SafetyProfileName
ListProfiles returns all available profile names.
func (*SafetyProfileManager) RemoveCustomRule ¶
func (mgr *SafetyProfileManager) RemoveCustomRule(ruleID string) error
RemoveCustomRule removes a custom safety rule.
func (*SafetyProfileManager) ResetProfile ¶
func (mgr *SafetyProfileManager) ResetProfile(name SafetyProfileName) error
ResetProfile resets a built-in profile to defaults.
func (*SafetyProfileManager) SetActiveProfile ¶
func (mgr *SafetyProfileManager) SetActiveProfile(name SafetyProfileName) error
SetActiveProfile sets the active profile.
func (*SafetyProfileManager) ShouldApprove ¶
func (mgr *SafetyProfileManager) ShouldApprove(dangerLevel DangerLevel) bool
ShouldApprove determines if an operation needs approval based on the active profile.
func (*SafetyProfileManager) ShouldConfirm ¶
func (mgr *SafetyProfileManager) ShouldConfirm(dangerLevel DangerLevel) bool
ShouldConfirm determines if an operation needs confirmation.
func (*SafetyProfileManager) ShouldSnapshot ¶
func (mgr *SafetyProfileManager) ShouldSnapshot(dangerLevel DangerLevel, operation string) bool
ShouldSnapshot determines if an operation should trigger a snapshot.
func (*SafetyProfileManager) UpdateProfile ¶
func (mgr *SafetyProfileManager) UpdateProfile(name SafetyProfileName, customizations ...ProfileCustomization) error
UpdateProfile updates an existing profile.
type SafetyProfileName ¶
type SafetyProfileName string
SafetyProfileName represents predefined safety profile names.
const ( // SafetyProfileStrict - Maximum safety, minimal automation // - All operations require approval // - Auto-snapshot on all changes // - All paths protected by default // - Network disabled SafetyProfileStrict SafetyProfileName = "strict" // SafetyProfileBalanced - Default profile, good balance // - Risky operations require approval // - Auto-snapshot on destructive ops // - Critical paths protected // - Network with restrictions SafetyProfileBalanced SafetyProfileName = "balanced" // SafetyProfilePermissive - High trust, high automation // - Only critical operations need approval // - Snapshots on user request // - Minimal path protection // - Full network access SafetyProfilePermissive SafetyProfileName = "permissive" // SafetyProfileCustom - User-defined profile SafetyProfileCustom SafetyProfileName = "custom" )
type Sandbox ¶
type Sandbox struct {
// contains filtered or unexported fields
}
Sandbox provides isolated execution environment for commands.
func NewSandbox ¶
func NewSandbox(config SandboxConfig) *Sandbox
NewSandbox creates a new sandbox instance.
func NewSandboxFromTemplate ¶
NewSandboxFromTemplate creates a sandbox from a template.
func (*Sandbox) AddVolumeMount ¶
AddVolumeMount adds a volume mount to the sandbox.
func (*Sandbox) ExecuteWithOutput ¶
func (s *Sandbox) ExecuteWithOutput(ctx context.Context, command string, args ...string) *SandboxResult
ExecuteWithOutput runs a command and streams output.
func (*Sandbox) GetContainerID ¶
GetContainerID returns the container ID.
func (*Sandbox) GetContainerStats ¶
GetContainerStats gets stats for a container.
type SandboxBuilder ¶
type SandboxBuilder struct {
// contains filtered or unexported fields
}
SandboxBuilder helps create Sandbox configurations.
func NewSandboxBuilder ¶
func NewSandboxBuilder() *SandboxBuilder
NewSandboxBuilder creates a new sandbox builder.
func (*SandboxBuilder) BuildConfig ¶
func (b *SandboxBuilder) BuildConfig() SandboxConfig
BuildConfig returns the configuration.
func (*SandboxBuilder) WithCPUShares ¶
func (b *SandboxBuilder) WithCPUShares(shares int64) *SandboxBuilder
WithCPUShares sets the CPU shares.
func (*SandboxBuilder) WithCleanupOnExit ¶
func (b *SandboxBuilder) WithCleanupOnExit(cleanup bool) *SandboxBuilder
WithCleanupOnExit sets whether to cleanup on exit.
func (*SandboxBuilder) WithEnvVar ¶
func (b *SandboxBuilder) WithEnvVar(key, value string) *SandboxBuilder
WithEnvVar sets an environment variable.
func (*SandboxBuilder) WithImage ¶
func (b *SandboxBuilder) WithImage(image string) *SandboxBuilder
WithImage sets the Docker image.
func (*SandboxBuilder) WithMemoryLimit ¶
func (b *SandboxBuilder) WithMemoryLimit(mb int64) *SandboxBuilder
WithMemoryLimit sets the memory limit in MB.
func (*SandboxBuilder) WithNetwork ¶
func (b *SandboxBuilder) WithNetwork(enabled bool) *SandboxBuilder
WithNetwork enables or disables network.
func (*SandboxBuilder) WithOutputCallback ¶
func (b *SandboxBuilder) WithOutputCallback(callback func(string)) *SandboxBuilder
WithOutputCallback sets the output callback.
func (*SandboxBuilder) WithPullImage ¶
func (b *SandboxBuilder) WithPullImage(pull bool) *SandboxBuilder
WithPullImage sets whether to pull the image.
func (*SandboxBuilder) WithTimeout ¶
func (b *SandboxBuilder) WithTimeout(timeout time.Duration) *SandboxBuilder
WithTimeout sets the execution timeout.
func (*SandboxBuilder) WithVolumeMount ¶
func (b *SandboxBuilder) WithVolumeMount(hostPath, containerPath string, readOnly bool) *SandboxBuilder
WithVolumeMount adds a volume mount.
func (*SandboxBuilder) WithWorkDir ¶
func (b *SandboxBuilder) WithWorkDir(dir string) *SandboxBuilder
WithWorkDir sets the working directory.
type SandboxConfig ¶
type SandboxConfig struct {
Image string `json:"image"`
WorkDir string `json:"work_dir"`
VolumeMounts []VolumeMount `json:"volume_mounts"`
EnvVars map[string]string `json:"env_vars"`
NetworkEnabled bool `json:"network_enabled"`
ResourceLimits SandboxResourceLimits `json:"resource_limits"`
ExecTimeout time.Duration `json:"exec_timeout"`
OutputCallback func(string) `json:"-"`
CleanupOnExit bool `json:"cleanup_on_exit"`
PullImage bool `json:"pull_image"`
}
SandboxConfig configures the sandbox environment.
func DefaultSandboxConfig ¶
func DefaultSandboxConfig() SandboxConfig
DefaultSandboxConfig returns default sandbox configuration.
type SandboxLimits ¶
type SandboxLimits struct {
// ID is the unique identifier
ID string `json:"id"`
// Name is a human-readable name
Name string `json:"name"`
// Profile is the resource profile type
Profile SandboxLimitsProfile `json:"profile"`
// CPU limits
CPUPercent int `json:"cpu_percent"` // CPU percentage (0-100)
CPUs float64 `json:"cpus"` // Number of CPUs (e.g., 1.5)
CPUQuota int64 `json:"cpu_quota"` // CPU quota in microseconds
CPUPeriod int64 `json:"cpu_period"` // CPU period in microseconds
// Memory limits
MemoryMB int64 `json:"memory_mb"` // Memory limit in MB
MemorySwapMB int64 `json:"memory_swap_mb"` // Memory + swap limit in MB
MemorySwapiness int `json:"memory_swappiness"` // Swappiness (0-100)
MemoryReservation int64 `json:"memory_reservation"` // Memory soft limit
// Process limits
PidsLimit int64 `json:"pids_limit"` // Max number of processes
OpenFilesLimit int64 `json:"open_files_limit"` // Max open files
// I/O limits
BlkioWeight uint16 `json:"blkio_weight"` // Block I/O weight (10-1000)
BlkioReadBPS int64 `json:"blkio_read_bps"` // Read bytes per second
BlkioWriteBPS int64 `json:"blkio_write_bps"` // Write bytes per second
BlkioReadIOPS int64 `json:"blkio_read_iops"` // Read I/O operations per second
BlkioWriteIOPS int64 `json:"blkio_write_iops"` // Write I/O operations per second
// Time limits
ExecTimeout time.Duration `json:"exec_timeout"` // Command execution timeout
MaxExecTime time.Duration `json:"max_exec_time"` // Maximum execution time
IdleTimeout time.Duration `json:"idle_timeout"` // Idle timeout before termination
// Network limits
NetworkIngressBPS int64 `json:"network_ingress_bps"` // Network ingress bytes/sec
NetworkEgressBPS int64 `json:"network_egress_bps"` // Network egress bytes/sec
// Enforcement settings
StrictEnforcement bool `json:"strict_enforcement"` // Kill on violation
WarnOnViolation bool `json:"warn_on_violation"` // Log warnings
// CreatedAt timestamp
CreatedAt time.Time `json:"created_at"`
// ModifiedAt timestamp
ModifiedAt time.Time `json:"modified_at"`
}
SandboxLimits defines comprehensive resource constraints for sandbox execution.
func (*SandboxLimits) ToDockerArgs ¶
func (limits *SandboxLimits) ToDockerArgs() []string
ToDockerArgs converts SandboxLimits to Docker run arguments.
func (*SandboxLimits) ToSandboxResourceLimits ¶
func (limits *SandboxLimits) ToSandboxResourceLimits() SandboxResourceLimits
ToSandboxResourceLimits converts to SandboxResourceLimits.
type SandboxLimitsConfig ¶
type SandboxLimitsConfig struct {
// Enabled turns on resource limit enforcement
Enabled bool `json:"enabled"`
// ConfigPath is where to load/save custom profiles
ConfigPath string `json:"config_path"`
// DefaultProfile is the default profile to use
DefaultProfile SandboxLimitsProfile `json:"default_profile"`
// MonitorInterval is how often to check resource usage
MonitorInterval time.Duration `json:"monitor_interval"`
// LogUsage logs resource usage periodically
LogUsage bool `json:"log_usage"`
// KillOnViolation kills containers on violation
KillOnViolation bool `json:"kill_on_violation"`
}
SandboxLimitsConfig configures the sandbox resource limits manager.
func DefaultSandboxLimitsConfig ¶
func DefaultSandboxLimitsConfig() SandboxLimitsConfig
DefaultSandboxLimitsConfig returns the default configuration.
type SandboxLimitsManager ¶
type SandboxLimitsManager struct {
// contains filtered or unexported fields
}
SandboxLimitsManager manages resource limits for sandboxes.
func NewSandboxLimitsManager ¶
func NewSandboxLimitsManager(config SandboxLimitsConfig) *SandboxLimitsManager
NewSandboxLimitsManager creates a new resource limits manager.
func (*SandboxLimitsManager) AddCustomProfile ¶
func (mgr *SandboxLimitsManager) AddCustomProfile(profile SandboxLimits) error
AddCustomProfile adds a new custom profile.
func (*SandboxLimitsManager) AssignLimits ¶
func (mgr *SandboxLimitsManager) AssignLimits(containerID string, limits *SandboxLimits)
AssignLimits assigns resource limits to a container.
func (*SandboxLimitsManager) AssignProfile ¶
func (mgr *SandboxLimitsManager) AssignProfile(containerID string, profile SandboxLimitsProfile) error
AssignProfile assigns a predefined profile to a container.
func (*SandboxLimitsManager) CheckViolation ¶
func (mgr *SandboxLimitsManager) CheckViolation(containerID string, usage *ContainerUsage) *ContainerViolation
CheckViolation checks if current usage violates limits.
func (*SandboxLimitsManager) CreateLimitsFromProfile ¶
func (mgr *SandboxLimitsManager) CreateLimitsFromProfile(profile SandboxLimitsProfile, overrides map[string]interface{}) *SandboxLimits
CreateLimitsFromProfile creates SandboxLimits from a profile with overrides.
func (*SandboxLimitsManager) Export ¶
func (mgr *SandboxLimitsManager) Export() ([]byte, error)
Export exports all profiles to JSON.
func (*SandboxLimitsManager) GetCustomProfile ¶
func (mgr *SandboxLimitsManager) GetCustomProfile(id string) *SandboxLimits
GetCustomProfile returns a custom profile by ID.
func (*SandboxLimitsManager) GetDefaultLimits ¶
func (mgr *SandboxLimitsManager) GetDefaultLimits() *SandboxLimits
GetDefaultLimits returns the default resource limits based on config.
func (*SandboxLimitsManager) GetLimits ¶
func (mgr *SandboxLimitsManager) GetLimits(containerID string) *SandboxLimits
GetLimits returns the limits for a container.
func (*SandboxLimitsManager) GetProfile ¶
func (mgr *SandboxLimitsManager) GetProfile(profile SandboxLimitsProfile) *SandboxLimits
GetProfile returns a resource profile by name.
func (*SandboxLimitsManager) GetStats ¶
func (mgr *SandboxLimitsManager) GetStats() SandboxResourceStats
GetStats returns resource statistics.
func (*SandboxLimitsManager) GetUsageHistory ¶
func (mgr *SandboxLimitsManager) GetUsageHistory(containerID string) []ContainerUsage
GetUsageHistory returns usage history for a container.
func (*SandboxLimitsManager) GetViolations ¶
func (mgr *SandboxLimitsManager) GetViolations() []ContainerViolation
GetViolations returns all recorded violations.
func (*SandboxLimitsManager) ListProfiles ¶
func (mgr *SandboxLimitsManager) ListProfiles() []*SandboxLimits
ListProfiles lists all available profiles.
func (*SandboxLimitsManager) RecordUsage ¶
func (mgr *SandboxLimitsManager) RecordUsage(containerID string, usage *ContainerUsage)
RecordUsage records resource usage for a container.
func (*SandboxLimitsManager) RemoveContainer ¶
func (mgr *SandboxLimitsManager) RemoveContainer(containerID string)
RemoveContainer removes a container from tracking.
func (*SandboxLimitsManager) RemoveCustomProfile ¶
func (mgr *SandboxLimitsManager) RemoveCustomProfile(id string) error
RemoveCustomProfile removes a custom profile.
func (*SandboxLimitsManager) Reset ¶
func (mgr *SandboxLimitsManager) Reset()
Reset resets the manager state.
type SandboxLimitsProfile ¶
type SandboxLimitsProfile string
SandboxLimitsProfile represents a predefined sandbox resource limit profile.
const ( // SandboxLimitsProfileLow - Low resource limits (suitable for simple tasks) SandboxLimitsProfileLow SandboxLimitsProfile = "low" // SandboxLimitsProfileMedium - Medium resource limits (balanced) SandboxLimitsProfileMedium SandboxLimitsProfile = "medium" // SandboxLimitsProfileHigh - High resource limits (for complex builds/tests) SandboxLimitsProfileHigh SandboxLimitsProfile = "high" // SandboxLimitsProfileUnlimited - No resource limits (use with caution) SandboxLimitsProfileUnlimited SandboxLimitsProfile = "unlimited" // SandboxLimitsProfileCustom - Custom resource limits SandboxLimitsProfileCustom SandboxLimitsProfile = "custom" )
type SandboxResourceLimits ¶
type SandboxResourceLimits struct {
MemoryMB int64 `json:"memory_mb"`
MemorySwapMB int64 `json:"memory_swap_mb"`
CPUPercent int `json:"cpu_percent"`
PidsLimit int64 `json:"pids_limit"`
Timeout time.Duration `json:"timeout"`
}
SandboxResourceLimits defines resource constraints for Docker containers. This is distinct from ResourceLimits which controls autonomous operation limits.
type SandboxResourceStats ¶
type SandboxResourceStats struct {
TotalContainers int `json:"total_containers"`
ActiveContainers int `json:"active_containers"`
TotalViolations int `json:"total_violations"`
ViolationsByType map[string]int `json:"violations_by_type"`
KilledContainers int `json:"killed_containers"`
AvgCPUUsage float64 `json:"avg_cpu_usage"`
AvgMemoryUsage float64 `json:"avg_memory_usage"`
PeakCPUUsage float64 `json:"peak_cpu_usage"`
PeakMemoryUsage float64 `json:"peak_memory_usage"`
}
SandboxResourceStats tracks resource statistics.
type SandboxResult ¶
type SandboxResult struct {
Success bool `json:"success"`
ExitCode int `json:"exit_code"`
Output string `json:"output"`
Error string `json:"error,omitempty"`
Duration time.Duration `json:"duration"`
Command string `json:"command"`
TimedOut bool `json:"timed_out"`
Metadata map[string]any `json:"metadata,omitempty"`
}
SandboxResult contains the result of a sandboxed execution.
type SandboxTemplate ¶
type SandboxTemplate struct {
Name string `json:"name"`
Image string `json:"image"`
Description string `json:"description"`
DefaultWorkDir string `json:"default_work_dir"`
ResourceLimits SandboxResourceLimits `json:"resource_limits"`
EnvVars map[string]string `json:"env_vars"`
DefaultPackages []string `json:"default_packages"`
}
SandboxTemplate provides a pre-configured sandbox setup for a specific language/runtime.
func GetSandboxTemplate ¶
func GetSandboxTemplate(name string) (SandboxTemplate, bool)
GetSandboxTemplate returns a sandbox template by name.
func ListSandboxTemplates ¶
func ListSandboxTemplates() []SandboxTemplate
ListSandboxTemplates returns all available sandbox templates.
type SessionState ¶
type SessionState struct {
SessionID string `json:"session_id"`
Task string `json:"task"`
Status SessionStatus `json:"status"`
StartTime int64 `json:"start_time"`
LastUpdate int64 `json:"last_update"`
Checkpoints []Checkpoint `json:"checkpoints"`
CurrentPhase string `json:"current_phase"`
Iteration int `json:"iteration"`
TotalCost float64 `json:"total_cost"`
Error string `json:"error,omitempty"`
}
SessionState represents the full state of an autonomous session.
type SessionStatus ¶
type SessionStatus string
SessionStatus represents the status of a session.
const ( SessionStatusRunning SessionStatus = "running" SessionStatusPaused SessionStatus = "paused" SessionStatusCompleted SessionStatus = "completed" SessionStatusFailed SessionStatus = "failed" SessionStatusInterrupted SessionStatus = "interrupted" )
type SmartRetry ¶
type SmartRetry struct {
// contains filtered or unexported fields
}
SmartRetry implements intelligent retry logic with pattern learning.
func NewSmartRetry ¶
func NewSmartRetry(config RetryConfig) *SmartRetry
NewSmartRetry creates a new SmartRetry instance.
func (*SmartRetry) AddPattern ¶
func (sr *SmartRetry) AddPattern(pattern *RetryPattern)
AddPattern adds a new retry pattern.
func (*SmartRetry) AnalyzeFailure ¶
func (sr *SmartRetry) AnalyzeFailure(errorMsg string) *FailureAnalysis
AnalyzeFailure analyzes an error and returns structured information.
func (*SmartRetry) ExecuteWithRetry ¶
func (sr *SmartRetry) ExecuteWithRetry(ctx context.Context, taskID string, fn func() error) *RetryResult
ExecuteWithRetry runs a function with smart retry logic.
func (*SmartRetry) GetBestFixHint ¶
func (sr *SmartRetry) GetBestFixHint(errorMsg string) string
GetBestFixHint returns the best fix hint based on learned history.
func (*SmartRetry) GetHistory ¶
func (sr *SmartRetry) GetHistory() []RetryAttempt
GetHistory returns the retry history.
func (*SmartRetry) GetPatternStats ¶
func (sr *SmartRetry) GetPatternStats(patternID string) *PatternStats
GetPatternStats returns statistics for a pattern.
func (*SmartRetry) GetStats ¶
func (sr *SmartRetry) GetStats() RetryStats
GetStats returns overall retry statistics.
func (*SmartRetry) LearnFromHistory ¶
func (sr *SmartRetry) LearnFromHistory()
LearnFromHistory updates pattern success rates based on history.
type SnapshotConfig ¶
type SnapshotConfig struct {
// Enabled turns snapshot functionality on/off
Enabled bool `json:"enabled"`
// StoragePath is where snapshots are stored
StoragePath string `json:"storage_path"`
// MaxSnapshots is the maximum snapshots to keep
MaxSnapshots int `json:"max_snapshots"`
// DefaultTTL is the default time-to-live
DefaultTTL time.Duration `json:"default_ttl"`
// AutoSnapshot enables automatic snapshots before destructive ops
AutoSnapshot bool `json:"auto_snapshot"`
// DestructivePatterns are patterns that trigger auto-snapshot
DestructivePatterns []string `json:"destructive_patterns,omitempty"`
// ExcludePatterns are patterns to exclude from snapshots
ExcludePatterns []string `json:"exclude_patterns,omitempty"`
// IncludeHidden includes hidden files
IncludeHidden bool `json:"include_hidden"`
// Compress enables compression
Compress bool `json:"compress"`
}
SnapshotConfig configures snapshot behavior.
func DefaultSnapshotConfig ¶
func DefaultSnapshotConfig() SnapshotConfig
DefaultSnapshotConfig returns the default snapshot configuration.
type SnapshotFile ¶
type SnapshotFile struct {
// OriginalPath is the original file path
OriginalPath string `json:"original_path"`
// SnapshotPath is the path in the snapshot
SnapshotPath string `json:"snapshot_path"`
// Size is the file size
Size int64 `json:"size"`
// Mode is the file permissions
Mode uint32 `json:"mode"`
// ModTime is the modification time
ModTime time.Time `json:"mod_time"`
// IsDir indicates if it's a directory
IsDir bool `json:"is_dir"`
// Checksum is the file checksum
Checksum string `json:"checksum"`
}
SnapshotFile represents a file in a snapshot.
type SnapshotManager ¶
type SnapshotManager struct {
// contains filtered or unexported fields
}
SnapshotManager manages file/directory snapshots.
func NewSnapshotManager ¶
func NewSnapshotManager(config SnapshotConfig) *SnapshotManager
NewSnapshotManager creates a new snapshot manager.
func (*SnapshotManager) AutoSnapshot ¶
func (sm *SnapshotManager) AutoSnapshot(operation, path string, paths []string) (*SnapshotMetadata, error)
AutoSnapshot creates a snapshot if the operation is destructive.
func (*SnapshotManager) CreateSnapshot ¶
func (sm *SnapshotManager) CreateSnapshot(name string, snapshotType SnapshotType, paths []string, opts ...SnapshotOption) (*SnapshotMetadata, error)
CreateSnapshot creates a new snapshot.
func (*SnapshotManager) DeleteSnapshot ¶
func (sm *SnapshotManager) DeleteSnapshot(snapshotID string) error
DeleteSnapshot deletes a snapshot.
func (*SnapshotManager) ExpireSnapshots ¶
func (sm *SnapshotManager) ExpireSnapshots() int
ExpireSnapshots removes expired snapshots.
func (*SnapshotManager) ExportMetadata ¶
func (sm *SnapshotManager) ExportMetadata(snapshotID string) ([]byte, error)
ExportMetadata exports snapshot metadata as JSON.
func (*SnapshotManager) GetSnapshot ¶
func (sm *SnapshotManager) GetSnapshot(snapshotID string) (*SnapshotMetadata, bool)
GetSnapshot retrieves snapshot metadata.
func (*SnapshotManager) GetSnapshotsByType ¶
func (sm *SnapshotManager) GetSnapshotsByType(snapshotType SnapshotType) []*SnapshotMetadata
GetSnapshotsByType lists snapshots of a specific type.
func (*SnapshotManager) GetStats ¶
func (sm *SnapshotManager) GetStats() SnapshotStats
GetStats returns snapshot statistics.
func (*SnapshotManager) ListSnapshots ¶
func (sm *SnapshotManager) ListSnapshots() []*SnapshotMetadata
ListSnapshots lists all snapshots.
func (*SnapshotManager) RestoreSnapshot ¶
func (sm *SnapshotManager) RestoreSnapshot(snapshotID string, opts ...RestoreOption) error
RestoreSnapshot restores a snapshot.
func (*SnapshotManager) SetAuditLogger ¶
func (sm *SnapshotManager) SetAuditLogger(logger *AuditLogger)
SetAuditLogger sets the audit logger.
func (*SnapshotManager) VerifyAndRepair ¶
func (sm *SnapshotManager) VerifyAndRepair(snapshotID string) (*VerifyResult, error)
VerifyAndRepair verifies a restore and attempts to repair any issues.
func (*SnapshotManager) VerifyRestore ¶
func (sm *SnapshotManager) VerifyRestore(snapshotID string) (*VerifyResult, error)
VerifyRestore verifies that a snapshot restore was successful. It checks that all files exist, have correct checksums, and proper permissions.
func (*SnapshotManager) VerifySnapshotIntegrity ¶
func (sm *SnapshotManager) VerifySnapshotIntegrity(snapshotID string) error
VerifySnapshotIntegrity verifies the integrity of a snapshot's stored data.
type SnapshotMetadata ¶
type SnapshotMetadata struct {
// ID is the unique snapshot identifier
ID string `json:"id"`
// Name is a human-readable name
Name string `json:"name,omitempty"`
// Type is the snapshot type
Type SnapshotType `json:"type"`
// Status is the current status
Status SnapshotStatus `json:"status"`
// CreatedAt is when the snapshot was created
CreatedAt time.Time `json:"created_at"`
// ExpiresAt is when the snapshot expires
ExpiresAt *time.Time `json:"expires_at,omitempty"`
// Size is the total size in bytes
Size int64 `json:"size"`
// FileCount is the number of files included
FileCount int `json:"file_count"`
// Files is the list of files in the snapshot
Files []SnapshotFile `json:"files,omitempty"`
// BasePath is the original base path
BasePath string `json:"base_path"`
// StoragePath is where the snapshot is stored
StoragePath string `json:"storage_path"`
// Tags are user-defined tags
Tags []string `json:"tags,omitempty"`
// Reason is why the snapshot was created
Reason string `json:"reason,omitempty"`
// ParentSnapshot is the parent snapshot ID (for incremental)
ParentSnapshot string `json:"parent_snapshot,omitempty"`
// Checksum for snapshot integrity
Checksum string `json:"checksum"`
// RestoredAt is when it was restored
RestoredAt *time.Time `json:"restored_at,omitempty"`
// RestoreCount is how many times it was restored
RestoreCount int `json:"restore_count"`
}
SnapshotMetadata contains metadata about a snapshot.
type SnapshotOption ¶
type SnapshotOption func(*SnapshotMetadata)
SnapshotOption is a functional option for creating snapshots.
func WithExpiry ¶
func WithExpiry(expiresAt time.Time) SnapshotOption
WithExpiry sets the expiry time.
func WithParent ¶
func WithParent(parentID string) SnapshotOption
WithParent sets the parent snapshot.
type SnapshotSafetySettings ¶
type SnapshotSafetySettings struct {
// Enabled turns on auto-snapshot
Enabled bool `json:"enabled"`
// AutoOnDestructive creates snapshot before destructive ops
AutoOnDestructive bool `json:"auto_on_destructive"`
// AutoOnModify creates snapshot before modifications
AutoOnModify bool `json:"auto_on_modify"`
// AutoOnAll creates snapshot before any operation
AutoOnAll bool `json:"auto_on_all"`
// MinDangerLevel is the minimum danger level to trigger snapshot
MinDangerLevel DangerLevel `json:"min_danger_level"`
// RetentionCount is how many snapshots to keep
RetentionCount int `json:"retention_count"`
// RetentionDuration is how long to keep snapshots
RetentionDuration time.Duration `json:"retention_duration"`
// VerifyAfterRestore verifies integrity after restore
VerifyAfterRestore bool `json:"verify_after_restore"`
}
SnapshotSafetySettings controls snapshot behavior.
type SnapshotStats ¶
type SnapshotStats struct {
TotalSnapshots int `json:"total_snapshots"`
TotalSize int64 `json:"total_size"`
TotalFiles int `json:"total_files"`
ActiveSnapshots int `json:"active_snapshots"`
ExpiredSnapshots int `json:"expired_snapshots"`
RestoredCount int `json:"restored_count"`
FailedCount int `json:"failed_count"`
ByType map[string]int `json:"by_type"`
OldestSnapshot *time.Time `json:"oldest_snapshot,omitempty"`
NewestSnapshot *time.Time `json:"newest_snapshot,omitempty"`
}
SnapshotStats tracks snapshot statistics.
type SnapshotStatus ¶
type SnapshotStatus string
SnapshotStatus represents the status of a snapshot.
const ( // SnapshotStatusCreating - Snapshot is being created SnapshotStatusCreating SnapshotStatus = "creating" // SnapshotStatusComplete - Snapshot is complete SnapshotStatusComplete SnapshotStatus = "complete" // SnapshotStatusRestoring - Snapshot is being restored SnapshotStatusRestoring SnapshotStatus = "restoring" // SnapshotStatusRestored - Snapshot has been restored SnapshotStatusRestored SnapshotStatus = "restored" // SnapshotStatusFailed - Snapshot operation failed SnapshotStatusFailed SnapshotStatus = "failed" // SnapshotStatusExpired - Snapshot has expired SnapshotStatusExpired SnapshotStatus = "expired" )
type SnapshotType ¶
type SnapshotType string
SnapshotType represents the type of snapshot.
const ( // SnapshotTypeFile - Single file snapshot SnapshotTypeFile SnapshotType = "file" // SnapshotTypeDirectory - Directory snapshot SnapshotTypeDirectory SnapshotType = "directory" // SnapshotTypeProject - Full project snapshot SnapshotTypeProject SnapshotType = "project" // SnapshotTypeSelective - Selective files/directories SnapshotTypeSelective SnapshotType = "selective" )
type StateManager ¶
type StateManager struct {
// contains filtered or unexported fields
}
StateManager handles persistence and recovery of autonomous session state.
func NewStateManager ¶
func NewStateManager(stateDir string, sessionID string) *StateManager
NewStateManager creates a new state manager.
func (*StateManager) CreateCheckpoint ¶
func (sm *StateManager) CreateCheckpoint(phase string, iteration int, task string, plan *Plan, completedSteps, pendingSteps []int, result *Result) (*Checkpoint, error)
CreateCheckpoint saves the current state for later resumption.
func (*StateManager) DeleteSession ¶
func (sm *StateManager) DeleteSession(sessionID string) error
DeleteSession removes a saved session.
func (*StateManager) GetLatestCheckpoint ¶
func (sm *StateManager) GetLatestCheckpoint() *Checkpoint
GetLatestCheckpoint returns the most recent checkpoint.
func (*StateManager) ListSessions ¶
func (sm *StateManager) ListSessions() ([]SessionState, error)
ListSessions returns all saved sessions.
func (*StateManager) RestoreFromCheckpoint ¶
func (sm *StateManager) RestoreFromCheckpoint(checkpointID string) (*Checkpoint, error)
RestoreFromCheckpoint restores state from a specific checkpoint.
func (*StateManager) ResumeSession ¶
func (sm *StateManager) ResumeSession(sessionID string) (*SessionState, error)
ResumeSession loads a previously interrupted session.
func (*StateManager) SaveSession ¶
func (sm *StateManager) SaveSession(task string, status SessionStatus, phase string, iteration int, totalCost float64, errMsg string) error
SaveSession persists the current session state.
type Status ¶
type Status struct {
Phase string // current phase: "planning", "executing", "verifying", "retrying", "completed", "failed"
Iteration int // current iteration number
Task string // current task description
FilesModified []string // files modified so far
CommandsRun []string // commands run so far
SuccessRate float64 // success rate of iterations
StartTime time.Time // when the run started
ElapsedTime time.Duration // time elapsed since start
EstimatedCost float64 // estimated cost so far
LastError string // last error encountered
Confidence float64 // agent confidence score (0-1)
PendingAction string // next action to be taken (for approval)
NeedsApproval bool // whether approval is needed for next action
}
Status represents the current state of an autonomous run.
type StepStatus ¶
type StepStatus string
StepStatus represents the status of a step.
const ( StepPending StepStatus = "pending" StepRunning StepStatus = "running" StepCompleted StepStatus = "completed" StepFailed StepStatus = "failed" StepSkipped StepStatus = "skipped" StepRetrying StepStatus = "retrying" )
type SuccessCriteriaConfig ¶
type SuccessCriteriaConfig struct {
DefaultTimeout time.Duration `json:"default_timeout"`
DefaultRetries int `json:"default_retries"`
DefaultRetryDelay time.Duration `json:"default_retry_delay"`
ParallelChecks bool `json:"parallel_checks"`
StopOnFirstFail bool `json:"stop_on_first_fail"`
}
SuccessCriteriaConfig configures the success criteria validator
func DefaultSuccessCriteriaConfig ¶
func DefaultSuccessCriteriaConfig() SuccessCriteriaConfig
DefaultSuccessCriteriaConfig returns default configuration
type SuccessCriteriaValidator ¶
type SuccessCriteriaValidator struct {
// contains filtered or unexported fields
}
SuccessCriteriaValidator validates success criteria before task completion
func NewSuccessCriteriaValidator ¶
func NewSuccessCriteriaValidator(config SuccessCriteriaConfig) *SuccessCriteriaValidator
NewSuccessCriteriaValidator creates a new validator
func (*SuccessCriteriaValidator) GetStats ¶
func (v *SuccessCriteriaValidator) GetStats() map[string]any
GetStats returns statistics about the validator
func (*SuccessCriteriaValidator) QuickValidate ¶
func (v *SuccessCriteriaValidator) QuickValidate(ctx context.Context, criterion *SuccessCriterion) (*ValidationResult, error)
QuickValidate performs a quick validation of a single criterion
func (*SuccessCriteriaValidator) RegisterChecker ¶
func (v *SuccessCriteriaValidator) RegisterChecker(criterionType CriterionType, checker CriterionChecker)
RegisterChecker registers a custom criterion checker
func (*SuccessCriteriaValidator) SetLogger ¶
func (v *SuccessCriteriaValidator) SetLogger(logger interface { Info(msg string, args ...any) Warn(msg string, args ...any) Error(msg string, args ...any) })
SetLogger sets the logger for the validator
func (*SuccessCriteriaValidator) Validate ¶
func (v *SuccessCriteriaValidator) Validate(ctx context.Context, criteria []*SuccessCriterion) *ValidationReport
Validate validates all criteria and returns a report
type SuccessCriterion ¶
type SuccessCriterion struct {
ID string `json:"id"`
Type CriterionType `json:"type"`
Name string `json:"name"`
Description string `json:"description"`
Required bool `json:"required"` // Must pass for overall success
Weight float64 `json:"weight"` // Weight for scoring (0.0-1.0)
Target string `json:"target"` // File path, command, or target identifier
Pattern string `json:"pattern"` // Pattern to match (regex or substring)
Expected string `json:"expected"` // Expected value or output
Negate bool `json:"negate"` // Negate the result
Timeout time.Duration `json:"timeout"`
RetryCount int `json:"retry_count"`
RetryDelay time.Duration `json:"retry_delay"`
Status CriterionStatus `json:"status"`
Message string `json:"message"` // Result message
CheckedAt time.Time `json:"checked_at"`
Duration time.Duration `json:"duration"` // How long the check took
Metadata map[string]any `json:"metadata,omitempty"`
}
SuccessCriterion represents a single success criterion
type TaskExecutor ¶
type TaskExecutor func(ctx context.Context, task *QueuedTask) (*Result, error)
TaskExecutor is a function that executes a task.
type TaskPriority ¶
type TaskPriority int
TaskPriority represents the priority level of a task.
const ( PriorityLow TaskPriority = iota PriorityNormal PriorityHigh PriorityCritical )
func (TaskPriority) String ¶
func (p TaskPriority) String() string
String returns the string representation of TaskPriority.
type TaskQueue ¶
type TaskQueue struct {
// contains filtered or unexported fields
}
TaskQueue manages parallel execution of autonomous tasks.
func NewTaskQueue ¶
func NewTaskQueue(executor TaskExecutor, config TaskQueueConfig) *TaskQueue
NewTaskQueue creates a new task queue.
func (*TaskQueue) AddTask ¶
func (tq *TaskQueue) AddTask(name string, description string, priority TaskPriority, dependencies []string) *QueuedTask
AddTask adds a new task to the queue.
func (*TaskQueue) GetCompleted ¶
func (tq *TaskQueue) GetCompleted() []*QueuedTask
GetCompleted returns all completed tasks.
func (*TaskQueue) GetPending ¶
func (tq *TaskQueue) GetPending() []*QueuedTask
GetPending returns all pending tasks.
func (*TaskQueue) GetRunning ¶
func (tq *TaskQueue) GetRunning() []*QueuedTask
GetRunning returns all running tasks.
func (*TaskQueue) GetStats ¶
func (tq *TaskQueue) GetStats() QueueStats
GetStats returns queue statistics.
func (*TaskQueue) GetTask ¶
func (tq *TaskQueue) GetTask(id string) *QueuedTask
GetTask returns a task by ID.
func (*TaskQueue) SetTaskMetadata ¶
SetTaskMetadata sets metadata on a task.
func (*TaskQueue) Stop ¶
func (tq *TaskQueue) Stop()
Stop stops the queue and waits for running tasks.
func (*TaskQueue) WaitForCompletion ¶
WaitForCompletion waits for all tasks to complete.
func (*TaskQueue) WaitForTask ¶
WaitForTask waits for a specific task to complete.
type TaskQueueConfig ¶
type TaskQueueConfig struct {
MaxParallel int // Maximum parallel tasks (default: 4)
Timeout time.Duration // Default task timeout (default: 5min)
MaxRetries int // Max retries per task (default: 2)
}
TaskQueueConfig holds configuration for the task queue.
func DefaultTaskQueueConfig ¶
func DefaultTaskQueueConfig() TaskQueueConfig
DefaultTaskQueueConfig returns sensible defaults.
type TaskStatus ¶
type TaskStatus string
TaskStatus represents the current status of a task.
const ( TaskStatusPending TaskStatus = "pending" TaskStatusQueued TaskStatus = "queued" TaskStatusRunning TaskStatus = "running" TaskStatusCompleted TaskStatus = "completed" TaskStatusFailed TaskStatus = "failed" TaskStatusCancelled TaskStatus = "cancelled" TaskStatusRetrying TaskStatus = "retrying" )
type TestFailure ¶
type TestFailure struct {
TestName string
Package string
Error string
File string
Line int
Expected string
Got string
Category string
FixSuggestion string
}
TestFailure represents a single test failure.
type TestResult ¶
type TestResult struct {
Passed bool
Output string
BuildOutput string
TestOutput string
Duration time.Duration
Failures []TestFailure
Summary TestSummary
}
TestResult holds the result of a test run.
type TestRunner ¶
type TestRunner struct {
// contains filtered or unexported fields
}
TestRunner provides autonomous test execution with failure analysis.
func NewTestRunner ¶
func NewTestRunner(engine *Engine) *TestRunner
NewTestRunner creates a new test runner.
func (*TestRunner) DetectFlakyTests ¶
DetectFlakyTests runs tests multiple times to detect flakiness.
func (*TestRunner) RunBenchmarks ¶
func (tr *TestRunner) RunBenchmarks(ctx context.Context) (*TestResult, error)
RunBenchmarks runs benchmark tests.
func (*TestRunner) RunSpecificTests ¶
func (tr *TestRunner) RunSpecificTests(ctx context.Context, testNames []string) (*TestResult, error)
RunSpecificTests runs only the specified test functions.
func (*TestRunner) RunTestsWithAnalysis ¶
func (tr *TestRunner) RunTestsWithAnalysis(ctx context.Context) (*TestResult, error)
RunTestsWithAnalysis runs tests and analyzes failures.
func (*TestRunner) RunTestsWithAutoFix ¶
func (tr *TestRunner) RunTestsWithAutoFix(ctx context.Context) (*TestResult, error)
RunTestsWithAutoFix runs tests and attempts to auto-fix failures.
type TestSummary ¶
type TestSummary struct {
TotalTests int
PassedTests int
FailedTests int
SkippedTests int
Coverage float64
}
TestSummary holds aggregated test statistics.
type TimeRestriction ¶
type TimeRestriction struct {
// AllowedHours are the hours (0-23) when the command is allowed
AllowedHours []int `json:"allowed_hours,omitempty"`
// BlockedHours are the hours when the command is blocked
BlockedHours []int `json:"blocked_hours,omitempty"`
// AllowedDays are the days (0=Sunday, 6=Saturday) when allowed
AllowedDays []int `json:"allowed_days,omitempty"`
// BlockedDays are the days when blocked
BlockedDays []int `json:"blocked_days,omitempty"`
// StartTime is the start time (HH:MM format)
StartTime string `json:"start_time,omitempty"`
// EndTime is the end time (HH:MM format)
EndTime string `json:"end_time,omitempty"`
}
TimeRestriction restricts when commands can run.
type TriggerAction ¶
type TriggerAction struct {
AutoEscalate bool `json:"auto_escalate"` // Automatically escalate urgency
Timeout time.Duration `json:"timeout"` // Time before auto-decision
AutoDecision string `json:"auto_decision"` // Default choice on timeout
NotifyChannels []string `json:"notify_channels"` // Where to notify (slack, email, etc.)
BlockExecution bool `json:"block_execution"` // Block until response
}
TriggerAction defines what happens when a trigger fires
type TriggerCondition ¶
type TriggerCondition struct {
Type DecisionType `json:"type"`
MinConfidence float64 `json:"min_confidence"` // Fire if confidence below this
MaxConfidence float64 `json:"max_confidence"` // Or if confidence above this (for risky ops)
Patterns []string `json:"patterns,omitempty"` // Regex patterns to match
Keywords []string `json:"keywords,omitempty"` // Keywords to trigger on
CostThreshold float64 `json:"cost_threshold,omitempty"` // Cost in dollars
CustomCheck string `json:"custom_check,omitempty"` // Named custom check function
}
TriggerCondition defines when a human-in-loop trigger should fire
type UrgencyLevel ¶
type UrgencyLevel string
UrgencyLevel represents how quickly a decision is needed
const ( UrgencyLow UrgencyLevel = "low" // Can wait hours UrgencyMedium UrgencyLevel = "medium" // Should be addressed soon UrgencyHigh UrgencyLevel = "high" // Blocking current operation UrgencyCritical UrgencyLevel = "critical" // System stuck without input )
type ValidationReport ¶
type ValidationReport struct {
TaskID string `json:"task_id"`
TaskName string `json:"task_name"`
TotalCriteria int `json:"total_criteria"`
Passed int `json:"passed"`
Failed int `json:"failed"`
Skipped int `json:"skipped"`
Score float64 `json:"score"` // 0.0-1.0 weighted score
AllRequiredPass bool `json:"all_required_pass"`
Criteria []*SuccessCriterion `json:"criteria"`
GeneratedAt time.Time `json:"generated_at"`
Duration time.Duration `json:"duration"`
Summary string `json:"summary"`
}
ValidationReport represents a complete validation report
func (*ValidationReport) IsSuccess ¶
func (r *ValidationReport) IsSuccess() bool
IsSuccess checks if a validation report indicates success
type ValidationResult ¶
type ValidationResult struct {
CriterionID string `json:"criterion_id"`
Passed bool `json:"passed"`
Message string `json:"message"`
Details map[string]any `json:"details,omitempty"`
Error error `json:"error,omitempty"`
Duration time.Duration `json:"duration"`
}
ValidationResult represents the result of validating a criterion
type VerificationResult ¶
type VerifyResult ¶
type VerifyResult struct {
// Success indicates if verification passed
Success bool `json:"success"`
// VerifiedFiles is the number of files verified
VerifiedFiles int `json:"verified_files"`
// FailedFiles is the number of files that failed verification
FailedFiles int `json:"failed_files"`
// MissingFiles are files that were not found after restore
MissingFiles []string `json:"missing_files,omitempty"`
// ChecksumMismatches are files with checksum mismatches
ChecksumMismatches []ChecksumMismatch `json:"checksum_mismatches,omitempty"`
// PermissionErrors are files with permission mismatches
PermissionErrors []PermissionError `json:"permission_errors,omitempty"`
// ExtraFiles are files found that weren't in the snapshot
ExtraFiles []string `json:"extra_files,omitempty"`
// Duration is how long verification took
Duration time.Duration `json:"duration"`
}
VerifyResult contains the result of a restore verification.
type VolumeMount ¶
type VolumeMount struct {
HostPath string `json:"host_path"`
ContainerPath string `json:"container_path"`
ReadOnly bool `json:"read_only"`
}
VolumeMount represents a volume mount in the container.
Source Files
¶
- audit_log.go
- autonomous.go
- command_approval.go
- confidence.go
- danger_assessment.go
- debug_mode.go
- emergency_stop.go
- failure_learner.go
- goal_state.go
- human_in_loop.go
- planner.go
- playbook.go
- progress_dashboard.go
- protected_paths.go
- resource_limits.go
- resource_limits_manager.go
- restricted_commands.go
- review_checkpoint.go
- rollback.go
- safety_profile.go
- sandbox.go
- sandbox_isolation.go
- sandbox_network.go
- sandbox_templates.go
- smart_retry.go
- snapshot.go
- state_manager.go
- success_criteria.go
- task_queue.go
- test_runner.go