agent

package
v0.4.2 Latest Latest
Warning

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

Go to latest
Published: May 25, 2026 License: MIT Imports: 23 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

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) 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) GetSubTaskManager

func (a *Agent) GetSubTaskManager() *SubTaskManager

GetSubTaskManager returns or creates the global SubTaskManager (deprecated)

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) 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) RunConversationWithSubTask

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

RunConversationWithSubTask is an enhanced RunConversation that automatically delegates complex sub-tasks to the sub-task executor

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 six Cortex systems: 1. User Message Trigger (increments turn, may trigger nudge) 2. Periodic Nudge Mechanism (provides proactive suggestions) 3. Background Review System (continuous quality assessment) 4. Dual File Storage (MEMORY.md + USER.md with frozen snapshots) 5. Holographic Memory (SQLite FTS5 for semantic retrieval) 6. Memory Manager with Frozen Snapshot (prefix cache protection)

Plus the three-layer architecture: - Layer 1: Perception (intent classification, entity extraction, noise detection) - Layer 2: Cognition (task planning, dynamic adjustment, sub-agent decisions) - Layer 3: Execution (checkpoint persistence, resume, result validation)

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 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 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

type ApprovalHook

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

ApprovalHook provides command approval functionality using the smart approval system

func NewApprovalHook

func NewApprovalHook() *ApprovalHook

NewApprovalHook creates a new approval hook with smart approval

func (*ApprovalHook) AfterLLM

AfterLLM passes through

func (*ApprovalHook) AfterTool

AfterTool passes through the result

func (*ApprovalHook) ApproveTool

ApproveTool handles approval request (for gateway integration)

func (*ApprovalHook) BeforeLLM

BeforeLLM passes through

func (*ApprovalHook) BeforeTool

BeforeTool handles approval for tool execution

func (*ApprovalHook) Name

func (h *ApprovalHook) Name() string

type ComplexityAnalyzer

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

ComplexityAnalyzer analyzes task complexity and determines if decomposition is needed

func NewComplexityAnalyzer

func NewComplexityAnalyzer() *ComplexityAnalyzer

NewComplexityAnalyzer creates a new complexity analyzer

func (*ComplexityAnalyzer) AnalyzeComplexity

func (ca *ComplexityAnalyzer) AnalyzeComplexity(task string) float64

AnalyzeComplexity analyzes a task and returns a complexity score (0.0 - 1.0)

func (*ComplexityAnalyzer) ShouldDecompose

func (ca *ComplexityAnalyzer) ShouldDecompose(task string) bool

ShouldDecompose returns true if the task should be decomposed

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

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 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 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) ExecuteSubTask

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

ExecuteSubTask executes a single sub-task and returns the result

func (*SubTaskManager) GetSubTaskSummary

func (stm *SubTaskManager) GetSubTaskSummary() string

GetSubTaskSummary returns a summary of all sub-tasks and their results

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

Directories

Path Synopsis

Jump to

Keyboard shortcuts

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