agent

package
v0.5.3 Latest Latest
Warning

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

Go to latest
Published: Jul 31, 2026 License: MIT Imports: 31 Imported by: 0

Documentation

Index

Constants

View Source
const (
	EventKindWarning = "warning"
)

Additional event kinds for Cortex integration

Variables

This section is empty.

Functions

func BuildHandoffPrompt added in v0.3.1

func BuildHandoffPrompt(result *HandoffResult, lastUserMessage string) string

BuildHandoffPrompt builds the continuation prompt after a handoff This preserves context while switching to the new model/profile

func MarshalHandoffResult added in v0.3.1

func MarshalHandoffResult(r *HandoffResult) string

MarshalHandoffResult returns a JSON string representation of the handoff result

func SanitizeMessageHistory added in v0.5.1

func SanitizeMessageHistory(messages []provider.Message) []provider.Message

SanitizeMessageHistory returns a copy of the history with offending messages dropped so the result passes ValidateMessageAlternation. It is a best-effort repair: it preserves system messages and the maximal legal prefix/suffix, dropping only the messages that break alternation. Tool messages that lose their preceding assistant are also dropped (they are meaningless alone).

This is used as a defensive last resort before sending to a provider; the agent loop should ideally not produce illegal histories, but streaming fallbacks and partial failures can.

Types

type Agent

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

Agent handles AI conversation with tool execution

func NewAIAgent

func NewAIAgent(prov provider.Provider, registry ToolRegistry, tools []map[string]interface{}, systemPrompt string) *Agent

NewAIAgent creates a new AI agent

func NewEnhancedAgent

func NewEnhancedAgent(prov provider.Provider, registry ToolRegistry, tools []map[string]interface{}, systemPrompt string, opts ...AgentOption) *Agent

NewEnhancedAgent creates an agent with enhanced features

func (*Agent) AddSkillsContext

func (a *Agent) AddSkillsContext(skillsCtx string)

AddSkillsContext adds skills context to system prompt

func (*Agent) AddSystemContext

func (a *Agent) AddSystemContext(ctx string)

AddSystemContext appends context to the system prompt message. If no system message exists, creates one.

func (*Agent) Emit

func (a *Agent) Emit(kind bus.EventKind, data interface{})

Emit emits an event to the event bus

func (*Agent) EnableCompression

func (a *Agent) EnableCompression(enabled bool)

EnableCompression enables/disables context compression

func (*Agent) ExecuteComplexTask

func (a *Agent) ExecuteComplexTask(ctx context.Context, taskDescription string) (string, error)

ExecuteComplexTask decomposes a complex task, executes sub-tasks, and returns aggregated results

func (*Agent) GetApprovalHook added in v0.4.10

func (a *Agent) GetApprovalHook() *ApprovalHook

GetApprovalHook returns the agent's approval hook for web API access. Returns nil if the approval hook is not available.

func (*Agent) GetHistory

func (a *Agent) GetHistory() []provider.Message

GetHistory returns the conversation history

func (*Agent) GetHistoryLength

func (a *Agent) GetHistoryLength() int

GetHistoryLength returns the current history length in characters

func (*Agent) GetProvider

func (a *Agent) GetProvider() provider.Provider

GetProvider returns the agent's provider for use by other components

func (*Agent) GetTokenStats added in v0.3.0

func (a *Agent) GetTokenStats() (inputTokens, outputTokens, cacheReadTokens int)

GetTokenStats returns the token usage statistics

func (*Agent) GetTokenUsage added in v0.3.0

func (a *Agent) GetTokenUsage() TokenUsage

GetTokenUsage returns the usage statistics as a TokenUsage struct

func (*Agent) Reset

func (a *Agent) Reset()

Reset clears the conversation history

func (*Agent) RunConversation

func (a *Agent) RunConversation(ctx context.Context, input string) (string, error)

RunConversation runs a conversation with automatic tool execution

func (*Agent) RunConversationStream

func (a *Agent) RunConversationStream(ctx context.Context, input string, handler StreamHandler) error

RunConversationStream runs a streaming conversation

func (*Agent) RunConversationStreamWithMedia added in v0.4.11

func (a *Agent) RunConversationStreamWithMedia(ctx context.Context, input string, contentParts []types.ContentPart, handler StreamHandler) error

RunConversationStreamWithMedia runs a streaming conversation with multimodal input support. If contentParts is provided, it takes priority over plain text input.

func (*Agent) RunConversationStreamWithOutput

