Documentation
¶
Overview ¶
Package agent provides the multi-agent system for Smara.
Package agent implements the multi-agent system for Smara.
Index ¶
- Constants
- Variables
- func BuildGraphContext(db *sql.DB, prompt string, workspaceID int64) (string, error)
- func DisableRushAutoApprovalEnv()
- func EnableRushAutoApprovalEnv()
- func ExecuteBuiltinTool(toolName string, args map[string]interface{}, ...) (result string, err error)
- func ExecuteBuiltinToolWithContext(ctx context.Context, toolName string, args map[string]interface{}, ...) (result string, err error)
- func GetBuiltinTools() []llm.ToolFunction
- func GetBuiltinToolsFiltered(disabledGroups []string) []llm.ToolFunction
- func InstallContext7Skill(entry Context7RegistryEntry) (*skill.Skill, error)
- func IsCodebaseQuery(prompt string) bool
- func IsRushAutoApprovalEnabled() bool
- func RecordPrompt(db *sql.DB) error
- func RecordSession(db *sql.DB) error
- func SaveProfile(db *sql.DB, p *UserProfile) error
- func SaveSelfImprovementMemory(db *sql.DB, lesson SelfImprovementMemory) (int64, error)
- func SetActiveBudgetController(c activeBudgetController)
- func ShouldAutoOrchestrate(prompt string, cfg config.ParallelOrchestrationConfig) bool
- func UpdateFromPreference(db *sql.DB, key, value string) error
- func ValidMode(s string) bool
- type AgentConfig
- type AgenticCallback
- type BudgetSnapshot
- type Context7DocResult
- type Context7Injector
- type Context7RegistryEntry
- type Context7RegistryManifest
- type ExtensionRequest
- type IterationBudget
- func (b *IterationBudget) HardCap() int
- func (b *IterationBudget) Limit() int
- func (b *IterationBudget) RecordToolCalls(toolName string, args map[string]interface{}) bool
- func (b *IterationBudget) RequestExtension(requested int, reason string) ExtensionRequest
- func (b *IterationBudget) ShouldContinue(i int) bool
- func (b *IterationBudget) Snapshot() BudgetSnapshot
- func (b *IterationBudget) Stuck() bool
- type MCPServerInfo
- type Mode
- type ModeInfo
- type PromptResult
- type SearchResult
- type SelfImprovementMemory
- type Session
- type SessionConfig
- type SessionManager
- func (m *SessionManager) AddMemoryReference(sessionID string, memoryID int64) error
- func (m *SessionManager) ConnectMCP(sessionID string, serverName string, client *mcp.Client) error
- func (m *SessionManager) DisconnectMCP(sessionID string, serverName string) error
- func (m *SessionManager) GetMCPClients(sessionID string) map[string]*mcp.Client
- func (m *SessionManager) LoadSessions() error
- func (m *SessionManager) Registry() *SessionRegistry
- func (m *SessionManager) ResumeSession(sessionID string) (*session.Session, error)
- func (m *SessionManager) SaveSession(sessionID string) error
- func (m *SessionManager) SetSaveOnTurn(enabled bool)
- func (m *SessionManager) UpdateContext(sessionID string, context string) error
- type SessionRegistry
- func (r *SessionRegistry) AddTask(sessionID string, task session.Task)
- func (r *SessionRegistry) AppendHistory(sessionID string, userMsg, assistantMsg string) string
- func (r *SessionRegistry) Create(cfg SessionConfig) (*session.Session, error)
- func (r *SessionRegistry) Current() *session.Session
- func (r *SessionRegistry) Delete(id string) error
- func (r *SessionRegistry) End(id string) error
- func (r *SessionRegistry) EndCurrent() error
- func (r *SessionRegistry) Get(id string) (*session.Session, bool)
- func (r *SessionRegistry) IsCurrent(id string) bool
- func (r *SessionRegistry) List() []*session.Session
- func (r *SessionRegistry) Register(s *session.Session)
- func (r *SessionRegistry) SetMode(sessionID string, mode string)
- func (r *SessionRegistry) Switch(id string) error
- func (r *SessionRegistry) UpdateHistory(sessionID string, userMsg, assistantMsg string)
- type SessionState
- type SessionStore
- type Stats
- type Supervisor
- func (s *Supervisor) AddContext(context string)
- func (s *Supervisor) ClearHistory()
- func (s *Supervisor) Close()
- func (s *Supervisor) ConvertMCPToolsToToolFunctions() []llm.ToolFunction
- func (s *Supervisor) CreateSession(cfg SessionConfig) (*Session, error)
- func (s *Supervisor) DeleteSession(id string) error
- func (s *Supervisor) EndCurrentSession() error
- func (s *Supervisor) ExecuteTask(ctx context.Context, task Task) TaskResult
- func (s *Supervisor) GetCurrentSession() *Session
- func (s *Supervisor) GetLastActiveSession() (*Session, error)
- func (s *Supervisor) GetMCPClient(name string) (*mcp.Client, bool)
- func (s *Supervisor) GetMCPClients() map[string]*mcp.Client
- func (s *Supervisor) GetMCPInfo() map[string]MCPServerInfo
- func (s *Supervisor) GetMemoryStore() memory.MemoryStore
- func (s *Supervisor) GetMode() Mode
- func (s *Supervisor) GetModel() string
- func (s *Supervisor) GetModelInfo() (string, string)
- func (s *Supervisor) GetProvider() llm.Provider
- func (s *Supervisor) GetProviderName() string
- func (s *Supervisor) GetSession(id string) (*Session, bool)
- func (s *Supervisor) GetSessionHistory(id string) ([]llm.Message, error)
- func (s *Supervisor) GetStats() Stats
- func (s *Supervisor) GetWorkspaceID() int64
- func (s *Supervisor) InitializeSessions() error
- func (s *Supervisor) IsCurrentSession(id string) bool
- func (s *Supervisor) IterationBudgetSnapshot() (BudgetSnapshot, bool)
- func (s *Supervisor) ListMCPServers() []string
- func (s *Supervisor) ListSessions() []*Session
- func (s *Supervisor) ProcessPrompt(ctx context.Context, userPrompt string) (*PromptResult, error)
- func (s *Supervisor) RegisterMCPClient(name string, client *mcp.Client)
- func (s *Supervisor) RequestIterationExtension(amount int, reason string) ExtensionRequest
- func (s *Supervisor) RunAgenticLoop(ctx context.Context, userPrompt string) (string, string, []string, []string, error)
- func (s *Supervisor) SaveSession() error
- func (s *Supervisor) SearchSessions(query string, topN int) ([]SearchResult, error)
- func (s *Supervisor) SetCallback(cb AgenticCallback)
- func (s *Supervisor) SetCognitiveValidator(validator *cognitive.Validator)
- func (s *Supervisor) SetLSPManager(manager *lsp.Manager)
- func (s *Supervisor) SetMaxIterations(n int)
- func (s *Supervisor) SetMode(mode Mode)
- func (s *Supervisor) SetModel(provider, model string) error
- func (s *Supervisor) SetSafetyEngine(engine *safety.Engine)
- func (s *Supervisor) SetSessionStore(store SessionStore)
- func (s *Supervisor) SetWorkspaceID(id int64)
- func (s *Supervisor) SkillExecutor() skill.StepExecutor
- func (s *Supervisor) SwitchSession(id string) error
- func (s *Supervisor) UnregisterMCPClient(name string)
- func (s *Supervisor) UpdateMCPError(name string, errMsg string)
- func (s *Supervisor) UpdateMCPInfo(name string, tools []mcp.Tool)
- type Task
- type TaskResult
- type TaskStatus
- type UserProfile
- type Worker
- type WorkerCallback
Constants ¶
const ( // MaxManualExtRequests caps how many separate extension grants we honor // per ProcessPrompt call to prevent runaway expansion. MaxManualExtRequests = 5 // MaxManualExtMultiplier is the absolute multiplier of the original // hardCap: hardCap can never grow beyond this factor of its initial // value via manual requests. Auto-extend (progress-based) still // respects this same ceiling once it's reached. MaxManualExtMultiplier = 3 // AbsoluteIterationHardCap is the global safety ceiling for adaptive // hard caps derived from user/config overrides. This prevents the agent // from turning a reasonable base budget into an unbounded long-running turn. AbsoluteIterationHardCap = 240 )
Constants governing how aggressively the agent itself can request more iterations via `request_iteration_budget`.
const ( SessionActive = session.StateActive SessionPaused = session.StatePaused SessionEnded = session.StateEnded )
const ( TaskPending = session.TaskPending TaskRunning = session.TaskRunning TaskCompleted = session.TaskCompleted TaskFailed = session.TaskFailed )
Variables ¶
var AgentVersion = "dev"
AgentVersion is set by the main package at startup so the LLM knows which version of Smara it is running. Injected into every system prompt.
var BuiltinDB *sql.DB
BuiltinDB is set by the Supervisor so built-in tools can access SQLite.
Functions ¶
func BuildGraphContext ¶ added in v1.19.2
BuildGraphContext attempts to load a graph for the current workspace and returns compact graph context relevant to the query.
func DisableRushAutoApprovalEnv ¶ added in v1.20.69
func DisableRushAutoApprovalEnv()
DisableRushAutoApprovalEnv unsets RUSH mode environment variables.
func EnableRushAutoApprovalEnv ¶ added in v1.20.66
func EnableRushAutoApprovalEnv()
EnableRushAutoApprovalEnv makes RUSH mode sticky for child processes and CLI subcommands that only inspect environment variables. Explicit user opt-out via SMARA_RUSH_AUTO_APPROVE=false/0 is respected by IsRushAutoApprovalEnabled before this helper is called.
func ExecuteBuiltinTool ¶ added in v1.10.0
func ExecuteBuiltinTool(toolName string, args map[string]interface{}, logCallback func(role, content string)) (result string, err error)
ExecuteBuiltinTool eksekusi fungsi tool built-in tanpa harus melewati koneksi MCP
func ExecuteBuiltinToolWithContext ¶ added in v1.20.12
func ExecuteBuiltinToolWithContext(ctx context.Context, toolName string, args map[string]interface{}, logCallback func(role, content string)) (result string, err error)
ExecuteBuiltinToolWithContext eksekusi tool built-in dengan context cancellation untuk tool yang mendukungnya.
func GetBuiltinTools ¶
func GetBuiltinTools() []llm.ToolFunction
GetBuiltinTools returns the standard OS and file manipulation tools
func GetBuiltinToolsFiltered ¶ added in v1.20.12
func GetBuiltinToolsFiltered(disabledGroups []string) []llm.ToolFunction
GetBuiltinToolsFiltered returns builtin tools with disabled groups removed.
func InstallContext7Skill ¶ added in v1.19.2
func InstallContext7Skill(entry Context7RegistryEntry) (*skill.Skill, error)
InstallContext7Skill creates a skill recipe for a Context7 library entry and saves it. It first tries to load a predefined skill file from the skills/ directory. If not found, it generates a generic context7-help wrapper skill.
func IsCodebaseQuery ¶ added in v1.19.2
IsCodebaseQuery returns true if the prompt appears to ask about the codebase.
func IsRushAutoApprovalEnabled ¶ added in v1.20.66
func IsRushAutoApprovalEnabled() bool
IsRushAutoApprovalEnabled returns true when the environment explicitly opts into RUSH autonomous execution / auto-approval. It is used by CLI commands, the TUI, and the agent core to default to RUSH mode and to bypass confirmation/permission gates.
func RecordPrompt ¶ added in v1.10.0
RecordPrompt increments total_prompts.
func RecordSession ¶ added in v1.10.0
RecordSession increments session count and updates last_active.
func SaveProfile ¶ added in v1.10.0
func SaveProfile(db *sql.DB, p *UserProfile) error
SaveProfile writes the profile back to DB.
func SaveSelfImprovementMemory ¶ added in v1.20.33
func SaveSelfImprovementMemory(db *sql.DB, lesson SelfImprovementMemory) (int64, error)
SaveSelfImprovementMemory stores or merges a self-improvement lesson in the existing memories table. It is intentionally best-effort for agent flows: call sites may ignore errors when learning must not block the primary task.
func SetActiveBudgetController ¶ added in v1.20.2
func SetActiveBudgetController(c activeBudgetController)
func ShouldAutoOrchestrate ¶ added in v1.20.33
func ShouldAutoOrchestrate(prompt string, cfg config.ParallelOrchestrationConfig) bool
ShouldAutoOrchestrate is a lightweight, side-effect-free heuristic used before the normal supervisor loop to decide whether a prompt is a good candidate for safe parallel task orchestration.
func UpdateFromPreference ¶ added in v1.10.0
UpdateFromPreference applies a user-stated preference to the profile.
Types ¶
type AgentConfig ¶
type AgentConfig struct {
Name string `json:"name"`
SystemPrompt string `json:"system_prompt"`
MaxRetries int `json:"max_retries"`
TimeoutSec int `json:"timeout_sec"`
}
AgentConfig configures an agent instance.
type AgenticCallback ¶
type AgenticCallback struct {
OnToolCall func(server, tool string, args map[string]interface{})
OnToolResult func(output string)
OnIteration func(current, max int)
OnStream func(chunk string, isThinking bool)
OnPhaseChange func(phase, description string)
OnLog func(role, content string)
OnConfirm func(message string) bool
OnExplore func(path string, results string)
}
AgenticCallback defines callbacks for agentic loop events.
type BudgetSnapshot ¶ added in v1.20.2
type BudgetSnapshot struct {
Mode string
Base int
Current int
HardCap int
ManualExtCount int
ManualExtTotal int
ManualExtRemaining int
StuckRepeats int
UniqueRecent int
WindowSize int
}
Snapshot returns a read-only view of the budget state. Useful for the `iteration_budget_status` tool the agent calls when it wants to know how much headroom it has left.
type Context7DocResult ¶ added in v1.19.2
Context7DocResult holds the outcome of a single library docs fetch.
type Context7Injector ¶ added in v1.19.2
type Context7Injector struct {
// contains filtered or unexported fields
}
Context7Injector handles auto-detection and injection of Context7 docs into prompts.
func NewContext7Injector ¶ added in v1.19.2
func NewContext7Injector() *Context7Injector
NewContext7Injector creates a fresh injector for a new session.
func (*Context7Injector) DetectAndInject ¶ added in v1.19.2
func (ci *Context7Injector) DetectAndInject(prompt string, executor skill.StepExecutor) (string, []Context7DocResult, error)
DetectAndInject scans the user prompt for library keywords, resolves them via Context7, and returns injected context + any docs that were fetched. The executor is used to run the context7-resolve and context7-docs skills.
type Context7RegistryEntry ¶ added in v1.19.2
type Context7RegistryEntry struct {
Name string `json:"name"`
Description string `json:"description"`
Tags []string `json:"tags"`
Keywords []string `json:"keywords"`
Context7Library string `json:"context7_library"`
SkillFile string `json:"skill_file,omitempty"`
}
Context7RegistryEntry maps keywords to a Context7 library for auto-resolve.
func DetectLibrariesFromPrompt ¶ added in v1.19.2
func DetectLibrariesFromPrompt(prompt string) ([]Context7RegistryEntry, error)
DetectLibrariesFromPrompt scans a user prompt and returns matching registry entries. Keywords are matched with word boundaries to avoid false positives (e.g., "image" in "next/image" matching docker, "class" in "utility class" matching python).
func SearchContext7Registry ¶ added in v1.19.2
func SearchContext7Registry(query string) ([]Context7RegistryEntry, error)
SearchContext7Registry searches the registry for entries matching query. Matches against name, description, tags, and keywords.
type Context7RegistryManifest ¶ added in v1.19.2
type Context7RegistryManifest struct {
Version int `json:"version"`
Skills []Context7RegistryEntry `json:"skills"`
}
Context7RegistryManifest is the top-level curated library index.
type ExtensionRequest ¶ added in v1.20.2
type ExtensionRequest struct {
Granted bool // true if any iterations were added
GrantedAmount int // how many iterations actually added (may be < requested)
NewLimit int // new b.current after the grant
NewHardCap int // new b.hardCap after the grant
Reason string // user-visible reason returned to agent
Denial string // populated when Granted == false explaining why
RemainingGrant int // grants left under MaxManualExtRequests
}
ExtensionRequest captures one runtime extension attempt. Returned by RequestExtension so the caller can render a structured response back to the agent (the LLM sees exactly how its request was processed).
type IterationBudget ¶ added in v1.19.2
type IterationBudget struct {
// contains filtered or unexported fields
}
IterationBudget controls how many agentic iterations a prompt may use.
Behavior — adaptive in three ways:
- Per-mode base budget (ASK is small, WORKFLOW is large).
- Stuck-loop detection: if the same tool call (function + args) is repeated 3 times in a row OR appears 5 times in the trailing window, the budget is forced to terminate early to avoid wasting tokens.
- Progress extension: when the model is still calling new tools at the end of the base budget, the budget extends in chunks toward a hard ceiling. "Progress" = a tool fingerprint we have not seen recently.
func NewIterationBudget ¶ added in v1.19.2
func NewIterationBudget(mode Mode, userMax int) *IterationBudget
NewIterationBudget creates a budget with sensible defaults for the mode. userMax is the value from config / SetMaxIterations; pass 0 to use mode defaults.
func (*IterationBudget) HardCap ¶ added in v1.19.2
func (b *IterationBudget) HardCap() int
HardCap returns the absolute upper bound.
func (*IterationBudget) Limit ¶ added in v1.19.2
func (b *IterationBudget) Limit() int
Limit returns the current iteration cap.
func (*IterationBudget) RecordToolCalls ¶ added in v1.19.2
func (b *IterationBudget) RecordToolCalls(toolName string, args map[string]interface{}) bool
RecordToolCalls records a batch of tool calls executed in one iteration. Returns true if a stuck-loop was detected and the loop should terminate.
func (*IterationBudget) RequestExtension ¶ added in v1.20.2
func (b *IterationBudget) RequestExtension(requested int, reason string) ExtensionRequest
RequestExtension grows the iteration budget at runtime when the agent itself decides it needs more room (via the request_iteration_budget tool).
Safety rails:
- At most MaxManualExtRequests grants per budget.
- hardCap never exceeds initialHardCap * MaxManualExtMultiplier.
- Each grant is between 1 and `requested` iterations, clamped to the remaining headroom under the multiplier ceiling.
- A short reason is required; empty/whitespace requests are denied.
func (*IterationBudget) ShouldContinue ¶ added in v1.19.2
func (b *IterationBudget) ShouldContinue(i int) bool
ShouldContinue reports whether iteration `i` (0-indexed) is allowed. It also extends the budget when the model is still making progress.
func (*IterationBudget) Snapshot ¶ added in v1.20.2
func (b *IterationBudget) Snapshot() BudgetSnapshot
func (*IterationBudget) Stuck ¶ added in v1.19.2
func (b *IterationBudget) Stuck() bool
Stuck returns true if the most recent activity matched a known stuck pattern.
type MCPServerInfo ¶
MCPServerInfo holds detailed MCP server information.
type Mode ¶
type Mode string
Mode represents the agent's operating mode.
const ( // ModeAsk is a simple Q&A mode. The agent answers questions directly // without executing tasks or using tools. Fastest response time. ModeAsk Mode = "ask" // ModeRush is a fast execution mode. The agent acts immediately // with minimal planning — executes tools and writes code directly. ModeRush Mode = "rush" // ModePlan is a planning mode. The agent first creates a step-by-step // plan, presents it to the user for approval, then executes each step. ModePlan Mode = "plan" // ModeTest is a testing mode. The agent focuses on running tests, // verifying behavior, and fixing bugs based on test failures. ModeTest Mode = "test" // ModeImage is a visual generation/editing focused mode. It prioritizes // image prompts, image analysis, and safe image-to-image routing. ModeImage Mode = "image" // ModeWorkflow is the custom workflow/blueprint authoring mode. ModeWorkflow Mode = "workflow" // ModeParallel is the only mode allowed to run generic parallel task orchestration. ModeParallel Mode = "parallel" )
type ModeInfo ¶
ModeInfo holds metadata about an agent mode.
func GetModeInfo ¶
GetModeInfo returns info for a specific mode.
type PromptResult ¶
type PromptResult struct {
Response string
Thinking string // The <thinking> block content
Thoughts []string // Intermediate reasoning text
ToolsExecuted []string // List of tools run during this prompt
InputTokens int
OutputTokens int
TotalTokens int
Duration time.Duration
}
PromptResult contains the result and statistics of a prompt processing.
type SearchResult ¶ added in v1.15.0
SearchResult holds a single session search result with relevance.
type SelfImprovementMemory ¶ added in v1.20.33
type SelfImprovementMemory struct {
Type string `json:"type"`
Scope string `json:"scope"`
Summary string `json:"summary"`
Lesson string `json:"lesson"`
AppliesTo []string `json:"applies_to,omitempty"`
Confidence float64 `json:"confidence"`
AutoApply bool `json:"auto_apply"`
}
SelfImprovementMemory captures lessons Smara should auto-apply in later turns.
type SessionConfig ¶
SessionConfig is an alias for session.Config for backwards compatibility.
type SessionManager ¶
type SessionManager struct {
// contains filtered or unexported fields
}
SessionManager manages sessions with persistence and MCP integration.
func NewSessionManager ¶
func NewSessionManager(store *session.SQLiteStore) *SessionManager
NewSessionManager creates a new session manager with persistence.
func (*SessionManager) AddMemoryReference ¶
func (m *SessionManager) AddMemoryReference(sessionID string, memoryID int64) error
AddMemoryReference adds a memory reference to the session.
func (*SessionManager) ConnectMCP ¶
ConnectMCP connects an MCP server to a session.
func (*SessionManager) DisconnectMCP ¶
func (m *SessionManager) DisconnectMCP(sessionID string, serverName string) error
DisconnectMCP disconnects an MCP server from a session.
func (*SessionManager) GetMCPClients ¶
func (m *SessionManager) GetMCPClients(sessionID string) map[string]*mcp.Client
GetMCPClients returns all MCP clients for a session.
func (*SessionManager) LoadSessions ¶
func (m *SessionManager) LoadSessions() error
LoadSessions loads all sessions from persistent store.
func (*SessionManager) Registry ¶
func (m *SessionManager) Registry() *SessionRegistry
Registry returns the underlying session registry.
func (*SessionManager) ResumeSession ¶
func (m *SessionManager) ResumeSession(sessionID string) (*session.Session, error)
ResumeSession resumes an agentic session.
func (*SessionManager) SaveSession ¶
func (m *SessionManager) SaveSession(sessionID string) error
SaveSession persists a session to the store.
func (*SessionManager) SetSaveOnTurn ¶
func (m *SessionManager) SetSaveOnTurn(enabled bool)
SetSaveOnTurn enables or disables auto-save after each turn.
func (*SessionManager) UpdateContext ¶
func (m *SessionManager) UpdateContext(sessionID string, context string) error
UpdateContext updates the session context/summary.
type SessionRegistry ¶
type SessionRegistry struct {
// contains filtered or unexported fields
}
SessionRegistry manages active sessions in memory.
func NewSessionRegistry ¶
func NewSessionRegistry() *SessionRegistry
NewSessionRegistry creates a new session registry.
func (*SessionRegistry) AddTask ¶
func (r *SessionRegistry) AddTask(sessionID string, task session.Task)
AddTask adds a task to a session.
func (*SessionRegistry) AppendHistory ¶
func (r *SessionRegistry) AppendHistory(sessionID string, userMsg, assistantMsg string) string
AppendHistory appends messages to a session's history and returns the session ID for auto-save.
func (*SessionRegistry) Create ¶
func (r *SessionRegistry) Create(cfg SessionConfig) (*session.Session, error)
Create creates a new session and sets it as current.
func (*SessionRegistry) Current ¶
func (r *SessionRegistry) Current() *session.Session
Current returns the current active session.
func (*SessionRegistry) Delete ¶ added in v1.15.0
func (r *SessionRegistry) Delete(id string) error
Delete removes a session by ID.
func (*SessionRegistry) End ¶
func (r *SessionRegistry) End(id string) error
End marks a session as ended by ID.
func (*SessionRegistry) EndCurrent ¶
func (r *SessionRegistry) EndCurrent() error
EndCurrent marks the current session as ended.
func (*SessionRegistry) Get ¶
func (r *SessionRegistry) Get(id string) (*session.Session, bool)
Get retrieves a session by ID.
func (*SessionRegistry) IsCurrent ¶
func (r *SessionRegistry) IsCurrent(id string) bool
IsCurrent checks if a session ID is the current session.
func (*SessionRegistry) List ¶
func (r *SessionRegistry) List() []*session.Session
List returns all sessions.
func (*SessionRegistry) Register ¶
func (r *SessionRegistry) Register(s *session.Session)
Register adds a session to the registry (for loading from persistence).
func (*SessionRegistry) SetMode ¶
func (r *SessionRegistry) SetMode(sessionID string, mode string)
SetMode changes the mode of a session.
func (*SessionRegistry) Switch ¶
func (r *SessionRegistry) Switch(id string) error
Switch changes the current session.
func (*SessionRegistry) UpdateHistory ¶
func (r *SessionRegistry) UpdateHistory(sessionID string, userMsg, assistantMsg string)
UpdateHistory appends to a session's history.
type SessionState ¶
SessionState is an alias for session.State for backwards compatibility.
type SessionStore ¶
SessionStore is an alias for session.Store for backwards compatibility.
type Stats ¶
type Stats struct {
PromptCount int // Total prompts processed
TotalTokens int // Total tokens used (estimate)
TotalCost float64 // Estimated cost in USD
TotalDuration time.Duration // Total processing time
AvgTokensPerReq int // Average tokens per request
SessionStart time.Time // Session start time
InputTokens int // Total input tokens
OutputTokens int // Total output tokens
LastDuration time.Duration // Duration of the last request
// contains filtered or unexported fields
}
Stats holds usage statistics for the supervisor.
type Supervisor ¶
type Supervisor struct {
// contains filtered or unexported fields
}
Supervisor orchestrates multi-agent task execution.
func NewSupervisor ¶
func NewSupervisor(provider llm.Provider, memStore memory.MemoryStore) *Supervisor
NewSupervisor creates a new supervisor agent.
func NewSupervisorWithConfig ¶
func NewSupervisorWithConfig(provider llm.Provider, providerCfg llm.ProviderConfig, memStore memory.MemoryStore) *Supervisor
NewSupervisorWithConfig creates a supervisor with a stored provider config for runtime switching.
func (*Supervisor) AddContext ¶
func (s *Supervisor) AddContext(context string)
AddContext adds system context to the current session history.
func (*Supervisor) ClearHistory ¶ added in v1.13.0
func (s *Supervisor) ClearHistory()
ClearHistory clears the conversation history and session registry history.
func (*Supervisor) Close ¶
func (s *Supervisor) Close()
Close shuts down all MCP client connections.
func (*Supervisor) ConvertMCPToolsToToolFunctions ¶
func (s *Supervisor) ConvertMCPToolsToToolFunctions() []llm.ToolFunction
ConvertMCPToolsToToolFunctions converts MCP tools to LLM ToolFunction format.
func (*Supervisor) CreateSession ¶
func (s *Supervisor) CreateSession(cfg SessionConfig) (*Session, error)
CreateSession creates a new session and sets it as current.
func (*Supervisor) DeleteSession ¶ added in v1.15.0
func (s *Supervisor) DeleteSession(id string) error
DeleteSession deletes a session by ID from both registry and store.
func (*Supervisor) EndCurrentSession ¶
func (s *Supervisor) EndCurrentSession() error
EndCurrentSession marks the current session as ended.
func (*Supervisor) ExecuteTask ¶
func (s *Supervisor) ExecuteTask(ctx context.Context, task Task) TaskResult
ExecuteTask runs a single task with timeout.
func (*Supervisor) GetCurrentSession ¶
func (s *Supervisor) GetCurrentSession() *Session
GetCurrentSession returns the currently active session.
func (*Supervisor) GetLastActiveSession ¶
func (s *Supervisor) GetLastActiveSession() (*Session, error)
GetLastActiveSession returns the last active session from store.
func (*Supervisor) GetMCPClient ¶
func (s *Supervisor) GetMCPClient(name string) (*mcp.Client, bool)
GetMCPClient retrieves an MCP client by name.
func (*Supervisor) GetMCPClients ¶ added in v1.13.0
func (s *Supervisor) GetMCPClients() map[string]*mcp.Client
GetMCPClients returns all connected MCP clients.
func (*Supervisor) GetMCPInfo ¶
func (s *Supervisor) GetMCPInfo() map[string]MCPServerInfo
GetMCPInfo returns detailed info for all MCP servers.
func (*Supervisor) GetMemoryStore ¶ added in v1.20.4
func (s *Supervisor) GetMemoryStore() memory.MemoryStore
GetMemoryStore returns the active long-term memory store.
func (*Supervisor) GetMode ¶
func (s *Supervisor) GetMode() Mode
GetMode returns the current agent mode.
func (*Supervisor) GetModel ¶
func (s *Supervisor) GetModel() string
GetModel returns the current model name.
func (*Supervisor) GetModelInfo ¶
func (s *Supervisor) GetModelInfo() (string, string)
GetModelInfo returns the current provider and model name.
func (*Supervisor) GetProvider ¶ added in v1.13.0
func (s *Supervisor) GetProvider() llm.Provider
GetProvider returns the current LLM provider.
func (*Supervisor) GetProviderName ¶
func (s *Supervisor) GetProviderName() string
GetProviderName returns the current provider name.
func (*Supervisor) GetSession ¶
func (s *Supervisor) GetSession(id string) (*Session, bool)
GetSession retrieves a session by ID.
func (*Supervisor) GetSessionHistory ¶ added in v1.15.0
func (s *Supervisor) GetSessionHistory(id string) ([]llm.Message, error)
GetSessionHistory returns the history messages for a session by ID.
func (*Supervisor) GetStats ¶
func (s *Supervisor) GetStats() Stats
GetStats returns a copy of current usage statistics.
func (*Supervisor) GetWorkspaceID ¶ added in v1.8.6
func (s *Supervisor) GetWorkspaceID() int64
GetWorkspaceID returns the active workspace ID.
func (*Supervisor) InitializeSessions ¶
func (s *Supervisor) InitializeSessions() error
InitializeSessions loads existing sessions from store into the registry.
func (*Supervisor) IsCurrentSession ¶
func (s *Supervisor) IsCurrentSession(id string) bool
IsCurrentSession checks if a session ID is the current session.
func (*Supervisor) IterationBudgetSnapshot ¶ added in v1.20.2
func (s *Supervisor) IterationBudgetSnapshot() (BudgetSnapshot, bool)
IterationBudgetSnapshot returns a snapshot of the active budget, or zero value if no prompt is running.
func (*Supervisor) ListMCPServers ¶
func (s *Supervisor) ListMCPServers() []string
ListMCPServers returns names of all connected MCP servers.
func (*Supervisor) ListSessions ¶
func (s *Supervisor) ListSessions() []*Session
ListSessions returns all sessions.
func (*Supervisor) ProcessPrompt ¶
func (s *Supervisor) ProcessPrompt(ctx context.Context, userPrompt string) (*PromptResult, error)
ProcessPrompt handles a user prompt using the current agent mode.
func (*Supervisor) RegisterMCPClient ¶
func (s *Supervisor) RegisterMCPClient(name string, client *mcp.Client)
RegisterMCPClient adds an MCP server connection.
func (*Supervisor) RequestIterationExtension ¶ added in v1.20.2
func (s *Supervisor) RequestIterationExtension(amount int, reason string) ExtensionRequest
RequestIterationExtension allows the running prompt to extend its own iteration budget. Returns the structured ExtensionRequest result. If no prompt is currently running the call is denied.
func (*Supervisor) RunAgenticLoop ¶
func (s *Supervisor) RunAgenticLoop(ctx context.Context, userPrompt string) (string, string, []string, []string, error)
RunAgenticLoop executes the agentic loop: LLM → tool calls → execute → feed back → repeat. Returns the final text response when the LLM stops calling tools.
func (*Supervisor) SaveSession ¶ added in v1.13.0
func (s *Supervisor) SaveSession() error
SaveSession persists the current session to the store.
func (*Supervisor) SearchSessions ¶ added in v1.15.0
func (s *Supervisor) SearchSessions(query string, topN int) ([]SearchResult, error)
SearchSessions searches sessions using AI embeddings for semantic relevance.
func (*Supervisor) SetCallback ¶
func (s *Supervisor) SetCallback(cb AgenticCallback)
SetCallback sets the agentic callback functions.
func (*Supervisor) SetCognitiveValidator ¶ added in v1.8.9
func (s *Supervisor) SetCognitiveValidator(validator *cognitive.Validator)
SetCognitiveValidator sets the cognitive schema validator for tool argument validation.
func (*Supervisor) SetLSPManager ¶ added in v1.9.0
func (s *Supervisor) SetLSPManager(manager *lsp.Manager)
SetLSPManager sets the LSP Manager for code intelligence tools.
func (*Supervisor) SetMaxIterations ¶
func (s *Supervisor) SetMaxIterations(n int)
SetMaxIterations sets the maximum number of agentic loop iterations.
func (*Supervisor) SetMode ¶
func (s *Supervisor) SetMode(mode Mode)
SetMode changes the agent's operating mode.
func (*Supervisor) SetModel ¶
func (s *Supervisor) SetModel(provider, model string) error
SetModel switches the LLM model/provider at runtime.
func (*Supervisor) SetSafetyEngine ¶ added in v1.8.9
func (s *Supervisor) SetSafetyEngine(engine *safety.Engine)
SetSafetyEngine sets the safety engine for execution mode enforcement.
func (*Supervisor) SetSessionStore ¶
func (s *Supervisor) SetSessionStore(store SessionStore)
SetSessionStore sets the session persistence store.
func (*Supervisor) SetWorkspaceID ¶ added in v1.8.6
func (s *Supervisor) SetWorkspaceID(id int64)
SetWorkspaceID sets the active workspace for this supervisor.
func (*Supervisor) SkillExecutor ¶ added in v1.11.0
func (s *Supervisor) SkillExecutor() skill.StepExecutor
SkillExecutor returns a StepExecutor that routes tool calls through the supervisor's existing tool routing (built-in + MCP + nested skills). If toolName is prefixed with "skill:", it loads and executes the named skill from the skill store recursively (max depth 5 to prevent infinite loops).
func (*Supervisor) SwitchSession ¶
func (s *Supervisor) SwitchSession(id string) error
SwitchSession switches to a different session by ID.
func (*Supervisor) UnregisterMCPClient ¶ added in v1.11.0
func (s *Supervisor) UnregisterMCPClient(name string)
UnregisterMCPClient disconnects and removes an MCP server.
func (*Supervisor) UpdateMCPError ¶
func (s *Supervisor) UpdateMCPError(name string, errMsg string)
UpdateMCPError marks an MCP server as having an error.
func (*Supervisor) UpdateMCPInfo ¶
func (s *Supervisor) UpdateMCPInfo(name string, tools []mcp.Tool)
UpdateMCPInfo updates detailed MCP server info after tools are listed.
type TaskResult ¶
TaskResult is an alias for session.Result for backwards compatibility.
type TaskStatus ¶
TaskStatus is an alias for session.Status for backwards compatibility.
type UserProfile ¶ added in v1.10.0
type UserProfile struct {
ID int64
Verbosity string `json:"verbosity"`
RiskTolerance string `json:"risk_tolerance"`
PrimaryDomains string `json:"primary_domains"`
PreferredLanguages string `json:"preferred_languages"`
CustomPatterns string `json:"custom_patterns"`
SessionCount int `json:"session_count"`
TotalPrompts int `json:"total_prompts"`
LastActive *time.Time
UpdatedAt time.Time
}
UserProfile stores adaptive preferences inferred from user behavior.
func DefaultProfile ¶ added in v1.10.0
func DefaultProfile() *UserProfile
DefaultProfile returns a new profile with sensible defaults.
func LoadProfile ¶ added in v1.10.0
func LoadProfile(db *sql.DB) (*UserProfile, error)
LoadProfile retrieves the user profile from DB (singleton row with id=1).
func (*UserProfile) ToContext ¶ added in v1.10.0
func (p *UserProfile) ToContext() string
ToContext returns a short string to inject into the system prompt.
type Worker ¶
type Worker struct {
Role string
AllowedTools []string
SystemPrompt string
// contains filtered or unexported fields
}
Worker executes individual tasks as delegated by the Supervisor.
func NewSpecializedWorker ¶ added in v1.13.0
func NewSpecializedWorker(provider llm.Provider, mcpClients map[string]*mcp.Client, role string, allowedTools []string, systemPrompt string) *Worker
NewSpecializedWorker creates a role-specialized worker with custom system prompt and tool filtering.
func (*Worker) Execute ¶
func (w *Worker) Execute(ctx context.Context, task Task) TaskResult
Execute runs a task and returns the result.
func (*Worker) ExecuteWithCallback ¶ added in v1.20.33
func (w *Worker) ExecuteWithCallback(ctx context.Context, task Task, cb *WorkerCallback) TaskResult
ExecuteWithCallback runs a task and emits optional live progress for LLM-backed work.
type WorkerCallback ¶ added in v1.20.33
Source Files
¶
- analyze_image.go
- auto_skill.go
- builtin_tools.go
- change_journal.go
- context7_injector.go
- context7_registry.go
- context7_registry_embed.go
- graph_context.go
- image_intent.go
- image_tool.go
- iteration_budget.go
- memory_context.go
- mode.go
- mode_env.go
- ninedrive_tool.go
- orchestration_decision.go
- planning_template.go
- proc_unix.go
- read_document.go
- runtime_learning.go
- self_improvement_memory.go
- session.go
- skill_context.go
- skill_semantic_validator.go
- supervisor.go
- types.go
- user_model.go
- web_headless.go
- web_tools.go
- worker.go