func (a *Agent) RunConversationStreamWithOutput(ctx context.Context, input string) (*strings.Builder, error)

RunConversationStreamWithOutput runs streaming and returns output builder

func (*Agent) RunConversationWithMedia

func (a *Agent) RunConversationWithMedia(ctx context.Context, input string, contentParts []types.ContentPart) (string, error)

RunConversationWithMedia runs a conversation with multimodal input support. If contentParts is provided, it takes priority over plain text input.

func (*Agent) RunWithCortex

func (a *Agent) RunWithCortex(ctx context.Context, input string) (string, error)

RunWithCortex runs a conversation with full Cortex Agent integration. This enhanced method leverages all Cortex systems:

  • SOUL.md system personality
  • USER.md user profile
  • LLM Planner for complex task decomposition
  • Context compression for long conversations
  • Trajectory recording for self-evolution (GEPA)
  • Prompt caching
  • Perception / Cognition / Execution three-layer architecture
  • Frozen snapshot memory protection

func (*Agent) SetCompressionRatio

func (a *Agent) SetCompressionRatio(ratio float64)

SetCompressionRatio sets the threshold ratio for compression

func (*Agent) SetHistory

func (a *Agent) SetHistory(history []provider.Message)

SetHistory sets the conversation history

func (*Agent) SetMaxIterations

func (a *Agent) SetMaxIterations(max int)

SetMaxIterations sets the maximum iterations

func (*Agent) SetSession

func (a *Agent) SetSession(session string)

SetSession sets the session ID for event tracking

type AgentOption

type AgentOption func(*Agent)

AgentOption configures the agent

func WithApprovalManager added in v0.4.12

func WithApprovalManager(mgr *approval.Manager) AgentOption

WithApprovalManager sets an external approval manager for the agent.

func WithConvertConfig added in v0.4.19

func WithConvertConfig(cfg *provider.ConvertConfig) AgentOption

WithConvertConfig sets the file conversion configuration

func WithCortex

func WithCortex(mgr *cortex.Manager) AgentOption

WithCortex enables Cortex Agent six-system integration

func WithEventBus

func WithEventBus(eventBus *bus.EventBus) AgentOption

WithEventBus sets a custom event bus

func WithHooks

func WithHooks(hookRegs ...hooks.HookRegistration) AgentOption

WithHooks registers hooks

func WithLoopLimits

func WithLoopLimits(sameToolLimit, consecutiveLimit int) AgentOption

WithLoopLimits configures loop detection limits

func WithMemory

func WithMemory(enabled bool) AgentOption

WithMemory enables memory integration

func WithPlanExecution added in v0.5.1

func WithPlanExecution(cfg PlanExecutorConfig) AgentOption

WithPlanExecution enables plan-guided agent execution

func WithReflection added in v0.5.1

func WithReflection(cfg ReflectionConfig) AgentOption

WithReflection configures the self-reflection mechanism

func WithRepeatedFailureDetector added in v0.5.1

func WithRepeatedFailureDetector(d *retry.RepeatedFailureDetector) AgentOption

WithRepeatedFailureDetector installs a custom repeated-failure detector. Pass nil to disable escalation. When enabled, the agent halts with a structured diagnostic once the same equivalent failure recurs Threshold times within Window, instead of silently retrying until the turn cap (Hermes #22112).

func WithSecretRedaction

func WithSecretRedaction(enabled bool) AgentOption

WithSecretRedaction enables or disables secret redaction (API keys, tokens, etc.)

func WithSteering

func WithSteering(cfg SteeringConfig) AgentOption

WithSteering configures steering settings

func WithSubTask

func WithSubTask(enabled bool) AgentOption

WithSubTask enables or disables automatic sub-task delegation

func WithTrajectoryLearning added in v0.5.1

func WithTrajectoryLearning(store *cortex.TrajectoryStore, cfg cortex.TrajectoryInjectorConfig) AgentOption

WithTrajectoryLearning enables trajectory-based learning from past executions

type ApprovalHook

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

ApprovalHook provides command approval functionality using the smart approval system. It supports CLI interactive prompts with rich risk display, Web-based approval mode, TUI mode via injectable PromptFunc, approval timeout handling, and session-level skip behavior.

func NewApprovalHook

func NewApprovalHook() *ApprovalHook

NewApprovalHook creates a new approval hook with smart approval.

func NewApprovalHookWithManager added in v0.4.12

func NewApprovalHookWithManager(mgr *approval.Manager) *ApprovalHook

NewApprovalHookWithManager creates a new approval hook using an existing manager.

func (*ApprovalHook) AfterLLM

AfterLLM passes through the response unchanged.

func (*ApprovalHook) AfterTool

AfterTool passes through the result unchanged.

func (*ApprovalHook) ApproveTool

ApproveTool handles approval request (for gateway integration).

func (*ApprovalHook) BeforeLLM

BeforeLLM passes through the request unchanged.

func (*ApprovalHook) BeforeTool

BeforeTool handles approval for tool execution. Intercepts high-risk tools: execute_command, write_file, file_edit, execute_code

func (*ApprovalHook) ClearAllSessionSkip added in v0.5.1

func (h *ApprovalHook) ClearAllSessionSkip()

ClearAllSessionSkip removes all skip patterns for every session. Agent.Reset 调用此方法以避免上个会话的 skip 决策污染新会话。

func (*ApprovalHook) ClearSessionSkip added in v0.5.1

func (h *ApprovalHook) ClearSessionSkip(sessionID string)

ClearSessionSkip removes all skip patterns for the given session.

func (*ApprovalHook) GetManager added in v0.4.10

func (h *ApprovalHook) GetManager() *approval.Manager

GetManager exposes the underlying approval.Manager for Web API usage.

func (*ApprovalHook) Name

func (h *ApprovalHook) Name() string

Name returns the hook name.

func (*ApprovalHook) SetPromptFunc added in v0.4.12

func (h *ApprovalHook) SetPromptFunc(fn ApprovalPromptFunc)

SetPromptFunc injects a custom approval prompt function for TUI or other non-stdio environments. When set, this function is called instead of the default CLI stdin reader.

func (*ApprovalHook) SetWebMode added in v0.4.10

func (h *ApprovalHook) SetWebMode(enabled bool)

SetWebMode enables or disables Web-based approval mode. When enabled, user-facing confirmations are routed through the Web callback system (PendingWebApproval) instead of CLI prompts.

type ApprovalPromptFunc added in v0.4.12

type ApprovalPromptFunc func(command, reason string, riskLevel approval.RiskLevel) bool

ApprovalPromptFunc is the signature for a custom approval prompt. Returns true to approve, false to deny.

type ComplexityAnalyzer

type ComplexityAnalyzer = complexity.Analyzer

ComplexityAnalyzer is an alias for complexity.Analyzer for backward compatibility

func NewComplexityAnalyzer

func NewComplexityAnalyzer() *ComplexityAnalyzer

NewComplexityAnalyzer creates a new complexity analyzer This is a wrapper around complexity.NewAnalyzer() for backward compatibility

type ComplexityScore added in v0.4.10

type ComplexityScore = complexity.Score

ComplexityScore is an alias for complexity.Score for backward compatibility

type CompressionConfig

type CompressionConfig struct {
	// Threshold ratio to trigger compression (0.0-1.0)
	ThresholdRatio float64
	// Minimum messages to keep
	MinMessages int
	// Keep recent messages count
	KeepRecent int
	// Keep first messages count
	KeepFirst int
	// Preserve tool results
	PreserveToolResults bool
	// Preserve decisions
	PreserveDecisions bool
}

CompressionConfig holds configuration for context compression

func DefaultCompressionConfig

func DefaultCompressionConfig() *CompressionConfig

DefaultCompressionConfig returns default compression configuration

type CompressionResult

type CompressionResult struct {
	OriginalCount int
	NewCount      int
	Summary       string
	KeptMessages  []provider.Message
}

CompressionResult holds the result of a compression operation

type Goal

type Goal struct {
	ID          string     `json:"id"`
	Text        string     `json:"text"`
	State       GoalState  `json:"state"`
	TurnCount   int        `json:"turn_count"`
	MaxTurns    int        `json:"max_turns"`
	CreatedAt   time.Time  `json:"created_at"`
	LastJudgeAt *time.Time `json:"last_judge_at"`
	JudgeResult string     `json:"judge_result"`
}

Goal represents a persistent cross-turn goal

type GoalManager

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

GoalManager manages the lifecycle of goals

func NewGoalManager

func NewGoalManager(prov provider.Provider, dataDir string) *GoalManager

NewGoalManager creates a new GoalManager

func (*GoalManager) AddSubGoal added in v0.3.1

func (gm *GoalManager) AddSubGoal(text string) (*SubGoal, error)

AddSubGoal adds a new sub-goal to the current active goal Returns the sub-goal text that should be appended to the goal prompt

func (*GoalManager) BuildSubGoalPrompt added in v0.3.1

func (gm *GoalManager) BuildSubGoalPrompt() string

BuildSubGoalPrompt builds the prompt text including all sub-goals This is appended to the judge prompt so the LLM considers sub-goals

func (*GoalManager) Clear

func (gm *GoalManager) Clear()

Clear clears the current goal

func (*GoalManager) ClearSubGoals added in v0.3.1

func (gm *GoalManager) ClearSubGoals()

ClearSubGoals removes all sub-goals

func (*GoalManager) GetContinuationPrompt

func (gm *GoalManager) GetContinuationPrompt() string

GetContinuationPrompt generates a continuation prompt

func (*GoalManager) GetSessionID

func (gm *GoalManager) GetSessionID() string

GetSessionID extracts session ID from the goal's ID field (used as session identifier)

func (*GoalManager) GetStatus

func (gm *GoalManager) GetStatus() *Goal

GetStatus returns the current goal status

func (*GoalManager) GetSubGoals added in v0.3.1

func (gm *GoalManager) GetSubGoals() []SubGoal

GetSubGoals returns all sub-goals for the current goal

func (*GoalManager) IncrementTurn

func (gm *GoalManager) IncrementTurn()

IncrementTurn increments the turn count

func (*GoalManager) IsExhausted

func (gm *GoalManager) IsExhausted() bool

IsExhausted checks if the goal has exhausted its turn budget

func (*GoalManager) JudgeGoal

func (gm *GoalManager) JudgeGoal(ctx context.Context, lastResponse string) (achieved bool, reason string, err error)

JudgeGoal judges if the goal has been achieved based on the last assistant response

func (*GoalManager) Load

func (gm *GoalManager) Load(sessionID string) error

Load loads a goal from disk

func (*GoalManager) Pause

func (gm *GoalManager) Pause() *Goal

Pause pauses the current goal

func (*GoalManager) RemoveSubGoal added in v0.3.1

func (gm *GoalManager) RemoveSubGoal(id string) bool

RemoveSubGoal removes a sub-goal by ID

func (*GoalManager) Resume

func (gm *GoalManager) Resume() *Goal

Resume resumes a paused goal

func (*GoalManager) Save

func (gm *GoalManager) Save() error

Save persists the goal to disk using the goal's ID as session identifier

func (*GoalManager) SaveWithSessionID

func (gm *GoalManager) SaveWithSessionID(sessionID string) error

SaveWithSessionID persists the goal with a specific session ID

func (*GoalManager) SetGoal

func (gm *GoalManager) SetGoal(text string) *Goal

SetGoal creates a new goal

func (*GoalManager) SetMaxTurns

func (gm *GoalManager) SetMaxTurns(max int)

SetMaxTurns sets the maximum turns for new goals

func (*GoalManager) SetState

func (gm *GoalManager) SetState(state GoalState)

SetState sets the goal state

type GoalState

type GoalState string

GoalState represents the state of a goal

const (
	GoalActive    GoalState = "active"
	GoalPaused    GoalState = "paused"
	GoalAchieved  GoalState = "achieved"
	GoalExhausted GoalState = "exhausted"
	GoalCleared   GoalState = "cleared"
)

type HandoffManager added in v0.3.1

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

HandoffManager manages session handoffs between models/profiles

func NewHandoffManager added in v0.3.1

func NewHandoffManager() *HandoffManager

NewHandoffManager creates a new HandoffManager

func (*HandoffManager) ExecuteHandoff added in v0.3.1

func (hm *HandoffManager) ExecuteHandoff(ctx context.Context, sessionID, currentModel, currentProfile string, req HandoffRequest) *HandoffResult

ExecuteHandoff performs a session handoff It transfers the current session context to a new model/profile

func (*HandoffManager) GetHandoffHistory added in v0.3.1

func (hm *HandoffManager) GetHandoffHistory(sessionID string) []HandoffRecord

GetHandoffHistory returns the handoff history for a session

type HandoffRecord added in v0.3.1

type HandoffRecord struct {
	ID           string    `json:"id"`
	SessionID    string    `json:"session_id"`
	FromModel    string    `json:"from_model"`
	ToModel      string    `json:"to_model"`
	FromProfile  string    `json:"from_profile"`
	ToProfile    string    `json:"to_profile"`
	MessageCount int       `json:"message_count"`
	Reason       string    `json:"reason"`
	Timestamp    time.Time `json:"timestamp"`
}

HandoffRecord stores the history of handoffs

type HandoffRequest added in v0.3.1

type HandoffRequest struct {
	TargetModel       string `json:"target_model"`
	TargetProfile     string `json:"target_profile"`
	TargetPersonality string `json:"target_personality"`
	Reason            string `json:"reason"`
}

HandoffRequest represents a session handoff request

type HandoffResult added in v0.3.1

type HandoffResult struct {
	Success      bool      `json:"success"`
	FromModel    string    `json:"from_model"`
	ToModel      string    `json:"to_model"`
	FromProfile  string    `json:"from_profile"`
	ToProfile    string    `json:"to_profile"`
	MessageCount int       `json:"message_count"`
	TokenCount   int       `json:"token_count"`
	HandoffID    string    `json:"handoff_id"`
	Timestamp    time.Time `json:"timestamp"`
	Error        string    `json:"error,omitempty"`
}

HandoffResult represents the result of a handoff operation

type IntelligentCompressor

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

IntelligentCompressor provides smart context compression

func NewIntelligentCompressor

func NewIntelligentCompressor(cfg *CompressionConfig) *IntelligentCompressor

NewIntelligentCompressor creates a new intelligent compressor

func (*IntelligentCompressor) Compress

func (ic *IntelligentCompressor) Compress(history []provider.Message) *CompressionResult

Compress performs intelligent compression on the message history

func (*IntelligentCompressor) CompressRatio

func (ic *IntelligentCompressor) CompressRatio(history []provider.Message) float64

CompressRatio calculates the current compression ratio

func (*IntelligentCompressor) CompressWithLLM

func (ic *IntelligentCompressor) CompressWithLLM(history []provider.Message, summaryPrompt string) (*CompressionResult, error)

CompressWithLLM performs LLM-assisted compression (advanced feature) This requires an LLM provider and is more expensive but produces better summaries

func (*IntelligentCompressor) EstimateCompressionSavings

func (ic *IntelligentCompressor) EstimateCompressionSavings(history []provider.Message) (originalSize, compressedSize, savingsPercent int)

EstimateCompressionSavings estimates the compression savings

func (*IntelligentCompressor) ShouldCompress

func (ic *IntelligentCompressor) ShouldCompress(history []provider.Message) bool

ShouldCompress returns true if compression should be triggered

type PlanExecutor added in v0.5.1

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

PlanExecutor manages plan-guided execution of agent tasks

func NewPlanExecutor added in v0.5.1

func NewPlanExecutor(prov provider.Provider, cfg PlanExecutorConfig) *PlanExecutor

NewPlanExecutor creates a new plan executor

func (*PlanExecutor) CreatePlan added in v0.5.1

func (pe *PlanExecutor) CreatePlan(ctx context.Context, task string) (*cognition.ExecutionPlan, error)

CreatePlan creates an execution plan for a task

func (*PlanExecutor) DetectStepCompletion added in v0.5.1

func (pe *PlanExecutor) DetectStepCompletion(history []provider.Message, toolResults map[string]interface{}) bool

DetectStepCompletion tries to detect if the current step is complete based on the conversation history and tool results

func (*PlanExecutor) GenerateStepSummary added in v0.5.1

func (pe *PlanExecutor) GenerateStepSummary(ctx context.Context, stepID int, history []provider.Message) string

GenerateStepSummary generates a summary of a completed step

func (*PlanExecutor) GetCurrentStep added in v0.5.1

func (pe *PlanExecutor) GetCurrentStep() *cognition.Step

GetCurrentStep returns the step that should be executed next

func (*PlanExecutor) GetPlan added in v0.5.1

func (pe *PlanExecutor) GetPlan() *cognition.ExecutionPlan

GetPlan returns the current plan

func (*PlanExecutor) GetPlanAsJSON added in v0.5.1

func (pe *PlanExecutor) GetPlanAsJSON() (string, error)

GetPlanAsJSON returns the plan in JSON format for storage/transport

func (*PlanExecutor) GetPlanPrompt added in v0.5.1

func (pe *PlanExecutor) GetPlanPrompt() string

GetPlanPrompt returns a prompt fragment describing the current plan state

func (*PlanExecutor) GetProgress added in v0.5.1

func (pe *PlanExecutor) GetProgress() float64

GetProgress returns the plan progress (0.0 - 1.0)

func (*PlanExecutor) GetState added in v0.5.1

func (pe *PlanExecutor) GetState() *cognition.ExecutionState

GetState returns the current execution state

func (*PlanExecutor) IsPlanComplete added in v0.5.1

func (pe *PlanExecutor) IsPlanComplete() bool

IsPlanComplete returns whether all steps are completed

func (*PlanExecutor) MarkStepComplete added in v0.5.1

func (pe *PlanExecutor) MarkStepComplete(stepID int)

MarkStepComplete marks a step as completed

func (*PlanExecutor) MarkStepFailed added in v0.5.1

func (pe *PlanExecutor) MarkStepFailed(stepID int, reason string)

MarkStepFailed marks a step as failed

func (*PlanExecutor) Replan added in v0.5.1

func (pe *PlanExecutor) Replan(ctx context.Context, feedback string) (*cognition.PlanAdjustment, error)

Replan adjusts the plan based on execution feedback

func (*PlanExecutor) ShouldReplan added in v0.5.1

func (pe *PlanExecutor) ShouldReplan(failStreak int) bool

ShouldReplan checks if the plan needs to be adjusted

func (*PlanExecutor) StepsCompletedCount added in v0.5.1

func (pe *PlanExecutor) StepsCompletedCount() int

StepsCompletedCount returns the number of completed steps

func (*PlanExecutor) TotalSteps added in v0.5.1

func (pe *PlanExecutor) TotalSteps() int

TotalSteps returns the total number of steps

type PlanExecutorConfig added in v0.5.1

type PlanExecutorConfig struct {
	UseLLMPlanning bool
	AutoReplan     bool
	MaxReplans     int
}

PlanExecutorConfig configures the plan executor

func DefaultPlanExecutorConfig added in v0.5.1

func DefaultPlanExecutorConfig() PlanExecutorConfig

DefaultPlanExecutorConfig returns default config

type PluginInvokeTool

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

PluginInvokeTool provides skill/plugin invocation functionality

func NewPluginInvokeTool

func NewPluginInvokeTool(manager *PluginManager) *PluginInvokeTool

NewPluginInvokeTool creates a new plugin invoke tool

func (*PluginInvokeTool) GetDescription

func (t *PluginInvokeTool) GetDescription(name string) (string, error)

GetDescription returns the description for a plugin

func (*PluginInvokeTool) Invoke

func (t *PluginInvokeTool) Invoke(ctx context.Context, name string, args map[string]interface{}) (interface{}, error)

Invoke invokes a plugin by name

func (*PluginInvokeTool) ListAvailable

func (t *PluginInvokeTool) ListAvailable() []string

ListAvailable returns all available plugins

type PluginManager

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

PluginManager manages plugin integration with the Agent

func NewPluginManager

func NewPluginManager(agent *Agent) (*PluginManager, error)

NewPluginManager creates a new plugin manager

func (*PluginManager) AutoInstallMissing

func (pm *PluginManager) AutoInstallMissing(recommended []string) error

AutoInstallMissing installs plugins that are missing but recommended

func (*PluginManager) Close

func (pm *PluginManager) Close() error

Close shuts down the plugin manager

func (*PluginManager) DisablePlugin

func (pm *PluginManager) DisablePlugin(pluginID string) error

DisablePlugin disables a plugin

func (*PluginManager) EnablePlugin

func (pm *PluginManager) EnablePlugin(pluginID string) error

EnablePlugin enables a plugin

func (*PluginManager) ExecutePlugin

func (pm *PluginManager) ExecutePlugin(pluginID, command string, args []string) (interface{}, error)

ExecutePlugin executes a plugin command

func (*PluginManager) ExportPlugins

func (pm *PluginManager) ExportPlugins() ([]byte, error)

ExportPlugins exports plugin configurations

func (*PluginManager) GetPluginConfig

func (pm *PluginManager) GetPluginConfig(pluginID string) map[string]interface{}

GetPluginConfig returns plugin configuration

func (*PluginManager) GetPluginContent

func (pm *PluginManager) GetPluginContent() string

GetPluginContent returns the content/metadata for enabled plugins

func (*PluginManager) GetPluginDir

func (pm *PluginManager) GetPluginDir() string

GetPluginDir returns the plugin directory

func (*PluginManager) GetPluginStats

func (pm *PluginManager) GetPluginStats() map[string]interface{}

GetPluginStats returns plugin usage statistics

func (*PluginManager) GetRecommendedPlugins

func (pm *PluginManager) GetRecommendedPlugins(task string) []*plugin.PluginInfo

GetRecommendedPlugins returns plugins recommended for a task

func (*PluginManager) HotReload

func (pm *PluginManager) HotReload(pluginID string) error

HotReload reloads a plugin without restarting

func (*PluginManager) ImportPlugins

func (pm *PluginManager) ImportPlugins(data []byte) error

ImportPlugins imports plugin configurations

func (*PluginManager) Initialize

func (pm *PluginManager) Initialize(ctx context.Context) error

Initialize initializes the plugin manager

func (*PluginManager) InstallPlugin

func (pm *PluginManager) InstallPlugin(pluginID string, version string) error

InstallPlugin installs a plugin from repository

func (*PluginManager) IsPluginEnabled

func (pm *PluginManager) IsPluginEnabled(pluginID string) bool

IsPluginEnabled returns whether a plugin is enabled

func (*PluginManager) ListEnabledPlugins

func (pm *PluginManager) ListEnabledPlugins() []*plugin.PluginInfo

ListEnabledPlugins returns only enabled plugins

func (*PluginManager) ListPlugins

func (pm *PluginManager) ListPlugins() []*plugin.PluginInfo

ListPlugins returns all plugin information

func (*PluginManager) RegisterPluginSchema

func (pm *PluginManager) RegisterPluginSchema(pluginID string, schema []plugin.ConfigField)

RegisterPluginSchema registers a configuration schema for a plugin

func (*PluginManager) SearchPlugins

func (pm *PluginManager) SearchPlugins(query string) []*plugin.PluginManifest

SearchPlugins searches for plugins

func (*PluginManager) SetPluginConfig

func (pm *PluginManager) SetPluginConfig(pluginID string, config map[string]interface{}) error

SetPluginConfig sets plugin configuration

func (*PluginManager) SetRepositoryURL

func (pm *PluginManager) SetRepositoryURL(url string) error

SetRepositoryURL sets the plugin repository URL

func (*PluginManager) TriggerLifecycleEvent

func (pm *PluginManager) TriggerLifecycleEvent(event plugin.LifecycleEvent, data interface{})

TriggerLifecycleEvent triggers a lifecycle event for all enabled plugins

func (*PluginManager) UninstallPlugin

func (pm *PluginManager) UninstallPlugin(pluginID string) error

UninstallPlugin uninstalls a plugin

func (*PluginManager) UpdatePlugin

func (pm *PluginManager) UpdatePlugin(pluginID string) (bool, string, error)

UpdatePlugin updates a plugin to the latest version

type ProgressStatus added in v0.5.1

type ProgressStatus string

ProgressStatus represents the current progress assessment

const (
	ProgressOnTrack   ProgressStatus = "on_track"
	ProgressSlow      ProgressStatus = "slow"
	ProgressStuck     ProgressStatus = "stuck"
	ProgressOffTrack  ProgressStatus = "off_track"
	ProgressCompleted ProgressStatus = "completed"
)

type ReflectionConfig added in v0.5.1

type ReflectionConfig struct {
	Enabled            bool
	Interval           int     // Reflect every N turns
	MaxReflections     int     // Max reflections per session
	StuckThreshold     float64 // Progress increase below this = stuck
	StuckConsecutive   int     // Consecutive low-progress rounds to trigger stuck
	EnableToolAnalysis bool
}

ReflectionConfig configures the self-reflection mechanism

func DefaultReflectionConfig added in v0.5.1

func DefaultReflectionConfig() ReflectionConfig

DefaultReflectionConfig returns default reflection settings

type ReflectionResult added in v0.5.1

type ReflectionResult struct {
	Status         ProgressStatus     `json:"status"`
	Progress       float64            `json:"progress"`       // 0.0 - 1.0
	GoalAlignment  float64            `json:"goal_alignment"` // 0.0 - 1.0
	Summary        string             `json:"summary"`
	Blockers       []string           `json:"blockers"`
	Achievements   []string           `json:"achievements"`
	NextSteps      []string           `json:"next_steps"`
	StrategyAdjust string             `json:"strategy_adjustment"`
	NeedReplan     bool               `json:"need_replan"`
	ToolEfficiency map[string]float64 `json:"tool_efficiency"`
	WarningFlags   []string           `json:"warning_flags"`
}

ReflectionResult holds the result of a self-reflection

type Reflector added in v0.5.1

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

Reflector manages self-reflection for an agent

func NewReflector added in v0.5.1

func NewReflector(cfg ReflectionConfig, prov provider.Provider, goal string) *Reflector

NewReflector creates a new self-reflection manager

func (*Reflector) GetLastResult added in v0.5.1

func (r *Reflector) GetLastResult() *ReflectionResult

GetLastResult returns the most recent reflection result

func (*Reflector) InjectReflectionPrompt added in v0.5.1

func (r *Reflector) InjectReflectionPrompt(result *ReflectionResult) string

InjectReflectionPrompt injects reflection insights into the next LLM call

func (*Reflector) RecordAchievement added in v0.5.1

func (r *Reflector) RecordAchievement(achievement string)

RecordAchievement records something that was accomplished

func (*Reflector) RecordBlocker added in v0.5.1

func (r *Reflector) RecordBlocker(blocker string)

RecordBlocker records an obstacle encountered

func (*Reflector) RecordToolCall added in v0.5.1

func (r *Reflector) RecordToolCall(name string, success bool, duration time.Duration)

RecordToolCall records a tool call for later analysis

func (*Reflector) Reflect added in v0.5.1

func (r *Reflector) Reflect(ctx context.Context, history []provider.Message, currentTurn int) (*ReflectionResult, error)

Reflect performs a self-reflection using LLM

func (*Reflector) ShouldReflect added in v0.5.1

func (r *Reflector) ShouldReflect(turn int) bool

ShouldReflect checks if it's time to reflect based on turn count

type SteeringConfig

type SteeringConfig struct {
	MaxIterations  int
	MaxTokenBudget int64
}

SteeringConfig holds steering configuration

type StreamHandler

type StreamHandler func(content string, done bool)

StreamHandler is called for each streaming chunk

type SubGoal added in v0.3.1

type SubGoal struct {
	ID        string    `json:"id"`
	Text      string    `json:"text"`
	CreatedAt time.Time `json:"created_at"`
}

SubGoal represents an additional success criterion layered onto an active goal

type SubTask

type SubTask struct {
	ID          string    `json:"id"`
	Title       string    `json:"title"`
	Description string    `json:"description"`
	Goal        string    `json:"goal"`
	Status      string    `json:"status"` // pending, running, completed, failed
	Result      string    `json:"result,omitempty"`
	Error       string    `json:"error,omitempty"`
	StartedAt   time.Time `json:"started_at,omitempty"`
	FinishedAt  time.Time `json:"finished_at,omitempty"`
}

SubTask represents a sub-task to be executed

type SubTaskManager

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

SubTaskManager manages sub-task decomposition and execution

func NewSubTaskManager

func NewSubTaskManager(prov provider.Provider, registry ToolRegistry, tools []map[string]interface{}) *SubTaskManager

NewSubTaskManager creates a new SubTaskManager

func (*SubTaskManager) DecomposeTask

func (stm *SubTaskManager) DecomposeTask(ctx context.Context, taskDescription string) ([]SubTask, error)

DecomposeTask analyzes a complex task and breaks it into sub-tasks

func (*SubTaskManager) ExecuteAll added in v0.4.10

func (stm *SubTaskManager) ExecuteAll(ctx context.Context) ([]SubTask, error)

ExecuteAll executes all sub-tasks sequentially

func (*SubTaskManager) ExecuteSubTask

func (stm *SubTaskManager) ExecuteSubTask(ctx context.Context, subTask *SubTask) error

ExecuteSubTask executes a single sub-task

func (*SubTaskManager) GetTasks added in v0.4.10

func (stm *SubTaskManager) GetTasks() []SubTask

GetTasks returns all tasks

type TokenUsage added in v0.3.0

type TokenUsage struct {
	InputTokens     int `json:"input_tokens"`
	OutputTokens    int `json:"output_tokens"`
	CacheReadTokens int `json:"cache_read_tokens"`
}

TokenUsage represents token usage statistics for tracking

type ToolCallResult

type ToolCallResult struct {
	ID        string
	Name      string
	Content   string
	Err       error
	Execution time.Duration
}

ToolCallResult holds the result of a tool execution

type ToolRegistry

type ToolRegistry interface {
	Execute(ctx context.Context, name string, args map[string]interface{}) (interface{}, error)
}

ToolRegistry interface for tool execution

type Violation added in v0.5.1

type Violation struct {
	Index    int    // index of the offending message
	Role     string // role of the offending message
	Reason   string // human-readable reason
	PrevRole string // role of the preceding message, if any
}

Violation describes a single alternation problem in a message history.

func ValidateMessageAlternation added in v0.5.1

func ValidateMessageAlternation(messages []provider.Message) []Violation

ValidateMessageAlternation checks a message history against the alternation rules and returns all violations. An empty/nil history is valid. A history containing only system messages is valid.

func (Violation) Error added in v0.5.1

func (v Violation) Error() string

Error renders a violation as a string.

Directories

Path Synopsis

Jump to

Keyboard shortcuts

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