Documentation
¶
Overview ¶
Package agent: delegation getters and setters for sub-managers.
Package agent: change tracking and revision management.
Package agent.
Package agent: risk evaluation and profile management.
Package agent: LLM response generation and cost tracking.
Package agent: security accessors and content security checks (split from agent_getters.go)
Package agent: shell working directory and shell command history.
Package agent: conversation state, tokens/cost, tasks, output, and file reading.
Package agent — test helpers exported for use by tests in other packages. initSubManagers is unexported but downstream tests (notably pkg/webui/api_command_test.go's harness) need a way to bring a bare &Agent{} up to the "all sub-managers initialised" state without driving a full agent creation. These wrappers exist because alternative approaches (e.g. internal test files, testdata pre-populated fixtures) would either leak implementation details across package boundaries or be more invasive than the wrappers.
Auto-skip learning for ChangeTracker shell-mutation tracking.
After the first walk of a fat directory (one whose file count exceeds autoSkipFileCountThreshold or autoSkipCumulativeThreshold), the dir is added to autoSkipDirs so subsequent walks skip it entirely. Learned sets persist across agent sessions via change_tracking_shell_persist.go.
Mutation recording and bulk rollup for ChangeTracker shell-mutation tracking.
Takes the diff from before/after snapshots and records TrackedFileChange entries, collapsing high-churn directories into bulk rollups when appropriate.
Shell-mutation tracking: captures before/after snapshots around shell_command invocations to detect file changes the structured tools miss (sed, mv, rm, etc.). Supporting code: change_tracking_snapshot.go, change_tracking_mutations.go, change_tracking_autoskip.go, change_tracking_shell_persist.go.
Persistence for the ChangeTracker's adaptive auto-skip set.
The walker learns "fat directories" on first visit (those with more immediate child files than autoSkipFileCountThreshold) and skips them on subsequent walks within the same session. Without persistence, every new agent session re-learns from scratch — paying the first-walk cost over and over for the same dirs.
This file persists the learned set to `~/.config/sprout/shell_skip_dirs.json`, keyed by absolute workspace root, so subsequent sessions in the same workspace inherit the learning. The file is best-effort: read failures fall back to an empty set (re-learn), write failures log a warning.
To prevent unbounded growth across many workspaces, the file caps at maxPersistedWorkspaces entries — least-recently-used workspaces are evicted first when the cap is exceeded.
Snapshot walking and file I/O for ChangeTracker shell-mutation tracking.
Walks the workspace tree before and after shell commands, capturing file bytes inside size/binary limits, then diffing the two snapshots.
Package agent provides error definitions for the agent package.
Consolidated memory tool.
One handler that dispatches on `operation` to the existing per-op helpers — replaces add_memory / read_memory / list_memories / delete_memory / search_memories so the LLM only sees one entry for memory management.
Package agent provides typed error classification for tool error retry decisions.
The retry package defines a classification system that uses the typed AgentError system from pkg/errors to determine appropriate retry behavior instead of relying on string matching against error messages.
Classification is driven by the error category:
- SecurityError → Escalate (ask user/LLM)
- PermissionError → Fail (approval denied/timeout — not retryable)
- TransientError → Retry (backoff)
- RateLimitError → Retry (longer backoff)
- InvalidInputError → Fail (input must be fixed)
- ContextError → Fail (context overflow, needs compaction)
- PermanentError → Fail (non-recoverable)
- ProviderError → Fail (auth/config) or Retry (server errors) depending on Retryable field
- Unknown errors → Retry once then Fail
RiskAssessment provides a unified, single-vocabulary risk assessment for tool calls, folding the static classifier and persona cascade onto the Low/Medium/High/Critical scale.
Package agent: rollup embedding — writes rollup summaries into the conversation store.
Package agent: LLM-augmented security analysis for shell commands.
Package agent: session-scoped cache for LLM security analyses.
Security circuit breaker + audit logging for the live seed tool path.
Package agent: token-anchoring for sproutProvider.EstimateTokens.
EstimateTokens (seed_provider.go) fed both seed's compaction trigger and CalculateOutputBudget's max_tokens sizing from a from-scratch heuristic estimate of the *entire* conversation, every single call — even though the exact actual prompt-token count is already known from the previous response's Usage.PromptTokens. This file anchors the estimate to that real number instead of discarding it: only the messages appended since the last real measurement go through the (error-prone) heuristic, so estimation error no longer compounds across a long-running conversation.
Package agent: richEventPublisher type and its Publish method for enriching seed tool events with display_name, persona, subagent metadata and emitting CLI tool_log output. (split from seed_tool_registry.go)
Package agent: tool error handling (handleToolError), local provider detection, and the postProcessResult pipeline for seed tool execution. (split from seed_tool_registry.go)
Package agent: payload and display-name helpers for seed tool events, secret source building, and TodoWrite event formatting. (split from seed_tool_registry.go)
Package agent: seed ToolRegistry construction and registration of all sprout tools.
Package agent: pre-execute hook, security caution wrapping, and loop detection for the seed tool registry. (split from seed_tool_registry.go)
Package agent — shell command parsing and classification.
This file provides pure-function utilities for splitting shell commands into logical parts and classifying each part by destructive intent. It contains no Agent wiring, no broker, no events, and no UI.
Package agent — exported test helpers for the shell approval broker.
These let tests in other packages (e.g. pkg/webui) interact with the shellApprovalBroker without needing a full agent instance. They are NOT for production use — only for tests.
Destructive shell command classifier.
Peer to shellLooksReadOnly. Identifies shell commands that are likely to clobber the user's active changes — either by reverting working-tree edits (`git checkout .`, `git reset --hard`, `git restore .`) or by deleting untracked work (`git clean -fd`, `git stash drop`, etc.).
When the change tracker sees a destructive command, it pivots to a safer (slower) mode:
- The adaptive autoSkipDirs set is IGNORED for the walk (and the walk doesn't add to it during a destructive run). A directory that was learned as "fat" during a build might contain edits the user wants back after a `git checkout .` — we'd rather pay the walk cost than silently drop the recovery payload.
- The bulk-rollup branch in RecordShellMutations is BYPASSED so every mutation lands as a per-file entry with full OriginalCode for recovery. A 300-file `git checkout .` produces 300 recoverable rows, not one opaque "src/ — 300 files" row.
- Truncation (50k file / 500ms / 32 MiB caps) gets promoted from a log line to a user-visible manifest entry so partial coverage during a destructive op is impossible to miss.
Bias: CONSERVATIVE in the opposite direction from shellLooksReadOnly. False positive ("said destructive when it wasn't") means we run a fuller walk and emit per-file for a normal command — cheap. False negative ("missed a destructive op") means we might silently drop a recoverable change — expensive. So unrecognised flags or subcommands on a known-destructive program err toward "destructive".
Read-only shell command classifier.
Used to short-circuit the shell-snapshot pass for commands that provably can't mutate the filesystem. Skipping the snapshot avoids the ~10 ms warm-walk cost (and the full prime cost when uncached) on every `ls`, `grep`, `cat`, `git status`, etc. — by far the most common shell_command invocations.
Bias: the classifier is CONSERVATIVE. False positive ("said read-only when it wasn't") means we miss tracking the mutation — bad. False negative ("said write when it was read-only") means we pay the snapshot cost we didn't need — cheap. So any unknown program, chaining operator, redirect, subshell, or known-dangerous flag forces the snapshot.
Package agent provides subagent management via the SubagentRunner, which supports both serial (Run) and parallel (RunParallel) execution of subagent tasks.
SubagentRunner Concurrency Invariants:
MaxConcurrentSubagents: When > 0, a buffered channel semaphore limits the number of concurrently executing subagents. Tasks waiting for a slot respect parent context cancellation and return Cancelled=true.
FleetTokenBudget: When > 0, tracks cumulative token usage across the fleet via atomic.Int64. Once the budget is reached, not-yet-started tasks are skipped with BudgetExceeded=true. Currently running tasks are NOT interrupted.
Order Preservation: RunParallel returns results in the same order as the input tasks, regardless of execution order.
Package agent: StateManager facade and its focused sub-managers.
AgentStateManager is a thin facade composed via Go struct embedding. It holds 4 focused sub-managers, each owning a logical domain:
*AgentSessionManager — MessageStore, SessionStore, CheckpointStore, SummaryStore, OptimizerStore, ContextBudgetStore, ConversationPrunerStore, CommandHistoryStore, PauseStore, SessionConfigStore, ConfigOverrideStore, IterationStore, SessionIntentStore. (13 sub-interfaces)
*AgentMetricsManager — TaskActionStore, CostTracker, TokenCounter, LLMCallTracker, ToolCallTracker, CacheStats, EstimatedTokenStore. (7 sub-interfaces)
*AgentPersonaManager — PersonaStore, ToolGuidanceStore, FalseStopStore. (3 sub-interfaces)
*AgentSecurityStateManager — CircuitBreakerStore, PendingStateStore, TerminationStore, ProviderErrorStore, TraceStore. (5 sub-interfaces)
Method promotion makes every method on each sub-manager automatically visible on the AgentStateManager, satisfying the full StateManager interface (all 28 sub-interfaces composed) without explicit delegation.
**PREFER THE FOCUSED SUB-MANAGER** in code that only needs one domain. Holding a *AgentSessionManager (for example) instead of a *StateManager makes the dependency narrower and reduces the temptation to reach across domains.
Tool call formatting: display-friendly representations of tool calls for logging, progress output, and CLI status reporting.
Package agent: direct tool execution for daemon-routed one-shot calls.
Tool execution helpers shared across the agent package.
Free-function survivors from the deleted pkg/agent/tool_executor_helpers.go. Only these two remained in live use after ToolExecutor was replaced by seed's core.ToolRegistry:
getCurrentTime: security_circuit_breaker.go updates action.LastUsed with the current Unix timestamp.
normalizePositiveInt: tool_handlers_search.go normalises numeric LLM-supplied search arguments (top_k, etc.) that may arrive as int, float, json.Number, or string.
Kept package-private since the callers are also in this package.
Agent-facing tools backed by the ChangeTracker's session buffer. Provides list_changes and revert_my_changes.
recover_file tool: restores a file's tracked content from the ChangeTracker's session buffer. Supports scope="latest" (default), scope="session_start", and scope="bulk".
Package agent provides the shell command handler with a unified security model. When UnifiedRiskResolver is ON (the default), a single ResolveToolRisk assessment gates every shell command. When OFF, the older dual-gate model applies.
Subagent tool handlers: constants, types, globals, and shared declarations.
Implementation details are split across:
- tool_handlers_subagent_events.go — event batching and publishing
- tool_handlers_subagent_result.go — typed result envelope builders
- tool_handlers_subagent_spawn.go — spawn / dispatch logic
Subagent spawn and dispatch logic.
Subagent spawn helper functions (extracted from tool_handlers_subagent_spawn.go). These helpers operate on textual output and provider/model resolution produced during subagent dispatch.
Subagent spawn lifecycle helpers: args parsing, working_dir validation, persona parsing, and enhanced prompt building. Extracted from tool_handlers_subagent_spawn.go for large-file decomposition.
Subagent spawn worktree helpers: file path validation, external workspace approval, and workspace root override. Extracted from tool_handlers_subagent_spawn.go for large-file decomposition.
Package agent provides the core agent functionality including tool registry and handlers.
Tool functionality is organized across:
- tool_definitions.go: Tool configuration structs and registry initialization
- tool_handlers.go: Tool handler implementations
Tool result constraint: truncation and compaction of tool results before they are sent to the model context window. It also owns the shared result-size limits and universal truncation helper moved from the legacy tool executor configuration.
Extracted from tool_security.go — audit/logging helpers.
Extracted from tool_security.go — path-related security helpers.
Subagent tool classification used by the seed event publisher to classify subagent events for the WebUI.
Package agent — batch splitting with fallback.
Provides proactive batch splitting for vision images to avoid provider 400 (context overflow) errors. The splitter considers both image count and total payload bytes, routing overflow images to the existing OCR fallback path so the model still gets text descriptions of images that exceed the provider's inline limits.
Package agent provides the in-process workflow runner for TODO-loop workflows. It eliminates subprocess spawning (the BPM/exec.Command path that requires nohup and breaks across OS/process-group boundaries) by running the workflow loop in-process as a goroutine with a fresh Agent.
Index ¶
- Constants
- Variables
- func ApplyHunks(original string, hunks []Hunk, acceptedIDs []string) string
- func AssertNoStateLeak(realDir string, before map[string]time.Time) int
- func BuildScopedSessionPathForTesting(stateDir, sessionID, workingDir string) (string, error)
- func BuildToolDefinitions() []api.Tool
- func BuildToolDefinitionsForAgent(a *Agent) []api.Tool
- func ChainCacheKey(input string) string
- func CleanupPasswordRequestForTest(requestID string)
- func ContextWithSproutDir(ctx context.Context, dir string) context.Context
- func DecrementActiveSubagents()
- func DeleteMemory(name string) error
- func DeleteMemoryEmbedding(mgr *embedding.EmbeddingManager, name string) error
- func DeleteSession(sessionID string) error
- func DeleteSessionScoped(sessionID, workingDir string) error
- func DeliverEditDecision(requestID string, decision EditDecision) bool
- func DeliverShellDecision(requestID string, decisions map[string]bool) bool
- func DetectLanguages(dir string) []string
- func EmbedAndStoreTurn(ctx context.Context, mgr *embedding.EmbeddingManager, turn *ConversationTurn, ...) error
- func EmbedMemory(ctx context.Context, mgr *embedding.EmbeddingManager, name string, ...) error
- func EstimateTokens(text string) int
- func EvaluateCommandPolicy(command string, policies *configuration.CommandPolicies) (configuration.CommandPolicyAction, string, bool)
- func ExecuteTool(ctx context.Context, toolName string, args map[string]interface{}, ...) ([]api.ImageData, string, error)
- func ExportStateToJSON(state *ConversationState) ([]byte, error)
- func FormatCLIMessage(similarity float64, threshold float64) string
- func FormatFileChangesForSummary(changes []TranscriptFileChange) string
- func FormatProactiveContext(results []ProactiveContextResult, config ProactiveContextConfig, now time.Time) string
- func FormatSemanticRecall(items []RecalledItem, maxChars int) string
- func FormatWakeupBatch(notifications []Notification) string
- func GenerateUnifiedDiff(path, original, proposed string) (string, error)
- func GetActiveSubagents() int
- func GetEmbeddedPlanningPrompt(createTodos bool) (string, error)
- func GetEmbeddedRollupPrompt() string
- func GetEmbeddedSystemPrompt() (string, error)
- func GetEmbeddedSystemPromptForProfile(profile configuration.ContextProfile, provider string, contextWindow int, ...) (string, error)
- func GetEmbeddedSystemPromptWithProvider(provider string) (string, error)
- func GetSessionName(sessionID string) string
- func GetSessionNameScoped(sessionID, workingDir string) string
- func GetSessionPreview(sessionID string) string
- func GetSessionPreviewScoped(sessionID, workingDir string) string
- func GetSettingValue(cfg *configuration.Config, key string) (string, error)
- func GetSkillManifest(content string) (map[string]string, string, error)
- func GetStateDir() (string, error)
- func IncrementActiveSubagents()
- func InjectUserMessageTimestamp(userMessage string) string
- func InjectUserMessageTimestampAt(userMessage string, at time.Time) string
- func InstrumentedRecall(a *Agent, ctx context.Context, query string)
- func IsInteractiveTool(name string) bool
- func IsMemoryIntensiveCommand(cmd string) bool
- func ListChangesEmpty() string
- func ListChangesPersistedOnly(args map[string]interface{}) (string, error)
- func ListSessions() ([]string, error)
- func ListTranscriptSnapshots(sessionID, workingDir string) ([]string, error)
- func LoadContextFiles() (string, error)
- func LoadMemoriesForPrompt() string
- func LoadMemoryContent(name string) (string, error)
- func LoadStateRecoverable(sessionID, workingDir string) (*ConversationState, RecoveryReport, error)
- func MigrateMemories(ctx context.Context, mgr *embedding.EmbeddingManager)
- func NewCascadingPasswordPrompter(prompters ...tools.PasswordPrompter) *cascadingPasswordPrompter
- func NewConversationPruner(debug bool) *core.ConversationPruner
- func NewSeedToolRegistry(agent *Agent) *core.ToolRegistry
- func NewSproutProvider(agent *Agent, client api.ClientInterface) (core.Provider, error)
- func NewTestStateDir(t *testing.T) func()
- func NormalizeChain(chain Chain) string
- func NormalizeYAMLOrdered(v interface{}) interface{}
- func ParseAgentsMd(path string) (name string, description string)
- func ParseJSONOrderedAny(content string) (interface{}, error)
- func PublishModel(model string)
- func RegisterComputerUseTools(cfg *configuration.Config) error
- func RegisterPasswordRequestForTest(requestID string) chan string
- func RemoveTurnJournal(sessionID, workingDir string) error
- func RenameSession(sessionID string, newName string) error
- func RenameSessionScoped(sessionID, newName, workingDir string) error
- func ResetMigrationForTesting()
- func SaveMemory(name string, content string) error
- func SerializeJSONOrdered(data interface{}) (string, error)
- func SerializeYAMLOrdered(data interface{}) (string, error)
- func SetActiveComputerUseAgent(a *Agent)
- func SetEditApprovalTimeout(d time.Duration)
- func SetGetStateDirForTest(dir string) func() (string, error)
- func SetGetStateDirForTestError(msg string) func() (string, error)
- func SetGetStateDirFunc(fn func() (string, error)) func() (string, error)
- func SetPackageDebugLogging(enabled bool)
- func SetPackageLogger(l *AgentLogger)
- func SetSettingValue(cfg *configuration.Config, key, value string) error
- func SetStateDirFuncForTesting(fn func() (string, error)) func()
- func SetTestStateDirHook(dir string) func()
- func SettingEnumValues(key string) []string
- func SettingIsListType(key string) bool
- func SnapshotRealStateDir() (realDir string, before map[string]time.Time)
- func SproutDirFromContext(ctx context.Context) string
- func StripUserMessageTimestamp(userMessage string) string
- func SummarizeMySessionEmpty() string
- func SupportedSettingKeys() []string
- func SweepExpiredEntries(retentionDays int, storePath string) (int, error)
- func TestShellApprovalCleanup(requestID string)
- func TestShellApprovalRegister(requestID string) chan map[string]bool
- func TestShellApprovalRespond(requestID string, decisions map[string]bool) bool
- func ValidateStreamConfig(sc *StreamConfig) error
- func WorkflowRequiresApproval(workflowName string) bool
- func WorkflowRequiresApprovalIn(dir, workflowName string) bool
- func WriteTestSessionFile(stateDir, sessionID, workingDir string, state *ConversationState) error
- type Agent
- func NewAgent() (*Agent, error)
- func NewAgentWithClient(client api.ClientInterface, clientType api.ClientType, ...) (*Agent, error)
- func NewAgentWithConfigDir(configDir, model string) (*Agent, error)
- func NewAgentWithLayers(globalDir, workspaceDir, model string) (*Agent, error)
- func NewAgentWithLayersInWorkspace(globalDir, workspaceDir, workspaceRoot, model string) (*Agent, error)
- func NewAgentWithModel(model string) (*Agent, error)
- func NewTestAgent() *Agent
- func (a *Agent) AddMessage(message api.Message)
- func (a *Agent) AddSessionAllowedFolder(folder string)
- func (a *Agent) AddTaskAction(actionType, description, details string)
- func (a *Agent) AddToHistory(command string)
- func (a *Agent) AllowAppForComputerUse(key string)
- func (a *Agent) ApplyPersona(personaID string) error
- func (a *Agent) ApplyRecoveredState(state *ConversationState) RecoveryReport
- func (a *Agent) ApplyState(state *ConversationState)
- func (a *Agent) ApplySyncOp(op SyncOp, workspaceRoot string) SyncOpResult
- func (a *Agent) ApplySyncOpBatch(ops []SyncOp, workspaceRoot string) []SyncOpResult
- func (a *Agent) Breakpoints() []Breakpoint
- func (a *Agent) BuildCheckpointCompactedMessages(messages []api.Message) ([]api.Message, []TurnCheckpoint)
- func (a *Agent) BuildTranscriptSnapshot(label string, includePreview bool) *TranscriptSnapshot
- func (a *Agent) CanSpawnSubagents() bool
- func (a *Agent) CaptureTranscriptSnapshot(label string, includePreview bool) (string, error)
- func (a *Agent) CheckFileContentSecurity(filePath string, content string)
- func (a *Agent) CheckForInterrupt() bool
- func (a *Agent) CheckPatchConflict(path string) (bool, string)
- func (a *Agent) ClassifyFileAccess(ctx context.Context, filePath, resolvedPath, mode string) string
- func (a *Agent) ClearActivePersona()
- func (a *Agent) ClearConversationHistory()
- func (a *Agent) ClearInputInjectionContext()
- func (a *Agent) ClearInterrupt()
- func (a *Agent) ClearSecurityAnalysisCache()
- func (a *Agent) ClearSessionOverrides()
- func (a *Agent) ClearShellCommandHistory()
- func (a *Agent) ClearTrackedChanges()
- func (a *Agent) CommitChanges(llmResponse string) error
- func (a *Agent) ConsumePendingStrictSwitchNotice() string
- func (a *Agent) DeferredMessageCount() int
- func (a *Agent) DisableAutoPruning()
- func (a *Agent) DisableChangeTracking()
- func (a *Agent) DisableEmbeddingIndex()
- func (a *Agent) DisableStreaming()
- func (a *Agent) DisableWakeup()
- func (a *Agent) DrainDeferredMessages() []string
- func (a *Agent) DrainNotifications() []Notification
- func (a *Agent) ElevateSessionToPermissive()
- func (a *Agent) EnableAutoPruning()
- func (a *Agent) EnableChangeTracking(instructions string)
- func (a *Agent) EnableEmbeddingIndex() error
- func (a *Agent) EnableStreaming(callback func(string))
- func (a *Agent) EnableWakeupIfDisabled()
- func (a *Agent) EndQuery()
- func (a *Agent) EnqueueDeferredMessage(text string)
- func (a *Agent) EnsureLocalServer() error
- func (a *Agent) EvaluateOperationRisk(command string) configuration.RiskLevel
- func (a *Agent) ExecuteToolByName(ctx context.Context, name, argsJSON string) (content string, toolErr string)
- func (a *Agent) ExportState() ([]byte, error)
- func (a *Agent) FleetBudgetExceeded() bool
- func (a *Agent) ForceSaveAndExit(code int)
- func (a *Agent) ForkAtBreakpoint(breakpointIndex int) (string, error)
- func (a *Agent) GenerateActionSummary() string
- func (a *Agent) GenerateCompactSummary() string
- func (a *Agent) GenerateConversationSummary() string
- func (a *Agent) GenerateResponse(messages []api.Message) (string, error)
- func (a *Agent) GenerateSessionSummary() string
- func (a *Agent) GetActivePersona() string
- func (a *Agent) GetActiveRiskProfile() configuration.RiskProfile
- func (a *Agent) GetAllShellCommandHistory() map[string]*ShellCommandResult
- func (a *Agent) GetAuditLogger() *tools.AuditLogger
- func (a *Agent) GetAvailablePersonaIDs() []string
- func (a *Agent) GetAvailableToolNames() []string
- func (a *Agent) GetAverageTPS() float64
- func (a *Agent) GetBackgroundProcessManager() *tools.BackgroundProcessManager
- func (a *Agent) GetCacheWriteTokens() int
- func (a *Agent) GetCachedCostSavings() float64
- func (a *Agent) GetCachedTokens() int
- func (a *Agent) GetChangeCount() int
- func (a *Agent) GetChangeTracker() *ChangeTracker
- func (a *Agent) GetChangesSummary() string
- func (a *Agent) GetChargedCostTotal() float64
- func (a *Agent) GetCompletionTokens() int
- func (a *Agent) GetConfig() *configuration.Config
- func (a *Agent) GetConfigManager() *configuration.Manager
- func (a *Agent) GetConfigOverrides() map[string]interface{}
- func (a *Agent) GetContextProfile() configuration.ContextProfile
- func (a *Agent) GetContextTokens() (used, limit int)
- func (a *Agent) GetContextWarningIssued() bool
- func (a *Agent) GetContinuationNudges() int
- func (a *Agent) GetCurrentContextTokens() int
- func (a *Agent) GetCurrentIteration() int
- func (a *Agent) GetCurrentTPS() float64
- func (a *Agent) GetDebugLogPath() string
- func (a *Agent) GetEffectiveContextCap() int
- func (a *Agent) GetElevationGate() *security.ElevationGate
- func (a *Agent) GetEmbeddingManager() *embedding.EmbeddingManager
- func (a *Agent) GetEstimatedTokenResponses() int
- func (a *Agent) GetEventBus() *events.EventBus
- func (a *Agent) GetEventChatID() string
- func (a *Agent) GetEventClientID() string
- func (a *Agent) GetEventUserID() string
- func (a *Agent) GetFileMetadata(path string) (WorkspaceFileMetadata, bool)
- func (a *Agent) GetFleetUsdBudget() *FleetUsdBudget
- func (a *Agent) GetHistory() []string
- func (a *Agent) GetHistoryCommand(index int) string
- func (a *Agent) GetHistorySize() int
- func (a *Agent) GetImageTokens() int
- func (a *Agent) GetInputInjectionContext() <-chan string
- func (a *Agent) GetLLMCallCount() int
- func (a *Agent) GetLastMessages(n int) []api.Message
- func (a *Agent) GetLastPreparedToolNames() []string
- func (a *Agent) GetLastRunTerminationReason() string
- func (a *Agent) GetLastTPS() float64
- func (a *Agent) GetMaxContextTokens() int
- func (a *Agent) GetMaxContextTokensCached() int
- func (a *Agent) GetMaxIterations() int
- func (a *Agent) GetMessages() []api.Message
- func (a *Agent) GetModel() string
- func (a *Agent) GetOptimizationStats() map[string]interface{}
- func (a *Agent) GetOutputRedactor() *security.OutputRedactor
- func (a *Agent) GetPasswordPrompter() tools.PasswordPrompter
- func (a *Agent) GetPersonaProviderModel(personaID string) (string, string, error)
- func (a *Agent) GetPreviousSummary() string
- func (a *Agent) GetPromptTokens() int
- func (a *Agent) GetProvider() string
- func (a *Agent) GetProviderType() api.ClientType
- func (a *Agent) GetPruningStats() map[string]interface{}
- func (a *Agent) GetRevisionID() string
- func (a *Agent) GetSecurityApprovalMgr() *security.ApprovalManager
- func (a *Agent) GetSecurityCautionsIssued() int64
- func (a *Agent) GetSecurityLoopsDetected() int64
- func (a *Agent) GetSecurityRetriesAfterCaution() int64
- func (a *Agent) GetSessionID() string
- func (a *Agent) GetSessionName() string
- func (a *Agent) GetShellCommandHistoryEntry(command string) (*ShellCommandResult, bool)
- func (a *Agent) GetShellCwd() string
- func (a *Agent) GetSubagentRunner() *SubagentRunner
- func (a *Agent) GetSyncStatus() map[string]WorkspaceFileMetadata
- func (a *Agent) GetSystemPrompt() string
- func (a *Agent) GetTPSStats() map[string]float64
- func (a *Agent) GetTaskActions() []TaskAction
- func (a *Agent) GetTerminalManager() tools.TerminalAccess
- func (a *Agent) GetTodoManager() *tools.TodoManager
- func (a *Agent) GetTokenCostTotal() float64
- func (a *Agent) GetTotalCost() float64
- func (a *Agent) GetTotalTokens() int
- func (a *Agent) GetTrackedFiles() []string
- func (a *Agent) GetTurnCheckpoints() []TurnCheckpoint
- func (a *Agent) GetUnsafeMode() bool
- func (a *Agent) GetUnsafeShellMode() bool
- func (a *Agent) GetValidator() *validation.Validator
- func (a *Agent) GetVisionProcessor() *tools.VisionProcessor
- func (a *Agent) GetWorkspaceRoot() string
- func (a *Agent) HandleInterrupt() string
- func (a *Agent) HasActiveWebUIClients() bool
- func (a *Agent) HasPasswordPrompter() bool
- func (a *Agent) HasPendingNotifications() bool
- func (a *Agent) HasSessionOverrides() bool
- func (a *Agent) HasTurnCheckpoints() bool
- func (a *Agent) ImportState(data []byte) error
- func (a *Agent) IncrementWakeupResume(cfg configuration.WakeupConfig) bool
- func (a *Agent) InitSubManagersForTest()
- func (a *Agent) InjectInputContext(input string) error
- func (a *Agent) InjectProactiveContext(ctx context.Context, query string) error
- func (a *Agent) InjectSemanticRecall(ctx context.Context, query string)
- func (a *Agent) InjectSemanticRecallWithItems(ctx context.Context, query string, items []RecalledItem)
- func (a *Agent) InjectWebUIManagers(approvalMgr *security.ApprovalManager, askUserMgr *tools.AskUserManager)
- func (a *Agent) InterruptCtx() context.Context
- func (a *Agent) IsAppAllowedForComputerUse(key string) bool
- func (a *Agent) IsCdTargetAllowed(target string) bool
- func (a *Agent) IsChangeTrackingEnabled() bool
- func (a *Agent) IsDebugMode() bool
- func (a *Agent) IsEmbeddingIndexEnabled() bool
- func (a *Agent) IsFolderSessionAllowed(absPath string) bool
- func (a *Agent) IsFolderSessionWriteAllowed(absPath string) bool
- func (a *Agent) IsInteractiveMode() bool
- func (a *Agent) IsInterrupted() bool
- func (a *Agent) IsLocalMode() bool
- func (a *Agent) IsPathOutsideWorkspace(path string) bool
- func (a *Agent) IsQueryInProgress() bool
- func (a *Agent) IsReadOnlyAllowedFolder(absPath string) bool
- func (a *Agent) IsSecurityBypassApproved() bool
- func (a *Agent) IsSessionElevated() bool
- func (a *Agent) IsShellCommandAllowlisted(command string) bool
- func (a *Agent) IsShutdown() bool
- func (a *Agent) IsStreamingEnabled() bool
- func (a *Agent) IsSubagent() bool
- func (a *Agent) IsUnderWorkspaceRoot(absPath string) bool
- func (a *Agent) IsWakeupDisabled() bool
- func (a *Agent) IsWorkflowApprovedInSession(workflow string) bool
- func (a *Agent) LifetimeCtx() context.Context
- func (a *Agent) ListAllowedCdTargets() []string
- func (a *Agent) ListChanges(args map[string]interface{}) (string, error)
- func (a *Agent) LoadState(sessionID string) (*ConversationState, error)
- func (a *Agent) LoadStateFromFile(filename string) error
- func (a *Agent) LoadStateScoped(sessionID, workingDir string) (*ConversationState, error)
- func (a *Agent) LoadSummaryFromFile(filename string) error
- func (a *Agent) LogToolCall(tc api.ToolCall, phase string)
- func (a *Agent) Logger() *AgentLogger
- func (a *Agent) MarkEstimatedTokenUsageResponse()
- func (a *Agent) MarkWorkflowApprovedInSession(workflow string)
- func (a *Agent) MaxSubagentDepth() int
- func (a *Agent) MergeEventMetadata(extras map[string]interface{})
- func (a *Agent) MergeSubagentChanges(changes []TrackedFileChange, persona string)
- func (a *Agent) MyRecentChanges(since string) (string, error)
- func (a *Agent) NavigateHistory(direction int, currentIndex int) (string, int)
- func (a *Agent) NoteRecoveredSession()
- func (a *Agent) NotifyCompletion(sessionID, kind, content string)
- func (a *Agent) OutputRouter() *OutputRouter
- func (a *Agent) PendingSteerCount() int
- func (a *Agent) PersistShellCommandAllowlist(command string) error
- func (a *Agent) PersistShellCommandAskPolicy(command string) error
- func (a *Agent) PersistShellCommandPattern(pattern string) error
- func (a *Agent) PrintCompactProgress()
- func (a *Agent) PrintConversationSummary(forceFull bool)
- func (a *Agent) PrintLine(text string)
- func (a *Agent) PrintLineAsync(text string)
- func (a *Agent) PrintTerminalOnly(text string)
- func (a *Agent) ProcessQuery(userQuery string) (string, error)
- func (a *Agent) ProcessQueryAs(source, userQuery string) (string, error)
- func (a *Agent) ProcessQueryWithContinuity(userQuery string) (string, error)
- func (a *Agent) ProcessQueryWithContinuityAs(source, userQuery string) (string, error)
- func (a *Agent) PromptChoice(prompt string, choices []ChoiceOption) (string, error)
- func (a *Agent) PromptFileAccess(ctx context.Context, toolName, filePath, resolvedPath, mode string) (context.Context, bool)
- func (a *Agent) PublishAgentMessage(category, message string, extra map[string]interface{})
- func (a *Agent) PublishCompactCompleted(source string, beforeCount, afterCount, summaryChars int, err error)
- func (a *Agent) PublishCompactStarted(source string, messageCount, checkpointCount int)
- func (a *Agent) PublishContextManagementDiagnostic(...)
- func (a *Agent) PublishEvent(eventType string, data interface{})
- func (a *Agent) PublishFileChange(filePath, action, content string)
- func (a *Agent) PublishQueryProgress(message string, iteration int, tokensUsed int)
- func (a *Agent) PublishRateLimited(ev *events.RateLimitedEvent)
- func (a *Agent) PublishRecallDiagnostic(diag recallRetrievalDiagnostic)
- func (a *Agent) PublishStreamChunk(chunk string, contentType string)
- func (a *Agent) PublishTodoUpdate(todos []map[string]interface{})
- func (a *Agent) PublishToolEnd(toolCallID, toolName, status, result, errorMessage string, ...)
- func (a *Agent) PublishToolExecution(toolName, action string, details map[string]interface{})
- func (a *Agent) PublishToolStart(toolName, toolCallID, arguments, displayName, persona string, isSubagent bool, ...)
- func (a *Agent) QueryGuardOwner() QueryGuardOwner
- func (a *Agent) QueueNotification(n Notification)
- func (a *Agent) ReadFileContent(path string) (string, error)
- func (a *Agent) Recall(ctx context.Context, query string, limit int) ([]RecalledItem, error)
- func (a *Agent) RecordErrorCategory(err error)
- func (a *Agent) RecordFileReadThisTurn(path string)
- func (a *Agent) RecordTurnCheckpoint(startIndex, endIndex int)
- func (a *Agent) RecordTurnCheckpointAsync(startIndex, endIndex int)
- func (a *Agent) RecordWakeupTokens(tokens int, cfg configuration.WakeupConfig)
- func (a *Agent) RecoverFile(path string) (string, error)
- func (a *Agent) RefreshContextCapFromConfig()
- func (a *Agent) RefreshMCPTools() error
- func (a *Agent) RefreshRuntimeConfig(ctx context.Context) error
- func (a *Agent) RefreshSkills() error
- func (a *Agent) RemoveSessionAllowedFolder(folder string) error
- func (a *Agent) ReplaceTurnCheckpoints(checkpoints []TurnCheckpoint)
- func (a *Agent) RequestApproval(assessment RiskAssessment, toolName string, args map[string]interface{}) (BrokerDecision, error)
- func (a *Agent) RequestEditApproval(ctx context.Context, p EditProposal) (applied string, summary string, err error)
- func (a *Agent) RequestShellApproval(ctx context.Context, p ShellProposal) (map[string]bool, error)
- func (a *Agent) ResetComputerUseSessionApproval()
- func (a *Agent) ResetFileReadsForNewTurn()
- func (a *Agent) ResetHistoryIndex()
- func (a *Agent) ResolveBillingType() string
- func (a *Agent) ResolveToolRisk(toolName string, args map[string]interface{}) RiskAssessment
- func (a *Agent) RespondToEditApproval(requestID string, decision EditDecision) bool
- func (a *Agent) RespondToPasswordRequest(requestID string, password string) bool
- func (a *Agent) RespondToShellApproval(requestID string, decisions map[string]bool) bool
- func (a *Agent) RestoreEmbeddingIndex()
- func (a *Agent) RetractLatestDeferredMessage() (string, bool)
- func (a *Agent) RetractLatestSteer() (string, bool)
- func (a *Agent) RevertMyChanges(scope, file, since string) (string, error)
- func (a *Agent) Rewind(opts RewindOptions) (*RewindResult, error)
- func (a *Agent) RotateSession() (string, error)
- func (a *Agent) RunAutomateWorkflow(ctx context.Context, workflow string) (string, error)
- func (a *Agent) SaveConversationSummary() error
- func (a *Agent) SaveState(sessionID string) error
- func (a *Agent) SaveStateScoped(sessionID, workingDir string) error
- func (a *Agent) SaveStateToFile(filename string) error
- func (a *Agent) SelectProvider() error
- func (a *Agent) SetAuditLogger(l *tools.AuditLogger)
- func (a *Agent) SetBackgroundProcessManager(bpm *tools.BackgroundProcessManager)
- func (a *Agent) SetBaseSystemPrompt(prompt string)
- func (a *Agent) SetBudgetExceededCallback(fn func(spent, limit float64))
- func (a *Agent) SetBudgetWarningCallback(fn func(threshold, spent, limit float64))
- func (a *Agent) SetConfigOverrides(overrides map[string]interface{})
- func (a *Agent) SetConversationOptimization(enabled bool)
- func (a *Agent) SetElevationGatePrompter()
- func (a *Agent) SetEventBus(eventBus *events.EventBus)
- func (a *Agent) SetEventMetadata(metadata map[string]interface{})
- func (a *Agent) SetFileMetadata(path string, md WorkspaceFileMetadata)
- func (a *Agent) SetFleetBudget(tracker *atomic.Int64, limit int64)
- func (a *Agent) SetFleetUsdBudget(b *FleetUsdBudget)
- func (a *Agent) SetFlushCallback(callback func())
- func (a *Agent) SetHasActiveWebUIClients(fn func() bool)
- func (a *Agent) SetInterruptHandler(ch chan struct{})
- func (a *Agent) SetLastPreparedToolNames(tools []api.Tool)
- func (a *Agent) SetMaxIterations(max int)
- func (a *Agent) SetMessages(messages []api.Message)
- func (a *Agent) SetModel(model string) error
- func (a *Agent) SetModelPersisted(model string) error
- func (a *Agent) SetOutputMutex(mutex *sync.Mutex)
- func (a *Agent) SetPasswordPrompter(pp tools.PasswordPrompter)
- func (a *Agent) SetPreviousSummary(summary string)
- func (a *Agent) SetProvider(provider api.ClientType) error
- func (a *Agent) SetProviderPersisted(provider api.ClientType) error
- func (a *Agent) SetPruningSlidingWindowSize(size int)
- func (a *Agent) SetPruningStrategy(strategy PruningStrategy)
- func (a *Agent) SetPruningThreshold(threshold float64)
- func (a *Agent) SetRecentMessagesToKeep(count int)
- func (a *Agent) SetRiskProfileOverride(profile configuration.RiskProfile)
- func (a *Agent) SetSessionAllowedFolderMode(folder, mode string)
- func (a *Agent) SetSessionID(sessionID string)
- func (a *Agent) SetSessionName(name string)
- func (a *Agent) SetShellCommandHistoryEntry(command string, result *ShellCommandResult)
- func (a *Agent) SetShellCwd(dir string)
- func (a *Agent) SetSlashCommands(registry any)
- func (a *Agent) SetStatsUpdateCallback(callback func(int, float64))
- func (a *Agent) SetStreamingCallback(callback func(string))
- func (a *Agent) SetStreamingEnabled(enabled bool)
- func (a *Agent) SetSystemPrompt(prompt string)
- func (a *Agent) SetSystemPromptFromFile(filePath string) error
- func (a *Agent) SetTerminalManager(tm tools.TerminalAccess)
- func (a *Agent) SetTraceSession(traceSession interface{})
- func (a *Agent) SetTrainingConfig(cfg configuration.TrainingConfig)
- func (a *Agent) SetTrainingPushFunc(fn func(state ConversationState, endpoint string, excludePaths []string) error)
- func (a *Agent) SetUI(ui UI)
- func (a *Agent) SetUnsafeMode(unsafe bool)
- func (a *Agent) SetUnsafeShellMode(unsafe bool)
- func (a *Agent) SetWorkspaceRoot(workspaceRoot string)
- func (a *Agent) ShouldGateEdit(path string) bool
- func (a *Agent) ShowColoredDiff(oldContent, newContent string, maxLines int)
- func (a *Agent) ShowDropdown(items interface{}, options DropdownOptions) (interface{}, error)
- func (a *Agent) ShowMyChange(path string) (string, error)
- func (a *Agent) ShowQuickPrompt(prompt string, options []QuickOption, horizontal bool) (QuickOption, error)
- func (a *Agent) Shutdown()
- func (a *Agent) SlashCommands() any
- func (a *Agent) SnapshotSessionAllowedFolderModes() map[string]string
- func (a *Agent) SnapshotSessionAllowedFolders() []string
- func (a *Agent) StageSteerInput(text string) error
- func (a *Agent) SteeringChannel() <-chan string
- func (a *Agent) SubagentDepth() int
- func (a *Agent) SummarizeMySession() (string, error)
- func (a *Agent) SummarizeViaLLM(ctx context.Context, messages []api.Message, hint core.SummarizerHint) (string, error)
- func (a *Agent) ToolLog(action string, target string)
- func (a *Agent) TrackFileEdit(filePath string, originalContent string, newContent string) error
- func (a *Agent) TrackFileWrite(filePath string, content string) error
- func (a *Agent) TrackMetricsFromResponse(promptTokens, completionTokens, totalTokens int, estimatedCost float64, ...)
- func (a *Agent) TriggerInterrupt()
- func (a *Agent) TryAutoResume() bool
- func (a *Agent) TryBeginQuery() error
- func (a *Agent) TryBeginQueryAs(source string) error
- type AgentLogger
- func (l *AgentLogger) Debug(format string, args ...interface{})
- func (l *AgentLogger) Error(format string, args ...interface{})
- func (l *AgentLogger) Info(format string, args ...interface{})
- func (l *AgentLogger) SetJSONMode(jsonMode bool)
- func (l *AgentLogger) Warn(format string, args ...interface{})
- func (l *AgentLogger) WithFields(fields map[string]string) *LogContext
- type AgentMCPManager
- func (m *AgentMCPManager) GetInitError() error
- func (m *AgentMCPManager) GetManager() mcp.MCPManager
- func (m *AgentMCPManager) GetToolsCache() []api.Tool
- func (m *AgentMCPManager) IsInitialized() bool
- func (m *AgentMCPManager) LockInit()
- func (m *AgentMCPManager) SetInitError(err error)
- func (m *AgentMCPManager) SetInitialized(initialized bool)
- func (m *AgentMCPManager) SetManager(mgr mcp.MCPManager)
- func (m *AgentMCPManager) SetToolsCache(tools []api.Tool)
- func (m *AgentMCPManager) UnlockInit()
- type AgentMetricsManager
- func (m *AgentMetricsManager) AddCost(c float64)
- func (m *AgentMetricsManager) AddCostEntry(entry CostEntry)
- func (m *AgentMetricsManager) GetCacheWriteTokens() int
- func (m *AgentMetricsManager) GetCachedCostSavings() float64
- func (m *AgentMetricsManager) GetCachedTokens() int
- func (m *AgentMetricsManager) GetChargedCostTotal() float64
- func (m *AgentMetricsManager) GetCompletionTokens() int
- func (m *AgentMetricsManager) GetContinuationNudges() int
- func (m *AgentMetricsManager) GetEstimatedTokenResponses() int
- func (m *AgentMetricsManager) GetFreeTokens() int
- func (m *AgentMetricsManager) GetImageTokens() int
- func (m *AgentMetricsManager) GetLLMCallCount() int
- func (m *AgentMetricsManager) GetPromptTokens() int
- func (m *AgentMetricsManager) GetSubscriptionTokens() int
- func (m *AgentMetricsManager) GetTokenCostTotal() float64
- func (m *AgentMetricsManager) GetTotalCost() float64
- func (m *AgentMetricsManager) GetTotalTokens() int
- func (m *AgentMetricsManager) GetTotalToolCalls() int
- func (m *AgentMetricsManager) IncrementLLMCallCount()
- func (m *AgentMetricsManager) IncrementTotalToolCalls()
- func (m *AgentMetricsManager) RecordContinuationNudges(n int)
- func (m *AgentMetricsManager) SetCacheWriteTokens(n int)
- func (m *AgentMetricsManager) SetCachedCostSavings(c float64)
- func (m *AgentMetricsManager) SetCachedTokens(n int)
- func (m *AgentMetricsManager) SetChargedCostTotal(v float64)
- func (m *AgentMetricsManager) SetCompletionTokens(n int)
- func (m *AgentMetricsManager) SetEstimatedTokenResponses(n int)
- func (m *AgentMetricsManager) SetFreeTokens(v int)
- func (m *AgentMetricsManager) SetImageTokens(n int)
- func (m *AgentMetricsManager) SetLLMCallCount(n int)
- func (m *AgentMetricsManager) SetPromptTokens(n int)
- func (m *AgentMetricsManager) SetSubscriptionTokens(v int)
- func (m *AgentMetricsManager) SetTokenCostTotal(v float64)
- func (m *AgentMetricsManager) SetTotalCost(c float64)
- func (m *AgentMetricsManager) SetTotalTokens(n int)
- func (m *AgentMetricsManager) SetTotalToolCalls(n int)
- type AgentOutputManager
- func (m *AgentOutputManager) EnsureAsyncOutputWorker(fn func())
- func (m *AgentOutputManager) GetAsyncBufferSize() int
- func (m *AgentOutputManager) GetAsyncOutput() chan string
- func (m *AgentOutputManager) GetEventMetadata() map[string]interface{}
- func (m *AgentOutputManager) GetEventMetadataMutex() *sync.RWMutex
- func (m *AgentOutputManager) GetFlushCallback() func()
- func (m *AgentOutputManager) GetOutputMutex() *sync.Mutex
- func (m *AgentOutputManager) GetOutputRouter() *OutputRouter
- func (m *AgentOutputManager) GetReasoningBuffer() *strings.Builder
- func (m *AgentOutputManager) GetReasoningCallback() func(string)
- func (m *AgentOutputManager) GetStreamingBuffer() *strings.Builder
- func (m *AgentOutputManager) GetStreamingCallback() func(string)
- func (m *AgentOutputManager) GetTerminalWriter() func(string)
- func (m *AgentOutputManager) IsStreamingEnabled() bool
- func (m *AgentOutputManager) SetAsyncBufferSize(size int)
- func (m *AgentOutputManager) SetAsyncOutput(ch chan string)
- func (m *AgentOutputManager) SetEventMetadata(meta map[string]interface{})
- func (m *AgentOutputManager) SetEventMetadataUnlocked(meta map[string]interface{})
- func (m *AgentOutputManager) SetFlushCallback(cb func())
- func (m *AgentOutputManager) SetOutputMutex(mu *sync.Mutex)
- func (m *AgentOutputManager) SetOutputRouter(router *OutputRouter)
- func (m *AgentOutputManager) SetReasoningCallback(cb func(string))
- func (m *AgentOutputManager) SetStreamingCallback(cb func(string))
- func (m *AgentOutputManager) SetStreamingEnabled(enabled bool)
- func (m *AgentOutputManager) SetTerminalWriter(fn func(string))
- type AgentPersonaManager
- func (p *AgentPersonaManager) AddTaskAction(action TaskAction)
- func (p *AgentPersonaManager) GetActivePersona() string
- func (p *AgentPersonaManager) GetActiveSkills() []string
- func (p *AgentPersonaManager) GetTaskActions() []TaskAction
- func (p *AgentPersonaManager) GetTaskActionsMutex() *sync.RWMutex
- func (p *AgentPersonaManager) IsFalseStopDetectionEnabled() bool
- func (p *AgentPersonaManager) IsToolCallGuidanceAdded() bool
- func (p *AgentPersonaManager) SetActivePersona(persona string)
- func (p *AgentPersonaManager) SetActiveSkills(skills []string)
- func (p *AgentPersonaManager) SetFalseStopDetectionEnabled(v bool)
- func (p *AgentPersonaManager) SetTaskActions(actions []TaskAction)
- func (p *AgentPersonaManager) SetToolCallGuidanceAdded(v bool)
- type AgentSecurityManager
- func (m *AgentSecurityManager) AddSessionAllowedFolder(folder string)
- func (m *AgentSecurityManager) GetAskUserMgr() *agenttools.AskUserManager
- func (m *AgentSecurityManager) GetElevationGate() *security.ElevationGate
- func (m *AgentSecurityManager) GetOutputRedactor() *security.OutputRedactor
- func (m *AgentSecurityManager) GetSecurityApprovalMgr() *security.ApprovalManager
- func (m *AgentSecurityManager) GetUnsafeMode() bool
- func (m *AgentSecurityManager) GetUnsafeShellMode() bool
- func (m *AgentSecurityManager) HasActiveWebUIClients() bool
- func (m *AgentSecurityManager) IsConcernIgnored(filePath, concern string) bool
- func (m *AgentSecurityManager) IsFolderSessionAllowed(absPath string) bool
- func (m *AgentSecurityManager) IsFolderSessionWriteAllowed(absPath string) bool
- func (m *AgentSecurityManager) IsSecurityBypassApproved() bool
- func (m *AgentSecurityManager) RemoveSessionAllowedFolder(folder string) error
- func (m *AgentSecurityManager) SetApprovalMgr(mgr *security.ApprovalManager)
- func (m *AgentSecurityManager) SetAskUserMgr(mgr *agenttools.AskUserManager)
- func (m *AgentSecurityManager) SetConcernIgnored(filePath, concern string)
- func (m *AgentSecurityManager) SetElevationGate(gate *security.ElevationGate)
- func (m *AgentSecurityManager) SetHasActiveWebUIClients(fn func() bool)
- func (m *AgentSecurityManager) SetSessionAllowedFolderMode(folder, mode string)
- func (m *AgentSecurityManager) SetUnsafeMode(unsafe bool)
- func (m *AgentSecurityManager) SetUnsafeShellMode(unsafe bool)
- func (m *AgentSecurityManager) SnapshotSessionAllowedFolderModes() map[string]string
- func (m *AgentSecurityManager) SnapshotSessionAllowedFolders() []string
- type AgentSecurityStateManager
- func (s *AgentSecurityStateManager) GetCircuitBreaker() *CircuitBreakerState
- func (s *AgentSecurityStateManager) GetLastProviderError() *ProviderErrorInfo
- func (s *AgentSecurityStateManager) GetLastRunTerminationReason() string
- func (s *AgentSecurityStateManager) GetPendingStrictSwitchNotice() string
- func (s *AgentSecurityStateManager) GetPendingSwitchContextRefresh() string
- func (s *AgentSecurityStateManager) GetPendingSystemSupplement() string
- func (s *AgentSecurityStateManager) GetTraceSession() interface{}
- func (s *AgentSecurityStateManager) SetCircuitBreaker(cb *CircuitBreakerState)
- func (s *AgentSecurityStateManager) SetLastProviderError(err *ProviderErrorInfo)
- func (s *AgentSecurityStateManager) SetLastRunTerminationReason(reason string)
- func (s *AgentSecurityStateManager) SetPendingStrictSwitchNotice(v string)
- func (s *AgentSecurityStateManager) SetPendingSwitchContextRefresh(v string)
- func (s *AgentSecurityStateManager) SetPendingSystemSupplement(v string)
- func (s *AgentSecurityStateManager) SetTraceSession(ts interface{})
- type AgentSessionManager
- func (m *AgentSessionManager) AddMessage(msg api.Message)
- func (m *AgentSessionManager) AddTurnCheckpoint(cp TurnCheckpoint)
- func (m *AgentSessionManager) GetCheckpointMutex() *sync.RWMutex
- func (m *AgentSessionManager) GetCommandHistory() []string
- func (m *AgentSessionManager) GetConfigOverrides() map[string]interface{}
- func (m *AgentSessionManager) GetConversationPruner() *ConversationPruner
- func (m *AgentSessionManager) GetCurrentContextTokens() int
- func (m *AgentSessionManager) GetCurrentIteration() int
- func (m *AgentSessionManager) GetHistoryIndex() int
- func (m *AgentSessionManager) GetHistoryMutex() *sync.Mutex
- func (m *AgentSessionManager) GetMaxContextTokens() int
- func (m *AgentSessionManager) GetMessageTimestamps() []time.Time
- func (m *AgentSessionManager) GetMessages() []api.Message
- func (m *AgentSessionManager) GetOptimizer() *ConversationOptimizer
- func (m *AgentSessionManager) GetPauseMutex() *sync.Mutex
- func (m *AgentSessionManager) GetPauseState() *PauseState
- func (m *AgentSessionManager) GetPreviousSummary() string
- func (m *AgentSessionManager) GetSessionID() string
- func (m *AgentSessionManager) GetSessionIntentEmbedding() []float32
- func (m *AgentSessionManager) GetSessionModel() string
- func (m *AgentSessionManager) GetSessionProvider() api.ClientType
- func (m *AgentSessionManager) GetTurnCheckpoints() []TurnCheckpoint
- func (m *AgentSessionManager) IsContextWarningIssued() bool
- func (m *AgentSessionManager) SetCommandHistory(h []string)
- func (m *AgentSessionManager) SetConfigOverrides(overrides map[string]interface{})
- func (m *AgentSessionManager) SetContextWarningIssued(v bool)
- func (m *AgentSessionManager) SetConversationPruner(pruner *ConversationPruner)
- func (m *AgentSessionManager) SetCurrentContextTokens(n int)
- func (m *AgentSessionManager) SetCurrentIteration(iter int)
- func (m *AgentSessionManager) SetHistoryIndex(i int)
- func (m *AgentSessionManager) SetMaxContextTokens(n int)
- func (m *AgentSessionManager) SetMessageTimestamps(ts []time.Time)
- func (m *AgentSessionManager) SetMessages(msgs []api.Message)
- func (m *AgentSessionManager) SetOptimizer(o *ConversationOptimizer)
- func (m *AgentSessionManager) SetPauseState(ps *PauseState)
- func (m *AgentSessionManager) SetPreviousSummary(summary string)
- func (m *AgentSessionManager) SetSessionID(id string)
- func (m *AgentSessionManager) SetSessionIntentEmbedding(emb []float32)
- func (m *AgentSessionManager) SetSessionIntentEmbeddingIfNil(emb []float32) bool
- func (m *AgentSessionManager) SetSessionModel(model string)
- func (m *AgentSessionManager) SetSessionProvider(ct api.ClientType)
- func (m *AgentSessionManager) SetTurnCheckpoints(cps []TurnCheckpoint)
- type AgentState
- type AgentStateManager
- type BatchSplitResult
- type Breakpoint
- type BrokerDecision
- type CLIPasswordPrompter
- type CacheStats
- type Chain
- type ChangeTracker
- func (ct *ChangeTracker) Clear()
- func (ct *ChangeTracker) CollectFileChangesForCheckpoint() ([]CheckpointFileChange, string)
- func (ct *ChangeTracker) Commit(llmResponse string, conversation []api.Message) error
- func (ct *ChangeTracker) Disable()
- func (ct *ChangeTracker) Enable()
- func (ct *ChangeTracker) GenerateAISummary() (string, error)
- func (ct *ChangeTracker) GetChangeCount() int
- func (ct *ChangeTracker) GetChanges() []TrackedFileChange
- func (ct *ChangeTracker) GetRevisionID() string
- func (ct *ChangeTracker) GetSummary() string
- func (ct *ChangeTracker) GetTrackedFiles() []string
- func (ct *ChangeTracker) IsEnabled() bool
- func (ct *ChangeTracker) MergeChild(changes []TrackedFileChange, source string)
- func (ct *ChangeTracker) PrimeShellTracking(workDir string)
- func (ct *ChangeTracker) RecordShellMutations(before, after map[string]*shellSnapshotEntry, toolCall string)
- func (ct *ChangeTracker) Reset(instructions string)
- func (ct *ChangeTracker) SyncShellCacheForPath(path string)
- func (ct *ChangeTracker) TrackFileEdit(filePath string, originalContent string, newContent string) error
- func (ct *ChangeTracker) TrackFileWrite(filePath string, newContent string) error
- func (ct *ChangeTracker) TrackShellTurn(workDir, toolCall string, destructive bool)
- type CheckpointFileChange
- type CheckpointStore
- type ChoiceOption
- type CircuitBreakerAction
- type CircuitBreakerState
- type CircuitBreakerStore
- type ClarificationManager
- func (m *ClarificationManager) Cleanup()
- func (m *ClarificationManager) Close()
- func (m *ClarificationManager) GetPendingClarifications(subagentID string) []ClarificationRequest
- func (m *ClarificationManager) RequestClarification(ctx context.Context, subagentID, question string) (string, error)
- func (m *ClarificationManager) RespondClarification(requestID, response string) error
- type ClarificationRequest
- type CommandHistoryStore
- type CommandKind
- type CompactPreview
- type ConfigOverrideStore
- type ContextBudgetStore
- type ContextFileInfo
- type ContinuationNudgeStore
- type ConversationOptimizer
- func (co *ConversationOptimizer) CompactConversation(messages []api.Message) []api.Message
- func (co *ConversationOptimizer) GetOptimizationStats() map[string]interface{}
- func (co *ConversationOptimizer) Inner() *core.ConversationOptimizer
- func (co *ConversationOptimizer) InvalidateFile(filePath string)
- func (co *ConversationOptimizer) IsEnabled() bool
- func (co *ConversationOptimizer) OptimizeConversation(messages []api.Message) []api.Message
- func (co *ConversationOptimizer) Reset()
- func (co *ConversationOptimizer) SetEnabled(enabled bool)
- func (co *ConversationOptimizer) SetLLMClient(client api.ClientInterface, provider string, printLine func(string))
- type ConversationPruner
- type ConversationPrunerStore
- type ConversationState
- func ImportStateFromJSONFile(filename string) (*ConversationState, error)
- func LoadSessionInfo(sessionID string) (*ConversationState, error)
- func LoadStateWithoutAgent(sessionID string) (*ConversationState, error)
- func LoadStateWithoutAgentScoped(sessionID, workingDir string) (*ConversationState, error)
- type ConversationTurn
- type CostEntry
- type CostTracker
- type DiffChange
- type DiffLine
- type DiffLineType
- type DriftDetector
- func (d *DriftDetector) CheckDrift(sessionIntent []float32, currentEmbedding []float32) (isDrift bool, similarity float64)
- func (d *DriftDetector) DriftCount() int
- func (d *DriftDetector) IsSuppressed() bool
- func (d *DriftDetector) RecordAcceptance()
- func (d *DriftDetector) RecordDrift()
- func (d *DriftDetector) RecordRejection()
- func (d *DriftDetector) RejectionCount() int
- func (d *DriftDetector) ShouldCheck(turnNumber int) bool
- type DriftNotification
- type DropdownItem
- type DropdownOptions
- type EditDecision
- type EditProposal
- type EstimatedTokenStore
- type FalseStopStore
- type FileAccessDecision
- type FileChange
- type FleetUsdBudget
- type Hunk
- type IterationStore
- type LLMCallTracker
- type LogContext
- type LogEntry
- type MCPSubManager
- type MemoryGate
- type MemoryGateError
- type MemoryInfo
- type MessageAnnotation
- type MessageImportance
- type MessageSource
- type MessageStore
- type MockLLMProvider
- func (m *MockLLMProvider) CheckConnection() error
- func (m *MockLLMProvider) GetAverageTPS() float64
- func (m *MockLLMProvider) GetLastTPS() float64
- func (m *MockLLMProvider) GetModel() string
- func (m *MockLLMProvider) GetModelContextLimit() (int, error)
- func (m *MockLLMProvider) GetProvider() string
- func (m *MockLLMProvider) GetTPSStats() map[string]float64
- func (m *MockLLMProvider) GetVisionModel() string
- func (m *MockLLMProvider) ListModels(ctx context.Context) ([]api.ModelInfo, error)
- func (m *MockLLMProvider) ResetTPSStats()
- func (m *MockLLMProvider) SendChatRequest(ctx context.Context, messages []api.Message, tools []api.Tool, ...) (*api.ChatResponse, error)
- func (m *MockLLMProvider) SendChatRequestStream(ctx context.Context, messages []api.Message, tools []api.Tool, ...) (*api.ChatResponse, error)
- func (m *MockLLMProvider) SendVisionRequest(ctx context.Context, messages []api.Message, tools []api.Tool, ...) (*api.ChatResponse, error)
- func (m *MockLLMProvider) SetDebug(debug bool)
- func (m *MockLLMProvider) SetModel(model string) error
- func (m *MockLLMProvider) SupportsConversationalVision() bool
- func (m *MockLLMProvider) SupportsVision() bool
- func (m *MockLLMProvider) VisionCapabilities() api.VisionCapabilities
- type ModelItem
- type Notification
- type NotificationKind
- type OOMProbeResult
- type OOMWatchdog
- type OptimizerStore
- type OrderedMap
- func (om *OrderedMap) Delete(key string)
- func (om *OrderedMap) Get(key string) (interface{}, bool)
- func (om *OrderedMap) InOrder() []orderedmap.Pair[string, interface{}]
- func (om *OrderedMap) Keys() []string
- func (om *OrderedMap) Len() int
- func (om *OrderedMap) Set(key string, value interface{})
- func (om *OrderedMap) String() string
- func (om *OrderedMap) ToMap() map[string]interface{}
- type OutputBuffer
- type OutputManager
- type OutputMode
- type OutputRouter
- func (r *OutputRouter) FlushExternalWrite()
- func (r *OutputRouter) Mode() OutputMode
- func (r *OutputRouter) RouteAgentMessage(category, message string, extra map[string]interface{})
- func (r *OutputRouter) RouteStreamChunk(chunk string, contentType string)
- func (r *OutputRouter) RouteTerminalOnly(message string)
- func (r *OutputRouter) RouteToolCompletion(ok bool, duration time.Duration, errMsg string)
- func (r *OutputRouter) RouteToolLog(action string, target string)
- func (r *OutputRouter) SetEventBus(eventBus *events.EventBus)
- func (r *OutputRouter) SetExternalWriteHook(fn func())
- func (r *OutputRouter) SetReasoningCallback(fn func(string))
- func (r *OutputRouter) SetReasoningTerminalEnabled(enabled bool)
- func (r *OutputRouter) SetTerminalSubscriberActive(active bool)
- func (r *OutputRouter) TerminalSubscriberActive() bool
- func (r *OutputRouter) Write(p []byte) (int, error)
- type PathTier
- type PauseState
- type PauseStore
- type PendingStateStore
- type PersonaStore
- type ProactiveContextConfig
- type ProactiveContextResult
- type ProgressEntry
- type ProjectInfo
- type PromptTokensDetails
- type ProviderErrorInfo
- type ProviderErrorStore
- type PruningStrategy
- type QueryGuardOwner
- type QuickOption
- type RateLimitExceededError
- type RecallMetricsRecord
- type RecalledItem
- type ReconciliationActionResult
- type ReconciliationActionType
- type RecoveryReport
- type RepairReport
- type RetryAction
- type RewindOptions
- type RewindResult
- type RiskAssessment
- type RiskSource
- type ScriptedClient
- func (c *ScriptedClient) AddResponse(response *ScriptedResponse)
- func (c *ScriptedClient) AdvanceIndex()
- func (c *ScriptedClient) Cancel()
- func (c *ScriptedClient) CheckConnection() error
- func (c *ScriptedClient) ClearHistory()
- func (c *ScriptedClient) ClearSentRequests()
- func (c *ScriptedClient) Close()
- func (c *ScriptedClient) GetAverageTPS() float64
- func (c *ScriptedClient) GetIndex() int
- func (c *ScriptedClient) GetLastTPS() float64
- func (c *ScriptedClient) GetModel() string
- func (c *ScriptedClient) GetModelContextLimit() (int, error)
- func (c *ScriptedClient) GetNextResponse() *ScriptedResponse
- func (c *ScriptedClient) GetProvider() string
- func (c *ScriptedClient) GetSentRequest(index int) []api.Message
- func (c *ScriptedClient) GetSentRequests() [][]api.Message
- func (c *ScriptedClient) GetTPSStats() map[string]float64
- func (c *ScriptedClient) GetVisionModel() string
- func (c *ScriptedClient) LastResponse() *ScriptedResponse
- func (c *ScriptedClient) Length() int
- func (c *ScriptedClient) ListModels(ctx context.Context) ([]api.ModelInfo, error)
- func (c *ScriptedClient) Reset()
- func (c *ScriptedClient) ResetTPSStats()
- func (c *ScriptedClient) ResponseHistory() []*ScriptedResponse
- func (c *ScriptedClient) SendChatRequest(ctx context.Context, messages []api.Message, tools []api.Tool, ...) (*api.ChatResponse, error)
- func (c *ScriptedClient) SendChatRequestStream(ctx context.Context, messages []api.Message, tools []api.Tool, ...) (*api.ChatResponse, error)
- func (c *ScriptedClient) SendVisionRequest(ctx context.Context, messages []api.Message, tools []api.Tool, ...) (*api.ChatResponse, error)
- func (c *ScriptedClient) SetDebug(debug bool)
- func (c *ScriptedClient) SetIndex(idx int)
- func (c *ScriptedClient) SetModel(model string) error
- func (c *ScriptedClient) SetResponses(responses []*ScriptedResponse)
- func (c *ScriptedClient) SupportsConversationalVision() bool
- func (c *ScriptedClient) SupportsVision() bool
- type ScriptedResponse
- func NewErrorResponse(err error) *ScriptedResponse
- func NewKeepGoingResponse(content string) *ScriptedResponse
- func NewLengthResponse(content string) *ScriptedResponse
- func NewRateLimitResponse() *ScriptedResponse
- func NewStopResponse(content string) *ScriptedResponse
- func NewTimeoutResponse() *ScriptedResponse
- func NewToolCallResponse(name, args string, toolCalls ...api.ToolCall) *ScriptedResponse
- type ScriptedResponseBuilder
- func (b *ScriptedResponseBuilder) Build() *ScriptedResponse
- func (b *ScriptedResponseBuilder) Content(content string) *ScriptedResponseBuilder
- func (b *ScriptedResponseBuilder) Delay(d time.Duration) *ScriptedResponseBuilder
- func (b *ScriptedResponseBuilder) Error(err error) *ScriptedResponseBuilder
- func (b *ScriptedResponseBuilder) FinishReason(reason string) *ScriptedResponseBuilder
- func (b *ScriptedResponseBuilder) Images(images []api.ImageData) *ScriptedResponseBuilder
- func (b *ScriptedResponseBuilder) RateLimitAfter(n int) *ScriptedResponseBuilder
- func (b *ScriptedResponseBuilder) ReasoningContent(content string) *ScriptedResponseBuilder
- func (b *ScriptedResponseBuilder) StreamConfig(sc *StreamConfig) *ScriptedResponseBuilder
- func (b *ScriptedResponseBuilder) ToolCall(tc api.ToolCall) *ScriptedResponseBuilder
- func (b *ScriptedResponseBuilder) ToolCalls(tcs []api.ToolCall) *ScriptedResponseBuilder
- func (b *ScriptedResponseBuilder) Usage(promptTokens, completionTokens, totalTokens int, estimatedCost float64) *ScriptedResponseBuilder
- func (b *ScriptedResponseBuilder) VisionOnly() *ScriptedResponseBuilder
- type ScriptedTokenUsage
- type SecurityAnalysis
- func AnalyzeChain(ctx context.Context, agent *Agent, chain Chain, ...) (*SecurityAnalysis, error)
- func AnalyzeChainFallback(ctx context.Context, agent *Agent, chain Chain, ...) (*SecurityAnalysis, error)
- func AnalyzeShellCommand(ctx context.Context, agent *Agent, command, cwd string) (*SecurityAnalysis, error)
- type SecurityAnalysisCache
- type SecurityManager
- type SessionConfigStore
- type SessionInfo
- type SessionIntentStore
- type SessionItem
- type SessionManager
- type SessionStore
- type SettingDetail
- type SharedState
- type ShellCommandResult
- type ShellPart
- type ShellProposal
- type SimpleUI
- type SkillInfo
- type StateManager
- type StreamConfig
- type SubagentError
- type SubagentMetrics
- type SubagentOptions
- type SubagentProgressEntry
- type SubagentResult
- type SubagentReturn
- type SubagentRunMetrics
- type SubagentRunner
- func (r *SubagentRunner) CancelAll()
- func (r *SubagentRunner) CancelSubagent(id string) bool
- func (r *SubagentRunner) GetActiveSubagents() []*runningSubagent
- func (r *SubagentRunner) InjectInputIntoActive(input string) (string, bool)
- func (r *SubagentRunner) Metrics() SubagentMetrics
- func (r *SubagentRunner) Run(ctx context.Context, prompt string, opts SubagentOptions) *SubagentResult
- func (r *SubagentRunner) RunParallel(ctx context.Context, tasks []SubagentTask, opts SubagentOptions) []*SubagentResult
- type SubagentStatus
- type SubagentTask
- type SummaryStore
- type SyncOp
- type SyncOpResult
- type TaskAction
- type TaskActionStore
- type TerminationStore
- type Theme
- type ThemeManager
- type TokenCounter
- type TokenUsage
- type ToolCallTracker
- type ToolGuidanceStore
- type TraceStore
- type TrackedBulkItem
- type TrackedFileChange
- type TranscriptDiff
- type TranscriptDiffEntry
- type TranscriptFileChange
- type TranscriptSnapshot
- type TurnCheckpoint
- type TurnEvaluation
- type TurnJournal
- type TurnJournalEvent
- type TurnJournalTokens
- type UI
- type WebUIPasswordPrompter
- type WorkflowBudgetConfig
- type WorkflowLoopConfig
- type WorkflowProgressConfig
- type WorkflowResult
- type WorkspaceFileMetadata
Constants ¶
const ( QuerySourceCLI = "cli" QuerySourceWebUI = "webui" QuerySourceAutoResume = "auto-resume" QuerySourceUnknown = "unknown" )
Query source constants used for QueryGuardOwner.Source.
const ( PruneStrategyNone = core.PruneStrategyNone PruneStrategySlidingWindow = core.PruneStrategySlidingWindow PruneStrategyImportance = core.PruneStrategyImportance PruneStrategyHybrid = core.PruneStrategyHybrid PruneStrategyAdaptive = core.PruneStrategyAdaptive )
Pruning strategy constants — re-exported from seed for backward compatibility with sprout call sites that reference them unqualified.
const ( BillingPayPerToken = providers.BillingPayPerToken BillingSubscription = providers.BillingSubscription BillingFree = providers.BillingFree )
Billing type constants (re-exported for convenience within the agent package).
const ( DefaultMinMemoryBytes = 8 * 1024 * 1024 * 1024 // 8 GB DefaultRetryMinBytes = 16 * 1024 * 1024 * 1024 // 16 GB DefaultRetrySleep = 30 * time.Second DefaultMaxRetries = 5 )
Default thresholds.
const ( RunTerminationCompleted = "completed" RunTerminationMaxIterations = "max_iterations" RunTerminationInterrupted = "interrupted" RunTerminationFleetBudgetExceeded = "fleet_budget_exceeded" )
const ( MAX_SUBAGENT_OUTPUT_SIZE = 10 * 1024 * 1024 // 10MB MAX_SUBAGENT_CONTEXT_SIZE = 1024 * 1024 // 1MB // Lines to batch before publishing a subagent "output" event. Kept small // so output streams to the WebUI in near-real-time — subagent output is // line-level (LLM-paced), not char-level, so this won't flood the event // bus, while still coalescing bursty tool dumps. (Was 50, which made most // subagent runs show nothing until they finished.) BATCH_SIZE = 8 DefaultSubagentTokenBudget = 2_000_000 // Default token budget for subagents )
const CompactedFilesHeader = "Files modified during compacted segment:"
CompactedFilesHeader marks the file-change manifest block that `/compact` appends to its LLM-generated summary. Future compactions re-parse this block to keep the running file-change history visible across the summary boundary — without this, every `/compact` would lose the manifest of files touched in the summarized turns.
const DefaultClarificationTimeout = 60 * time.Second
DefaultClarificationTimeout is the default timeout for clarification requests.
const DefaultDriftCheckInterval = 5
DefaultDriftCheckInterval is the default number of turns between drift checks.
const DefaultDriftThreshold = 0.60
DefaultDriftThreshold is the default cosine similarity threshold below which a conversation is considered to have drifted from its original intent.
const MaxChainSubcommandsForBatchPrompt = 10
MaxChainSubcommandsForBatchPrompt caps chain length for the batch prompt; longer chains fall back to per-subcommand analysis.
const MaxDriftRejections = 3
MaxDriftRejections is the number of CONSECUTIVE rejections after which drift detection is suppressed for the remainder of the session.
const RedactedContentMarker = history.RedactedContentMarker
RedactedContentMarker aliases history.RedactedContentMarker so existing call sites within this package keep working.
const SkillFileName = skills.SkillFileName
SkillFileName is the conventional name of the markdown file inside each skill directory. Re-exported from pkg/skills so callers in this package don't need to learn two import paths for the same constant.
const TranscriptSnapshotFormat = "sprout-transcript/v1"
TranscriptSnapshotFormat identifies snapshot file shape. Bump when breaking shape changes land so older readers don't silently misparse.
Variables ¶
var ( ErrUINotAvailable = errors.New("UI not available") ErrCancelled = errors.New("user cancelled") )
UI errors
var ( ErrWriteStale = errors.New("write refused: file may be stale") ErrWriteHasUnsyncedEdits = errors.New("write refused: user has unsynced edits to this file") )
Sentinel errors for write-staleness and conflict detection. Both are wrappable via errors.Is for caller distinction.
var ErrModelNotAvailable = errors.New("configured model is not available for this provider")
ErrModelNotAvailable is returned when the configured model for the current provider is not available. In daemon mode, this allows the web UI to detect the issue and present a model selection UI rather than hard-failing.
var ErrProviderNotConfigured = errors.New("provider is not configured — configure via webui settings")
ErrProviderNotConfigured is returned when the provider cannot be initialized (unrecognized provider, missing API key, etc.) in daemon mode. This allows the web UI to start without an agent and present a provider configuration UI instead of crashing the daemon.
var ErrQueryInProgress = errors.New("a query is already in progress on this agent")
ErrQueryInProgress is returned when ProcessQuery is called while another query is already running on the same Agent instance. This happens when two frontends (CLI REPL and WebUI) share the same Agent — only one query can execute at a time to prevent message-list and state corruption.
var FleetBudgetExceededError = errors.New("fleet token budget exceeded")
FleetBudgetExceededError is returned by the seed provider when the shared fleet token budget has been exceeded mid-conversation. It is caught by processQueryWithSeed to truncate gracefully rather than surfacing as a generic API error.
var MILESTONE_PHASES = []string{"spawn", "complete", "step"}
MILESTONE_PHASES defines phases that trigger immediate publish without batching
var PruningConfig = struct { Default struct { StandardPercent float64 MinMessages int RecentMessages int SlidingWindow int } Structural struct { RecentMessagesToKeep int MinMessagesToCompact int MinMiddleMessages int } AgenticRequiredAvailableTokens int }{ Default: struct { StandardPercent float64 MinMessages int RecentMessages int SlidingWindow int }{ StandardPercent: 0.87, MinMessages: 5, RecentMessages: 24, SlidingWindow: 30, }, Structural: struct { RecentMessagesToKeep int MinMessagesToCompact int MinMiddleMessages int }{ RecentMessagesToKeep: core.StructuralRecentToKeep, MinMessagesToCompact: core.StructuralMinMessagesToCompact, MinMiddleMessages: core.StructuralMinMiddleMessages, }, AgenticRequiredAvailableTokens: 12000, }
PruningConfig preserves the historical "single source of truth" symbol some sprout tests reference. Values come from seed's defaults so any drift between sprout and seed is impossible by construction.
New code should not read from this — query the pruner instance directly or use seed's exported constants. Retained as a thin shim only.
var UseMockLLM bool
UseMockLLM, when true, causes agent creation to return a MockLLMProvider instead of the real provider.
Functions ¶
func ApplyHunks ¶ added in v0.16.12
ApplyHunks reconstructs file content by applying only the accepted hunks.
func AssertNoStateLeak ¶ added in v0.16.6
AssertNoStateLeak is the TestMain counterpart of the Layer-5 check in NewTestStateDir(t). Compares the current file set under realDir against the snapshot from SnapshotRealStateDir; if any new file appeared, it writes a noisy stderr warning AND returns a non-zero suggested exit code so TestMain can fail the run.
Why warning + exit-code instead of t.Errorf: TestMain has no *testing.T to attach an error to. We could panic, but tests that raced through to completion would already be marked PASS by `go test`; a panic in TestMain then prints a misleading "test passed but cleanup failed" message. Returning a code lets the caller `os.Exit(testCode | leakCode)` so CI fails on real leaks while preserving the underlying test-failure signal.
Returns 0 when nothing leaked, 1 when something did.
Detection model: only flag files whose mtime is *newer than the snapshot start time*. Pre-existing files in the developer's real state dir (e.g. sessions from prior CLI runs) have mtimes from before TestMain started; if their content is re-read in-place the read access doesn't update mtime, so they don't trigger a false positive. Only files that were created or rewritten during this test run are reported.
func BuildScopedSessionPathForTesting ¶
BuildScopedSessionPathForTesting constructs the scoped session file path for test setup.
func BuildToolDefinitions ¶ added in v0.16.4
BuildToolDefinitions converts all handler-based tool definitions into the []api.Tool shape the LLM, persona allowlist, and MCP-merge code paths expect.
mcp_tools is added as a synthetic entry because it is a meta-tool handled outside the registry (see pkg/agent/mcp.go::handleMCPToolsCommand and pkg/agent/tools.go's mcp_tools dispatch). Removing it would hide MCP discovery from the model.
func BuildToolDefinitionsForAgent ¶ added in v0.17.17
BuildToolDefinitionsForAgent is BuildToolDefinitions filtered to the tools the given agent can actually execute. Tools marked RequiresEmbeddings are dropped when the agent has no embedding manager (the default — embeddings are OPT-IN), keeping this roster in sync with the seed registry filter in seed_tool_registry.go so the model is never offered a tool that would fail at call time.
func ChainCacheKey ¶ added in v0.17.7
ChainCacheKey returns the cache key for storing/retrieving analyses of a shell chain. The key is normalized so that equivalent chains (modulo whitespace and outer trimming) collide, but distinct operators keep distinct keys.
func CleanupPasswordRequestForTest ¶ added in v0.16.18
func CleanupPasswordRequestForTest(requestID string)
CleanupPasswordRequestForTest removes a password request from the broker.
func ContextWithSproutDir ¶ added in v0.16.25
ContextWithSproutDir returns a context that carries the sprout directory.
func DecrementActiveSubagents ¶
func DecrementActiveSubagents()
DecrementActiveSubagents lowers the active-subagent counter when a subagent finishes (success, error, cancel — any terminal state).
func DeleteMemory ¶
DeleteMemory deletes a memory file by name (with .md extension)
func DeleteMemoryEmbedding ¶
func DeleteMemoryEmbedding(mgr *embedding.EmbeddingManager, name string) error
DeleteMemoryEmbedding removes a memory's embedding from the ConversationStore. This is called after DeleteMemory() to keep the vector index in sync.
Graceful failure: Errors are logged but not returned as fatal. Memory files are always deleted from disk regardless of embedding cleanup.
func DeleteSession ¶
DeleteSession removes a session state file
func DeleteSessionScoped ¶
func DeliverEditDecision ¶ added in v0.17.18
func DeliverEditDecision(requestID string, decision EditDecision) bool
DeliverEditDecision delivers a user decision to a pending edit approval request without requiring an Agent instance. This is used by the WASM JS bridge so the webui can resolve edit approval requests in cloud mode.
func DeliverShellDecision ¶ added in v0.17.18
DeliverShellDecision delivers a per-part approval decision to a pending shell approval request without requiring an Agent instance. This is used by the WASM JS bridge so the webui can resolve shell approval requests in cloud mode. Mirrors DeliverEditDecision (edit_approval.go).
func DetectLanguages ¶
func EmbedAndStoreTurn ¶
func EmbedAndStoreTurn(ctx context.Context, mgr *embedding.EmbeddingManager, turn *ConversationTurn, checkpointID string) error
EmbedAndStoreTurn computes embeddings for a conversation turn's prompt and actionable summary using the static embedding provider, then stores the result as a VectorRecord in the ConversationStore.
The checkpointID is stamped into the record's metadata so that collectCheckpointVectors can look it up during rollup boundary detection. Pass "" when no checkpoint ID is available (e.g. in tests).
Graceful failure: Errors are logged but not returned. The caller (checkpoint recording) should always succeed regardless of embedding failures.
func EmbedMemory ¶
func EmbedMemory(ctx context.Context, mgr *embedding.EmbeddingManager, name string, content string) error
EmbedMemory embeds a memory file's content and stores it in the ConversationStore as a VectorRecord with Type "memory". This is called after SaveMemory() to keep the vector index in sync.
Graceful failure: Errors are logged but not returned as fatal. Memory files are always saved to disk regardless of embedding success.
func EstimateTokens ¶
EstimateTokens provides a token estimation based on OpenAI's tiktoken approach. Delegates to the centralized implementation in agent_api for consistency across all providers.
func EvaluateCommandPolicy ¶ added in v0.17.5
func EvaluateCommandPolicy( command string, policies *configuration.CommandPolicies, ) (configuration.CommandPolicyAction, string, bool)
EvaluateCommandPolicy checks user-defined command policies against a shell command. Returns the matched action, the matched pattern, and whether a match was found.
Algorithm:
- Split the command on &&, ||, ;, | (quote-aware) using SplitChainedCommand.
- For each subcommand, check rules in order (first-match-wins).
- Pattern matching uses Go path.Match (glob), case-insensitive.
- Return the highest-severity action across all subcommands: deny > ask > allow.
- If no subcommand matched any rule, return ("", "", false).
func ExecuteTool ¶ added in v0.16.19
func ExecuteTool(ctx context.Context, toolName string, args map[string]interface{}, agent *Agent, rawArgsJSON string) ([]api.ImageData, string, error)
ExecuteTool executes a tool with standardized parameter validation and error handling
func ExportStateToJSON ¶
func ExportStateToJSON(state *ConversationState) ([]byte, error)
ExportStateToJSON converts a ConversationState to JSON bytes
func FormatCLIMessage ¶
FormatCLIMessage returns a human-readable drift notification for CLI display.
func FormatFileChangesForSummary ¶ added in v0.16.4
func FormatFileChangesForSummary(changes []TranscriptFileChange) string
FormatFileChangesForSummary renders a manifest into the canonical text block appended to a /compact summary. The format is chosen so parseCompactedFilesBlock can round-trip it back to TranscriptFileChange entries, preserving source / tool attribution across compaction boundaries. Returns the empty string when the manifest is empty so callers can skip appending altogether.
func FormatProactiveContext ¶
func FormatProactiveContext(results []ProactiveContextResult, config ProactiveContextConfig, now time.Time) string
FormatProactiveContext formats retrieved results as a "Previous Work" section for injection into the agent's system prompt. Returns "" when results is empty. Output is capped at config.MaxContextChars characters. Pass now=Zero to use current time.
func FormatSemanticRecall ¶ added in v0.16.4
func FormatSemanticRecall(items []RecalledItem, maxChars int) string
FormatSemanticRecall renders the recall items as a markdown block to inject into the system supplement. Returns "" when there's nothing to inject so the caller can short-circuit.
maxChars caps the total output size. Use semanticRecallMaxInjectedChars (8000) for the default ceiling, or a model-aware value for per-model tuning.
func FormatWakeupBatch ¶ added in v0.16.19
func FormatWakeupBatch(notifications []Notification) string
func GenerateUnifiedDiff ¶ added in v0.16.12
GenerateUnifiedDiff produces a standard unified-diff string from original and proposed content.
func GetActiveSubagents ¶
func GetActiveSubagents() int
GetActiveSubagents returns the current number of running subagents.
func GetEmbeddedPlanningPrompt ¶
GetEmbeddedPlanningPrompt returns the embedded planning prompt
func GetEmbeddedRollupPrompt ¶ added in v0.16.4
func GetEmbeddedRollupPrompt() string
GetEmbeddedRollupPrompt returns the rollup summarizer prompt.
func GetEmbeddedSystemPrompt ¶
GetEmbeddedSystemPrompt returns the embedded system prompt
func GetEmbeddedSystemPromptForProfile ¶ added in v0.17.7
func GetEmbeddedSystemPromptForProfile(profile configuration.ContextProfile, provider string, contextWindow int, workspaceRoot string) (string, error)
GetEmbeddedSystemPromptForProfile selects the full or lite system prompt based on the ContextProfile.
func GetEmbeddedSystemPromptWithProvider ¶
GetEmbeddedSystemPromptWithProvider returns the embedded system prompt
func GetSessionName ¶
GetSessionName returns the name of a session
func GetSessionNameScoped ¶
func GetSessionPreview ¶
GetSessionPreview returns the first 50 characters of the first user message
func GetSessionPreviewScoped ¶
func GetSettingValue ¶ added in v0.16.19
func GetSettingValue(cfg *configuration.Config, key string) (string, error)
GetSettingValue returns the string representation of a config setting by key. It's an exported wrapper around getConfigValue for use by other packages.
func GetStateDir ¶
GetStateDir returns the directory for storing conversation state
func IncrementActiveSubagents ¶
func IncrementActiveSubagents()
IncrementActiveSubagents bumps the active-subagent counter; paired with DecrementActiveSubagents under a defer in the spawner.
func InjectUserMessageTimestamp ¶ added in v0.17.7
InjectUserMessageTimestamp prepends a <current-time>...</current-time> tag to the user message so the model sees the exact moment of each turn without invalidating the prompt-prefix cache. The system prompt stays static across requests (date/time injection there would defeat provider caching and cost users real money on every turn); the timestamp is added only at the provider boundary, where Anthropic and OpenAI do not cache the user-message suffix. ISO 8601 with timezone offset is machine-parseable; the Local parenthetical matches what the user sees in their OS clock so the model can reason about time-of-day naturally.
Empty or whitespace-only input is returned unchanged so wakeup-only turns (background-task notifications with no user message) don't produce a bare timestamp that the model would have to interpret.
func InjectUserMessageTimestampAt ¶ added in v0.17.7
InjectUserMessageTimestampAt prepends a timestamp fixed at at. Providers use it to keep one turn's prompt byte-identical across iterations and retries.
func InstrumentedRecall ¶ added in v0.16.19
InstrumentedRecall wraps an InjectSemanticRecall invocation with per-turn telemetry. Calls a.Recall() once to capture metrics, then passes the items to InjectSemanticRecallWithItems.
func IsInteractiveTool ¶
IsInteractiveTool reports whether the named tool is registered with Interactive=true in the handler registry. Unknown tools return false. Use this from CLI subscribers (e.g. the activity-indicator goroutine) to decide whether to suppress transient chrome that would clobber the tool's own prompt.
func IsMemoryIntensiveCommand ¶ added in v0.16.19
IsMemoryIntensiveCommand returns true when a shell command is likely to spawn multiple processes or workers that consume significant memory. Test runners, bundlers, and compilers are the primary targets.
func ListChangesEmpty ¶ added in v0.16.18
func ListChangesEmpty() string
ListChangesEmpty returns the disabled-tracker response: an empty manifest.
func ListChangesPersistedOnly ¶ added in v0.16.18
ListChangesPersistedOnly returns a session manifest from the persisted history store.
func ListSessions ¶
ListSessions returns all available session IDs
func ListTranscriptSnapshots ¶ added in v0.16.4
ListTranscriptSnapshots returns snapshot file paths for the given session within the current workspace scope, sorted oldest-first.
func LoadContextFiles ¶
LoadContextFiles loads and formats context files for inclusion in system prompt
func LoadMemoriesForPrompt ¶
func LoadMemoriesForPrompt() string
LoadMemoriesForPrompt loads all memories and formats them for inclusion in the system prompt Returns empty string if no memories exist
func LoadMemoryContent ¶
LoadMemoryContent reads a single memory file by name The name should be without the .md extension (e.g., "git-safety" reads git-safety.md)
func LoadStateRecoverable ¶ added in v0.17.17
func LoadStateRecoverable(sessionID, workingDir string) (*ConversationState, RecoveryReport, error)
LoadStateRecoverable loads a session and, when a turn journal survives, replays it onto the base state. A partial final journal line (crash mid-append) is tolerated and ignored.
func MigrateMemories ¶
func MigrateMemories(ctx context.Context, mgr *embedding.EmbeddingManager)
MigrateMemories performs a one-time migration of all existing memory files to the ConversationStore. It uses sync.Once to ensure it only runs once per process lifetime, even if called multiple times.
Migration skips files that are already embedded (by checking if a record with ID "memory:<name>" exists in the store).
The manager's closeChan is also selected alongside ctx.Done() so a DisableEmbeddingIndex call that arrives mid-migration aborts the loop promptly instead of continuing to call provider.Embed / store.Store on a torn-down manager.
func NewCascadingPasswordPrompter ¶ added in v0.17.7
func NewCascadingPasswordPrompter(prompters ...tools.PasswordPrompter) *cascadingPasswordPrompter
NewCascadingPasswordPrompter returns a prompter that tries each candidate in order, stopping on the first non-ErrNoInteractiveSurface result. Pass at least one prompter; the result is undefined for none.
Exported because cmd/agent_modes.go composes the mux after agent_creation.go has already registered the CLI prompter — both packages need to reference this constructor.
func NewConversationPruner ¶
func NewConversationPruner(debug bool) *core.ConversationPruner
NewConversationPruner constructs a pruner with sprout's traditional defaults: adaptive strategy with seed-default thresholds. The debug flag is retained for caller compatibility but unused — seed routes observability through the EventPublisher instead of stderr prints.
func NewSeedToolRegistry ¶
func NewSeedToolRegistry(agent *Agent) *core.ToolRegistry
NewSeedToolRegistry creates a seed core.ToolRegistry with all sprout tools registered.
func NewSproutProvider ¶
NewSproutProvider creates a Provider that wraps a sprout ClientInterface.
func NewTestStateDir ¶ added in v0.16.6
NewTestStateDir redirects pkg/agent's session-persistence path AND the global search-index updater to an isolated t.TempDir so that tests creating real Agents don't leak state JSONs or search-index.json into the caller's ~/.sprout/sessions/.
The search-index redirect is load-bearing: SaveStateScoped triggers search.MarkSessionDirty, which schedules a debounced BuildIndex. Without isolation that BuildIndex walks the entire real sessions corpus (~250 MB including 93 MB session JSONs), building an HNSW index with 30+ GB peak allocation.
Backstory: tests in cmd/ build real Agent instances to exercise the chat/plan loop. Each Agent runs autoSaveState() on a timer, which writes to whatever GetStateDir() returns. Without this helper that's the developer's real ~/.sprout/sessions/, and ~90 mock-provider session JSONs accumulated there before we caught it on 2026-06-08. See the `cleanup` body below for the Layer-5 detector that fails any future test that bypasses this isolation.
Returns a cleanup func that:
- Restores the original getStateDirFunc (mirrors t.Setenv unwind semantics but for our package-level function var).
- Snapshots the real ~/.sprout/sessions/ contents at test start and re-checks at cleanup. Any new file under that tree fails the test with a clear pointer at this helper — the same pattern pkg/configuration/testing_isolation.go uses for the config file.
Usage:
func TestMyCmdThingy(t *testing.T) {
defer agent.NewTestStateDir(t)()
// ... build and use a real Agent without leaking state.
}
The helper lives in a non-_test.go file so it can be imported from cmd/ tests (Go forbids importing from _test.go across packages).
func NormalizeChain ¶ added in v0.17.7
NormalizeChain returns a normalized cache key for a chain. It walks chain.Original to recover operators and produces distinct keys for "a && b" and "a || b". Chains with identical subcommands and operators normalize to the same key regardless of internal whitespace.
func NormalizeYAMLOrdered ¶ added in v0.16.4
func NormalizeYAMLOrdered(v interface{}) interface{}
NormalizeYAMLOrdered recursively normalizes YAML-parsed values into *OrderedMap-safe representations. It handles the remaining cases where yaml.Unmarshal into interface{} produces map[interface{}]interface{} or map[string]interface{} values, converting them to *OrderedMap. This replaces the old normalizeYAMLValue function.
When key order is unknown (e.g., from a regular map), keys are sorted alphabetically as a deterministic fallback.
func ParseAgentsMd ¶
func ParseJSONOrderedAny ¶ added in v0.16.8
ParseJSONOrderedAny parses a JSON string, preserving key order in objects. Returns *OrderedMap for objects and []interface{} for arrays (with nested objects also wrapped in *OrderedMap).
func PublishModel ¶
func PublishModel(model string)
PublishModel publishes a model selection (placeholder implementation)
func RegisterComputerUseTools ¶ added in v0.16.18
func RegisterComputerUseTools(cfg *configuration.Config) error
RegisterComputerUseTools wires the computer_user persona's desktop-control tools into the agent's registries — but only when cfg explicitly enables them.
func RegisterPasswordRequestForTest ¶ added in v0.16.18
RegisterPasswordRequestForTest registers a password request in the broker for use by webui tests. Returns the response channel so the test can verify delivery. Call CleanupPasswordRequestForTest after the test.
func RemoveTurnJournal ¶ added in v0.17.17
func RenameSession ¶
RenameSession renames a session by updating the name field in the state file
func RenameSessionScoped ¶
func ResetMigrationForTesting ¶
func ResetMigrationForTesting()
ResetMigrationForTesting resets the one-time migration guard for testing purposes.
func SaveMemory ¶
SaveMemory writes a memory file Sanitizes the name: lowercase, replace spaces with hyphens, strip special chars Keeps only alphanumeric, hyphens, and underscores
func SerializeJSONOrdered ¶ added in v0.16.4
SerializeJSONOrdered serializes data to a pretty-printed JSON string with 2-space indentation. When data is an *OrderedMap, keys are emitted in insertion order. For regular map[string]interface{} and other types, the standard json.Marshal behavior is used as a fallback.
HTML escaping is disabled to match the behavior of the existing serializeStructuredContent function.
func SerializeYAMLOrdered ¶ added in v0.16.4
SerializeYAMLOrdered serializes data to a YAML string. When data is an *OrderedMap, keys are emitted in insertion order by constructing a yaml.Node tree. For regular map[string]interface{} and other types, the standard yaml.Marshal is used as a fallback.
A trailing newline is always included to match existing YAML behavior.
func SetActiveComputerUseAgent ¶ added in v0.16.19
func SetActiveComputerUseAgent(a *Agent)
SetActiveComputerUseAgent marks a as the agent currently driving computer_use actions. Called from agent creation / ApplyPersona when the computer_user persona activates. Cleared when the persona is deactivated or the agent is shut down.
func SetEditApprovalTimeout ¶ added in v0.16.17
SetEditApprovalTimeout overrides the default WebUI response timeout.
func SetGetStateDirForTest ¶
SetGetStateDirForTest is a convenience helper that sets getStateDirFunc to return a fixed directory for testing.
func SetGetStateDirForTestError ¶
SetGetStateDirForTestError is a convenience helper that sets getStateDirFunc to return an error for testing error handling.
func SetGetStateDirFunc ¶
SetGetStateDirFunc sets the getStateDirFunc for testing purposes. Returns the previous function so it can be restored after the test.
func SetPackageDebugLogging ¶
func SetPackageDebugLogging(enabled bool)
SetPackageDebugLogging toggles the debug gate at runtime. Useful for tests and for the agent's --debug flag wiring.
func SetPackageLogger ¶
func SetPackageLogger(l *AgentLogger)
SetPackageLogger sets the package-level AgentLogger that package-level functions (without an *Agent receiver) use for structured logging. Called during agent initialization so embedding, proactive context, etc. all route through the same logger with session context.
func SetSettingValue ¶ added in v0.16.19
func SetSettingValue(cfg *configuration.Config, key, value string) error
SetSettingValue updates a config setting by key and value string. It's an exported wrapper around setConfigValue for use by other packages.
func SetStateDirFuncForTesting ¶
SetStateDirFuncForTesting replaces the internal GetStateDir implementation for tests. It returns a restore function that will reset the original implementation when called. This function is safe for use in test code only.
Usage:
restore := agent.SetStateDirFuncForTesting(func() (string, error) {
return t.TempDir(), nil
})
defer restore()
func SetTestStateDirHook ¶ added in v0.16.6
func SetTestStateDirHook(dir string) func()
SetTestStateDirHook overrides the session state dir to the given path for the lifetime of the returned restore func. Lower-level primitive than NewTestStateDir(t) — useful from TestMain in test packages that don't yet have a *testing.T. Prefer NewTestStateDir inside individual tests; this is for package-wide isolation hooks.
Returns a restore func that puts getStateDirFunc back to its prior value. Idempotent — calling restore more than once is a no-op.
func SettingEnumValues ¶ added in v0.16.19
SettingEnumValues returns the enum values for a setting key, or nil if the setting is not an enum (freeform input). It is used by the interactive settings browser to offer a picker instead of raw text input.
func SettingIsListType ¶ added in v0.16.19
SettingIsListType returns true if the setting key is a list-type setting that should get an add/remove/set sub-menu in the interactive browser.
func SnapshotRealStateDir ¶ added in v0.16.6
SnapshotRealStateDir captures the current file set under the user's real ~/.sprout/sessions/ for later leak-detection. Use this from TestMain before installing SetTestStateDirHook; pair it with AssertNoStateLeak at the end of TestMain to fail loudly if any test bypassed the isolation hook and wrote to the real dir.
Returns ("", nil) when the real dir can't be resolved (e.g. no HOME env in CI) — the post-snapshot call then degrades to a no-op rather than fabricating a false negative.
func SproutDirFromContext ¶ added in v0.16.25
SproutDirFromContext returns the workspace-aware sprout directory from ctx, or falls back to os.Getwd() (matching the legacy behavior for CLI-triggered workflows where CWD is the workspace root).
func StripUserMessageTimestamp ¶ added in v0.17.7
StripUserMessageTimestamp removes a leading provider timestamp envelope from a user message. It accepts legacy LF and CRLF separators and leaves malformed tags or tags that do not start at offset zero unchanged.
The matching uses the first <current-time>...</current-time> envelope in the input. Because the envelope is a small fixed shape and our injector (InjectUserMessageTimestamp) only emits well-formed envelopes whose body (the RFC3339 / formatted time / zone name) never contains "</current-time>" or "\n\n" between the tags, a substring scan is sufficient. A leading tag whose body is empty returns "". Tag detection is anchored at offset 0, so anything with leading whitespace before the tag is left intact.
func SummarizeMySessionEmpty ¶ added in v0.16.18
func SummarizeMySessionEmpty() string
SummarizeMySessionEmpty returns the disabled-tracker block-summary response.
func SupportedSettingKeys ¶ added in v0.16.19
func SupportedSettingKeys() []string
SupportedSettingKeys returns a sorted slice of all supported setting keys.
func SweepExpiredEntries ¶
SweepExpiredEntries removes persistent context entries older than retentionDays. No-op if retentionDays <= 0. Returns the number of entries removed.
func TestShellApprovalCleanup ¶ added in v0.17.10
func TestShellApprovalCleanup(requestID string)
TestShellApprovalCleanup removes a pending entry from the broker. Used by tests to clean up after themselves so the global broker doesn't accumulate stale entries across tests.
func TestShellApprovalRegister ¶ added in v0.17.10
TestShellApprovalRegister creates a buffered response channel for the given request ID in the shellApprovalBroker and returns it.
For testing only — called from webui tests to simulate the agent side registering a pending request before the handler POSTs back.
func TestShellApprovalRespond ¶ added in v0.17.10
TestShellApprovalRespond delivers decisions to a pending request. Returns true if the request was found and the decisions were delivered.
For testing only — called from webui tests to simulate the agent RespondToShellApproval without needing an agent instance.
func ValidateStreamConfig ¶
func ValidateStreamConfig(sc *StreamConfig) error
ValidateStreamConfig validates a StreamConfig and returns an error if invalid
func WorkflowRequiresApproval ¶ added in v0.16.4
WorkflowRequiresApproval reports whether the named workflow needs user confirmation before launching. This wraps WorkflowRequiresApprovalIn with the CWD-based automate.Dir() so the CLI tool path works correctly.
func WorkflowRequiresApprovalIn ¶ added in v0.16.25
WorkflowRequiresApprovalIn reports whether the named workflow needs user confirmation before launching, using the specified directory instead of the CWD-based automate.Dir().
FAIL-SAFE: any error resolving or parsing the workflow returns true so a missing file or malformed JSON can't be used to slip past the prompt.
func WriteTestSessionFile ¶
func WriteTestSessionFile(stateDir, sessionID, workingDir string, state *ConversationState) error
WriteTestSessionFile creates a scoped session file for testing.
Types ¶
type Agent ¶
type Agent struct {
// contains filtered or unexported fields
}
func NewAgentWithClient ¶
func NewAgentWithClient(client api.ClientInterface, clientType api.ClientType, configManager *configuration.Manager) (*Agent, error)
NewAgentWithClient builds an agent around a pre-constructed provider client. Skips the interactive provider-resolution path — useful for WASM/SDK callers where the caller already knows which provider and model to use. The configManager must already be initialized. The returned agent is a production agent.
func NewAgentWithConfigDir ¶
NewAgentWithConfigDir creates a new agent using a per-client config directory for WebUI isolation.
func NewAgentWithLayers ¶
NewAgentWithLayers creates a new agent using layered configuration (global + workspace).
func NewAgentWithLayersInWorkspace ¶ added in v0.16.25
func NewAgentWithLayersInWorkspace(globalDir, workspaceDir, workspaceRoot, model string) (*Agent, error)
NewAgentWithLayersInWorkspace creates a new agent using layered configuration with an explicit workspace root.
func NewAgentWithModel ¶
NewAgentWithModel creates a new agent with optional model override
func NewTestAgent ¶
func NewTestAgent() *Agent
NewTestAgent creates a minimal Agent suitable for unit tests.
Tests that create bare &Agent{} structs must remember to call initSubManagers() to avoid nil-pointer panics. NewTestAgent() eliminates that two-step dance by returning an Agent whose sub-managers (state, output, security, mcpSub) and basic fields (shellCommandHistory) are already initialised.
The returned agent has NO API client, config manager, or system prompt — those are only needed in integration-style tests that should use NewAgent() instead.
Callers may freely mutate the returned Agent (e.g. setting debug, swapping in a mock state manager) after construction.
func (*Agent) AddMessage ¶
AddMessage adds a single message to the conversation history
func (*Agent) AddSessionAllowedFolder ¶
AddSessionAllowedFolder records the folder picked by the user from the filesystem approval dialog so future accesses under it are auto-approved for the rest of this session. No-op when the security submanager is unset.
func (*Agent) AddTaskAction ¶
AddTaskAction records a completed task action for continuity
func (*Agent) AddToHistory ¶
AddToHistory adds a command to the history buffer
func (*Agent) AllowAppForComputerUse ¶ added in v0.16.19
AllowAppForComputerUse adds the given app key to the per-session allowlist. Guarded by computerUseMu.
func (*Agent) ApplyPersona ¶
func (*Agent) ApplyRecoveredState ¶ added in v0.17.17
func (a *Agent) ApplyRecoveredState(state *ConversationState) RecoveryReport
ApplyRecoveredState applies a recovered state and primes a system supplement so the model knows the session was interrupted.
func (*Agent) ApplyState ¶
func (a *Agent) ApplyState(state *ConversationState)
ApplyState applies a loaded state to the current agent
func (*Agent) ApplySyncOp ¶
func (a *Agent) ApplySyncOp(op SyncOp, workspaceRoot string) SyncOpResult
ApplySyncOp applies a single SyncOp to the workspace filesystem. It validates the operation, checks for conflicts with container-side changes, applies the change, and updates the file metadata.
func (*Agent) ApplySyncOpBatch ¶
func (a *Agent) ApplySyncOpBatch(ops []SyncOp, workspaceRoot string) []SyncOpResult
ApplySyncOpBatch applies a slice of SyncOps in order, collecting results. Stops on the first conflict, returning Accepted=false for remaining ops.
func (*Agent) Breakpoints ¶ added in v0.16.25
func (a *Agent) Breakpoints() []Breakpoint
Breakpoints returns all user messages as forkable breakpoints.
func (*Agent) BuildCheckpointCompactedMessages ¶
func (*Agent) BuildTranscriptSnapshot ¶ added in v0.16.4
func (a *Agent) BuildTranscriptSnapshot(label string, includePreview bool) *TranscriptSnapshot
BuildTranscriptSnapshot constructs an in-memory snapshot of the agent's current conversation state plus diagnostic annotations. Pure read — does not mutate the agent or touch disk.
func (*Agent) CanSpawnSubagents ¶
CanSpawnSubagents returns true if this agent is allowed to spawn subagents (i.e., current depth is less than the configured max depth).
func (*Agent) CaptureTranscriptSnapshot ¶ added in v0.16.4
CaptureTranscriptSnapshot builds a snapshot and writes it to ~/.sprout/transcripts/<scope-hash>/<session-id>/<UTC-ts>-<label>.json. Returns the absolute path of the file written so callers can report it to the user or log it.
func (*Agent) CheckFileContentSecurity ¶
CheckFileContentSecurity runs security concern detection on file content after a write. In WebUI mode, it uses the event-bus-based ApprovalManager to show a dialog. In CLI mode, it falls back to the interactive logger prompt. Ignored concerns are tracked per-file so they are not re-prompted.
func (*Agent) CheckForInterrupt ¶
CheckForInterrupt checks if an interrupt was requested
func (*Agent) CheckPatchConflict ¶
CheckPatchConflict checks whether a container patch to the given path conflicts with unsynced browser edits. Returns (conflict bool, theirsPath string). theirsPath is "<path>.theirs" when conflict is true, empty otherwise.
func (*Agent) ClassifyFileAccess ¶ added in v0.17.7
ClassifyFileAccess implements tools.FileAccessClassifier so handlers can consult Gate 1's path-tier verdict without importing pkg/agent. Translates the internal FileAccessDecision enum to the interface's string contract: "allow", "prompt", "deny". Logs the verdict to the audit logger on ctx so every decision appears in the audit trail.
func (*Agent) ClearActivePersona ¶
func (a *Agent) ClearActivePersona()
func (*Agent) ClearConversationHistory ¶
func (a *Agent) ClearConversationHistory()
func (*Agent) ClearInputInjectionContext ¶
func (a *Agent) ClearInputInjectionContext()
ClearInputInjectionContext clears any pending input injections.
Lock ordering invariant: steerStage.mu is never held while inputInjectionMutex is acquired. StageSteerInput releases steerStage.mu before its non-blocking channel mirror; here inputInjectionMutex is held only during the channel drain and steerStage.mu is acquired afterwards.
func (*Agent) ClearInterrupt ¶
func (a *Agent) ClearInterrupt()
ClearInterrupt resets the interrupt state. Cancels the previous ctx outside the lock to allow callbacks to re-enter.
func (*Agent) ClearSecurityAnalysisCache ¶ added in v0.17.7
func (a *Agent) ClearSecurityAnalysisCache()
ClearSecurityAnalysisCache resets the cache to empty. Call this when the session resets to avoid stale analyses from a previous session. Guards the pointer swap so a concurrent get/Set can't see a torn cache.
func (*Agent) ClearSessionOverrides ¶
func (a *Agent) ClearSessionOverrides()
ClearSessionOverrides clears any session-scoped provider/model overrides. This should be called when a webui session ends to restore config-based behavior.
func (*Agent) ClearShellCommandHistory ¶
func (a *Agent) ClearShellCommandHistory()
ClearShellCommandHistory removes all entries from shell command history
func (*Agent) ClearTrackedChanges ¶
func (a *Agent) ClearTrackedChanges()
ClearTrackedChanges clears all tracked changes (but keeps tracking enabled)
func (*Agent) CommitChanges ¶
CommitChanges commits all tracked changes to the change tracker
func (*Agent) ConsumePendingStrictSwitchNotice ¶
func (*Agent) DeferredMessageCount ¶
DeferredMessageCount returns the number of queued messages (advisory only).
func (*Agent) DisableAutoPruning ¶
func (a *Agent) DisableAutoPruning()
DisableAutoPruning disables automatic conversation pruning
func (*Agent) DisableChangeTracking ¶
func (a *Agent) DisableChangeTracking()
DisableChangeTracking disables change tracking
func (*Agent) DisableEmbeddingIndex ¶
func (a *Agent) DisableEmbeddingIndex()
DisableEmbeddingIndex stops and cleans up the embedding manager. It persists the preference to the workspace config so it stays disabled on restart.
func (*Agent) DisableStreaming ¶
func (a *Agent) DisableStreaming()
DisableStreaming disables response streaming
func (*Agent) DisableWakeup ¶ added in v0.16.19
func (a *Agent) DisableWakeup()
func (*Agent) DrainDeferredMessages ¶
DrainDeferredMessages atomically removes and returns all queued messages. Used by the CLI REPL loop.
func (*Agent) DrainNotifications ¶ added in v0.16.19
func (a *Agent) DrainNotifications() []Notification
func (*Agent) ElevateSessionToPermissive ¶
func (a *Agent) ElevateSessionToPermissive()
ElevateSessionToPermissive sets the transient risk-profile override to "permissive" for this session. Critical-tier ops still block; "permissive" only widens the auto-approved set.
func (*Agent) EnableAutoPruning ¶
func (a *Agent) EnableAutoPruning()
EnableAutoPruning enables automatic conversation pruning with default adaptive strategy
func (*Agent) EnableChangeTracking ¶
EnableChangeTracking enables change tracking for this agent session.
func (*Agent) EnableEmbeddingIndex ¶
EnableEmbeddingIndex initializes the embedding manager and starts building the index in the background. Call this when the user explicitly enables indexing for the workspace (via /index command or UI toggle). It persists the preference to the workspace config so it survives restarts.
Sets Experimental alongside Enabled: this is the one deliberate-action path that counts as informed opt-in for the experimental gate (see RestoreEmbeddingIndex and EmbeddingIndexConfig.Experimental). A user calling /index or the UI toggle today, after full-workspace auto-indexing was found to cause severe unbounded memory growth, is choosing it knowing the risk — unlike a pre-existing persisted "enabled: true" from before that finding, which must not silently carry the same weight.
func (*Agent) EnableStreaming ¶
EnableStreaming enables response streaming with a callback
func (*Agent) EnableWakeupIfDisabled ¶ added in v0.16.19
func (a *Agent) EnableWakeupIfDisabled()
func (*Agent) EndQuery ¶ added in v0.16.17
func (a *Agent) EndQuery()
EndQuery releases the "query in progress" flag set by TryBeginQuery. Safe to call multiple times and safe to call when the flag is already clear (idempotent).
func (*Agent) EnqueueDeferredMessage ¶
func (*Agent) EnsureLocalServer ¶ added in v0.17.17
EnsureLocalServer pre-loads the local model so the first chat request doesn't pay the load latency. Called when the user switches to sprout-local via /provider.
func (*Agent) EvaluateOperationRisk ¶
func (a *Agent) EvaluateOperationRisk(command string) configuration.RiskLevel
EvaluateOperationRisk determines the risk level of a command for the currently active persona. Resolution: Critical patterns always return Critical → persona rules → active risk profile → Low if no persona.
func (*Agent) ExecuteToolByName ¶ added in v0.17.20
func (a *Agent) ExecuteToolByName(ctx context.Context, name, argsJSON string) (content string, toolErr string)
ExecuteToolByName runs a single named tool against this agent's workspace and returns its content, or an error string when the tool failed.
It builds a fresh seed ToolRegistry (with the security PreExecuteHook) per call and executes exactly one ToolCall through seed's full pipeline — unknown-tool detection, arg parse/repair, circuit breakers, pre-execute security hooks, timeouts, truncation, and panic recovery are all handled by seed's Execute. Registry construction per call is intentional: it matches the throwaway-agent pattern used by the daemon's one-shot queries, and tool registration is cheap.
func (*Agent) ExportState ¶
ExportState exports the current agent state for persistence
func (*Agent) FleetBudgetExceeded ¶
FleetBudgetExceeded reports whether the fleet budget was exceeded (mid-run truncation).
func (*Agent) ForceSaveAndExit ¶ added in v0.17.17
ForceSaveAndExit performs a best-effort synchronous state save and exits. It backs the CLI's force-quit paths (second Ctrl+C, post-shutdown signal) where deferred saves never run — without it, an impatient exit discards the entire turn. Never returns.
func (*Agent) ForkAtBreakpoint ¶ added in v0.16.25
ForkAtBreakpoint saves the current session, then truncates the conversation to messages [0..breakpointIndex] (where breakpointIndex is 1-based, matching the Breakpoints list). Returns the new session ID. The original session is preserved on disk.
func (*Agent) GenerateActionSummary ¶
GenerateActionSummary creates a summary of completed actions for continuity
func (*Agent) GenerateCompactSummary ¶
GenerateCompactSummary creates a compact summary for session continuity (max 5K context)
func (*Agent) GenerateConversationSummary ¶
GenerateConversationSummary creates a comprehensive summary of the conversation including todos
func (*Agent) GenerateResponse ¶
GenerateResponse generates a simple response using the current model without tool calls.
func (*Agent) GenerateSessionSummary ¶
GenerateSessionSummary creates a summary of previous actions for continuity
func (*Agent) GetActivePersona ¶
func (*Agent) GetActiveRiskProfile ¶
func (a *Agent) GetActiveRiskProfile() configuration.RiskProfile
GetActiveRiskProfile returns the profile currently in effect for this agent (override > config > default). Exposed for status commands / debug logging.
func (*Agent) GetAllShellCommandHistory ¶
func (a *Agent) GetAllShellCommandHistory() map[string]*ShellCommandResult
GetAllShellCommandHistory returns a copy of the shell command history
func (*Agent) GetAuditLogger ¶ added in v0.16.12
func (a *Agent) GetAuditLogger() *tools.AuditLogger
GetAuditLogger returns the agent-owned security audit logger, or nil.
func (*Agent) GetAvailablePersonaIDs ¶
func (*Agent) GetAvailableToolNames ¶
func (*Agent) GetAverageTPS ¶
GetAverageTPS returns the average TPS across all requests
func (*Agent) GetBackgroundProcessManager ¶
func (a *Agent) GetBackgroundProcessManager() *tools.BackgroundProcessManager
GetBackgroundProcessManager returns the background process manager.
func (*Agent) GetCacheWriteTokens ¶ added in v0.16.17
GetCacheWriteTokens returns the total tokens written to the provider cache
func (*Agent) GetCachedCostSavings ¶
GetCachedCostSavings returns the cost savings from cached tokens
func (*Agent) GetCachedTokens ¶
GetCachedTokens returns the total cached/reused tokens
func (*Agent) GetChangeCount ¶
GetChangeCount returns the number of file changes tracked in this session
func (*Agent) GetChangeTracker ¶
func (a *Agent) GetChangeTracker() *ChangeTracker
GetChangeTracker returns the change tracker (can be nil)
func (*Agent) GetChangesSummary ¶
GetChangesSummary returns a summary of tracked changes
func (*Agent) GetChargedCostTotal ¶ added in v0.16.19
GetChargedCostTotal returns the total charged cost
func (*Agent) GetCompletionTokens ¶
GetCompletionTokens returns the total completion tokens used
func (*Agent) GetConfig ¶
func (a *Agent) GetConfig() *configuration.Config
GetConfig returns the configuration
func (*Agent) GetConfigManager ¶
func (a *Agent) GetConfigManager() *configuration.Manager
GetConfigManager returns the configuration manager
func (*Agent) GetConfigOverrides ¶
GetConfigOverrides returns the session-scoped config overrides.
func (*Agent) GetContextProfile ¶ added in v0.17.7
func (a *Agent) GetContextProfile() configuration.ContextProfile
GetContextProfile returns the resolved context profile active for this agent.
func (*Agent) GetContextTokens ¶
GetContextTokens returns the current and max token counts for the active model's context window.
func (*Agent) GetContextWarningIssued ¶
GetContextWarningIssued returns whether a context warning has been issued
func (*Agent) GetContinuationNudges ¶ added in v0.17.18
GetContinuationNudges returns how many seed transient continuation nudges ("Please continue…") were observed at the provider seam. These messages never enter conversation state, so this count explains consecutive assistant messages in transcripts.
func (*Agent) GetCurrentContextTokens ¶
GetCurrentContextTokens returns the current context token count
func (*Agent) GetCurrentIteration ¶
GetCurrentIteration returns the current iteration number
func (*Agent) GetCurrentTPS ¶
GetCurrentTPS returns the current TPS value (alias for GetLastTPS)
func (*Agent) GetDebugLogPath ¶
GetDebugLogPath returns the path to the current debug log file (if any)
func (*Agent) GetEffectiveContextCap ¶ added in v0.17.7
GetEffectiveContextCap returns the user-facing effective context cap — min of native window and user's MaxContextTokens setting.
func (*Agent) GetElevationGate ¶
func (a *Agent) GetElevationGate() *security.ElevationGate
GetElevationGate returns the agent's elevation gate for external use (e.g., commit flows).
func (*Agent) GetEmbeddingManager ¶
func (a *Agent) GetEmbeddingManager() *embedding.EmbeddingManager
GetEmbeddingManager returns the embedding index manager (may be nil if embedding is not configured or enabled in the agent's config).
func (*Agent) GetEstimatedTokenResponses ¶
GetEstimatedTokenResponses returns how many responses used estimated token usage.
func (*Agent) GetEventBus ¶
GetEventBus returns the current event bus
func (*Agent) GetEventChatID ¶
GetEventChatID returns the bound chat_id from event metadata, if present.
func (*Agent) GetEventClientID ¶
GetEventClientID returns the bound client_id from event metadata, if present.
func (*Agent) GetEventUserID ¶
GetEventUserID returns the bound user_id from event metadata, if present.
func (*Agent) GetFileMetadata ¶
func (a *Agent) GetFileMetadata(path string) (WorkspaceFileMetadata, bool)
GetFileMetadata returns the cached metadata for `path` (zero-value + false if absent). Read-side companion to SetFileMetadata.
func (*Agent) GetFleetUsdBudget ¶ added in v0.16.4
func (a *Agent) GetFleetUsdBudget() *FleetUsdBudget
GetFleetUsdBudget returns the agent's USD budget, or nil if none is set. Used by the SubagentRunner to propagate the same budget to spawned subagents (so the cap is workflow-wide, not per-agent).
func (*Agent) GetHistory ¶
GetHistory returns a defensive copy of the command history.
func (*Agent) GetHistoryCommand ¶
GetHistoryCommand returns the command at the given index from history
func (*Agent) GetHistorySize ¶
GetHistorySize returns the number of commands in history
func (*Agent) GetImageTokens ¶ added in v0.17.5
GetImageTokens returns the total image tokens used (vision model inputs). These are already included in PromptTokens/TotalTokens; this is for display only.
func (*Agent) GetInputInjectionContext ¶
GetInputInjectionContext returns the input injection channel for the new system
func (*Agent) GetLLMCallCount ¶
GetLLMCallCount returns the total number of LLM API calls made
func (*Agent) GetLastMessages ¶
GetLastMessages returns the last N messages for preview
func (*Agent) GetLastPreparedToolNames ¶
GetLastPreparedToolNames returns the tool names sent in the most recent model request.
func (*Agent) GetLastRunTerminationReason ¶
func (*Agent) GetLastTPS ¶
GetLastTPS returns the most recent TPS value from the provider
func (*Agent) GetMaxContextTokens ¶
GetMaxContextTokens returns the maximum context tokens for the current model
func (*Agent) GetMaxContextTokensCached ¶ added in v0.17.20
GetMaxContextTokensCached returns the state-cached context limit. Unlike GetMaxContextTokens it never resolves the limit from the provider, so it is safe to call from hot poll paths (WebUI /api/stats) that run under the server's exclusive mutex — GetModelContextLimit on local providers can block for seconds on a network fetch.
func (*Agent) GetMaxIterations ¶
GetMaxIterations returns the maximum iterations allowed (0 means unlimited)
func (*Agent) GetMessages ¶
GetMessages returns the current conversation messages
func (*Agent) GetOptimizationStats ¶
func (*Agent) GetOutputRedactor ¶
func (a *Agent) GetOutputRedactor() *security.OutputRedactor
GetOutputRedactor returns the agent's output redactor for external use.
func (*Agent) GetPasswordPrompter ¶ added in v0.16.18
func (a *Agent) GetPasswordPrompter() tools.PasswordPrompter
GetPasswordPrompter returns the registered password prompter, or nil.
func (*Agent) GetPersonaProviderModel ¶
func (*Agent) GetPreviousSummary ¶
GetPreviousSummary returns the summary of previous actions
func (*Agent) GetPromptTokens ¶
GetPromptTokens returns the total prompt tokens used
func (*Agent) GetProvider ¶
GetProvider returns the current provider name
func (*Agent) GetProviderType ¶
func (a *Agent) GetProviderType() api.ClientType
GetProviderType returns the current provider type
func (*Agent) GetPruningStats ¶
GetPruningStats returns information about the current pruning configuration
func (*Agent) GetRevisionID ¶
GetRevisionID returns the current revision ID (if change tracking is enabled)
func (*Agent) GetSecurityApprovalMgr ¶
func (a *Agent) GetSecurityApprovalMgr() *security.ApprovalManager
GetSecurityApprovalMgr returns the security approval manager. Returns nil when the security subsystem is not initialized (e.g., bare &Agent{} in tests), so callers can safely nil-check the result.
func (*Agent) GetSecurityCautionsIssued ¶ added in v0.16.12
GetSecurityCautionsIssued returns the number of SECURITY_CAUTION_REQUIRED errors produced this session.
func (*Agent) GetSecurityLoopsDetected ¶ added in v0.16.12
GetSecurityLoopsDetected returns the number of times loop detection fired (the same tool+args was blocked >= securityBlockThreshold times).
func (*Agent) GetSecurityRetriesAfterCaution ¶ added in v0.16.12
GetSecurityRetriesAfterCaution returns the number of times the LLM retried the same tool+args after seeing a security caution (the count went 1→2).
func (*Agent) GetSessionID ¶
GetSessionID returns the session identifier
func (*Agent) GetSessionName ¶ added in v0.16.18
GetSessionName returns a readable name for the current session. It is the exported form of generateSessionName.
func (*Agent) GetShellCommandHistoryEntry ¶
func (a *Agent) GetShellCommandHistoryEntry(command string) (*ShellCommandResult, bool)
GetShellCommandHistoryEntry retrieves a shell command result from history
func (*Agent) GetShellCwd ¶
GetShellCwd returns the current logical shell working directory.
func (*Agent) GetSubagentRunner ¶
func (a *Agent) GetSubagentRunner() *SubagentRunner
GetSubagentRunner returns the per-agent subagent runner, creating it lazily.
func (*Agent) GetSyncStatus ¶
func (a *Agent) GetSyncStatus() map[string]WorkspaceFileMetadata
GetSyncStatus returns a map of path → WorkspaceFileMetadata for all currently tracked files in the workspace metadata store.
func (*Agent) GetSystemPrompt ¶
GetSystemPrompt returns the current system prompt
func (*Agent) GetTPSStats ¶
GetTPSStats returns comprehensive TPS statistics
func (*Agent) GetTaskActions ¶
func (a *Agent) GetTaskActions() []TaskAction
GetTaskActions returns completed task actions
func (*Agent) GetTerminalManager ¶
func (a *Agent) GetTerminalManager() tools.TerminalAccess
GetTerminalManager returns the terminal manager (may be nil in CLI mode).
func (*Agent) GetTodoManager ¶
func (a *Agent) GetTodoManager() *tools.TodoManager
GetTodoManager returns the per-agent todo manager. This ensures session isolation in daemon mode where multiple agents run concurrently.
func (*Agent) GetTokenCostTotal ¶ added in v0.16.19
GetTokenCostTotal returns the total token-based cost
func (*Agent) GetTotalCost ¶
GetTotalCost returns the total cost of the conversation
func (*Agent) GetTotalTokens ¶
GetTotalTokens returns the total tokens used across all requests
func (*Agent) GetTrackedFiles ¶
GetTrackedFiles returns the list of files that have been modified in this session
func (*Agent) GetTurnCheckpoints ¶ added in v0.16.25
func (a *Agent) GetTurnCheckpoints() []TurnCheckpoint
GetTurnCheckpoints returns a defensive copy of the agent's turn checkpoints. Callers (e.g. the /rewind slash command) can read the list safely without holding the internal mutex.
func (*Agent) GetUnsafeMode ¶
GetUnsafeMode returns whether unsafe mode is enabled. Returns false when the security submanager is unset (typical for partially-constructed agents in unit tests).
func (*Agent) GetUnsafeShellMode ¶ added in v0.16.12
GetUnsafeShellMode returns whether unsafe shell mode is enabled. Returns false when the security submanager is unset.
func (*Agent) GetValidator ¶
func (a *Agent) GetValidator() *validation.Validator
GetValidator returns the syntax validator (nil until SetEventBus is called).
func (*Agent) GetVisionProcessor ¶ added in v0.16.18
func (a *Agent) GetVisionProcessor() *tools.VisionProcessor
GetVisionProcessor returns the agent's vision processor, creating it lazily on first call.
func (*Agent) GetWorkspaceRoot ¶
GetWorkspaceRoot returns the logical workspace root for this agent instance.
func (*Agent) HandleInterrupt ¶
HandleInterrupt processes an interrupt request. Deterministic: any interrupt stops the current task immediately.
func (*Agent) HasActiveWebUIClients ¶
HasActiveWebUIClients calls the registered callback (or returns false if none is set) to check whether WebUI clients are connected. Returns false when the security submanager is unset (typical for partially-constructed agents in unit tests).
func (*Agent) HasPasswordPrompter ¶ added in v0.16.18
HasPasswordPrompter returns true if a password prompter is registered. Used by the risk resolver to decide whether to downgrade privileged commands from block to prompt.
func (*Agent) HasPendingNotifications ¶ added in v0.16.19
func (*Agent) HasSessionOverrides ¶
HasSessionOverrides returns true if there are session-scoped provider/model overrides
func (*Agent) HasTurnCheckpoints ¶
func (*Agent) ImportState ¶
ImportState imports agent state from JSON data
func (*Agent) IncrementWakeupResume ¶ added in v0.16.19
func (a *Agent) IncrementWakeupResume(cfg configuration.WakeupConfig) bool
func (*Agent) InitSubManagersForTest ¶ added in v0.17.7
func (a *Agent) InitSubManagersForTest()
InitSubManagersForTest forces initialisation of every sub-manager on the receiver. Mirrors the production lazy-init path in initSubManagers but is exported so test fixtures in other packages can use it without poking at internal fields. Does not touch the LLM client, config manager, or any of the fields a real NewAgent call would set — the goal is "lazy-init done", not "fully production-ready".
func (*Agent) InjectInputContext ¶
InjectInputContext injects a new user input using the context-based interrupt system. Delivery goes through the retractable staging queue (steer_staging.go): the message sits staged until a conversation-loop boundary hands it to seed. Until that moment it can be pulled back with RetractLatestSteer.
func (*Agent) InjectProactiveContext ¶
InjectProactiveContext retrieves semantically relevant past turns and injects them into the agent's system prompt supplement. This is called once per session — on the first turn or after a cold session restore.
Graceful degradation: all errors are logged; the agent is never blocked.
func (*Agent) InjectSemanticRecall ¶ added in v0.16.4
InjectSemanticRecall runs recall over the current user query and appends the formatted block (if any) to the pending system supplement. Mirrors InjectProactiveContext — same shape, graceful degradation on every failure mode (no embedding manager, no store, embed failure, etc).
For callers that already have the items, use InjectSemanticRecallWithItems instead to avoid a redundant Recall() call (see InstrumentedRecall).
func (*Agent) InjectSemanticRecallWithItems ¶ added in v0.17.14
func (a *Agent) InjectSemanticRecallWithItems(ctx context.Context, query string, items []RecalledItem)
InjectSemanticRecallWithItems is like InjectSemanticRecall but accepts pre-retrieved items instead of calling Recall internally. This avoids duplicate recall work when the caller (e.g. InstrumentedRecall) already retrieved the items for its own metrics.
func (*Agent) InjectWebUIManagers ¶
func (a *Agent) InjectWebUIManagers(approvalMgr *security.ApprovalManager, askUserMgr *tools.AskUserManager)
InjectWebUIManagers replaces the agent's internal approval and ask-user managers with the webui-owned instances.
func (*Agent) InterruptCtx ¶
InterruptCtx returns the agent's interrupt context so child operations (e.g., tool execution) can derive from it and respect user cancellations.
func (*Agent) IsAppAllowedForComputerUse ¶ added in v0.16.19
IsAppAllowedForComputerUse reports whether the given app key is in the per-session allowlist. The key is a bundle ID (macOS) or a window class (Linux). Guarded by computerUseMu.
func (*Agent) IsCdTargetAllowed ¶ added in v0.17.7
IsCdTargetAllowed reports whether `target` (an absolute path that has already been resolved against the agent's effective cwd by the caller) is a legal cd destination for this agent.
A target is legal when it equals OR sits under any of:
- the agent's workspace root (a.currentWorkspaceRoot())
- any session-allowlisted folder (workflow-declared allowed_paths AND folders the user approved via "Allow folder this session")
Symlinks are NOT evaluated at this stage — the check is purely lexical. Symlink-escape re-validation is a Phase 2.5 concern and applies to file tools, not to cd-target gating.
Returns false when the agent or its security submanager is nil (typical for partially-constructed agents in tests) so bare-agent tests don't panic. Callers should still pass cleaned absolute paths.
func (*Agent) IsChangeTrackingEnabled ¶
IsChangeTrackingEnabled returns whether change tracking is enabled
func (*Agent) IsDebugMode ¶
IsDebugMode returns whether debug mode is enabled
func (*Agent) IsEmbeddingIndexEnabled ¶
IsEmbeddingIndexEnabled returns whether the embedding index is currently active.
func (*Agent) IsFolderSessionAllowed ¶
IsFolderSessionAllowed reports whether absPath sits under a folder the user has allowlisted via "Allow this folder for the rest of the session" on the filesystem approval dialog. Returns false when the security submanager is unset.
func (*Agent) IsFolderSessionWriteAllowed ¶ added in v0.17.7
IsFolderSessionWriteAllowed reports whether absPath sits under an allowlisted folder whose declared mode permits writes. Returns false when the security submanager is unset, mirroring the IsFolderSessionAllowed contract.
func (*Agent) IsInteractiveMode ¶
IsInteractiveMode returns true if running in interactive mode
func (*Agent) IsInterrupted ¶
IsInterrupted returns true if an interrupt has been requested
func (*Agent) IsLocalMode ¶
IsLocalMode returns true when the agent is running locally (CLI or local WebUI), not in a cloud environment. This controls whether LocalOnly personas (like the Executive Assistant) are available.
Cloud mode is detected via the SPROUT_CLOUD environment variable. Local mode is the default when the variable is unset or empty.
func (*Agent) IsPathOutsideWorkspace ¶ added in v0.16.12
IsPathOutsideWorkspace reports whether the resolved absolute path falls outside the agent's workspace root.
func (*Agent) IsQueryInProgress ¶ added in v0.16.17
IsQueryInProgress reports whether a query is currently executing on this Agent. Used by the WebUI to report busy state and by the CLI to check before starting a new query.
func (*Agent) IsReadOnlyAllowedFolder ¶ added in v0.17.7
IsReadOnlyAllowedFolder reports whether absPath sits under a session-allowlisted folder whose declared mode is "read_only". Used by the Gate 1 path-tier classifier to deny write attempts against read_only allowlist entries without consulting a prompt. Returns false when the security submanager is unset or when the matching folder has no declared mode (defaults to read-write).
func (*Agent) IsSecurityBypassApproved ¶
IsSecurityBypassApproved returns whether the user has approved any external filesystem access this session. Coarse signal: prefer the per-path IsFolderSessionAllowed for new code. Returns false when the security submanager is unset.
func (*Agent) IsSessionElevated ¶
IsSessionElevated reports whether the user has elevated the session to a permissive or unrestricted risk profile. Critical-tier operations are NOT covered by elevation and always block regardless.
func (*Agent) IsShellCommandAllowlisted ¶
IsShellCommandAllowlisted reports whether the command matches an approved literal or glob pattern. Critical-tier commands are still blocked regardless of allowlist matches.
func (*Agent) IsShutdown ¶ added in v0.17.17
IsShutdown reports whether Shutdown() has completed. The WebUI releases agents on background goroutines (workspace switch, chat deletion, idle eviction), so callers that need teardown to have finished — flushed history, closed embedding store, stopped MCP servers — have to be able to observe it.
func (*Agent) IsStreamingEnabled ¶
IsStreamingEnabled returns whether streaming is enabled
func (*Agent) IsSubagent ¶
IsSubagent returns true if this agent was spawned as a subagent (depth > 0). Used to prevent nested subagent spawning and skip interactive prompts.
func (*Agent) IsUnderWorkspaceRoot ¶ added in v0.17.7
IsUnderWorkspaceRoot reports whether absPath is at or under the agent's workspace root after symlink resolution. Symlink-evaluated on both sides to prevent a workspace symlink pointing outside from bypassing the gate. Returns false when the agent or workspace root is unset (nil-safe).
func (*Agent) IsWakeupDisabled ¶ added in v0.16.19
func (*Agent) IsWorkflowApprovedInSession ¶ added in v0.16.4
IsWorkflowApprovedInSession reports whether the user has already approved running this workflow during the current chat session. The cache is scoped per-agent and is reset whenever the agent is reinitialized.
func (*Agent) LifetimeCtx ¶ added in v0.17.14
LifetimeCtx returns a lazily-initialized, process-scoped context for background goroutines.
func (*Agent) ListAllowedCdTargets ¶ added in v0.17.7
ListAllowedCdTargets returns the set of folders the agent considers legal cd destinations, formatted as a sorted, deduplicated list suitable for inclusion in a shell-output rejection message. Includes the workspace root and every session-allowlisted folder.
func (*Agent) ListChanges ¶
ListChanges returns the session manifest.
func (*Agent) LoadState ¶
func (a *Agent) LoadState(sessionID string) (*ConversationState, error)
LoadState loads a conversation state by session ID
func (*Agent) LoadStateFromFile ¶
LoadStateFromFile loads agent state from a file
func (*Agent) LoadStateScoped ¶
func (a *Agent) LoadStateScoped(sessionID, workingDir string) (*ConversationState, error)
LoadStateScoped loads a conversation state by session ID within a specific working directory scope.
func (*Agent) LoadSummaryFromFile ¶
LoadSummaryFromFile loads ONLY the compact summary from a state file for minimal continuity
func (*Agent) LogToolCall ¶
LogToolCall appends a JSON line describing a tool call to a local file for quick debugging. File: ./tool_calls.log (in the current working directory)
func (*Agent) Logger ¶
func (a *Agent) Logger() *AgentLogger
Logger returns the agent logger, initializing it lazily if needed
func (*Agent) MarkEstimatedTokenUsageResponse ¶
func (a *Agent) MarkEstimatedTokenUsageResponse()
MarkEstimatedTokenUsageResponse records that token usage for one response was estimated.
func (*Agent) MarkWorkflowApprovedInSession ¶ added in v0.16.4
MarkWorkflowApprovedInSession records that the user has approved this workflow for the remainder of the chat session. Called by the security gate after a successful interactive approval, and by handleRunAutomate after a CLI-side confirmation path.
func (*Agent) MaxSubagentDepth ¶
MaxSubagentDepth returns the configured maximum nesting depth. EA root gets 3 levels (max depth 2), non-EA root gets 2 levels (max depth 1).
func (*Agent) MergeEventMetadata ¶
MergeEventMetadata adds extras to the current event metadata without discarding existing keys.
func (*Agent) MergeSubagentChanges ¶ added in v0.16.12
func (a *Agent) MergeSubagentChanges(changes []TrackedFileChange, persona string)
MergeSubagentChanges merges a completed subagent's tracked changes into this agent's ChangeTracker.
func (*Agent) MyRecentChanges ¶
MyRecentChanges returns the cross-session timeline. Thin wrapper around list_changes(include_persisted=true, include_cross_session=true, since=…).
func (*Agent) NavigateHistory ¶
NavigateHistory navigates through command history direction: 1 for up (older), -1 for down (newer) currentIndex: current position in the input line
func (*Agent) NoteRecoveredSession ¶ added in v0.17.17
func (a *Agent) NoteRecoveredSession()
NoteRecoveredSession primes the recovery supplement on an agent whose state was restored via ImportState (WebUI path), where ApplyRecoveredState wasn't used.
func (*Agent) NotifyCompletion ¶ added in v0.16.19
func (*Agent) OutputRouter ¶
func (a *Agent) OutputRouter() *OutputRouter
OutputRouter returns the current output router (nil if not initialized)
func (*Agent) PendingSteerCount ¶ added in v0.17.18
PendingSteerCount returns the number of staged entries not currently in flight (the retractable set, plus any rejected-then-released ones).
func (*Agent) PersistShellCommandAllowlist ¶
PersistShellCommandAllowlist appends command to the user's persistent approved-commands list (Config.ApprovedShellCommands) and saves to disk. Used by the "Always approve this command" choice on the approval dialog. Idempotent: re-adding an existing entry is a no-op but still triggers a save so the file's mtime updates (cheap).
func (*Agent) PersistShellCommandAskPolicy ¶ added in v0.17.5
PersistShellCommandAskPolicy adds a "always ask" command policy rule for the given command.
func (*Agent) PersistShellCommandPattern ¶ added in v0.16.12
PersistShellCommandPattern appends pattern to the user's persistent approved-command-pattern list (Config.ApprovedShellCommandPatterns) and saves to disk. Patterns use Go path.Match glob syntax (`*`, `?`, `[]`). Idempotent: re-adding an existing entry is a no-op but still triggers a save so the file's mtime updates (cheap).
func (*Agent) PrintCompactProgress ¶
func (a *Agent) PrintCompactProgress()
PrintCompactProgress prints a minimal progress indicator for non-interactive mode Format: [iteration:(current-context-tokens/context-limit) | total-tokens | cost]
func (*Agent) PrintConversationSummary ¶
PrintConversationSummary displays a comprehensive conversation summary with formatting
func (*Agent) PrintLine ¶
PrintLine prints a line of text to the console content area synchronously. It delegates to the internal renderer that handles streaming vs CLI output.
func (*Agent) PrintLineAsync ¶
PrintLineAsync enqueues a line for asynchronous output. Background goroutines (rate-limit handlers, streaming workers, etc.) should prefer this helper to avoid blocking on the UI mutex. If the queue is saturated, we fall back to bounded waiting and finally synchronous printing to avoid goroutine leaks while still preserving message ordering as much as possible.
func (*Agent) PrintTerminalOnly ¶
PrintTerminalOnly writes text to the terminal without publishing to the event bus. Use this for output already published via a more specific event type.
func (*Agent) ProcessQuery ¶
ProcessQuery handles the main conversation loop with the LLM
func (*Agent) ProcessQueryAs ¶ added in v0.17.20
ProcessQueryAs is ProcessQuery with an explicit caller source recorded on the query guard for accurate busy-state messaging.
func (*Agent) ProcessQueryWithContinuity ¶
func (*Agent) ProcessQueryWithContinuityAs ¶ added in v0.17.20
func (*Agent) PromptChoice ¶
func (a *Agent) PromptChoice(prompt string, choices []ChoiceOption) (string, error)
PromptChoice shows a dropdown selection of simple choices and returns the selected value
func (*Agent) PromptFileAccess ¶ added in v0.17.18
func (a *Agent) PromptFileAccess(ctx context.Context, toolName, filePath, resolvedPath, mode string) (context.Context, bool)
PromptFileAccess implements tools.FileAccessPrompter. Handlers in pkg/agent_tools call it when PrecheckFileAccess returns "prompt"; it re-enters the shared interactive approval flow (WebUI dialog or CLI prompt, session elevation, session folder allowlists, unsafe mode) by delegating to handleFileSecurityError with the mode-appropriate sentinel error.
func (*Agent) PublishAgentMessage ¶
PublishAgentMessage publishes a structured agent system message event.
func (*Agent) PublishCompactCompleted ¶ added in v0.16.4
func (a *Agent) PublishCompactCompleted(source string, beforeCount, afterCount, summaryChars int, err error)
PublishCompactCompleted emits a compact_completed event with the result of the compaction. Pass nil err on success.
func (*Agent) PublishCompactStarted ¶ added in v0.16.4
PublishCompactStarted emits a compact_started event with diagnostic fields describing the conversation state at the moment compaction begins. source is the path: "manual" (slash command) or "auto_llm_summary" (seed structural compaction).
func (*Agent) PublishContextManagementDiagnostic ¶ added in v0.16.4
func (a *Agent) PublishContextManagementDiagnostic(currentTokens, maxTokens, iteration, messageCount, cachedTokens, promptTokens, cacheWriteTokens int)
PublishContextManagementDiagnostic emits the per-iteration context-budget snapshot. Emits both the effective max (post-cap) and the native max (pre-cap).
func (*Agent) PublishEvent ¶ added in v0.17.17
PublishEvent publishes an event through the agent's event bus with metadata decoration.
func (*Agent) PublishFileChange ¶
PublishFileChange emits a file_changed event for ChangeTracker-detected mutations.
func (*Agent) PublishQueryProgress ¶
PublishQueryProgress publishes query progress for real-time updates
func (*Agent) PublishRateLimited ¶ added in v0.16.19
func (a *Agent) PublishRateLimited(ev *events.RateLimitedEvent)
PublishRateLimited emits a rate_limited event so the WebUI can show "rate-limited, retrying…" and gate the input until the backoff elapses.
func (*Agent) PublishRecallDiagnostic ¶ added in v0.16.4
func (a *Agent) PublishRecallDiagnostic(diag recallRetrievalDiagnostic)
PublishRecallDiagnostic emits a single semantic-recall pass diagnostic.
func (*Agent) PublishStreamChunk ¶
PublishStreamChunk publishes a streaming chunk for real-time updates
func (*Agent) PublishTodoUpdate ¶
PublishTodoUpdate publishes a structured todo update event
func (*Agent) PublishToolEnd ¶
func (a *Agent) PublishToolEnd(toolCallID, toolName, status, result, errorMessage string, duration time.Duration)
PublishToolEnd publishes a rich tool end event
func (*Agent) PublishToolExecution ¶
PublishToolExecution publishes tool execution events for real-time updates
func (*Agent) PublishToolStart ¶
func (a *Agent) PublishToolStart(toolName, toolCallID, arguments, displayName, persona string, isSubagent bool, subagentType string, toolIndex int)
PublishToolStart publishes a rich tool start event
func (*Agent) QueryGuardOwner ¶ added in v0.17.20
func (a *Agent) QueryGuardOwner() QueryGuardOwner
QueryGuardOwner reports which source currently holds the query guard and since when, for accurate busy-state messaging.
func (*Agent) QueueNotification ¶ added in v0.16.19
func (a *Agent) QueueNotification(n Notification)
func (*Agent) ReadFileContent ¶
ReadFileContent reads the content of a file from the workspace. The path is resolved relative to the agent's workspace root. Returns an error if the file does not exist or cannot be read.
func (*Agent) Recall ¶ added in v0.16.19
Recall runs the semantic-recall pipeline over the conversation store. Returns (nil, nil) when the agent or its embedding manager is missing, the query is blank, or limit <= 0. Used by InjectSemanticRecall and the future /recall CLI and webui /api/recall endpoints.
func (*Agent) RecordErrorCategory ¶ added in v0.16.19
RecordErrorCategory emits a metrics event with the given error's category label, so the cost/status footer can show "rate-limited, retrying…" vs "provider error" vs generic.
func (*Agent) RecordFileReadThisTurn ¶
RecordFileReadThisTurn marks `path` as read by the agent during the current turn. Called from the read_file tool handler.
func (*Agent) RecordTurnCheckpoint ¶
func (*Agent) RecordTurnCheckpointAsync ¶
func (*Agent) RecordWakeupTokens ¶ added in v0.16.19
func (a *Agent) RecordWakeupTokens(tokens int, cfg configuration.WakeupConfig)
func (*Agent) RecoverFile ¶
RecoverFile restores one file from the tracker's session buffer.
func (*Agent) RefreshContextCapFromConfig ¶ added in v0.17.17
func (a *Agent) RefreshContextCapFromConfig()
RefreshContextCapFromConfig re-resolves the effective context cap from the current config and client. Called by /max-context and the settings API after they persist a MaxContextTokens change, so the running session picks up the new cap without waiting for a model switch.
func (*Agent) RefreshMCPTools ¶
RefreshMCPTools refreshes the MCP tools cache
func (*Agent) RefreshRuntimeConfig ¶ added in v0.16.19
RefreshRuntimeConfig reloads configuration from disk and reconciles the in-memory MCP server state so that servers added, removed, or modified through the webui settings API take effect without restarting the sprout process. This is the single entry point the webui calls after changing MCP servers or installing skills.
The context propagates cancellation from the caller (e.g. an HTTP request that the user closed). MCP server startup goroutines honor ctx.Done().
The method is safe to call concurrently with an active query — the MCP manager's own mutex protects AddServer/RemoveServer/ListServers and RefreshMCPTools uses the init mutex for cache invalidation. Concurrent RefreshRuntimeConfig calls are serialized via refreshMu.
func (*Agent) RefreshSkills ¶ added in v0.16.19
RefreshSkills reloads configuration from disk so that newly discovered skills (e.g., SKILL.md files dropped on disk) appear in list_skills without requiring a restart. This is called by the webui after skill installation.
func (*Agent) RemoveSessionAllowedFolder ¶ added in v0.17.7
RemoveSessionAllowedFolder removes folder from the session allowlist. Idempotent: nil is returned (not an error) when the folder was not on the list. Also clears any associated mode entry so the folder reverts to the default read_write semantics. No-op when the security submanager is unset.
func (*Agent) ReplaceTurnCheckpoints ¶
func (a *Agent) ReplaceTurnCheckpoints(checkpoints []TurnCheckpoint)
func (*Agent) RequestApproval ¶ added in v0.16.18
func (a *Agent) RequestApproval(assessment RiskAssessment, toolName string, args map[string]interface{}) (BrokerDecision, error)
RequestApproval performs the unified approval flow for a RiskAssessment. Low-risk auto-approves. Critical/hard-blocks deny unconditionally. Medium/High/IntentConfirmation checks bypass paths then tries WebUI, CLI, or falls back to permissive auto-approve in non-interactive mode.
func (*Agent) RequestEditApproval ¶ added in v0.16.12
func (a *Agent) RequestEditApproval(ctx context.Context, p EditProposal) (applied string, summary string, err error)
RequestEditApproval builds a proposal, asks the approval broker for a decision, applies only accepted hunks, and returns the result.
func (*Agent) RequestShellApproval ¶ added in v0.16.19
RequestShellApproval asks the user (CLI or WebUI) to approve each part of the shell command individually. Returns a map from part ID to approved bool.
Flow:
- If no parts, returns empty map and nil error.
- If the WebUI has an active surface, dispatch via the security approval manager (the real WebUI per-part dialog is implemented in requestShellApprovalViaWebUI).
- Otherwise, call console.PromptShellApprovalParts (the CLI picker).
Errors come from the picker (e.g. context cancelled); a per-part rejection does NOT return an error — it's encoded in the decisions map.
func (*Agent) ResetComputerUseSessionApproval ¶ added in v0.16.18
func (a *Agent) ResetComputerUseSessionApproval()
ResetComputerUseSessionApproval clears the per-session computer-use opt-in flag. Called from ClearSessionOverrides.
func (*Agent) ResetFileReadsForNewTurn ¶
func (a *Agent) ResetFileReadsForNewTurn()
ResetFileReadsForNewTurn clears the per-turn read tracker at turn boundaries.
func (*Agent) ResetHistoryIndex ¶
func (a *Agent) ResetHistoryIndex()
ResetHistoryIndex resets the history navigation index
func (*Agent) ResolveBillingType ¶ added in v0.17.5
ResolveBillingType is the exported wrapper around resolveBillingType for the CLI footer.
func (*Agent) ResolveToolRisk ¶ added in v0.16.7
func (a *Agent) ResolveToolRisk(toolName string, args map[string]interface{}) RiskAssessment
ResolveToolRisk produces the unified risk assessment for a tool call by folding all security inputs onto the Low/Medium/High/Critical scale.
func (*Agent) RespondToEditApproval ¶ added in v0.16.17
func (a *Agent) RespondToEditApproval(requestID string, decision EditDecision) bool
RespondToEditApproval delivers a user decision to a pending edit approval request.
func (*Agent) RespondToPasswordRequest ¶ added in v0.16.18
RespondToPasswordRequest delivers a user password to a pending password request. Called by the WebUI handler.
func (*Agent) RespondToShellApproval ¶ added in v0.17.10
RespondToShellApproval delivers per-part decisions for a pending shell approval request. Called by the WebUI handler (POST /api/shell-approvals/{id}/decision) when the user submits their choices. Returns true if the request was found and the decisions were delivered.
func (*Agent) RestoreEmbeddingIndex ¶
func (a *Agent) RestoreEmbeddingIndex()
RestoreEmbeddingIndex enables the workspace embedding index only when the user has opted in. Called once during agent startup after workspace root is known.
Embeddings are EXPERIMENTAL and OPT-IN, not default-on. Full-workspace auto-indexing was found to cause severe, unbounded native-memory growth — multi-GB spikes outside what Go's own memory accounting or limits can see or bound (see pkg/embedding/index.go, and EmbeddingIndexConfig.Experimental in pkg/configuration). A workspace config persisted before the Experimental gate existed has no "experimental" key at all, so it decodes to false regardless of what "enabled" was — existing users who had it on must explicitly opt in again via /index or the UI toggle, which sets both. Enable it via any of:
- workspace config `embedding_index.enabled: true` AND `experimental: true` (both set together by /index or the UI toggle), or
- env `SPROUT_EXPERIMENTAL_EMBEDDINGS=1` for default-on globally.
`SPROUT_DISABLE_EMBEDDING_AUTOINDEX=1` always wins and hard-disables (used by the test suites — see cmd/main_test.go and pkg/agent's TestMain).
Resolution order:
- SPROUT_DISABLE_EMBEDDING_AUTOINDEX=1 → skip (hard off).
- Workspace config enabled: true AND experimental: true → enable (explicit opt-in).
- Workspace config enabled: false, or experimental missing/false → skip (opted out, or never re-opted-in since this gate was added).
- No section / no file / unreadable config → enable only if SPROUT_EXPERIMENTAL_EMBEDDINGS=1, else skip (lazy/opt-in default).
func (*Agent) RetractLatestDeferredMessage ¶ added in v0.17.18
RetractLatestDeferredMessage removes and returns the newest queued message. Queue messages sit in the queue until the current turn ends (they then auto-run), so any of them is retractable mid-turn. This powers steer-panel recall.
func (*Agent) RetractLatestSteer ¶ added in v0.17.18
RetractLatestSteer removes the newest staged (not yet delivered to seed) entry and returns its content. This is the "pull the steer message back into editing" primitive: once seed has accepted a message it is in the conversation pipeline and cannot be revised. Entries currently in-flight (being handed to seed at this instant) are skipped — retraction there is deterministically too late.
func (*Agent) RevertMyChanges ¶
RevertMyChanges performs a bulk revert.
func (*Agent) Rewind ¶ added in v0.16.12
func (a *Agent) Rewind(opts RewindOptions) (*RewindResult, error)
Rewind truncates the agent's message history and checkpoints back to a prior turn, optionally reverting file changes. Undoable via lastRewindSnapshot.
func (*Agent) RotateSession ¶ added in v0.16.25
RotateSession closes the current session as a complete, restorable unit (writing its final state to disk under the current SessionID), then assigns a new SessionID and clears in-memory conversation state. The previous session file remains loadable via LoadStateScoped. Returns the new session ID.
If the prior session's SaveStateScoped fails (e.g. invalid session ID or unwritable working directory), RotateSession returns that error WITHOUT rotating — the prior session must remain intact so the caller can retry.
func (*Agent) RunAutomateWorkflow ¶ added in v0.16.4
RunAutomateWorkflow executes a named workflow and returns the JSON result. This is the public entry point for the WebUI automate API.
func (*Agent) SaveConversationSummary ¶
SaveConversationSummary saves the conversation summary to the state file
func (*Agent) SaveStateScoped ¶
SaveStateScoped saves conversation state under a directory-scoped session namespace.
func (*Agent) SaveStateToFile ¶
SaveStateToFile saves agent state to a file
func (*Agent) SelectProvider ¶
SelectProvider allows interactive provider selection
func (*Agent) SetAuditLogger ¶ added in v0.16.12
func (a *Agent) SetAuditLogger(l *tools.AuditLogger)
SetAuditLogger attaches a security audit logger to this agent. Also sets the package-level logger in pkg/agent_tools. Pass nil to disable.
func (*Agent) SetBackgroundProcessManager ¶
func (a *Agent) SetBackgroundProcessManager(bpm *tools.BackgroundProcessManager)
SetBackgroundProcessManager sets the background process manager for CLI mode. When set, shell commands can run in background without PTY (os/exec).
func (*Agent) SetBaseSystemPrompt ¶
SetBaseSystemPrompt updates the baseline prompt used when persona overrides are cleared.
func (*Agent) SetBudgetExceededCallback ¶ added in v0.16.4
SetBudgetExceededCallback registers a function invoked when the USD budget is first reached or surpassed. Pass nil to unregister.
func (*Agent) SetBudgetWarningCallback ¶ added in v0.16.4
SetBudgetWarningCallback registers a function invoked when the USD budget first crosses each configured warning threshold (fired at most once per threshold). Pass nil to unregister.
func (*Agent) SetConfigOverrides ¶
SetConfigOverrides stores session-scoped config overrides on the agent. These are applied in-memory and persisted with the session state.
func (*Agent) SetConversationOptimization ¶
func (*Agent) SetElevationGatePrompter ¶
func (a *Agent) SetElevationGatePrompter()
SetElevationGatePrompter wires the agent's interactive UI into the elevation gate. Call this after agent.ui is initialized (done automatically by SetUI).
func (*Agent) SetEventBus ¶
SetEventBus sets the event bus for real-time UI updates and initializes the validator
func (*Agent) SetEventMetadata ¶
SetEventMetadata attaches metadata that should be merged into all emitted UI events.
func (*Agent) SetFileMetadata ¶
func (a *Agent) SetFileMetadata(path string, md WorkspaceFileMetadata)
SetFileMetadata replaces the cached sync metadata for `path`.
func (*Agent) SetFleetBudget ¶
SetFleetBudget enables per-LLM-call fleet budget tracking for this agent.
func (*Agent) SetFleetUsdBudget ¶ added in v0.16.4
func (a *Agent) SetFleetUsdBudget(b *FleetUsdBudget)
SetFleetUsdBudget attaches a shared USD budget to this agent. The budget is shared by reference, so all agents (primary + subagents) that hold the same pointer debit to the same counter.
func (*Agent) SetFlushCallback ¶
func (a *Agent) SetFlushCallback(callback func())
SetFlushCallback sets a callback to flush buffered output
func (*Agent) SetHasActiveWebUIClients ¶
SetHasActiveWebUIClients sets a callback that returns whether any WebUI clients are currently connected. The security prompting logic uses this to decide between WebUI event-bus routing and CLI-based prompting.
func (*Agent) SetInterruptHandler ¶
func (a *Agent) SetInterruptHandler(ch chan struct{})
SetInterruptHandler sets the interrupt handler for UI mode
func (*Agent) SetLastPreparedToolNames ¶
SetLastPreparedToolNames records the exact tool names prepared for the most recent model request.
func (*Agent) SetMaxIterations ¶
SetMaxIterations sets the maximum number of iterations for the agent. A value of 0 means unlimited (no iteration cap per prompt). Negative values are clamped to 0 (unlimited).
func (*Agent) SetMessages ¶
SetMessages sets the conversation messages (for restore)
func (*Agent) SetModel ¶
SetModel changes the current model for the session (session-scoped, not persisted).
func (*Agent) SetModelPersisted ¶
SetModelPersisted changes the current model and persists the choice to config.
func (*Agent) SetOutputMutex ¶
SetOutputMutex sets the output mutex for synchronized output
func (*Agent) SetPasswordPrompter ¶ added in v0.16.18
func (a *Agent) SetPasswordPrompter(pp tools.PasswordPrompter)
SetPasswordPrompter registers a password prompter for shell commands. When set, privileged commands (sudo, passwd) are allowed to run with password assistance instead of being hard-blocked. Pass nil to disable.
func (*Agent) SetPreviousSummary ¶
SetPreviousSummary sets the summary of previous actions for continuity
func (*Agent) SetProvider ¶
func (a *Agent) SetProvider(provider api.ClientType) error
SetProvider switches to a specific provider with its default or current model. Session-scoped (not persisted).
func (*Agent) SetProviderPersisted ¶
func (a *Agent) SetProviderPersisted(provider api.ClientType) error
SetProviderPersisted switches to a specific provider and persists the choice to config. Rejects test provider.
func (*Agent) SetPruningSlidingWindowSize ¶
SetPruningSlidingWindowSize sets the sliding window size for the sliding window strategy
func (*Agent) SetPruningStrategy ¶
func (a *Agent) SetPruningStrategy(strategy PruningStrategy)
SetPruningStrategy sets the conversation pruning strategy
func (*Agent) SetPruningThreshold ¶
SetPruningThreshold sets the context usage threshold for triggering automatic pruning threshold should be between 0 and 1 (e.g., 0.7 = 70%)
func (*Agent) SetRecentMessagesToKeep ¶
SetRecentMessagesToKeep sets how many recent messages to always preserve
func (*Agent) SetRiskProfileOverride ¶
func (a *Agent) SetRiskProfileOverride(profile configuration.RiskProfile)
SetRiskProfileOverride installs a transient risk profile that overrides the config-level setting for the lifetime of this agent. Pass "" to clear.
func (*Agent) SetSessionAllowedFolderMode ¶ added in v0.17.7
SetSessionAllowedFolderMode records the declared mode for an already-allowlisted folder. The folder must already be on the session allowlist (call AddSessionAllowedFolder first); passing a mode for an unallowlisted folder is a no-op so the mode cannot widen access the user never approved. No-op when the security submanager is unset.
func (*Agent) SetSessionID ¶
SetSessionID sets the session identifier for continuity
func (*Agent) SetSessionName ¶
SetSessionName explicitly sets a custom name for the current session
func (*Agent) SetShellCommandHistoryEntry ¶
func (a *Agent) SetShellCommandHistoryEntry(command string, result *ShellCommandResult)
SetShellCommandHistoryEntry stores a shell command result in history
func (*Agent) SetShellCwd ¶
SetShellCwd sets the logical shell working directory and records the previous.
func (*Agent) SetSlashCommands ¶ added in v0.17.5
SetSlashCommands stores the command registry on the agent. Called after the registry is created in cmd/agent_mode_interactive.go.
func (*Agent) SetStatsUpdateCallback ¶
SetStatsUpdateCallback sets a callback for token/cost updates
func (*Agent) SetStreamingCallback ¶
SetStreamingCallback sets a custom callback for streaming output
func (*Agent) SetStreamingEnabled ¶
SetStreamingEnabled enables or disables streaming responses
func (*Agent) SetSystemPrompt ¶
SetSystemPrompt sets the system prompt for the agent
func (*Agent) SetSystemPromptFromFile ¶
SetSystemPromptFromFile loads a custom system prompt from a file
func (*Agent) SetTerminalManager ¶
func (a *Agent) SetTerminalManager(tm tools.TerminalAccess)
SetTerminalManager sets the terminal manager for WebUI mode. When set (non-nil), shell commands can access hidden PTY sessions. When nil (CLI mode), shell commands use os/exec unchanged.
func (*Agent) SetTraceSession ¶
func (a *Agent) SetTraceSession(traceSession interface{})
SetTraceSession sets the trace session for dataset collection
func (*Agent) SetTrainingConfig ¶ added in v0.17.5
func (a *Agent) SetTrainingConfig(cfg configuration.TrainingConfig)
SetTrainingConfig configures opt-in session recording for training data collection. When enabled and an endpoint is set, each SaveStateScoped call pushes a PII-redacted copy of the session to the endpoint.
This uses a callback function (SetTrainingPushFunc) to invoke the actual push implementation from pkg/training, avoiding a circular import between pkg/agent and pkg/training.
func (*Agent) SetTrainingPushFunc ¶ added in v0.17.5
func (a *Agent) SetTrainingPushFunc(fn func(state ConversationState, endpoint string, excludePaths []string) error)
SetTrainingPushFunc wires the push implementation. The callback receives a ConversationState (already populated), the endpoint URL, and the exclude path list. It should be non-blocking or fast — SaveStateScoped calls it in a goroutine.
Typically called from cmd/ with training.PushSession as the argument.
func (*Agent) SetUnsafeMode ¶
SetUnsafeMode sets the unsafe mode flag. No-op when the security submanager is unset so bare-agent tests don't panic.
func (*Agent) SetUnsafeShellMode ¶ added in v0.16.12
SetUnsafeShellMode sets the unsafe shell mode flag. No-op when the security submanager is unset.
func (*Agent) SetWorkspaceRoot ¶
SetWorkspaceRoot records the logical workspace root for this agent instance.
func (*Agent) ShouldGateEdit ¶ added in v0.16.12
ShouldGateEdit reports whether a write to the given path should be routed through the diff-approval gate based on the agent's config.
func (*Agent) ShowColoredDiff ¶
ShowColoredDiff displays a colored diff between old and new content, focusing on actual changes Uses Python's difflib for better diff quality when available, falls back to Go implementation
func (*Agent) ShowDropdown ¶
func (a *Agent) ShowDropdown(items interface{}, options DropdownOptions) (interface{}, error)
ShowDropdown shows a dropdown if UI is available
func (*Agent) ShowMyChange ¶
ShowMyChange returns a unified diff JSON envelope for `path`.
func (*Agent) ShowQuickPrompt ¶
func (a *Agent) ShowQuickPrompt(prompt string, options []QuickOption, horizontal bool) (QuickOption, error)
ShowQuickPrompt shows a quick prompt if UI is available
func (*Agent) Shutdown ¶
func (a *Agent) Shutdown()
Shutdown attempts to gracefully stop background work and child processes (e.g., MCP servers), and releases resources. It is safe to call multiple times.
func (*Agent) SlashCommands ¶ added in v0.17.5
SlashCommands returns the agent's command registry, or nil if not set.
func (*Agent) SnapshotSessionAllowedFolderModes ¶ added in v0.17.7
SnapshotSessionAllowedFolderModes returns a copy of the folder-mode map. Used alongside SnapshotSessionAllowedFolders to seed a subagent's declared modes so workflow read_only constraints survive delegation. Returns nil when the security submanager is unset.
func (*Agent) SnapshotSessionAllowedFolders ¶
SnapshotSessionAllowedFolders returns a copy of the session allowlist. Used by SubagentRunner to seed a new subagent's allowlist from the parent (so previously approved folders remain usable inside delegated work). Returns nil when the security submanager is unset.
func (*Agent) StageSteerInput ¶ added in v0.17.18
StageSteerInput appends a steer message to the retractable pending list. Mirrors the text into inputInjectionChan (best-effort, non-blocking) so legacy consumers that read SteeringChannel directly keep observing submissions; nothing in the delivery path drains that channel anymore.
func (*Agent) SteeringChannel ¶ added in v0.16.19
SteeringChannel returns the receive-only input channel for steer/queue messages. Subagent plumbing consults this channel FIRST before falling back to its own input channel.
func (*Agent) SubagentDepth ¶
SubagentDepth returns the nesting depth of this agent. 0 = primary agent (EA), 1 = orchestrator, 2 = coder/tester, etc.
func (*Agent) SummarizeMySession ¶
SummarizeMySession returns the activity-block digest. Thin wrapper around list_changes(group_by="block").
func (*Agent) SummarizeViaLLM ¶ added in v0.16.4
func (a *Agent) SummarizeViaLLM(ctx context.Context, messages []api.Message, hint core.SummarizerHint) (string, error)
SummarizeViaLLM produces a real LLM-generated recap of the supplied message window, using the agent's bound LLM client. Returns the summary body — callers are responsible for wrapping it with the "Compacted earlier conversation state:" header before splicing it back into the message list. Used by `/compact` so the user-facing command does an actual recap instead of substituting pre-baked rule-based heuristic text.
func (*Agent) ToolLog ¶
ToolLog formats and prints a tool call message immediately for user visibility. Routes through OutputRouter for single-sourced event+terminal output. Format: [4 - 30%] read file filename.go
func (*Agent) TrackFileEdit ¶
TrackFileEdit is called by the EditFile tool to track file edits
func (*Agent) TrackFileWrite ¶
TrackFileWrite is called by the WriteFile tool to track file writes
func (*Agent) TrackMetricsFromResponse ¶
func (a *Agent) TrackMetricsFromResponse(promptTokens, completionTokens, totalTokens int, estimatedCost float64, cachedTokens, cacheWriteTokens, imageTokens int)
TrackMetricsFromResponse updates agent metrics from API response usage data. cacheWriteTokens: prompt tokens written to provider cache. imageTokens: tokens from image inputs (display only, not for budget).
func (*Agent) TriggerInterrupt ¶
func (a *Agent) TriggerInterrupt()
TriggerInterrupt manually triggers an interrupt for testing purposes
func (*Agent) TryAutoResume ¶ added in v0.17.14
TryAutoResume checks whether there are pending background-task notifications that warrant an automatic agent resume. If so, it drains them and calls ProcessQueryWithContinuity to re-invoke the agent so it can act on the completed background tasks.
This is the shared entry point used by both the WebUI wakeup poller (pkg/webui/wakeup_poller.go) and the CLI interactive loop (cmd/agent_mode_interactive.go). It encapsulates the budget checks (max resumes, max tokens), notification draining, and the actual resume call.
Returns true if a resume was performed, false if conditions were not met (no notifications, wakeup disabled, budget exhausted, or a query is already in progress).
func (*Agent) TryBeginQuery ¶ added in v0.16.17
TryBeginQuery attempts to mark this Agent as "query in progress." Returns ErrQueryInProgress if a query is already running on this Agent instance. The caller MUST call EndQuery when done (typically via defer) to release the flag.
This is the concurrency guard for shared-agent mode: when the CLI REPL and the WebUI use the same *Agent (non-daemon interactive mode), only one ProcessQuery can execute at a time. The losing caller gets the error and must either retry or present a "busy" message to the user.
For standalone daemon mode (separate agents per chat session) this flag is never contended because each chat has its own Agent, so it's effectively a no-op.
func (*Agent) TryBeginQueryAs ¶ added in v0.17.20
TryBeginQueryAs marks this Agent as "query in progress" and records the caller source so busy-state messages can name the actual holder.
type AgentLogger ¶
type AgentLogger struct {
// contains filtered or unexported fields
}
AgentLogger wraps the agent and provides context-aware logging
func NewAgentLogger ¶
func NewAgentLogger(agent *Agent) *AgentLogger
NewAgentLogger creates a logger, using the agent's existing debug log file if available
func (*AgentLogger) Debug ¶
func (l *AgentLogger) Debug(format string, args ...interface{})
Debug writes a debug-level log with context
func (*AgentLogger) Error ¶
func (l *AgentLogger) Error(format string, args ...interface{})
Error writes an error-level log with context
func (*AgentLogger) Info ¶
func (l *AgentLogger) Info(format string, args ...interface{})
Info writes an info-level log with context
func (*AgentLogger) SetJSONMode ¶
func (l *AgentLogger) SetJSONMode(jsonMode bool)
SetJSONMode sets whether the logger outputs JSON or human-readable text
func (*AgentLogger) Warn ¶
func (l *AgentLogger) Warn(format string, args ...interface{})
Warn writes a warn-level log with context
func (*AgentLogger) WithFields ¶
func (l *AgentLogger) WithFields(fields map[string]string) *LogContext
WithFields returns a context that adds extra fields to all subsequent logs
type AgentMCPManager ¶
type AgentMCPManager struct {
// contains filtered or unexported fields
}
AgentMCPManager implements MCPSubManager.
func NewAgentMCPManager ¶
func NewAgentMCPManager() *AgentMCPManager
NewAgentMCPManager creates a new AgentMCPManager with default values.
func (*AgentMCPManager) GetInitError ¶
func (m *AgentMCPManager) GetInitError() error
func (*AgentMCPManager) GetManager ¶
func (m *AgentMCPManager) GetManager() mcp.MCPManager
func (*AgentMCPManager) GetToolsCache ¶
func (m *AgentMCPManager) GetToolsCache() []api.Tool
func (*AgentMCPManager) IsInitialized ¶
func (m *AgentMCPManager) IsInitialized() bool
func (*AgentMCPManager) LockInit ¶
func (m *AgentMCPManager) LockInit()
func (*AgentMCPManager) SetInitError ¶
func (m *AgentMCPManager) SetInitError(err error)
func (*AgentMCPManager) SetInitialized ¶
func (m *AgentMCPManager) SetInitialized(initialized bool)
func (*AgentMCPManager) SetManager ¶
func (m *AgentMCPManager) SetManager(mgr mcp.MCPManager)
func (*AgentMCPManager) SetToolsCache ¶
func (m *AgentMCPManager) SetToolsCache(tools []api.Tool)
func (*AgentMCPManager) UnlockInit ¶
func (m *AgentMCPManager) UnlockInit()
type AgentMetricsManager ¶ added in v0.17.7
type AgentMetricsManager struct {
// contains filtered or unexported fields
}
AgentMetricsManager owns 6 sub-interfaces: CostTracker, TokenCounter, LLMCallTracker, ToolCallTracker, CacheStats, and EstimatedTokenStore. All fields are protected by a single RWMutex.
func NewAgentMetricsManager ¶ added in v0.17.7
func NewAgentMetricsManager() *AgentMetricsManager
NewAgentMetricsManager creates a new AgentMetricsManager with zero-initialized fields.
func (*AgentMetricsManager) AddCost ¶ added in v0.17.7
func (m *AgentMetricsManager) AddCost(c float64)
func (*AgentMetricsManager) AddCostEntry ¶ added in v0.17.7
func (m *AgentMetricsManager) AddCostEntry(entry CostEntry)
func (*AgentMetricsManager) GetCacheWriteTokens ¶ added in v0.17.7
func (m *AgentMetricsManager) GetCacheWriteTokens() int
func (*AgentMetricsManager) GetCachedCostSavings ¶ added in v0.17.7
func (m *AgentMetricsManager) GetCachedCostSavings() float64
func (*AgentMetricsManager) GetCachedTokens ¶ added in v0.17.7
func (m *AgentMetricsManager) GetCachedTokens() int
CacheStats
func (*AgentMetricsManager) GetChargedCostTotal ¶ added in v0.17.7
func (m *AgentMetricsManager) GetChargedCostTotal() float64
func (*AgentMetricsManager) GetCompletionTokens ¶ added in v0.17.7
func (m *AgentMetricsManager) GetCompletionTokens() int
func (*AgentMetricsManager) GetContinuationNudges ¶ added in v0.17.18
func (m *AgentMetricsManager) GetContinuationNudges() int
func (*AgentMetricsManager) GetEstimatedTokenResponses ¶ added in v0.17.7
func (m *AgentMetricsManager) GetEstimatedTokenResponses() int
EstimatedTokenStore
func (*AgentMetricsManager) GetFreeTokens ¶ added in v0.17.7
func (m *AgentMetricsManager) GetFreeTokens() int
func (*AgentMetricsManager) GetImageTokens ¶ added in v0.17.7
func (m *AgentMetricsManager) GetImageTokens() int
func (*AgentMetricsManager) GetLLMCallCount ¶ added in v0.17.7
func (m *AgentMetricsManager) GetLLMCallCount() int
LLMCallTracker
func (*AgentMetricsManager) GetPromptTokens ¶ added in v0.17.7
func (m *AgentMetricsManager) GetPromptTokens() int
func (*AgentMetricsManager) GetSubscriptionTokens ¶ added in v0.17.7
func (m *AgentMetricsManager) GetSubscriptionTokens() int
func (*AgentMetricsManager) GetTokenCostTotal ¶ added in v0.17.7
func (m *AgentMetricsManager) GetTokenCostTotal() float64
func (*AgentMetricsManager) GetTotalCost ¶ added in v0.17.7
func (m *AgentMetricsManager) GetTotalCost() float64
CostTracker
func (*AgentMetricsManager) GetTotalTokens ¶ added in v0.17.7
func (m *AgentMetricsManager) GetTotalTokens() int
TokenCounter
func (*AgentMetricsManager) GetTotalToolCalls ¶ added in v0.17.7
func (m *AgentMetricsManager) GetTotalToolCalls() int
ToolCallTracker
func (*AgentMetricsManager) IncrementLLMCallCount ¶ added in v0.17.7
func (m *AgentMetricsManager) IncrementLLMCallCount()
func (*AgentMetricsManager) IncrementTotalToolCalls ¶ added in v0.17.7
func (m *AgentMetricsManager) IncrementTotalToolCalls()
func (*AgentMetricsManager) RecordContinuationNudges ¶ added in v0.17.18
func (m *AgentMetricsManager) RecordContinuationNudges(n int)
Continuation-nudge observation (see field comment).
func (*AgentMetricsManager) SetCacheWriteTokens ¶ added in v0.17.7
func (m *AgentMetricsManager) SetCacheWriteTokens(n int)
func (*AgentMetricsManager) SetCachedCostSavings ¶ added in v0.17.7
func (m *AgentMetricsManager) SetCachedCostSavings(c float64)
func (*AgentMetricsManager) SetCachedTokens ¶ added in v0.17.7
func (m *AgentMetricsManager) SetCachedTokens(n int)
func (*AgentMetricsManager) SetChargedCostTotal ¶ added in v0.17.7
func (m *AgentMetricsManager) SetChargedCostTotal(v float64)
func (*AgentMetricsManager) SetCompletionTokens ¶ added in v0.17.7
func (m *AgentMetricsManager) SetCompletionTokens(n int)
func (*AgentMetricsManager) SetEstimatedTokenResponses ¶ added in v0.17.7
func (m *AgentMetricsManager) SetEstimatedTokenResponses(n int)
func (*AgentMetricsManager) SetFreeTokens ¶ added in v0.17.7
func (m *AgentMetricsManager) SetFreeTokens(v int)
func (*AgentMetricsManager) SetImageTokens ¶ added in v0.17.7
func (m *AgentMetricsManager) SetImageTokens(n int)
func (*AgentMetricsManager) SetLLMCallCount ¶ added in v0.17.7
func (m *AgentMetricsManager) SetLLMCallCount(n int)
func (*AgentMetricsManager) SetPromptTokens ¶ added in v0.17.7
func (m *AgentMetricsManager) SetPromptTokens(n int)
func (*AgentMetricsManager) SetSubscriptionTokens ¶ added in v0.17.7
func (m *AgentMetricsManager) SetSubscriptionTokens(v int)
func (*AgentMetricsManager) SetTokenCostTotal ¶ added in v0.17.7
func (m *AgentMetricsManager) SetTokenCostTotal(v float64)
func (*AgentMetricsManager) SetTotalCost ¶ added in v0.17.7
func (m *AgentMetricsManager) SetTotalCost(c float64)
func (*AgentMetricsManager) SetTotalTokens ¶ added in v0.17.7
func (m *AgentMetricsManager) SetTotalTokens(n int)
func (*AgentMetricsManager) SetTotalToolCalls ¶ added in v0.17.7
func (m *AgentMetricsManager) SetTotalToolCalls(n int)
type AgentOutputManager ¶
type AgentOutputManager struct {
// contains filtered or unexported fields
}
AgentOutputManager implements OutputManager.
func NewAgentOutputManager ¶
func NewAgentOutputManager() *AgentOutputManager
NewAgentOutputManager creates a new AgentOutputManager with default values.
func (*AgentOutputManager) EnsureAsyncOutputWorker ¶
func (m *AgentOutputManager) EnsureAsyncOutputWorker(fn func())
func (*AgentOutputManager) GetAsyncBufferSize ¶
func (m *AgentOutputManager) GetAsyncBufferSize() int
func (*AgentOutputManager) GetAsyncOutput ¶
func (m *AgentOutputManager) GetAsyncOutput() chan string
func (*AgentOutputManager) GetEventMetadata ¶
func (m *AgentOutputManager) GetEventMetadata() map[string]interface{}
func (*AgentOutputManager) GetEventMetadataMutex ¶
func (m *AgentOutputManager) GetEventMetadataMutex() *sync.RWMutex
func (*AgentOutputManager) GetFlushCallback ¶
func (m *AgentOutputManager) GetFlushCallback() func()
func (*AgentOutputManager) GetOutputMutex ¶
func (m *AgentOutputManager) GetOutputMutex() *sync.Mutex
func (*AgentOutputManager) GetOutputRouter ¶
func (m *AgentOutputManager) GetOutputRouter() *OutputRouter
func (*AgentOutputManager) GetReasoningBuffer ¶
func (m *AgentOutputManager) GetReasoningBuffer() *strings.Builder
func (*AgentOutputManager) GetReasoningCallback ¶
func (m *AgentOutputManager) GetReasoningCallback() func(string)
func (*AgentOutputManager) GetStreamingBuffer ¶
func (m *AgentOutputManager) GetStreamingBuffer() *strings.Builder
func (*AgentOutputManager) GetStreamingCallback ¶
func (m *AgentOutputManager) GetStreamingCallback() func(string)
func (*AgentOutputManager) GetTerminalWriter ¶
func (m *AgentOutputManager) GetTerminalWriter() func(string)
func (*AgentOutputManager) IsStreamingEnabled ¶
func (m *AgentOutputManager) IsStreamingEnabled() bool
func (*AgentOutputManager) SetAsyncBufferSize ¶
func (m *AgentOutputManager) SetAsyncBufferSize(size int)
func (*AgentOutputManager) SetAsyncOutput ¶
func (m *AgentOutputManager) SetAsyncOutput(ch chan string)
func (*AgentOutputManager) SetEventMetadata ¶
func (m *AgentOutputManager) SetEventMetadata(meta map[string]interface{})
func (*AgentOutputManager) SetEventMetadataUnlocked ¶
func (m *AgentOutputManager) SetEventMetadataUnlocked(meta map[string]interface{})
SetEventMetadataUnlocked sets metadata without acquiring the mutex. Caller must hold m.eventMetadataMu.
func (*AgentOutputManager) SetFlushCallback ¶
func (m *AgentOutputManager) SetFlushCallback(cb func())
func (*AgentOutputManager) SetOutputMutex ¶
func (m *AgentOutputManager) SetOutputMutex(mu *sync.Mutex)
func (*AgentOutputManager) SetOutputRouter ¶
func (m *AgentOutputManager) SetOutputRouter(router *OutputRouter)
func (*AgentOutputManager) SetReasoningCallback ¶
func (m *AgentOutputManager) SetReasoningCallback(cb func(string))
func (*AgentOutputManager) SetStreamingCallback ¶
func (m *AgentOutputManager) SetStreamingCallback(cb func(string))
func (*AgentOutputManager) SetStreamingEnabled ¶
func (m *AgentOutputManager) SetStreamingEnabled(enabled bool)
func (*AgentOutputManager) SetTerminalWriter ¶
func (m *AgentOutputManager) SetTerminalWriter(fn func(string))
type AgentPersonaManager ¶ added in v0.17.7
type AgentPersonaManager struct {
// contains filtered or unexported fields
}
AgentPersonaManager owns 4 sub-interfaces: PersonaStore, ToolGuidanceStore, FalseStopStore, and TaskActionStore.
func NewAgentPersonaManager ¶ added in v0.17.7
func NewAgentPersonaManager() *AgentPersonaManager
NewAgentPersonaManager creates a new AgentPersonaManager with sensible defaults.
func (*AgentPersonaManager) AddTaskAction ¶ added in v0.17.7
func (p *AgentPersonaManager) AddTaskAction(action TaskAction)
func (*AgentPersonaManager) GetActivePersona ¶ added in v0.17.7
func (p *AgentPersonaManager) GetActivePersona() string
func (*AgentPersonaManager) GetActiveSkills ¶ added in v0.17.7
func (p *AgentPersonaManager) GetActiveSkills() []string
PersonaStore
func (*AgentPersonaManager) GetTaskActions ¶ added in v0.17.7
func (p *AgentPersonaManager) GetTaskActions() []TaskAction
TaskActionStore — methods do NOT acquire taskActionsMu internally. Callers must acquire p.GetTaskActionsMutex() themselves.
func (*AgentPersonaManager) GetTaskActionsMutex ¶ added in v0.17.7
func (p *AgentPersonaManager) GetTaskActionsMutex() *sync.RWMutex
func (*AgentPersonaManager) IsFalseStopDetectionEnabled ¶ added in v0.17.7
func (p *AgentPersonaManager) IsFalseStopDetectionEnabled() bool
FalseStopStore
func (*AgentPersonaManager) IsToolCallGuidanceAdded ¶ added in v0.17.7
func (p *AgentPersonaManager) IsToolCallGuidanceAdded() bool
ToolGuidanceStore
func (*AgentPersonaManager) SetActivePersona ¶ added in v0.17.7
func (p *AgentPersonaManager) SetActivePersona(persona string)
func (*AgentPersonaManager) SetActiveSkills ¶ added in v0.17.7
func (p *AgentPersonaManager) SetActiveSkills(skills []string)
func (*AgentPersonaManager) SetFalseStopDetectionEnabled ¶ added in v0.17.7
func (p *AgentPersonaManager) SetFalseStopDetectionEnabled(v bool)
func (*AgentPersonaManager) SetTaskActions ¶ added in v0.17.7
func (p *AgentPersonaManager) SetTaskActions(actions []TaskAction)
func (*AgentPersonaManager) SetToolCallGuidanceAdded ¶ added in v0.17.7
func (p *AgentPersonaManager) SetToolCallGuidanceAdded(v bool)
type AgentSecurityManager ¶
type AgentSecurityManager struct {
// contains filtered or unexported fields
}
AgentSecurityManager implements SecurityManager, holding all security-related state.
func NewAgentSecurityManager ¶
func NewAgentSecurityManager() *AgentSecurityManager
NewAgentSecurityManager creates a new AgentSecurityManager with all fields initialized.
func (*AgentSecurityManager) AddSessionAllowedFolder ¶
func (m *AgentSecurityManager) AddSessionAllowedFolder(folder string)
func (*AgentSecurityManager) GetAskUserMgr ¶
func (m *AgentSecurityManager) GetAskUserMgr() *agenttools.AskUserManager
func (*AgentSecurityManager) GetElevationGate ¶
func (m *AgentSecurityManager) GetElevationGate() *security.ElevationGate
func (*AgentSecurityManager) GetOutputRedactor ¶
func (m *AgentSecurityManager) GetOutputRedactor() *security.OutputRedactor
func (*AgentSecurityManager) GetSecurityApprovalMgr ¶
func (m *AgentSecurityManager) GetSecurityApprovalMgr() *security.ApprovalManager
func (*AgentSecurityManager) GetUnsafeMode ¶
func (m *AgentSecurityManager) GetUnsafeMode() bool
func (*AgentSecurityManager) GetUnsafeShellMode ¶ added in v0.16.12
func (m *AgentSecurityManager) GetUnsafeShellMode() bool
func (*AgentSecurityManager) HasActiveWebUIClients ¶
func (m *AgentSecurityManager) HasActiveWebUIClients() bool
func (*AgentSecurityManager) IsConcernIgnored ¶
func (m *AgentSecurityManager) IsConcernIgnored(filePath, concern string) bool
func (*AgentSecurityManager) IsFolderSessionAllowed ¶
func (m *AgentSecurityManager) IsFolderSessionAllowed(absPath string) bool
func (*AgentSecurityManager) IsFolderSessionWriteAllowed ¶ added in v0.17.7
func (m *AgentSecurityManager) IsFolderSessionWriteAllowed(absPath string) bool
IsFolderSessionWriteAllowed reports whether absPath sits under an allowlisted folder whose mode permits writes.
func (*AgentSecurityManager) IsSecurityBypassApproved ¶
func (m *AgentSecurityManager) IsSecurityBypassApproved() bool
func (*AgentSecurityManager) RemoveSessionAllowedFolder ¶ added in v0.17.7
func (m *AgentSecurityManager) RemoveSessionAllowedFolder(folder string) error
RemoveSessionAllowedFolder removes folder from the session allowlist. Returns nil (not an error) when the folder was not present — this makes the restore path idempotent regardless of whether the step actually added anything. Also removes any mode entry for the folder from sessionPathModes so a subsequent SetSessionAllowedFolderMode call can't re-establish a mode for a folder that's no longer on the allowlist.
func (*AgentSecurityManager) SetApprovalMgr ¶
func (m *AgentSecurityManager) SetApprovalMgr(mgr *security.ApprovalManager)
func (*AgentSecurityManager) SetAskUserMgr ¶
func (m *AgentSecurityManager) SetAskUserMgr(mgr *agenttools.AskUserManager)
func (*AgentSecurityManager) SetConcernIgnored ¶
func (m *AgentSecurityManager) SetConcernIgnored(filePath, concern string)
func (*AgentSecurityManager) SetElevationGate ¶
func (m *AgentSecurityManager) SetElevationGate(gate *security.ElevationGate)
func (*AgentSecurityManager) SetHasActiveWebUIClients ¶
func (m *AgentSecurityManager) SetHasActiveWebUIClients(fn func() bool)
func (*AgentSecurityManager) SetSessionAllowedFolderMode ¶ added in v0.17.7
func (m *AgentSecurityManager) SetSessionAllowedFolderMode(folder, mode string)
SetSessionAllowedFolderMode records the declared mode for an already-allowlisted folder. Idempotent.
func (*AgentSecurityManager) SetUnsafeMode ¶
func (m *AgentSecurityManager) SetUnsafeMode(unsafe bool)
func (*AgentSecurityManager) SetUnsafeShellMode ¶ added in v0.16.12
func (m *AgentSecurityManager) SetUnsafeShellMode(unsafe bool)
func (*AgentSecurityManager) SnapshotSessionAllowedFolderModes ¶ added in v0.17.7
func (m *AgentSecurityManager) SnapshotSessionAllowedFolderModes() map[string]string
SnapshotSessionAllowedFolderModes returns a copy of the folder-mode map.
func (*AgentSecurityManager) SnapshotSessionAllowedFolders ¶
func (m *AgentSecurityManager) SnapshotSessionAllowedFolders() []string
type AgentSecurityStateManager ¶ added in v0.17.7
type AgentSecurityStateManager struct {
// contains filtered or unexported fields
}
AgentSecurityStateManager owns 5 sub-interfaces: CircuitBreakerStore, PendingStateStore, TerminationStore, ProviderErrorStore, and TraceStore. All fields are protected by a single RWMutex.
func NewAgentSecurityStateManager ¶ added in v0.17.7
func NewAgentSecurityStateManager() *AgentSecurityStateManager
NewAgentSecurityStateManager creates a new AgentSecurityStateManager with a default CircuitBreakerState.
func (*AgentSecurityStateManager) GetCircuitBreaker ¶ added in v0.17.7
func (s *AgentSecurityStateManager) GetCircuitBreaker() *CircuitBreakerState
CircuitBreakerStore
func (*AgentSecurityStateManager) GetLastProviderError ¶ added in v0.17.7
func (s *AgentSecurityStateManager) GetLastProviderError() *ProviderErrorInfo
ProviderErrorStore
func (*AgentSecurityStateManager) GetLastRunTerminationReason ¶ added in v0.17.7
func (s *AgentSecurityStateManager) GetLastRunTerminationReason() string
TerminationStore
func (*AgentSecurityStateManager) GetPendingStrictSwitchNotice ¶ added in v0.17.7
func (s *AgentSecurityStateManager) GetPendingStrictSwitchNotice() string
func (*AgentSecurityStateManager) GetPendingSwitchContextRefresh ¶ added in v0.17.7
func (s *AgentSecurityStateManager) GetPendingSwitchContextRefresh() string
PendingStateStore
func (*AgentSecurityStateManager) GetPendingSystemSupplement ¶ added in v0.17.7
func (s *AgentSecurityStateManager) GetPendingSystemSupplement() string
func (*AgentSecurityStateManager) GetTraceSession ¶ added in v0.17.7
func (s *AgentSecurityStateManager) GetTraceSession() interface{}
TraceStore
func (*AgentSecurityStateManager) SetCircuitBreaker ¶ added in v0.17.7
func (s *AgentSecurityStateManager) SetCircuitBreaker(cb *CircuitBreakerState)
func (*AgentSecurityStateManager) SetLastProviderError ¶ added in v0.17.7
func (s *AgentSecurityStateManager) SetLastProviderError(err *ProviderErrorInfo)
func (*AgentSecurityStateManager) SetLastRunTerminationReason ¶ added in v0.17.7
func (s *AgentSecurityStateManager) SetLastRunTerminationReason(reason string)
func (*AgentSecurityStateManager) SetPendingStrictSwitchNotice ¶ added in v0.17.7
func (s *AgentSecurityStateManager) SetPendingStrictSwitchNotice(v string)
func (*AgentSecurityStateManager) SetPendingSwitchContextRefresh ¶ added in v0.17.7
func (s *AgentSecurityStateManager) SetPendingSwitchContextRefresh(v string)
func (*AgentSecurityStateManager) SetPendingSystemSupplement ¶ added in v0.17.7
func (s *AgentSecurityStateManager) SetPendingSystemSupplement(v string)
func (*AgentSecurityStateManager) SetTraceSession ¶ added in v0.17.7
func (s *AgentSecurityStateManager) SetTraceSession(ts interface{})
type AgentSessionManager ¶ added in v0.17.7
type AgentSessionManager struct {
// contains filtered or unexported fields
}
AgentSessionManager implements SessionManager, holding all session-scoped state previously owned by AgentStateManager. Implements: MessageStore, SessionStore, CheckpointStore, SummaryStore, OptimizerStore, ContextBudgetStore, ConversationPrunerStore, CommandHistoryStore, PauseStore, SessionConfigStore, ConfigOverrideStore, IterationStore, SessionIntentStore (13 sub-interfaces).
All methods are nil-safe: calling any getter/setter on a nil *AgentSessionManager returns the zero value without panicking. This preserves the legacy behavior of *AgentStateManager (which had a single underlying mu, so a nil receiver returned zero values from the methods defined on a nil struct literal in tests).
func NewAgentSessionManager ¶ added in v0.17.7
func NewAgentSessionManager(debug bool) *AgentSessionManager
NewAgentSessionManager creates a new AgentSessionManager with sensible defaults.
func (*AgentSessionManager) AddMessage ¶ added in v0.17.7
func (m *AgentSessionManager) AddMessage(msg api.Message)
func (*AgentSessionManager) AddTurnCheckpoint ¶ added in v0.17.7
func (m *AgentSessionManager) AddTurnCheckpoint(cp TurnCheckpoint)
func (*AgentSessionManager) GetCheckpointMutex ¶ added in v0.17.7
func (m *AgentSessionManager) GetCheckpointMutex() *sync.RWMutex
func (*AgentSessionManager) GetCommandHistory ¶ added in v0.17.7
func (m *AgentSessionManager) GetCommandHistory() []string
func (*AgentSessionManager) GetConfigOverrides ¶ added in v0.17.7
func (m *AgentSessionManager) GetConfigOverrides() map[string]interface{}
func (*AgentSessionManager) GetConversationPruner ¶ added in v0.17.7
func (m *AgentSessionManager) GetConversationPruner() *ConversationPruner
func (*AgentSessionManager) GetCurrentContextTokens ¶ added in v0.17.7
func (m *AgentSessionManager) GetCurrentContextTokens() int
func (*AgentSessionManager) GetCurrentIteration ¶ added in v0.17.7
func (m *AgentSessionManager) GetCurrentIteration() int
func (*AgentSessionManager) GetHistoryIndex ¶ added in v0.17.7
func (m *AgentSessionManager) GetHistoryIndex() int
func (*AgentSessionManager) GetHistoryMutex ¶ added in v0.17.7
func (m *AgentSessionManager) GetHistoryMutex() *sync.Mutex
func (*AgentSessionManager) GetMaxContextTokens ¶ added in v0.17.7
func (m *AgentSessionManager) GetMaxContextTokens() int
func (*AgentSessionManager) GetMessageTimestamps ¶ added in v0.17.7
func (m *AgentSessionManager) GetMessageTimestamps() []time.Time
GetMessageTimestamps returns the creation timestamps for each message.
func (*AgentSessionManager) GetMessages ¶ added in v0.17.7
func (m *AgentSessionManager) GetMessages() []api.Message
func (*AgentSessionManager) GetOptimizer ¶ added in v0.17.7
func (m *AgentSessionManager) GetOptimizer() *ConversationOptimizer
func (*AgentSessionManager) GetPauseMutex ¶ added in v0.17.7
func (m *AgentSessionManager) GetPauseMutex() *sync.Mutex
func (*AgentSessionManager) GetPauseState ¶ added in v0.17.7
func (m *AgentSessionManager) GetPauseState() *PauseState
func (*AgentSessionManager) GetPreviousSummary ¶ added in v0.17.7
func (m *AgentSessionManager) GetPreviousSummary() string
func (*AgentSessionManager) GetSessionID ¶ added in v0.17.7
func (m *AgentSessionManager) GetSessionID() string
func (*AgentSessionManager) GetSessionIntentEmbedding ¶ added in v0.17.7
func (m *AgentSessionManager) GetSessionIntentEmbedding() []float32
func (*AgentSessionManager) GetSessionModel ¶ added in v0.17.7
func (m *AgentSessionManager) GetSessionModel() string
func (*AgentSessionManager) GetSessionProvider ¶ added in v0.17.7
func (m *AgentSessionManager) GetSessionProvider() api.ClientType
func (*AgentSessionManager) GetTurnCheckpoints ¶ added in v0.17.7
func (m *AgentSessionManager) GetTurnCheckpoints() []TurnCheckpoint
func (*AgentSessionManager) IsContextWarningIssued ¶ added in v0.17.7
func (m *AgentSessionManager) IsContextWarningIssued() bool
func (*AgentSessionManager) SetCommandHistory ¶ added in v0.17.7
func (m *AgentSessionManager) SetCommandHistory(h []string)
func (*AgentSessionManager) SetConfigOverrides ¶ added in v0.17.7
func (m *AgentSessionManager) SetConfigOverrides(overrides map[string]interface{})
func (*AgentSessionManager) SetContextWarningIssued ¶ added in v0.17.7
func (m *AgentSessionManager) SetContextWarningIssued(v bool)
func (*AgentSessionManager) SetConversationPruner ¶ added in v0.17.7
func (m *AgentSessionManager) SetConversationPruner(pruner *ConversationPruner)
func (*AgentSessionManager) SetCurrentContextTokens ¶ added in v0.17.7
func (m *AgentSessionManager) SetCurrentContextTokens(n int)
func (*AgentSessionManager) SetCurrentIteration ¶ added in v0.17.7
func (m *AgentSessionManager) SetCurrentIteration(iter int)
func (*AgentSessionManager) SetHistoryIndex ¶ added in v0.17.7
func (m *AgentSessionManager) SetHistoryIndex(i int)
func (*AgentSessionManager) SetMaxContextTokens ¶ added in v0.17.7
func (m *AgentSessionManager) SetMaxContextTokens(n int)
func (*AgentSessionManager) SetMessageTimestamps ¶ added in v0.17.7
func (m *AgentSessionManager) SetMessageTimestamps(ts []time.Time)
SetMessageTimestamps sets the creation timestamps for each message.
func (*AgentSessionManager) SetMessages ¶ added in v0.17.7
func (m *AgentSessionManager) SetMessages(msgs []api.Message)
func (*AgentSessionManager) SetOptimizer ¶ added in v0.17.7
func (m *AgentSessionManager) SetOptimizer(o *ConversationOptimizer)
func (*AgentSessionManager) SetPauseState ¶ added in v0.17.7
func (m *AgentSessionManager) SetPauseState(ps *PauseState)
func (*AgentSessionManager) SetPreviousSummary ¶ added in v0.17.7
func (m *AgentSessionManager) SetPreviousSummary(summary string)
func (*AgentSessionManager) SetSessionID ¶ added in v0.17.7
func (m *AgentSessionManager) SetSessionID(id string)
func (*AgentSessionManager) SetSessionIntentEmbedding ¶ added in v0.17.7
func (m *AgentSessionManager) SetSessionIntentEmbedding(emb []float32)
func (*AgentSessionManager) SetSessionIntentEmbeddingIfNil ¶ added in v0.17.7
func (m *AgentSessionManager) SetSessionIntentEmbeddingIfNil(emb []float32) bool
func (*AgentSessionManager) SetSessionModel ¶ added in v0.17.7
func (m *AgentSessionManager) SetSessionModel(model string)
func (*AgentSessionManager) SetSessionProvider ¶ added in v0.17.7
func (m *AgentSessionManager) SetSessionProvider(ct api.ClientType)
func (*AgentSessionManager) SetTurnCheckpoints ¶ added in v0.17.7
func (m *AgentSessionManager) SetTurnCheckpoints(cps []TurnCheckpoint)
type AgentState ¶
type AgentState struct {
Messages []api.Message `json:"messages"`
MessageTimestamps []time.Time `json:"message_timestamps,omitempty"`
TurnCheckpoints []TurnCheckpoint `json:"turn_checkpoints,omitempty"`
PreviousSummary string `json:"previous_summary"`
CompactSummary string `json:"compact_summary"` // New: 5K limit summary for continuity
TaskActions []TaskAction `json:"task_actions"`
SessionID string `json:"session_id"`
// Token and cost metrics
TotalTokens int `json:"total_tokens"`
TotalCost float64 `json:"total_cost"`
PromptTokens int `json:"prompt_tokens"`
CompletionTokens int `json:"completion_tokens"`
EstimatedTokenResponses int `json:"estimated_token_responses"`
CachedTokens int `json:"cached_tokens"`
CacheWriteTokens int `json:"cache_write_tokens,omitempty"`
CachedCostSavings float64 `json:"cached_cost_savings"`
ImageTokens int `json:"image_tokens,omitempty"`
// Billing-model-aware cost tracking
ChargedCostTotal float64 `json:"charged_cost_total,omitempty"`
TokenCostTotal float64 `json:"token_cost_total,omitempty"`
SubscriptionTokens int `json:"subscription_tokens,omitempty"`
FreeTokens int `json:"free_tokens,omitempty"`
}
AgentState represents the state of an agent that can be persisted
type AgentStateManager ¶
type AgentStateManager struct {
*AgentSessionManager
*AgentMetricsManager
*AgentPersonaManager
*AgentSecurityStateManager
}
AgentStateManager embeds all four focused sub-managers. Method promotion makes every method on each sub-manager automatically visible on the facade, satisfying all 28 sub-interfaces without explicit delegation.
Prefer using a focused sub-manager type (e.g. *AgentSessionManager) in new code that only needs one domain. The facade exists for backward compatibility with callers that already hold *StateManager.
func NewAgentStateManager ¶
func NewAgentStateManager(debug bool) *AgentStateManager
NewAgentStateManager creates a new AgentStateManager with sensible defaults. Each sub-manager is initialized with its own defaults: the Session sub-manager creates a fresh ConversationOptimizer and ConversationPruner (both needed before the first message); the Security sub-manager creates a CircuitBreakerState with an empty Actions map.
type BatchSplitResult ¶ added in v0.17.10
type BatchSplitResult struct {
// InlineIndices holds the indices of images that should be sent inline
// as multimodal content.
InlineIndices []int
// OverflowIndices holds the indices of images that should be processed
// via OCR fallback.
OverflowIndices []int
}
BatchSplitResult describes how a set of images should be split between inline multimodal processing and OCR fallback.
func BatchSplit ¶ added in v0.17.10
func BatchSplit(sizes []int, caps api.VisionCapabilities) BatchSplitResult
BatchSplit proactively determines which images fit within the provider's vision context window based on count and total payload size. Unlike a simple count-based split, it also considers total payload bytes to avoid provider 400 (context overflow) errors when embedding many/large images.
caps should already be resolved through VisionCapabilitiesOrDefault before calling this function so that zero-valued fields are replaced with safe defaults.
Algorithm: Greedy — images are taken in order until either the count limit (MaxImageCount) or the total byte budget (MaxImageBytes × MaxImageCount) is reached. The function is proactive: it splits before any provider call so the caller can route overflow images through OCR fallback.
type Breakpoint ¶ added in v0.16.25
type Breakpoint struct {
Index int // 1-based user-facing index
Content string // First ~80 chars for display
}
Breakpoint represents a user message that can be forked from.
type BrokerDecision ¶ added in v0.16.18
type BrokerDecision struct {
Approved bool
Decision security.ApprovalDecision
Outcome security.ApprovalOutcome
Surface string // "webui" or "cli" — which surface answered
Assessment RiskAssessment // echoed for caller diagnostics
Analysis *SecurityAnalysis // LLM-derived security analysis when available; nil otherwise
}
BrokerDecision is the typed verdict returned by RequestApproval.
type CLIPasswordPrompter ¶ added in v0.16.18
type CLIPasswordPrompter struct{}
CLIPasswordPrompter implements PasswordPrompter for CLI terminal sessions. Reads password from stdin with echo disabled.
func NewCLIPasswordPrompter ¶ added in v0.16.18
func NewCLIPasswordPrompter() *CLIPasswordPrompter
NewCLIPasswordPrompter constructs a CLI password prompter.
type CacheStats ¶ added in v0.16.25
type CacheStats interface {
GetCachedTokens() int
SetCachedTokens(int)
GetCacheWriteTokens() int
SetCacheWriteTokens(int)
GetCachedCostSavings() float64
SetCachedCostSavings(float64)
GetImageTokens() int
SetImageTokens(int)
}
CacheStats manages prompt cache statistics.
type Chain ¶ added in v0.17.7
type Chain struct {
Original string
Operators []string // len(Subcommands)-1
Subcommands []string // len >= 1 (split via SplitChainedCommand)
}
Chain is a top-level decomposition of a shell command. For unchained input, Subcommands has length 1. Operators carries the chain operator between each adjacent pair of subcommands.
func ParseChain ¶ added in v0.17.7
ParseChain splits a shell command string into a Chain value, delegating to SplitChainedCommand.
type ChangeTracker ¶
type ChangeTracker struct {
// contains filtered or unexported fields
}
ChangeTracker manages change tracking for the agent workflow
func NewChangeTracker ¶
func NewChangeTracker(agent *Agent, instructions string) *ChangeTracker
NewChangeTracker creates a new change tracker for an agent session
func (*ChangeTracker) Clear ¶
func (ct *ChangeTracker) Clear()
Clear clears all tracked changes (but keeps the tracker enabled). Also resets the shell-snapshot cache.
func (*ChangeTracker) CollectFileChangesForCheckpoint ¶
func (ct *ChangeTracker) CollectFileChangesForCheckpoint() ([]CheckpointFileChange, string)
CollectFileChangesForCheckpoint returns the (path, op) manifest of changes appended since the most recent checkpoint capture.
func (*ChangeTracker) Commit ¶
func (ct *ChangeTracker) Commit(llmResponse string, conversation []api.Message) error
Commit commits all tracked changes to the change tracker
func (*ChangeTracker) Disable ¶
func (ct *ChangeTracker) Disable()
Disable disables change tracking.
func (*ChangeTracker) GenerateAISummary ¶
func (ct *ChangeTracker) GenerateAISummary() (string, error)
GenerateAISummary creates an AI-generated summary of the changes.
func (*ChangeTracker) GetChangeCount ¶
func (ct *ChangeTracker) GetChangeCount() int
GetChangeCount returns the number of tracked changes
func (*ChangeTracker) GetChanges ¶
func (ct *ChangeTracker) GetChanges() []TrackedFileChange
GetChanges returns a copy of the tracked changes
func (*ChangeTracker) GetRevisionID ¶
func (ct *ChangeTracker) GetRevisionID() string
GetRevisionID returns the current revision ID
func (*ChangeTracker) GetSummary ¶
func (ct *ChangeTracker) GetSummary() string
GetSummary returns a deterministic summary of tracked changes (no LLM call).
func (*ChangeTracker) GetTrackedFiles ¶
func (ct *ChangeTracker) GetTrackedFiles() []string
GetTrackedFiles returns a list of files that have been modified
func (*ChangeTracker) IsEnabled ¶
func (ct *ChangeTracker) IsEnabled() bool
IsEnabled returns whether change tracking is enabled. Production code must call this instead of reading ct.enabled directly.
func (*ChangeTracker) MergeChild ¶ added in v0.16.12
func (ct *ChangeTracker) MergeChild(changes []TrackedFileChange, source string)
MergeChild appends a subagent's tracked changes into this (parent) tracker so list_changes / recover_file / revert_my_changes see subagent edits too. Each merged entry is tagged with Source.
func (*ChangeTracker) PrimeShellTracking ¶
func (ct *ChangeTracker) PrimeShellTracking(workDir string)
PrimeShellTracking captures the workspace's current state as the baseline against which future shell_command invocations are diffed. Idempotent: a second call against the already-primed tracker is a no-op. Safe to call multiple times — only the first does work.
Lazy callers can skip this and rely on TrackShellTurn to auto-prime on first invocation; in that mode the first shell_command's own pre-state is captured but no changes are recorded for it (the initial walk IS the baseline). When the first shell command's mutations need to be tracked, PrimeShellTracking should be called from EnableChangeTracking so the baseline pre-exists.
func (*ChangeTracker) RecordShellMutations ¶
func (ct *ChangeTracker) RecordShellMutations(before, after map[string]*shellSnapshotEntry, toolCall string)
RecordShellMutations diffs a pair of snapshots (before/after a shell_command invocation) and appends TrackedFileChange entries for every file that materially changed. Deduplicates against direct-tool hooks. Above shellBulkThreshold, collapses into bulk rollup.
func (*ChangeTracker) Reset ¶
func (ct *ChangeTracker) Reset(instructions string)
Reset resets the change tracker with a new revision ID and instructions
func (*ChangeTracker) SyncShellCacheForPath ¶
func (ct *ChangeTracker) SyncShellCacheForPath(path string)
SyncShellCacheForPath refreshes the shell cache entry for one path against its current on-disk state. Called by direct file-write hooks so the cache reflects writes the agent just performed.
func (*ChangeTracker) TrackFileEdit ¶
func (ct *ChangeTracker) TrackFileEdit(filePath string, originalContent string, newContent string) error
TrackFileEdit tracks an edit operation (EditFile tool)
func (*ChangeTracker) TrackFileWrite ¶
func (ct *ChangeTracker) TrackFileWrite(filePath string, newContent string) error
TrackFileWrite tracks a write operation (WriteFile tool)
func (*ChangeTracker) TrackShellTurn ¶
func (ct *ChangeTracker) TrackShellTurn(workDir, toolCall string, destructive bool)
TrackShellTurn diffs the workspace against the primed baseline, records mutations, and rebases the baseline to the new state. Auto-primes if the cache hasn't been primed yet (no changes recorded first time). `destructive` enables the safer mode that bypasses autoSkipDirs.
type CheckpointFileChange ¶
CheckpointFileChange is a single file-change entry in a TurnCheckpoint's manifest. Op is one of "A" (added), "M" (modified), "D" (deleted), "R" (renamed) to mirror git's status codes; anything else is "?" (other).
type CheckpointStore ¶ added in v0.16.25
type CheckpointStore interface {
GetTurnCheckpoints() []TurnCheckpoint
SetTurnCheckpoints([]TurnCheckpoint)
AddTurnCheckpoint(TurnCheckpoint)
GetCheckpointMutex() *sync.RWMutex
}
CheckpointStore manages turn checkpoints for state persistence.
type ChoiceOption ¶
ChoiceOption represents a simple label/value option for UI prompts
type CircuitBreakerAction ¶
type CircuitBreakerAction struct {
ActionType string // "edit_file", "shell_command", etc.
Target string // file path, command, etc.
Count int // number of times this action was performed
LastUsed int64 // unix timestamp of last use
}
CircuitBreakerAction tracks repetitive actions for circuit breaker logic
type CircuitBreakerState ¶
type CircuitBreakerState struct {
Actions map[string]*CircuitBreakerAction // key: actionType:target
// contains filtered or unexported fields
}
CircuitBreakerState tracks repetitive actions across the session.
Locking Strategy:
- The Actions map is protected by mu (sync.RWMutex)
- Use RLock/RLock for read-only access when you don't need exclusive access
- Use Lock for write operations or when you need exclusive access
- Always use defer to unlock (defer mu.Unlock() or defer mu.RUnlock())
- Helper functions ending with "Locked" must be called while holding the lock (they perform no locking themselves, allowing callers to hold lock for multiple ops)
Example patterns:
// Read-only access:
cb.mu.RLock()
defer cb.mu.RUnlock()
action := cb.Actions[key]
// Write access:
cb.mu.Lock()
defer cb.mu.Unlock()
cb.Actions[key] = &CircuitBreakerAction{...}
type CircuitBreakerStore ¶ added in v0.16.25
type CircuitBreakerStore interface {
GetCircuitBreaker() *CircuitBreakerState
SetCircuitBreaker(*CircuitBreakerState)
}
CircuitBreakerStore manages the circuit breaker state.
type ClarificationManager ¶
type ClarificationManager struct {
// contains filtered or unexported fields
}
ClarificationManager manages pending clarification requests between subagent and parent agents. It provides thread-safe tracking of clarification requests and responses via channels.
func NewClarificationManager ¶
func NewClarificationManager(eventBus *events.EventBus) *ClarificationManager
NewClarificationManager creates a manager with default 60s timeout.
func NewClarificationManagerWithTimeout ¶
func NewClarificationManagerWithTimeout(eventBus *events.EventBus, timeout time.Duration) *ClarificationManager
NewClarificationManagerWithTimeout creates a manager with a custom timeout.
func (*ClarificationManager) Cleanup ¶
func (m *ClarificationManager) Cleanup()
Cleanup removes expired entries.
func (*ClarificationManager) Close ¶
func (m *ClarificationManager) Close()
Close stops the background cleanup goroutine.
func (*ClarificationManager) GetPendingClarifications ¶
func (m *ClarificationManager) GetPendingClarifications(subagentID string) []ClarificationRequest
GetPendingClarifications returns all pending clarification requests for a subagent.
func (*ClarificationManager) RequestClarification ¶
func (m *ClarificationManager) RequestClarification(ctx context.Context, subagentID, question string) (string, error)
RequestClarification creates a clarification request, publishes an event, and blocks until a response arrives or timeout.
func (*ClarificationManager) RespondClarification ¶
func (m *ClarificationManager) RespondClarification(requestID, response string) error
RespondClarification finds a pending request and sends a response to it.
type ClarificationRequest ¶
type ClarificationRequest struct {
RequestID string `json:"request_id"`
SubagentID string `json:"subagent_id"`
Question string `json:"question"`
CreatedAt time.Time `json:"created_at"`
}
ClarificationRequest is the exported representation of a pending clarification request.
type CommandHistoryStore ¶ added in v0.16.25
type CommandHistoryStore interface {
GetCommandHistory() []string
SetCommandHistory([]string)
GetHistoryIndex() int
SetHistoryIndex(int)
GetHistoryMutex() *sync.Mutex
}
CommandHistoryStore manages command history navigation.
type CommandKind ¶ added in v0.16.19
type CommandKind string
CommandKind categorizes a shell command part by its destructive intent.
const ( CommandKindRm CommandKind = "rm" CommandKindGitPush CommandKind = "git_push" CommandKindGitReset CommandKind = "git_reset" CommandKindKubectl CommandKind = "kubectl" CommandKindDocker CommandKind = "docker" CommandKindChmod CommandKind = "chmod" CommandKindChown CommandKind = "chown" CommandKindWriteRedirect CommandKind = "write_redirect" CommandKindHttpPost CommandKind = "http_post" CommandKindUnknown CommandKind = "unknown" )
func ClassifyShellSegment ¶ added in v0.16.19
func ClassifyShellSegment(segment string) CommandKind
ClassifyShellSegment returns the CommandKind for a single shell segment by matching it against the classification pattern table.
func ClassifyShellSegmentWithSemantic ¶ added in v0.16.19
func ClassifyShellSegmentWithSemantic(segment string) (CommandKind, string)
ClassifyShellSegmentWithSemantic returns the CommandKind and a brief human-readable description for the segment.
type CompactPreview ¶ added in v0.16.4
type CompactPreview struct {
BeforeMessageCount int `json:"before_message_count"`
AfterMessageCount int `json:"after_message_count"`
WouldReduce bool `json:"would_reduce"`
CompactedMessages []api.Message `json:"compacted_messages"`
RemainingCheckpoints []TurnCheckpoint `json:"remaining_checkpoints"`
}
CompactPreview captures the would-be result of running /compact right now, without applying it. Populated only when CaptureTranscriptSnapshot is called with includePreview=true.
type ConfigOverrideStore ¶ added in v0.16.25
type ConfigOverrideStore interface {
GetConfigOverrides() map[string]interface{}
SetConfigOverrides(map[string]interface{})
}
ConfigOverrideStore manages config overrides for the current session.
type ContextBudgetStore ¶ added in v0.16.25
type ContextBudgetStore interface {
GetCurrentContextTokens() int
SetCurrentContextTokens(int)
GetMaxContextTokens() int
SetMaxContextTokens(int)
IsContextWarningIssued() bool
SetContextWarningIssued(bool)
}
ContextBudgetStore manages context window token budgeting and warnings.
type ContextFileInfo ¶
ContextFileInfo represents information about a discovered context file
func DiscoverContextFiles ¶
func DiscoverContextFiles() (*ContextFileInfo, error)
DiscoverContextFiles looks for context files in the current directory and parent directories Returns the first matching file based on priority order
type ContinuationNudgeStore ¶ added in v0.17.18
ContinuationNudgeStore observes seed transient continuation nudges. Seed's "Please continue…" messages are discarded before state sync, so they are invisible in transcripts; the provider seam counts them.
type ConversationOptimizer ¶
type ConversationOptimizer struct {
// contains filtered or unexported fields
}
ConversationOptimizer is sprout's thin wrapper around seed's core.ConversationOptimizer. The dedup + observation-masking implementation moved into seed so other consumers benefit; this wrapper preserves sprout's historical method surface (InvalidateFile, GetOptimizationStats, SetLLMClient) for callers that haven't migrated.
The LLM-based structural compaction that used to live here is now wired through seed's chat loop via Options.LLMSummarizer — see newLLMSummarizer in llm_summarizer.go and the construction site in seed_integration.go. SetLLMClient is consequently a no-op here.
func NewConversationOptimizer ¶
func NewConversationOptimizer(enabled, debug bool) *ConversationOptimizer
NewConversationOptimizer constructs the wrapper. The debug flag is kept for backward-compatible call sites but is unused now that seed's optimizer emits via the EventPublisher instead.
func (*ConversationOptimizer) CompactConversation ¶
func (co *ConversationOptimizer) CompactConversation(messages []api.Message) []api.Message
CompactConversation is retained for backward compatibility with callers that haven't migrated. Structural compaction now runs inside seed's chat loop via core.CompactWithLLMSummary, configured at seed-Agent construction. Calling this here is a no-op; the live request path no longer routes through this method.
func (*ConversationOptimizer) GetOptimizationStats ¶
func (co *ConversationOptimizer) GetOptimizationStats() map[string]interface{}
GetOptimizationStats returns a small status map. The per-file and per-command tracking counts are no longer maintained (seed scans fresh each call); the map shape stays so UI consumers continue to work.
func (*ConversationOptimizer) Inner ¶
func (co *ConversationOptimizer) Inner() *core.ConversationOptimizer
Inner exposes the wrapped seed optimizer for direct use when constructing seed-Agent options (see seed_integration.go).
func (*ConversationOptimizer) InvalidateFile ¶
func (co *ConversationOptimizer) InvalidateFile(filePath string)
InvalidateFile was used by sprout's per-file dedup cache. Seed's optimizer is stateless across calls (it scans the message list fresh each time), so there is no cache to invalidate. Kept as a no-op for caller compatibility.
func (*ConversationOptimizer) IsEnabled ¶
func (co *ConversationOptimizer) IsEnabled() bool
IsEnabled reports whether the optimizer was constructed enabled.
func (*ConversationOptimizer) OptimizeConversation ¶
func (co *ConversationOptimizer) OptimizeConversation(messages []api.Message) []api.Message
OptimizeConversation delegates to the seed optimizer. Returns the input unchanged when the optimizer is disabled.
func (*ConversationOptimizer) Reset ¶
func (co *ConversationOptimizer) Reset()
Reset clears optimizer state. Seed's optimizer is stateless across calls so this is a no-op; preserved for caller compatibility.
func (*ConversationOptimizer) SetEnabled ¶
func (co *ConversationOptimizer) SetEnabled(enabled bool)
SetEnabled toggles the optimizer at runtime. Since seed's optimizer captures Enabled at construction, this rebuilds the inner instance.
func (*ConversationOptimizer) SetLLMClient ¶
func (co *ConversationOptimizer) SetLLMClient(client api.ClientInterface, provider string, printLine func(string))
SetLLMClient is now a no-op. The LLM summary path is wired via seed Options.LLMSummarizer at seed-Agent construction (seed_integration.go).
type ConversationPruner ¶
type ConversationPruner = core.ConversationPruner
ConversationPruner is aliased to seed's core.ConversationPruner so sprout's existing callers (submanager_state.go, pruning_config.go, tests) continue to compile against the same type while the implementation lives in seed and is available to other consumers.
type ConversationPrunerStore ¶ added in v0.16.25
type ConversationPrunerStore interface {
GetConversationPruner() *ConversationPruner
SetConversationPruner(*ConversationPruner)
}
ConversationPrunerStore manages the conversation pruner instance.
type ConversationState ¶
type ConversationState struct {
Messages []api.Message `json:"messages"`
TurnCheckpoints []TurnCheckpoint `json:"turn_checkpoints,omitempty"`
TaskActions []TaskAction `json:"task_actions"`
TotalCost float64 `json:"total_cost"`
TotalTokens int `json:"total_tokens"`
PromptTokens int `json:"prompt_tokens"`
CompletionTokens int `json:"completion_tokens"`
EstimatedTokenResponses int `json:"estimated_token_responses"`
ContinuationNudges int `json:"continuation_nudges,omitempty"` // seed transient "continue" nudges observed (invisible in messages)
CachedTokens int `json:"cached_tokens"`
CacheWriteTokens int `json:"cache_write_tokens,omitempty"`
CachedCostSavings float64 `json:"cached_cost_savings"`
ImageTokens int `json:"image_tokens,omitempty"`
LastUpdated time.Time `json:"last_updated"`
SessionID string `json:"session_id"`
Name string `json:"name"` // Human-readable session name
WorkingDirectory string `json:"working_directory"` // Directory where session was created
InterruptedAt *time.Time `json:"interrupted_at,omitempty"`
RecoveredFromJournal bool `json:"recovered_from_journal,omitempty"`
// ConfigOverrides stores session-scoped configuration overrides.
// Applied on top of global and workspace config when the session is restored.
// Only non-empty values are considered overrides.
ConfigOverrides map[string]interface{} `json:"config_overrides,omitempty"`
// SessionIntentEmbedding stores the embedding of the first user prompt in a session.
// Used for drift detection to track conversation intent over time.
SessionIntentEmbedding []float32 `json:"session_intent_embedding,omitempty"`
// LastProviderError captures details about the last API error from the LLM provider.
// Persisted in the session file so errors can be diagnosed after the fact.
LastProviderError *ProviderErrorInfo `json:"last_provider_error,omitempty"`
}
ConversationState represents the state of a conversation that can be persisted
func ImportStateFromJSONFile ¶
func ImportStateFromJSONFile(filename string) (*ConversationState, error)
ImportStateFromJSONFile loads a ConversationState from a JSON file
func LoadSessionInfo ¶
func LoadSessionInfo(sessionID string) (*ConversationState, error)
LoadSessionInfo loads session information including timestamp
func LoadStateWithoutAgent ¶
func LoadStateWithoutAgent(sessionID string) (*ConversationState, error)
LoadStateWithoutAgent loads a conversation state by session ID without an Agent instance
func LoadStateWithoutAgentScoped ¶
func LoadStateWithoutAgentScoped(sessionID, workingDir string) (*ConversationState, error)
LoadStateWithoutAgentScoped loads a state for a specific working directory scope.
type ConversationTurn ¶
type ConversationTurn struct {
ID string `json:"id"`
SessionID string `json:"session_id"`
TurnNumber int `json:"turn_number"`
Timestamp time.Time `json:"timestamp"`
UserPrompt string `json:"user_prompt"`
ActionableSummary string `json:"actionable_summary,omitempty"`
PromptEmbedding []float32 `json:"prompt_embedding,omitempty"`
FilesTouched []string `json:"files_touched,omitempty"`
WorkingDir string `json:"working_dir"`
Duration float64 `json:"duration"`
TokenUsage int `json:"token_usage"`
}
ConversationTurn represents a completed conversation turn stored for persistent context retrieval and semantic search across sessions.
func NewConversationTurn ¶
func NewConversationTurn(sessionID string, turnNumber int, userPrompt, workingDir string) (*ConversationTurn, error)
NewConversationTurn creates a new ConversationTurn with a generated ID.
func (*ConversationTurn) String ¶
func (t *ConversationTurn) String() string
String returns a human-readable representation of the turn.
func (*ConversationTurn) ToVectorRecord ¶
func (t *ConversationTurn) ToVectorRecord() embedding.VectorRecord
ToVectorRecord converts a ConversationTurn into a VectorRecord for storage.
type CostEntry ¶ added in v0.16.19
type CostEntry struct {
BillingType string `json:"billing_type"`
Provider string `json:"provider"`
Model string `json:"model"`
ChargedCost float64 `json:"charged_cost"`
TokenCost float64 `json:"token_cost,omitempty"`
PromptTokens int `json:"prompt_tokens"`
CompletionTokens int `json:"completion_tokens"`
CachedTokens int `json:"cached_tokens,omitempty"`
ImageTokens int `json:"image_tokens,omitempty"`
}
CostEntry captures a single cost-bearing LLM call with billing-model awareness. It carries two cost numbers:
- ChargedCost: real USD charged for this call (only > 0 for pay_per_token)
- TokenCost: estimated USD value of tokens consumed, from per-model pricing
type CostTracker ¶ added in v0.16.25
type CostTracker interface {
GetTotalCost() float64
SetTotalCost(float64)
AddCost(float64)
AddCostEntry(CostEntry)
GetChargedCostTotal() float64
GetTokenCostTotal() float64
GetSubscriptionTokens() int
GetFreeTokens() int
SetChargedCostTotal(float64)
SetTokenCostTotal(float64)
SetSubscriptionTokens(int)
SetFreeTokens(int)
}
CostTracker manages billing costs, token costs, and subscription/free token counts.
type DiffChange ¶
DiffChange represents a change region in the diff
type DiffLine ¶ added in v0.16.12
type DiffLine struct {
Type DiffLineType
Content string
}
DiffLine represents a single line in a unified diff hunk.
type DiffLineType ¶ added in v0.16.12
type DiffLineType string
DiffLineType identifies whether a diff line is context, added, or removed.
const ( DiffLineContext DiffLineType = "context" DiffLineAdd DiffLineType = "add" DiffLineRemove DiffLineType = "remove" )
type DriftDetector ¶
type DriftDetector struct {
// contains filtered or unexported fields
}
DriftDetector tracks conversational drift by comparing the current turn's embedding against the session's original intent embedding.
func NewDriftDetector ¶
func NewDriftDetector(threshold float64, checkInterval int) *DriftDetector
NewDriftDetector creates a new DriftDetector with the given threshold and check interval. Zero values are replaced with sensible defaults.
func (*DriftDetector) CheckDrift ¶
func (d *DriftDetector) CheckDrift(sessionIntent []float32, currentEmbedding []float32) (isDrift bool, similarity float64)
CheckDrift computes the cosine similarity between the session's original intent embedding and the current turn's embedding. Returns true if the similarity is below the threshold, indicating drift.
If sessionIntent is nil or empty, returns false, 0 as a graceful no-op.
func (*DriftDetector) DriftCount ¶
func (d *DriftDetector) DriftCount() int
DriftCount returns the number of drift detections in this session.
func (*DriftDetector) IsSuppressed ¶
func (d *DriftDetector) IsSuppressed() bool
IsSuppressed returns true if drift detection has been suppressed for this session due to too many rejections.
func (*DriftDetector) RecordAcceptance ¶
func (d *DriftDetector) RecordAcceptance()
RecordAcceptance resets the consecutive rejection counter. Called when the user chooses "Continue here" (accepts) in response to a drift notification.
func (*DriftDetector) RecordDrift ¶
func (d *DriftDetector) RecordDrift()
RecordDrift increments the drift detection counter for this session.
func (*DriftDetector) RecordRejection ¶
func (d *DriftDetector) RecordRejection()
RecordRejection increments the consecutive rejection counter and suppresses drift detection if the user has rejected MaxDriftRejections times in a row.
func (*DriftDetector) RejectionCount ¶
func (d *DriftDetector) RejectionCount() int
RejectionCount returns the number of consecutive drift rejections. This counter is reset to 0 when RecordAcceptance is called.
func (*DriftDetector) ShouldCheck ¶
func (d *DriftDetector) ShouldCheck(turnNumber int) bool
ShouldCheck returns true if drift should be checked on the given turn number. Checks occur every checkInterval turns (turn 5, 10, 15, ...). Returns false if the detector is suppressed.
type DriftNotification ¶
type DriftNotification struct {
// contains filtered or unexported fields
}
DriftNotification handles emitting drift notifications through the event bus. The notification is non-blocking — the agent continues processing after emission.
func NewDriftNotification ¶
func NewDriftNotification(detector *DriftDetector, eventBus *events.EventBus, sessionID string) *DriftNotification
NewDriftNotification creates a new drift notification handler.
func (*DriftNotification) NotifyDrift ¶
func (n *DriftNotification) NotifyDrift(similarity float64, threshold float64) map[string]interface{}
NotifyDrift emits a drift detection event via the EventBus (for WebUI). Returns the notification data so the CLI layer can use it for display. This is non-blocking — it does not wait for user response.
type DropdownItem ¶
DropdownItem represents an item in a dropdown selection
type DropdownOptions ¶
DropdownOptions provides options for dropdown display
type EditDecision ¶ added in v0.16.12
EditDecision captures the user's per-hunk accept/reject choices.
type EditProposal ¶ added in v0.16.12
EditProposal describes a proposed file edit awaiting approval.
type EstimatedTokenStore ¶ added in v0.16.25
type EstimatedTokenStore interface {
GetEstimatedTokenResponses() int
SetEstimatedTokenResponses(int)
}
EstimatedTokenStore manages estimated token response counts.
type FalseStopStore ¶ added in v0.16.25
type FalseStopStore interface {
IsFalseStopDetectionEnabled() bool
SetFalseStopDetectionEnabled(bool)
}
FalseStopStore manages false stop detection enablement.
type FileAccessDecision ¶ added in v0.17.7
type FileAccessDecision int
FileAccessDecision describes the resolved verdict for a file-path operation from Gate 1's path-tier classifier.
const ( // FileAccessAllow: path is in an allowlisted location (workspace root, // session-allowlisted folder, or /tmp). FileAccessAllow FileAccessDecision = iota // FileAccessPrompt: path is outside the allowlist and not hard-blocked; // user must approve. FileAccessPrompt // FileAccessDeny: path targets a known hard-block location or violates // a declared read_only constraint. FileAccessDeny )
type FileChange ¶
type FileChange struct {
Path string `json:"path"`
Op string `json:"op"` // "created" | "modified" | "deleted"
}
FileChange is a single tracked write/edit/delete from a subagent run.
type FleetUsdBudget ¶ added in v0.16.4
type FleetUsdBudget struct {
// contains filtered or unexported fields
}
FleetUsdBudget caps the total USD cost across a primary agent and every subagent it spawns. It mirrors the token-based fleetBudget mechanism but in USD because mixed-provider workflows can't be reasonably capped by tokens — a token cap that fits an Opus orchestrator would let a DeepSeek coder run effectively unbounded for the same numeric value.
Threshold warnings are emitted at most once per threshold per budget instance (warnedIdx is monotonic). The truncation flag (Exceeded) is sticky once set — the agent's conversation loop polls it to stop gracefully after the current LLM response.
func NewFleetUsdBudget ¶ added in v0.16.4
func NewFleetUsdBudget(limit float64, warnAt []float64) *FleetUsdBudget
NewFleetUsdBudget returns a budget with the given hard cap (USD) and warning thresholds (fractions of the cap in (0, 1]). The thresholds are copied and sorted so the caller can pass them in any order.
func (*FleetUsdBudget) Add ¶ added in v0.16.4
func (b *FleetUsdBudget) Add(cost float64) (newSpent float64, crossed []float64, justExceeded bool)
Add debits a cost to the budget. Returns:
- newSpent: the cumulative spend after the addition
- crossed: the warning thresholds (as fractions of the limit) that this call newly crossed — empty if none
- justExceeded: true only on the call that first pushes spent past limit
When the cap is hit, the exceeded flag is set so the conversation loop can observe it via Exceeded() and stop gracefully. Subsequent calls still accumulate spend (so reporting stays accurate) but exceeded stays sticky and crossed stays empty.
func (*FleetUsdBudget) Exceeded ¶ added in v0.16.4
func (b *FleetUsdBudget) Exceeded() bool
Exceeded reports whether the budget has been reached or surpassed.
func (*FleetUsdBudget) Snapshot ¶ added in v0.16.4
func (b *FleetUsdBudget) Snapshot() (spent, limit float64)
Snapshot returns the current spend and limit for display purposes.
type Hunk ¶ added in v0.16.12
Hunk represents a discrete change region in a unified diff.
func SplitIntoHunks ¶ added in v0.16.12
SplitIntoHunks computes the unified diff and splits it into discrete hunks with stable IDs.
type IterationStore ¶ added in v0.16.25
IterationStore manages the current iteration count.
type LLMCallTracker ¶ added in v0.16.25
type LLMCallTracker interface {
GetLLMCallCount() int
SetLLMCallCount(int)
IncrementLLMCallCount()
}
LLMCallTracker manages LLM call count tracking.
type LogContext ¶
type LogContext struct {
// contains filtered or unexported fields
}
LogContext allows chaining fields for multiple log entries
func (*LogContext) Debug ¶
func (lc *LogContext) Debug(format string, args ...interface{})
Debug writes a debug-level log with context fields from the LogContext
func (*LogContext) Error ¶
func (lc *LogContext) Error(format string, args ...interface{})
Error writes an error-level log with context fields from the LogContext
func (*LogContext) Info ¶
func (lc *LogContext) Info(format string, args ...interface{})
Info writes an info-level log with context fields from the LogContext
func (*LogContext) Warn ¶
func (lc *LogContext) Warn(format string, args ...interface{})
Warn writes a warn-level log with context fields from the LogContext
type LogEntry ¶
type LogEntry struct {
Timestamp string `json:"timestamp"`
Level string `json:"level"` // "debug", "info", "warn", "error"
Message string `json:"message"`
SessionID string `json:"session_id,omitempty"`
Iteration int `json:"iteration,omitempty"`
Provider string `json:"provider,omitempty"`
Model string `json:"model,omitempty"`
Fields map[string]string `json:"fields,omitempty"`
}
LogEntry represents a structured log entry
type MCPSubManager ¶
type MCPSubManager interface {
GetManager() mcp.MCPManager
SetManager(mgr mcp.MCPManager)
GetToolsCache() []api.Tool
SetToolsCache(tools []api.Tool)
IsInitialized() bool
SetInitialized(initialized bool)
GetInitError() error
SetInitError(err error)
LockInit()
UnlockInit()
}
MCPSubManager manages all MCP-related state for an Agent.
type MemoryGate ¶ added in v0.16.19
type MemoryGate struct {
// MinMemoryBytes is the hard minimum; below this the gate refuses immediately. Default: 8 GB.
MinMemoryBytes int64
// RetryMinBytes is the retry threshold; between MinMemoryBytes and this value the gate sleeps and retries. Default: 16 GB.
RetryMinBytes int64
// RetrySleep is the duration to sleep between retries. Default: 30s.
RetrySleep time.Duration
// MaxRetries is the maximum number of retry attempts. Default: 5.
MaxRetries int
// contains filtered or unexported fields
}
MemoryGate checks available system memory before allowing memory-intensive operations.
func DefaultMemoryGate ¶ added in v0.16.19
func DefaultMemoryGate() *MemoryGate
DefaultMemoryGate returns a MemoryGate with production defaults.
func (*MemoryGate) Check ¶ added in v0.16.19
func (g *MemoryGate) Check() error
Check verifies that sufficient memory is available. Returns nil when sufficient or check fails (fail-open). Returns *MemoryGateError when memory is below the threshold.
type MemoryGateError ¶ added in v0.16.19
MemoryGateError is returned when available memory is below the threshold.
func (*MemoryGateError) Error ¶ added in v0.16.19
func (e *MemoryGateError) Error() string
type MemoryInfo ¶
type MemoryInfo struct {
Name string // Memory name, derived from filename (without .md extension)
Path string // Full file path
Content string // File content string
}
MemoryInfo represents information about a memory file
func ListMemories ¶
func ListMemories() ([]MemoryInfo, error)
ListMemories returns list of all memories with their name, path, and first line (title/heading) Sorts alphabetically by name
func LoadAllMemories ¶
func LoadAllMemories() ([]MemoryInfo, error)
LoadAllMemories reads all .md files from the memories directory Returns a slice of MemoryInfo sorted by filename Returns empty slice (not error) if no memories exist
type MessageAnnotation ¶ added in v0.16.4
type MessageAnnotation struct {
Index int `json:"index"`
Role string `json:"role"`
Source MessageSource `json:"source"`
ContentChars int `json:"content_chars"`
ToolCallCount int `json:"tool_call_count,omitempty"`
FirstLine string `json:"first_line,omitempty"`
}
MessageAnnotation is the per-message diagnostic view. Index aligns 1:1 with TranscriptSnapshot.State.Messages.
type MessageImportance ¶
type MessageImportance = core.MessageImportance
MessageImportance is aliased from seed for tests/diagnostics that inspect the structured score output of the importance scorer.
type MessageSource ¶ added in v0.16.4
type MessageSource string
MessageSource tags how a message arrived in the live conversation. It is the single most useful diagnostic field in a snapshot: it tells a reader whether what the model sees at index i is the user's original turn, a turn collapsed to a rule-based heuristic bullet list, or a structural summary produced by seed's LLM summarizer.
const ( MessageSourceOriginal MessageSource = "original" MessageSourceLLMCheckpoint MessageSource = "llm_checkpoint" )
type MessageStore ¶ added in v0.16.25
type MessageStore interface {
GetMessages() []api.Message
SetMessages([]api.Message)
AddMessage(api.Message)
GetMessageTimestamps() []time.Time
SetMessageTimestamps([]time.Time)
}
MessageStore manages conversation messages and their timestamps.
type MockLLMProvider ¶ added in v0.16.18
type MockLLMProvider struct {
ResponsesByPrompt map[string]string // substring match (case-insensitive) on last user message
DefaultResponse string
CallCount int
// contains filtered or unexported fields
}
MockLLMProvider implements api.ClientInterface with canned responses. Thread-safe.
func NewMockLLMProvider ¶ added in v0.16.18
func NewMockLLMProvider() *MockLLMProvider
NewMockLLMProvider creates a new mock LLM provider with sensible defaults.
func NewMockLLMProviderWithLimit ¶ added in v0.17.7
func NewMockLLMProviderWithLimit(limit int) *MockLLMProvider
NewMockLLMProviderWithLimit creates a mock provider with a specific context window for testing LCM and context floor.
func (*MockLLMProvider) CheckConnection ¶ added in v0.16.18
func (m *MockLLMProvider) CheckConnection() error
CheckConnection always succeeds.
func (*MockLLMProvider) GetAverageTPS ¶ added in v0.16.18
func (m *MockLLMProvider) GetAverageTPS() float64
GetAverageTPS returns a mock TPS value.
func (*MockLLMProvider) GetLastTPS ¶ added in v0.16.18
func (m *MockLLMProvider) GetLastTPS() float64
GetLastTPS returns a mock TPS value.
func (*MockLLMProvider) GetModel ¶ added in v0.16.18
func (m *MockLLMProvider) GetModel() string
GetModel returns the current model name.
func (*MockLLMProvider) GetModelContextLimit ¶ added in v0.16.18
func (m *MockLLMProvider) GetModelContextLimit() (int, error)
GetModelContextLimit returns a fixed context limit. Default 128K; use NewMockLLMProviderWithLimit for smaller windows.
func (*MockLLMProvider) GetProvider ¶ added in v0.16.18
func (m *MockLLMProvider) GetProvider() string
GetProvider returns the provider name.
func (*MockLLMProvider) GetTPSStats ¶ added in v0.16.18
func (m *MockLLMProvider) GetTPSStats() map[string]float64
GetTPSStats returns mock TPS stats.
func (*MockLLMProvider) GetVisionModel ¶ added in v0.16.18
func (m *MockLLMProvider) GetVisionModel() string
GetVisionModel returns empty string.
func (*MockLLMProvider) ListModels ¶ added in v0.16.18
ListModels returns a single mock model.
func (*MockLLMProvider) ResetTPSStats ¶ added in v0.16.18
func (m *MockLLMProvider) ResetTPSStats()
ResetTPSStats is a no-op.
func (*MockLLMProvider) SendChatRequest ¶ added in v0.16.18
func (m *MockLLMProvider) SendChatRequest(ctx context.Context, messages []api.Message, tools []api.Tool, reasoning string, disableThinking bool) (*api.ChatResponse, error)
SendChatRequest sends a chat request and returns a canned response.
func (*MockLLMProvider) SendChatRequestStream ¶ added in v0.16.18
func (m *MockLLMProvider) SendChatRequestStream(ctx context.Context, messages []api.Message, tools []api.Tool, reasoning string, disableThinking bool, callback api.StreamCallback) (*api.ChatResponse, error)
SendChatRequestStream streams a canned response.
func (*MockLLMProvider) SendVisionRequest ¶ added in v0.16.18
func (m *MockLLMProvider) SendVisionRequest(ctx context.Context, messages []api.Message, tools []api.Tool, reasoning string, disableThinking bool) (*api.ChatResponse, error)
SendVisionRequest returns an error (vision not supported).
func (*MockLLMProvider) SetDebug ¶ added in v0.16.18
func (m *MockLLMProvider) SetDebug(debug bool)
SetDebug sets debug mode.
func (*MockLLMProvider) SetModel ¶ added in v0.16.18
func (m *MockLLMProvider) SetModel(model string) error
SetModel sets the model name.
func (*MockLLMProvider) SupportsConversationalVision ¶ added in v0.16.19
func (m *MockLLMProvider) SupportsConversationalVision() bool
SupportsConversationalVision returns false; the mock never participates in inline multimodal turns.
func (*MockLLMProvider) SupportsVision ¶ added in v0.16.18
func (m *MockLLMProvider) SupportsVision() bool
SupportsVision returns false.
func (*MockLLMProvider) VisionCapabilities ¶ added in v0.16.20
func (m *MockLLMProvider) VisionCapabilities() api.VisionCapabilities
VisionCapabilities returns the safe defaults. Required by api.ClientInterface; keeps mock-routed requests harmless.
type ModelItem ¶
type ModelItem struct {
Label string
Value string
Provider string
Model string
InputCost float64
OutputCost float64
LegacyCost float64
ContextLength int
Tags []string
}
ModelItem represents a model in dropdown selections
type Notification ¶ added in v0.16.19
type Notification struct {
Content string // formatted message for the agent
SessionID string // bg session or automate session ID
Kind NotificationKind // source of the notification
Timestamp time.Time // when the notification was queued
}
Notification is a durable completion message queued when a background task finishes. It survives turn boundaries — unlike channel-based injection (InjectInputContext), which loses messages when the forwarder goroutine dies at turn end.
func (Notification) FormatForAgent ¶ added in v0.16.19
func (n Notification) FormatForAgent() string
type NotificationKind ¶ added in v0.16.19
type NotificationKind string
NotificationKind classifies the source of a background completion notification.
const ( NotifAutomate NotificationKind = "automate" NotifShellBg NotificationKind = "shell_bg" NotifShellBgTimeout NotificationKind = "shell_bg_timeout" )
type OOMProbeResult ¶ added in v0.16.19
OOMProbeResult holds the result of a single OOM probe scan.
type OOMWatchdog ¶ added in v0.16.19
type OOMWatchdog struct {
// contains filtered or unexported fields
}
OOMWatchdog monitors Node.js process count and total RSS via /proc scanning. It alerts BEFORE the kernel OOM-killer fires by publishing events when thresholds are exceeded.
func NewOOMWatchdog ¶ added in v0.16.19
func NewOOMWatchdog(eventBus *events.EventBus) *OOMWatchdog
NewOOMWatchdog creates a watchdog with sensible defaults.
func (*OOMWatchdog) Start ¶ added in v0.16.19
func (w *OOMWatchdog) Start(ctx context.Context)
Start launches a background goroutine that probes at the configured interval. The goroutine exits when ctx is cancelled.
func (*OOMWatchdog) Stop ¶ added in v0.16.19
func (w *OOMWatchdog) Stop()
Stop is a no-op. The watchdog goroutine is driven by context cancellation — call cancel() on the context passed to Start() to stop it. This method exists for API symmetry with other watchdog interfaces.
type OptimizerStore ¶ added in v0.16.25
type OptimizerStore interface {
GetOptimizer() *ConversationOptimizer
SetOptimizer(*ConversationOptimizer)
}
OptimizerStore manages the conversation optimizer instance.
type OrderedMap ¶ added in v0.16.4
type OrderedMap struct {
// contains filtered or unexported fields
}
OrderedMap wraps orderedmap.OrderedMap[string, interface{}] to preserve key insertion order throughout the structured file pipeline. All nested map[string]interface{} values are recursively converted so that ordering is maintained at every depth.
func NewOrderedMap ¶ added in v0.16.4
func NewOrderedMap() *OrderedMap
NewOrderedMap creates an empty OrderedMap.
func OrderedMapFromMap ¶ added in v0.16.4
func OrderedMapFromMap(m map[string]interface{}) *OrderedMap
OrderedMapFromMap converts a regular map[string]interface{} into an OrderedMap. Keys are sorted alphabetically to provide a deterministic (though not original-source) order. Nested maps and slices are converted recursively. This is intended as a fallback when source order is unavailable.
func ParseJSONOrdered ¶ added in v0.16.4
func ParseJSONOrdered(content string) (*OrderedMap, error)
ParseJSONOrdered parses a JSON string into an *OrderedMap, preserving the key order from the source text. Only top-level objects are supported — passing a top-level array or scalar returns an error.
Nested objects are recursively wrapped in *OrderedMap. Arrays become []interface{} slices where any contained objects are also *OrderedMap values.
func ParseYAMLOrdered ¶ added in v0.16.4
func ParseYAMLOrdered(content string) (*OrderedMap, error)
ParseYAMLOrdered parses a YAML string into an *OrderedMap, preserving the key order from the source text. The YAML content must represent a mapping (object) at the top level. Nested mappings are recursively wrapped in *OrderedMap so that ordering is maintained at every depth.
This function uses yaml.Node to walk the parsed tree, which preserves the original key ordering from the source document.
func (*OrderedMap) Delete ¶ added in v0.16.4
func (om *OrderedMap) Delete(key string)
Delete removes the key from the map.
func (*OrderedMap) Get ¶ added in v0.16.4
func (om *OrderedMap) Get(key string) (interface{}, bool)
Get retrieves the value for the given key. The second return value indicates whether the key was present.
func (*OrderedMap) InOrder ¶ added in v0.16.4
func (om *OrderedMap) InOrder() []orderedmap.Pair[string, interface{}]
InOrder returns all pairs in insertion order.
func (*OrderedMap) Keys ¶ added in v0.16.4
func (om *OrderedMap) Keys() []string
Keys returns all keys in insertion order.
func (*OrderedMap) Len ¶ added in v0.16.4
func (om *OrderedMap) Len() int
Len returns the number of key-value pairs.
func (*OrderedMap) Set ¶ added in v0.16.4
func (om *OrderedMap) Set(key string, value interface{})
Set stores the key-value pair. If the key already exists its value is replaced but the original insertion position is preserved (matching the underlying library semantics).
func (*OrderedMap) String ¶ added in v0.16.4
func (om *OrderedMap) String() string
String returns a human-readable representation useful for debugging.
func (*OrderedMap) ToMap ¶ added in v0.16.4
func (om *OrderedMap) ToMap() map[string]interface{}
ToMap converts the OrderedMap to a standard map[string]interface{}. Nested OrderedMap values are recursively converted back. This is useful for compatibility with existing code that expects regular maps.
type OutputBuffer ¶
type OutputBuffer struct {
// contains filtered or unexported fields
}
OutputBuffer captures agent output for controlled display
func NewOutputBuffer ¶
func NewOutputBuffer() *OutputBuffer
NewOutputBuffer creates a new output buffer
func (*OutputBuffer) GetAndClear ¶
func (ob *OutputBuffer) GetAndClear() string
GetAndClear returns the output and clears the buffer
func (*OutputBuffer) GetOutput ¶
func (ob *OutputBuffer) GetOutput() string
GetOutput returns the captured output
func (*OutputBuffer) Print ¶
func (ob *OutputBuffer) Print(args ...interface{})
Print captures output
func (*OutputBuffer) Printf ¶
func (ob *OutputBuffer) Printf(format string, args ...interface{})
Printf captures formatted output
func (*OutputBuffer) Println ¶
func (ob *OutputBuffer) Println(args ...interface{})
Println captures output with newline
type OutputManager ¶
type OutputManager interface {
SetStreamingEnabled(enabled bool)
IsStreamingEnabled() bool
SetStreamingCallback(cb func(string))
GetStreamingCallback() func(string)
SetReasoningCallback(cb func(string))
GetReasoningCallback() func(string)
SetFlushCallback(cb func())
GetFlushCallback() func()
SetOutputMutex(mu *sync.Mutex)
GetOutputMutex() *sync.Mutex
GetStreamingBuffer() *strings.Builder
GetReasoningBuffer() *strings.Builder
GetOutputRouter() *OutputRouter
SetOutputRouter(router *OutputRouter)
GetAsyncOutput() chan string
SetAsyncOutput(ch chan string)
EnsureAsyncOutputWorker(fn func())
GetAsyncBufferSize() int
SetAsyncBufferSize(size int)
GetEventMetadata() map[string]interface{}
SetEventMetadata(meta map[string]interface{})
SetEventMetadataUnlocked(meta map[string]interface{})
GetEventMetadataMutex() *sync.RWMutex
SetTerminalWriter(fn func(string))
GetTerminalWriter() func(string)
}
OutputManager manages all output and streaming-related state for an Agent.
type OutputMode ¶
type OutputMode int
OutputMode determines how output is routed
const ( OutputModeTerminal OutputMode = iota // CLI-only, no event bus OutputModeEventSourced // EventBus + terminal bridge )
type OutputRouter ¶
type OutputRouter struct {
// contains filtered or unexported fields
}
OutputRouter is the single routing point for all agent output. Routes to event bus (WebUI) and/or terminal.
func NewOutputRouter ¶
func NewOutputRouter(agent *Agent, eventBus *events.EventBus) *OutputRouter
NewOutputRouter creates an output router. If eventBus is nil, operates in terminal-only mode. agent may be nil during early initialization; set it later via the field directly.
func (*OutputRouter) FlushExternalWrite ¶ added in v0.17.10
func (r *OutputRouter) FlushExternalWrite()
FlushExternalWrite fires the external-write hook if one is registered. Used by the terminal subscriber to flush prose before tool chrome.
func (*OutputRouter) Mode ¶
func (r *OutputRouter) Mode() OutputMode
Mode returns the current output mode
func (*OutputRouter) RouteAgentMessage ¶
func (r *OutputRouter) RouteAgentMessage(category, message string, extra map[string]interface{})
RouteAgentMessage routes an agent system message to both WebUI (via event bus) and terminal.
func (*OutputRouter) RouteStreamChunk ¶
func (r *OutputRouter) RouteStreamChunk(chunk string, contentType string)
RouteStreamChunk routes a streaming chunk to the event bus and, when allowed, to terminal output.
func (*OutputRouter) RouteTerminalOnly ¶
func (r *OutputRouter) RouteTerminalOnly(message string)
RouteTerminalOnly writes a message directly to the terminal without publishing to the event bus.
func (*OutputRouter) RouteToolCompletion ¶
func (r *OutputRouter) RouteToolCompletion(ok bool, duration time.Duration, errMsg string)
RouteToolCompletion emits the inline duration/outcome chip for the WebUI. Terminal output is handled by the subscriber.
func (*OutputRouter) RouteToolLog ¶
func (r *OutputRouter) RouteToolLog(action string, target string)
RouteToolLog routes a tool execution log message. Terminal output is handled by the terminal subscriber; this publishes the WebUI event.
func (*OutputRouter) SetEventBus ¶
func (r *OutputRouter) SetEventBus(eventBus *events.EventBus)
SetEventBus updates the event bus (called when webui connects/disconnects). The streamingCallback on the agent is NOT affected — it always routes to the terminal regardless of WebUI state.
func (*OutputRouter) SetExternalWriteHook ¶
func (r *OutputRouter) SetExternalWriteHook(fn func())
SetExternalWriteHook registers a callback that fires before every writeTerminalMessage emission. Pass nil to clear.
func (*OutputRouter) SetReasoningCallback ¶ added in v0.16.2
func (r *OutputRouter) SetReasoningCallback(fn func(string))
SetReasoningCallback registers a dedicated sink for reasoning chunks so the CLI can render a collapsed header. Pass nil to clear.
func (*OutputRouter) SetReasoningTerminalEnabled ¶
func (r *OutputRouter) SetReasoningTerminalEnabled(enabled bool)
SetReasoningTerminalEnabled controls whether reasoning chunks are rendered in the terminal. It is disabled by default so reasoning stays available to the event bus/WebUI without polluting normal CLI output.
func (*OutputRouter) SetTerminalSubscriberActive ¶ added in v0.16.19
func (r *OutputRouter) SetTerminalSubscriberActive(active bool)
SetTerminalSubscriberActive marks whether a terminal subscriber owns agent_message rendering. When true, skip the raw write fallback.
func (*OutputRouter) TerminalSubscriberActive ¶ added in v0.16.25
func (r *OutputRouter) TerminalSubscriberActive() bool
TerminalSubscriberActive reports whether a terminal subscriber owns terminal rendering. Used to suppress duplicate output.
func (*OutputRouter) Write ¶ added in v0.16.19
func (r *OutputRouter) Write(p []byte) (int, error)
Write implements io.Writer so OutputRouter can be used directly as the OutputWriter in tools.ToolEnv. It buffers partial lines and flushes them on newline boundaries via the agent's PrintLineAsync, avoiding the need to allocate a separate outputRouter wrapper per tool call.
type PathTier ¶
type PathTier int
PathTier classifies a filesystem path for approval purposes. See ClassifyPathAccess for the resolution rules. The tiers are ordered from least to most restrictive.
const ( // PathTierUnknown is the zero value and shouldn't be returned; // it exists so a missing tier shows up loudly in tests rather // than silently behaving as "allow". PathTierUnknown PathTier = iota // PathTierWorkspace — the path is inside the agent's workspace // root (or the sprout config dir). No approval required. PathTierWorkspace // PathTierExternal — outside the workspace but not in a system // or off-CWD home directory. Eligible for the "Allow this folder // for the rest of the session" approval choice. Once a parent // folder is in the agent's session allowlist, future accesses // under it auto-approve. PathTierExternal // PathTierSensitive — system directories (/etc, /usr, ...) OR // home-directory paths when the agent's CWD is outside the user's // home. These ALWAYS prompt and CANNOT be added to the session // allowlist. The "Allow folder this session" choice is hidden // from the dialog for this tier. PathTierSensitive )
func ClassifyPathAccess ¶
ClassifyPathAccess decides which approval tier a path falls into. All three input paths should be absolute (or empty for unset fields). Behavior:
- Inside workspaceRoot → PathTierWorkspace.
- Under a known system directory (e.g. /etc, /usr, /var on Unix; C:\Windows, C:\Program Files on Windows) → PathTierSensitive.
- Under the user's home dir AND the agent's CWD is NOT under home → PathTierSensitive (working in /tmp, accessing ~ is unusual and shouldn't get session-wide allowlisting).
- Anything else outside the workspace → PathTierExternal.
homeDir and cwd are passed explicitly so tests can drive each branch deterministically. Production callers use os.UserHomeDir and the agent's effective CWD.
Symlinks: this classifier compares cleaned path strings; it does NOT call filepath.EvalSymlinks. The filesystem layer (pkg/filesystem) resolves symlinks before returning ErrOutsideWorkingDirectory, so the path we receive here is already the symlink-resolved target — the comparison is correct for cases where the filesystem layer hands us a real path. For non-filesystem callers (e.g. the WebUI file API consulting IsFolderSessionAllowed), the path is whatever the caller resolved. The classifier is therefore advisory: if you've crafted a clever symlink to dodge tier classification, the filesystem layer still enforces its own checks at write time.
type PauseState ¶
type PauseState struct {
IsPaused bool `json:"is_paused"`
PausedAt time.Time `json:"paused_at"`
OriginalTask string `json:"original_task"`
Clarifications []string `json:"clarifications"`
MessagesBefore []api.Message `json:"messages_before"`
}
PauseState tracks the state when a task is paused for clarification
type PauseStore ¶ added in v0.16.25
type PauseStore interface {
GetPauseState() *PauseState
SetPauseState(*PauseState)
GetPauseMutex() *sync.Mutex
}
PauseStore manages pause state and its mutex.
type PendingStateStore ¶ added in v0.16.25
type PendingStateStore interface {
GetPendingSwitchContextRefresh() string
SetPendingSwitchContextRefresh(string)
GetPendingStrictSwitchNotice() string
SetPendingStrictSwitchNotice(string)
GetPendingSystemSupplement() string
SetPendingSystemSupplement(string)
}
PendingStateStore manages pending state that will be applied on the next turn.
type PersonaStore ¶ added in v0.16.25
type PersonaStore interface {
GetActiveSkills() []string
SetActiveSkills([]string)
GetActivePersona() string
SetActivePersona(string)
}
PersonaStore manages active skills and persona.
type ProactiveContextConfig ¶
type ProactiveContextConfig struct {
// MinRelevanceScore is the minimum time-decayed similarity score required
// for a result to be included. Default: 0.50.
MinRelevanceScore float64
// MaxContextualResults caps the number of results returned. Default: 5.
MaxContextualResults int
// MaxContextChars is the character budget for FormatProactiveContext.
// The formatted string is truncated at this limit. Default: 4000.
MaxContextChars int
// WorkspaceScoped, if true, filters to turns from the same workingDir.
// Default: true. Cross-workspace bleed is almost always noise.
WorkspaceScoped bool
// RetentionDays controls how many days to keep persistent context entries.
// Default: 0 (forever, never expire).
RetentionDays int
}
ProactiveContextConfig holds configuration for proactive context retrieval.
func DefaultProactiveContextConfig ¶
func DefaultProactiveContextConfig() ProactiveContextConfig
DefaultProactiveContextConfig returns a ProactiveContextConfig with standard defaults.
type ProactiveContextResult ¶
type ProactiveContextResult struct {
Record embedding.VectorRecord
Score float64 // time-decayed cosine similarity
}
ProactiveContextResult holds a retrieved conversation turn with its time-decayed similarity score.
func RetrieveProactiveContext ¶
func RetrieveProactiveContext( ctx context.Context, mgr *embedding.EmbeddingManager, config ProactiveContextConfig, query string, workingDir string, now time.Time, ) ([]ProactiveContextResult, error)
RetrieveProactiveContext retrieves relevant conversation turns from the conversation store based on semantic similarity with time-decay scoring.
Pipeline: embed query → HNSW top-K → filter type/workspace → re-score with decay → cap results. Falls back to brute-force LoadAll for stores under 2000 records if HNSW returns no matches. Graceful degradation: all errors are logged and nil/empty is returned.
type ProgressEntry ¶
type ProgressEntry struct {
OffsetMS int64 `json:"offset_ms"`
Phase string `json:"phase"`
Message string `json:"message"`
}
ProgressEntry is the envelope-facing form of SubagentProgressEntry, kept separately from the runner-internal type so the runner struct can change without affecting the wire shape.
type ProjectInfo ¶
type ProjectInfo struct {
Path string // Absolute path to project root
Name string // Directory name or project name from AGENTS.md
Description string // First paragraph from AGENTS.md if present
HasAgentsMd bool // Whether project has AGENTS.md
HasGitRepo bool // Whether project has .git directory
Languages []string // Detected languages (from file extensions, go.mod, package.json, etc.)
RelPath string // Relative path from home directory
}
func DiscoverProjects ¶
func DiscoverProjects(homeDir string, maxDepth int) ([]ProjectInfo, error)
type PromptTokensDetails ¶
type PromptTokensDetails struct {
CachedTokens int `json:"cached_tokens"`
CacheWriteTokens *int `json:"cache_write_tokens"`
}
PromptTokensDetails contains detailed breakdown of prompt tokens
type ProviderErrorInfo ¶
type ProviderErrorInfo struct {
Timestamp string `json:"timestamp"` // ISO 8601 when the error occurred
Provider string `json:"provider"` // e.g. "zai", "openrouter"
Model string `json:"model"` // e.g. "glm-5.1"
StatusCode int `json:"status_code,omitempty"` // HTTP status code (400, 429, 500, etc.)
ErrorType string `json:"error_type,omitempty"` // e.g. "api_error_400", "streaming_response"
Message string `json:"message"` // The error message from the provider
Retries int `json:"retries,omitempty"` // Number of retries attempted
}
ProviderErrorInfo captures details about the last API error from the LLM provider. This is persisted in the session file so errors can be diagnosed after the fact.
type ProviderErrorStore ¶ added in v0.16.25
type ProviderErrorStore interface {
GetLastProviderError() *ProviderErrorInfo
SetLastProviderError(*ProviderErrorInfo)
}
ProviderErrorStore manages the last provider error information.
type PruningStrategy ¶
type PruningStrategy = core.PruningStrategy
PruningStrategy is aliased to seed's strategy type. Sprout's constants below mirror seed's so call sites need no rewrite.
type QueryGuardOwner ¶ added in v0.17.20
type QueryGuardOwner struct {
Source string // one of the QuerySource* constants
StartedAt time.Time // when the holder acquired the guard
}
QueryGuardOwner identifies what currently holds the agent's query guard.
type QuickOption ¶
QuickOption represents a quick choice option
type RateLimitExceededError ¶
RateLimitExceededError indicates repeated rate limit failures even after retries. This type is referenced by the scripted test client and must be available outside of the (now-deleted) APIClient file.
func (*RateLimitExceededError) Error ¶
func (e *RateLimitExceededError) Error() string
func (*RateLimitExceededError) Unwrap ¶
func (e *RateLimitExceededError) Unwrap() error
type RecallMetricsRecord ¶ added in v0.16.19
type RecallMetricsRecord struct {
Timestamp string `json:"timestamp"` // RFC3339
SessionID string `json:"session_id,omitempty"`
ItemsRecalled int `json:"items_recalled"`
TopSimilarity float64 `json:"top_similarity"`
UsedInResponse bool `json:"used_in_response"`
CheckpointIDs []string `json:"checkpoint_ids,omitempty"`
Workspaces []string `json:"workspaces,omitempty"`
RecallLatencyMS int64 `json:"recall_latency_ms"`
RecallQuery string `json:"recall_query,omitempty"` // first 200 runes, for debugging
}
RecallMetricsRecord is the per-turn entry persisted to recall_metrics.jsonl.
type RecalledItem ¶ added in v0.16.4
type RecalledItem struct {
CheckpointID string
Level int
StartIndex int
EndIndex int
Similarity float32
AgeDays float64
Score float64
Summary string
Actionable string
Workspace string
}
RecalledItem is one historical summary retrieved by the semantic recall pass and surfaced to the model on the next prompt. It carries both the scored numbers (for telemetry) and the text the prompt will render.
type ReconciliationActionResult ¶
type ReconciliationActionResult struct {
FilePath string `json:"file_path"`
Action ReconciliationActionType `json:"action"`
ContainerSeq int64 `json:"container_seq"`
BrowserSeq int64 `json:"browser_seq"`
}
ReconciliationActionResult is the per-file reconciliation outcome.
func ReconcileSeqNumbers ¶
func ReconcileSeqNumbers(ag *Agent, browserSeqs map[string]int64) ([]ReconciliationActionResult, error)
ReconcileSeqNumbers compares browser-supplied per-file sequence numbers against the container's stored metadata and returns a reconciliation plan.
type ReconciliationActionType ¶
type ReconciliationActionType string
ReconciliationActionType enumerates the possible outcomes of comparing browser and container sequence numbers for a single file.
const ( // ReconcileSyncOK means browser and container are at the same seq. ReconcileSyncOK ReconciliationActionType = "sync_ok" // ReconcileContainerAhead means the container has patches the browser hasn't seen. ReconcileContainerAhead ReconciliationActionType = "container_ahead" // ReconcileBrowserAhead means the browser has edits the container hasn't applied. ReconcileBrowserAhead ReconciliationActionType = "browser_ahead" // ReconcileDiverged means both sides have diverged and conflict resolution is needed. ReconcileDiverged ReconciliationActionType = "diverged" )
type RecoveryReport ¶ added in v0.17.17
type RecoveryReport struct {
JournalReplayed bool
JournalEvents int
InterruptedAt *time.Time
Repair RepairReport
}
RecoveryReport describes what load-time recovery applied.
type RepairReport ¶ added in v0.17.17
RepairReport summarizes what RepairMessageTail changed.
func RepairMessageTail ¶ added in v0.17.17
func RepairMessageTail(msgs []api.Message) ([]api.Message, RepairReport)
RepairMessageTail fixes provider-breaking tool-exchange shapes at the end of a message list: tool results whose tool_call_id no longer matches an assistant tool call are dropped, and trailing assistant tool_calls with no matching results are stripped (keeping the assistant text if any). Only the tail is examined — full-history reconciliation is not the goal.
type RetryAction ¶
type RetryAction int
RetryAction represents the action to take when a tool error occurs.
const ( // ActionRetry indicates the error is transient and the tool call should be retried. // Covers TransientError, RateLimitError, retryable ProviderError, and unknown/untyped errors. ActionRetry RetryAction = iota // ActionFail indicates the error is permanent and should not be retried. ActionFail // ActionEscalate indicates the error needs human/LLM review before proceeding. ActionEscalate )
func ClassifyError ¶
func ClassifyError(err error) RetryAction
ClassifyError examines an error and returns the appropriate RetryAction.
It uses typed error checks from pkg/errors (errors.As via helper functions) rather than string matching on error messages. This provides more reliable classification as the error types are structural rather than text-based.
Classification rules (checked in priority order):
- SecurityError → ActionEscalate (ask user/LLM)
- PermissionError → ActionFail (approval denied/timeout — not retryable)
- TransientError → ActionRetry (with backoff)
- RateLimitError → ActionRetry (with longer backoff)
- InvalidInputError → ActionFail (fix the input)
- ContextError (ContextOverflow) → ActionFail (need context compaction)
- ProviderError → ActionFail (auth/config) or ActionRetry (server errors) depending on Retryable
- PermanentError → ActionFail
- Retryable AgentError → ActionRetry
- Default (unknown/untyped errors) → ActionRetry once, then ActionFail
func (RetryAction) String ¶
func (a RetryAction) String() string
String returns a human-readable name for the retry action.
type RewindOptions ¶ added in v0.16.12
type RewindOptions struct {
ToTurnIndex int // 0-based: rewind to BEFORE this turn's messages
RevertFiles bool // default true: revert file changes from discarded turns
}
RewindOptions configures a rewind operation.
type RewindResult ¶ added in v0.16.12
type RewindResult struct {
TurnsDiscarded int // number of turns removed
MessagesRemoved int // number of messages removed from the history
FilesReverted []string // files that were reverted
FilesSkipped []string // files that could NOT be reverted (modified outside agent)
CheckpointsDropped int // orphaned checkpoints removed
}
RewindResult reports what a rewind operation did.
type RiskAssessment ¶ added in v0.16.7
type RiskAssessment struct {
Level configuration.RiskLevel
// IsHardBlock is true for critical-tier operations that no approval can
// override (rm -rf /, fork bombs, mkfs).
IsHardBlock bool
RequiresIntentConfirmation bool
Sources []RiskSource
Reason string
// PathTier and FileMode are structured fields for file-touching tools.
PathTier PathTier
FileMode string
}
RiskAssessment is the canonical, single-vocabulary verdict for a tool call.
func (RiskAssessment) Explain ¶ added in v0.16.7
func (ra RiskAssessment) Explain() string
Explain renders a one-line human-readable summary of the assessment for diagnostics ("why was this gated?"). Sources are listed alphabetically for a stable rendering regardless of combination order.
type RiskSource ¶ added in v0.16.7
type RiskSource string
RiskSource identifies which check contributed to an assessment.
const ( RiskSourceClassifier RiskSource = "classifier" RiskSourcePersonaCascade RiskSource = "persona-cascade" RiskSourceCriticalOp RiskSource = "critical-op" RiskSourceGitHistoryRewrite RiskSource = "git-history-rewrite" RiskSourceGitRebase RiskSource = "git-rebase" RiskSourceGitWrite RiskSource = "git-write" RiskSourceFSTier RiskSource = "fs-tier" RiskSourceWorkspacePolicy RiskSource = "workspace-policy" RiskSourceHandler RiskSource = "handler" RiskSourcePasswordPrompter RiskSource = "password-prompter" )
type ScriptedClient ¶
type ScriptedClient struct {
*factory.TestClient
// contains filtered or unexported fields
}
ScriptedClient is an enhanced mock client for comprehensive E2E testing It supports: - Sequential scripted responses with tool calls - Streaming simulation - Error injection - Vision support - Rate limit simulation
func NewScriptedClient ¶
func NewScriptedClient(responses ...*ScriptedResponse) *ScriptedClient
NewScriptedClient creates a new scripted client with optional initial responses
func NewScriptedClientWithVision ¶
func NewScriptedClientWithVision(model string, responses ...*ScriptedResponse) *ScriptedClient
NewScriptedClientWithVision creates a scripted client that supports vision models
func (*ScriptedClient) AddResponse ¶
func (c *ScriptedClient) AddResponse(response *ScriptedResponse)
AddResponse appends a response to the end of the queue
func (*ScriptedClient) AdvanceIndex ¶
func (c *ScriptedClient) AdvanceIndex()
AdvanceIndex advances to the next response
func (*ScriptedClient) Cancel ¶
func (c *ScriptedClient) Cancel()
Cancel cancels any pending operations
func (*ScriptedClient) CheckConnection ¶
func (c *ScriptedClient) CheckConnection() error
CheckConnection always returns nil for test client
func (*ScriptedClient) ClearHistory ¶
func (c *ScriptedClient) ClearHistory()
ClearHistory clears the response history
func (*ScriptedClient) ClearSentRequests ¶
func (c *ScriptedClient) ClearSentRequests()
ClearSentRequests clears all recorded sent requests
func (*ScriptedClient) Close ¶
func (c *ScriptedClient) Close()
Close closes the client and releases resources
func (*ScriptedClient) GetAverageTPS ¶
func (c *ScriptedClient) GetAverageTPS() float64
GetAverageTPS returns the average tokens per second
func (*ScriptedClient) GetIndex ¶
func (c *ScriptedClient) GetIndex() int
GetIndex returns the current response index
func (*ScriptedClient) GetLastTPS ¶
func (c *ScriptedClient) GetLastTPS() float64
GetLastTPS returns the last tokens per second
func (*ScriptedClient) GetModel ¶
func (c *ScriptedClient) GetModel() string
GetModel returns the current model
func (*ScriptedClient) GetModelContextLimit ¶
func (c *ScriptedClient) GetModelContextLimit() (int, error)
GetModelContextLimit returns the context limit. Defaults to 128K (realistic agentic window).
func (*ScriptedClient) GetNextResponse ¶
func (c *ScriptedClient) GetNextResponse() *ScriptedResponse
GetNextResponse returns the next response without advancing the index
func (*ScriptedClient) GetProvider ¶
func (c *ScriptedClient) GetProvider() string
GetProvider returns the provider name
func (*ScriptedClient) GetSentRequest ¶
func (c *ScriptedClient) GetSentRequest(index int) []api.Message
GetSentRequest returns a specific request's messages (nil if out of range)
func (*ScriptedClient) GetSentRequests ¶
func (c *ScriptedClient) GetSentRequests() [][]api.Message
GetSentRequests returns a defensive deep copy of all recorded request message arrays. Both the outer slice and each inner []api.Message slice are copied to prevent external mutation of the client's internal state.
func (*ScriptedClient) GetTPSStats ¶
func (c *ScriptedClient) GetTPSStats() map[string]float64
GetTPSStats returns TPS statistics
func (*ScriptedClient) GetVisionModel ¶
func (c *ScriptedClient) GetVisionModel() string
GetVisionModel returns the vision model name
func (*ScriptedClient) LastResponse ¶
func (c *ScriptedClient) LastResponse() *ScriptedResponse
LastResponse returns the last consumed response
func (*ScriptedClient) Length ¶
func (c *ScriptedClient) Length() int
Length returns the number of scripted responses
func (*ScriptedClient) ListModels ¶
ListModels returns available models
func (*ScriptedClient) Reset ¶
func (c *ScriptedClient) Reset()
Reset resets the response index to the beginning
func (*ScriptedClient) ResetTPSStats ¶
func (c *ScriptedClient) ResetTPSStats()
ResetTPSStats resets TPS statistics
func (*ScriptedClient) ResponseHistory ¶
func (c *ScriptedClient) ResponseHistory() []*ScriptedResponse
ResponseHistory returns all consumed responses
func (*ScriptedClient) SendChatRequest ¶
func (c *ScriptedClient) SendChatRequest(ctx context.Context, messages []api.Message, tools []api.Tool, reasoning string, disableThinking bool) (*api.ChatResponse, error)
SendChatRequest sends a chat request and returns a scripted response
func (*ScriptedClient) SendChatRequestStream ¶
func (c *ScriptedClient) SendChatRequestStream(ctx context.Context, messages []api.Message, tools []api.Tool, reasoning string, disableThinking bool, callback api.StreamCallback) (*api.ChatResponse, error)
SendChatRequestStream sends a streaming chat request with full simulation support
func (*ScriptedClient) SendVisionRequest ¶
func (c *ScriptedClient) SendVisionRequest(ctx context.Context, messages []api.Message, tools []api.Tool, reasoning string, disableThinking bool) (*api.ChatResponse, error)
SendVisionRequest sends a vision-enabled chat request
func (*ScriptedClient) SetDebug ¶
func (c *ScriptedClient) SetDebug(debug bool)
SetDebug enables debug mode
func (*ScriptedClient) SetIndex ¶
func (c *ScriptedClient) SetIndex(idx int)
SetIndex sets the response index (useful for replay scenarios)
func (*ScriptedClient) SetModel ¶
func (c *ScriptedClient) SetModel(model string) error
SetModel sets the model name
func (*ScriptedClient) SetResponses ¶
func (c *ScriptedClient) SetResponses(responses []*ScriptedResponse)
SetResponses replaces all responses and resets all derived state.
func (*ScriptedClient) SupportsConversationalVision ¶ added in v0.16.19
func (c *ScriptedClient) SupportsConversationalVision() bool
SupportsConversationalVision reports whether inline multimodal turns should embed the image. Defaults to false; overridden per client.
func (*ScriptedClient) SupportsVision ¶
func (c *ScriptedClient) SupportsVision() bool
SupportsVision returns whether vision is supported
type ScriptedResponse ¶
type ScriptedResponse struct {
// Message content to return
Content string
// Tool calls to include in the response
ToolCalls []api.ToolCall
// Finish reason for the choice
FinishReason string
// Reasoning content (for models that support it)
ReasoningContent string
// Images to include (vision support)
Images []api.ImageData
// Delay before returning the response (for rate limit simulation)
Delay time.Duration
// Error to return instead of a response
Error error
// Rate limit simulation: return rate limit error after N successful responses
RateLimitAfter int
// Stream configuration
StreamConfig *StreamConfig
// Whether this response should be used for vision requests
VisionOnly bool
// Token usage metrics for this response
Usage ScriptedTokenUsage
}
ScriptedResponse represents a single scripted response with full configuration options
func NewErrorResponse ¶
func NewErrorResponse(err error) *ScriptedResponse
NewErrorResponse creates a response that returns an error
func NewKeepGoingResponse ¶
func NewKeepGoingResponse(content string) *ScriptedResponse
NewKeepGoingResponse creates a keep-going response (empty finish_reason)
func NewLengthResponse ¶
func NewLengthResponse(content string) *ScriptedResponse
NewLengthResponse creates a length finish_reason response
func NewRateLimitResponse ¶
func NewRateLimitResponse() *ScriptedResponse
NewRateLimitResponse creates a response that simulates rate limiting
func NewStopResponse ¶
func NewStopResponse(content string) *ScriptedResponse
NewStopResponse creates a stop response
func NewTimeoutResponse ¶
func NewTimeoutResponse() *ScriptedResponse
NewTimeoutResponse creates a response with a timeout error
func NewToolCallResponse ¶
func NewToolCallResponse(name, args string, toolCalls ...api.ToolCall) *ScriptedResponse
NewToolCallResponse creates a response with tool calls
type ScriptedResponseBuilder ¶
type ScriptedResponseBuilder struct {
// contains filtered or unexported fields
}
ScriptedResponseBuilder provides a fluent interface for building ScriptedResponse
func NewScriptedResponseBuilder ¶
func NewScriptedResponseBuilder() *ScriptedResponseBuilder
NewScriptedResponseBuilder creates a new response builder
func (*ScriptedResponseBuilder) Build ¶
func (b *ScriptedResponseBuilder) Build() *ScriptedResponse
Build returns the constructed ScriptedResponse
func (*ScriptedResponseBuilder) Content ¶
func (b *ScriptedResponseBuilder) Content(content string) *ScriptedResponseBuilder
Content sets the message content
func (*ScriptedResponseBuilder) Delay ¶
func (b *ScriptedResponseBuilder) Delay(d time.Duration) *ScriptedResponseBuilder
Delay sets the delay before returning the response
func (*ScriptedResponseBuilder) Error ¶
func (b *ScriptedResponseBuilder) Error(err error) *ScriptedResponseBuilder
Error sets an error to be returned instead of a response
func (*ScriptedResponseBuilder) FinishReason ¶
func (b *ScriptedResponseBuilder) FinishReason(reason string) *ScriptedResponseBuilder
FinishReason sets the finish reason
func (*ScriptedResponseBuilder) Images ¶
func (b *ScriptedResponseBuilder) Images(images []api.ImageData) *ScriptedResponseBuilder
Images sets the images for vision support
func (*ScriptedResponseBuilder) RateLimitAfter ¶
func (b *ScriptedResponseBuilder) RateLimitAfter(n int) *ScriptedResponseBuilder
RateLimitAfter configures rate limit simulation
func (*ScriptedResponseBuilder) ReasoningContent ¶
func (b *ScriptedResponseBuilder) ReasoningContent(content string) *ScriptedResponseBuilder
ReasoningContent sets reasoning content for models that support it
func (*ScriptedResponseBuilder) StreamConfig ¶
func (b *ScriptedResponseBuilder) StreamConfig(sc *StreamConfig) *ScriptedResponseBuilder
StreamConfig sets streaming configuration
func (*ScriptedResponseBuilder) ToolCall ¶
func (b *ScriptedResponseBuilder) ToolCall(tc api.ToolCall) *ScriptedResponseBuilder
ToolCall adds a single tool call
func (*ScriptedResponseBuilder) ToolCalls ¶
func (b *ScriptedResponseBuilder) ToolCalls(tcs []api.ToolCall) *ScriptedResponseBuilder
ToolCalls sets multiple tool calls
func (*ScriptedResponseBuilder) Usage ¶
func (b *ScriptedResponseBuilder) Usage(promptTokens, completionTokens, totalTokens int, estimatedCost float64) *ScriptedResponseBuilder
Usage sets the token usage metrics for this response
func (*ScriptedResponseBuilder) VisionOnly ¶
func (b *ScriptedResponseBuilder) VisionOnly() *ScriptedResponseBuilder
VisionOnly marks this response for vision-only requests
type ScriptedTokenUsage ¶
type ScriptedTokenUsage struct {
PromptTokens int `json:"prompt_tokens"`
CompletionTokens int `json:"completion_tokens"`
TotalTokens int `json:"total_tokens"`
EstimatedCost float64 `json:"estimated_cost"`
Cost float64 `json:"cost,omitempty"`
PromptTokensDetails PromptTokensDetails `json:"prompt_tokens_details,omitempty"`
}
ScriptedTokenUsage represents token usage metrics for a scripted response
type SecurityAnalysis ¶ added in v0.17.7
type SecurityAnalysis struct {
// Summary is a one-sentence plain-language description of what the
// command does. Required.
Summary string `json:"summary"`
// Modifies lists files, directories, or system resources the command
// touches (e.g. "No local files; executes arbitrary code from URL").
Modifies string `json:"modifies"`
// RiskAssessment is one of "low", "moderate", "high" — the LLM's own
// assessment. Independent of (often overrides) the static classifier.
RiskAssessment string `json:"risk_assessment"`
// Recommendation is one of "approve", "review", "reject".
Recommendation string `json:"recommendation"`
// ChainLength is the number of subcommands in the analyzed chain.
// 0 means single-command path or analyzer didn't run.
ChainLength int `json:"chain_length,omitempty"`
// ChainSubcommands are the per-subcommand strings, in order. Used by the UI stepper.
ChainSubcommands []string `json:"chain_subcommands,omitempty"`
// ChainClassifications holds the per-subcommand risk classification for the stepper dots.
ChainClassifications []string `json:"chain_classifications,omitempty"`
}
SecurityAnalysis is the structured output of AnalyzeShellCommand.
func AnalyzeChain ¶ added in v0.17.7
func AnalyzeChain(ctx context.Context, agent *Agent, chain Chain, classifications []agenttools.ChainedClassification, cwd string) (*SecurityAnalysis, error)
AnalyzeChain analyzes a command chain using the LLM. Single subcommands use the single-command prompt; chains up to MaxChainSubcommandsForBatchPrompt use the chain-aware prompt with per-subcommand classifications; longer chains fall back to per-subcommand analyses via AnalyzeChainFallback.
func AnalyzeChainFallback ¶ added in v0.17.7
func AnalyzeChainFallback(ctx context.Context, agent *Agent, chain Chain, classifications []agenttools.ChainedClassification, cwd string) (*SecurityAnalysis, error)
AnalyzeChainFallback handles chains longer than MaxChainSubcommandsForBatchPrompt. It runs per-subcommand single-command analysis on each subcommand and synthesizes a single SecurityAnalysis: max severity, worst recommendation, deduped modifies.
func AnalyzeShellCommand ¶ added in v0.17.7
func AnalyzeShellCommand(ctx context.Context, agent *Agent, command, cwd string) (*SecurityAnalysis, error)
AnalyzeShellCommand sends a shell command to the agent's LLM for plain-language analysis.
type SecurityAnalysisCache ¶ added in v0.17.7
type SecurityAnalysisCache struct {
// contains filtered or unexported fields
}
SecurityAnalysisCache caches LLM security analyses keyed by command string.
func NewSecurityAnalysisCache ¶ added in v0.17.7
func NewSecurityAnalysisCache() *SecurityAnalysisCache
NewSecurityAnalysisCache creates an empty cache.
func (*SecurityAnalysisCache) Clear ¶ added in v0.17.7
func (c *SecurityAnalysisCache) Clear()
Clear resets the cache to empty.
func (*SecurityAnalysisCache) Get ¶ added in v0.17.7
func (c *SecurityAnalysisCache) Get(normalizedKey string) (*SecurityAnalysis, bool)
Get returns the cached analysis for a normalized key, or false if not found.
func (*SecurityAnalysisCache) Set ¶ added in v0.17.7
func (c *SecurityAnalysisCache) Set(normalizedKey string, sa *SecurityAnalysis)
Set stores an analysis under a normalized key.
type SecurityManager ¶
type SecurityManager interface {
GetSecurityApprovalMgr() *security.ApprovalManager
SetApprovalMgr(mgr *security.ApprovalManager)
SetAskUserMgr(mgr *agenttools.AskUserManager)
GetAskUserMgr() *agenttools.AskUserManager
SetUnsafeMode(unsafe bool)
GetUnsafeMode() bool
SetUnsafeShellMode(unsafe bool)
GetUnsafeShellMode() bool
IsSecurityBypassApproved() bool
IsFolderSessionAllowed(absPath string) bool
IsFolderSessionWriteAllowed(absPath string) bool
AddSessionAllowedFolder(folder string)
SetSessionAllowedFolderMode(folder, mode string)
SnapshotSessionAllowedFolders() []string
SnapshotSessionAllowedFolderModes() map[string]string
RemoveSessionAllowedFolder(folder string) error
IsConcernIgnored(filePath, concern string) bool
SetConcernIgnored(filePath, concern string)
GetOutputRedactor() *security.OutputRedactor
GetElevationGate() *security.ElevationGate
SetElevationGate(gate *security.ElevationGate)
SetHasActiveWebUIClients(fn func() bool)
HasActiveWebUIClients() bool
}
SecurityManager provides an interface for managing all security-related state.
type SessionConfigStore ¶ added in v0.16.25
type SessionConfigStore interface {
GetSessionProvider() api.ClientType
SetSessionProvider(api.ClientType)
GetSessionModel() string
SetSessionModel(string)
}
SessionConfigStore manages per-session provider and model configuration.
type SessionInfo ¶
type SessionInfo struct {
SessionID string `json:"session_id"`
LastUpdated time.Time `json:"last_updated"`
Name string `json:"name"` // Human-readable session name
WorkingDirectory string `json:"working_directory"` // Directory where session was created
StoragePath string `json:"storage_path,omitempty"`
Interrupted bool `json:"interrupted,omitempty"` // Turn journal survived — session ended mid-turn
}
SessionInfo represents session information with timestamp
func ListAllSessionsWithTimestamps ¶
func ListAllSessionsWithTimestamps() ([]SessionInfo, error)
ListAllSessionsWithTimestamps returns all available sessions across all scopes.
func ListSessionsWithTimestamps ¶
func ListSessionsWithTimestamps() ([]SessionInfo, error)
ListSessionsWithTimestamps returns sessions for the current working directory scope.
func ListSessionsWithTimestampsScoped ¶
func ListSessionsWithTimestampsScoped(workingDir string) ([]SessionInfo, error)
ListSessionsWithTimestampsScoped returns sessions only for the given working directory scope.
type SessionIntentStore ¶ added in v0.16.25
type SessionIntentStore interface {
GetSessionIntentEmbedding() []float32
SetSessionIntentEmbedding([]float32)
SetSessionIntentEmbeddingIfNil(emb []float32) bool
}
SessionIntentStore manages the session intent embedding vector.
type SessionItem ¶
type SessionItem struct {
Label string
Value string
SessionID string
Model string
LastUpdated time.Time
Name string // Human-readable session name
}
SessionItem represents a session in dropdown selections
type SessionManager ¶ added in v0.17.7
type SessionManager interface {
MessageStore
SessionStore
CheckpointStore
SummaryStore
OptimizerStore
ContextBudgetStore
ConversationPrunerStore
CommandHistoryStore
PauseStore
SessionConfigStore
ConfigOverrideStore
IterationStore
SessionIntentStore
}
SessionManager is composed of the session/scoped sub-interfaces. It owns all state that is scoped to a single conversation/session.
type SessionStore ¶ added in v0.16.25
SessionStore manages the session identifier.
type SettingDetail ¶ added in v0.16.19
type SettingDetail struct {
Key string
Description string
ValidValues string
GetValue func(cfg *configuration.Config) string
ListType bool // true for comma-separated list settings (add/remove/set UI)
}
SettingDetail holds metadata for a setting key used by describe and describe_all.
func AllSettings ¶ added in v0.16.19
func AllSettings() []SettingDetail
AllSettings returns the complete list of setting definitions, derived from the single settingDefs registry.
type SharedState ¶
type SharedState struct {
}
SharedState holds resources shared between parent and subagents
type ShellCommandResult ¶
type ShellCommandResult struct {
Command string // The command that was run
FullOutput string // Complete output (for future reference)
TruncatedOutput string // Truncated output (what was shown)
Error error // Any error that occurred
ExecutedAt int64 // Unix timestamp
MessageIndex int // Index in messages array where this result appears
WasTruncated bool // Whether output was truncated
FullOutputPath string // Optional path to the saved full output
TruncatedTokens int // Number of tokens omitted from the middle section
TruncatedLines int // Approximate number of lines omitted from the middle
}
ShellCommandResult tracks shell command execution for deduplication
type ShellPart ¶ added in v0.16.19
type ShellPart struct {
ID string // stable ID for UI tracking (e.g. "part-0")
Text string // raw text of this part (e.g. "rm -rf foo")
Kind CommandKind // classified kind
Semantic string // human-readable description (e.g. "Recursively delete foo")
}
ShellPart represents one logical command in a potentially-pipelined shell line.
func SplitShellIntoParts ¶ added in v0.16.19
SplitShellIntoParts tokenizes a shell command at &&, ||, ;, and | boundaries, respecting balanced parentheses and quoted strings.
Inside quotes (single or double) all metacharacters are treated as literal text. Inside parentheses (depth > 0), the pipe character is treated as literal.
Empty input produces an empty slice. Consecutive separators with no content are skipped. Each part is trimmed of leading/trailing whitespace.
type ShellProposal ¶ added in v0.16.19
type ShellProposal struct {
Command string // original full command
Parts []ShellPart // split + classified
RiskLevel configuration.RiskLevel // folded from the most-destructive part
}
ShellProposal is a parsed shell command submitted for approval.
func NewShellProposal ¶ added in v0.16.19
func NewShellProposal(cmd string) ShellProposal
NewShellProposal creates a ShellProposal by splitting the command into parts, classifying each part (kind + semantic), and folding the overall RiskLevel from the most-destructive part.
func (ShellProposal) HighRiskParts ¶ added in v0.16.19
func (p ShellProposal) HighRiskParts() []ShellPart
HighRiskParts returns all parts whose RiskLevel is >= High (Critical or High). Returns nil if none qualify.
func (ShellProposal) MostDestructivePart ¶ added in v0.16.19
func (p ShellProposal) MostDestructivePart() *ShellPart
MostDestructivePart returns a pointer to the part with the highest RiskLevel. Returns nil if the proposal has no parts. Ties return the first part in command order.
type SimpleUI ¶
type SimpleUI struct{}
SimpleUI provides a minimal fallback UI implementation
func (*SimpleUI) IsInteractive ¶
IsInteractive returns false for simple UI (non-interactive)
func (*SimpleUI) ShowDropdown ¶
func (s *SimpleUI) ShowDropdown(ctx context.Context, items interface{}, options DropdownOptions) (interface{}, error)
ShowDropdown returns an error since simple UI doesn't support dropdowns
func (*SimpleUI) ShowQuickPrompt ¶
func (s *SimpleUI) ShowQuickPrompt(ctx context.Context, prompt string, options []QuickOption, horizontal bool) (QuickOption, error)
ShowQuickPrompt returns an error since simple UI doesn't support prompts
type SkillInfo ¶
type SkillInfo struct {
ID string
Name string
Description string
Path string
Content string
Source string // "builtin", "user", or "project"
}
func ListSkills ¶
func ListSkills(config *configuration.Config) []SkillInfo
func LoadSkill ¶
func LoadSkill(skillID string, config *configuration.Config) (*SkillInfo, error)
LoadSkill resolves a skill by ID: built-ins come from the embedded pkg/skills library (the single source of truth that also seeds Config.Skills), user/project skills come from disk via skill.Path. The config registry is still the gate — a skill that isn't registered or is explicitly disabled cannot be activated, even if its content happens to be embedded.
func LoadSkillInWorkspace ¶ added in v0.17.16
func LoadSkillInWorkspace(skillID string, config *configuration.Config, workspaceRoot string) (*SkillInfo, error)
LoadSkillInWorkspace is the workspace-aware variant of LoadSkill. Project-level skills (e.g., .sprout/skills/) are resolved relative to workspaceRoot instead of os.Getwd(). This is critical in daemon mode where the process CWD differs from the workspace being served.
type StateManager ¶
type StateManager interface {
MessageStore
SessionStore
CheckpointStore
SummaryStore
OptimizerStore
ContextBudgetStore
TaskActionStore
CostTracker
TokenCounter
LLMCallTracker
ToolCallTracker
CacheStats
PersonaStore
CircuitBreakerStore
PendingStateStore
TerminationStore
ConversationPrunerStore
CommandHistoryStore
PauseStore
TraceStore
SessionConfigStore
ConfigOverrideStore
IterationStore
SessionIntentStore
ProviderErrorStore
EstimatedTokenStore
ContinuationNudgeStore
ToolGuidanceStore
FalseStopStore
}
StateManager is the composed interface of all 28 state sub-interfaces.
type StreamConfig ¶
type StreamConfig struct {
// Chunks to stream (content pieces)
Chunks []string
// Delay between chunks
ChunkDelay time.Duration
// Simulated tokens per chunk
TokensPerChunk int
// Error to inject during streaming
StreamError error
// Finish reason for the final chunk
FinishReason string
// ErrorAfterChunks specifies after how many chunks to fail (0 = never fail)
ErrorAfterChunks int
// ChunkErrors allows specifying per-chunk errors (index corresponds to chunk index)
ChunkErrors []error
}
StreamConfig configures streaming behavior for a response
type SubagentError ¶
type SubagentError struct {
Status SubagentStatus
Reason string
}
SubagentError is an in-process error value carrying both the terminal Status and a free-form Reason. Returned alongside the JSON envelope when callers in Go-land want to switch on the failure mode without re-parsing the result JSON.
func (*SubagentError) Error ¶
func (e *SubagentError) Error() string
type SubagentMetrics ¶
type SubagentMetrics struct {
Active int64 // Currently executing subagents
Queued int64 // Waiting for semaphore slot
Completed int64 // Successfully completed
Failed int64 // Completed with error
Cancelled int64 // Cancelled (parent ctx or budget)
TotalQueuedWaitMS int64 // Cumulative milliseconds spent waiting in queue
}
SubagentMetrics tracks operational metrics for the subagent runner.
type SubagentOptions ¶
type SubagentOptions struct {
Persona string // "coder", "tester", "debugger", etc.
Model string // optional model override
Provider string // optional provider override
SystemPrompt string // optional system prompt override
MaxTokens int // token budget (0 = unlimited)
Timeout time.Duration // execution timeout; <=0 defaults to 30 minutes, 1 hour for the orchestrator persona (see runTask)
WorkingDir string // optional: override workspace root (must be within $HOME)
MaxConcurrentSubagents int // max parallel subagents (0 = unlimited, default unlimited)
FleetTokenBudget int // shared token budget across all parallel subagents (0 = unlimited)
}
SubagentOptions configures an in-process subagent
type SubagentProgressEntry ¶
type SubagentProgressEntry struct {
OffsetMS int64 `json:"offset_ms"` // ms since subagent started
Phase string `json:"phase"` // "spawn" | "output" | "complete"
Message string `json:"message"`
}
SubagentProgressEntry is one timeline entry from a subagent run. Kept minimal to avoid bloating the envelope the primary's LLM sees.
type SubagentResult ¶
type SubagentResult struct {
ID string
Output string
Error error
TokensUsed int
Cost float64
ToolCalls int
// Iterations is the assistant-turn count consumed by this subagent
// run. Surfaced to the primary via SubagentRunMetrics.Iterations so
// the model has visibility into how many LLM rounds a delegated task
// burned.
Iterations int
Elapsed time.Duration
Cancelled bool
BudgetExceeded bool // true if task was skipped because fleet budget was already exceeded before starting
Truncated bool // true if subagent was cut short due to fleet budget exceeded mid-run
// OutputComplete signals whether the subagent produced a substantive
// final response. false when the output is empty or suspiciously brief
// (under 50 trimmed chars) despite a clean exit — the orchestrator can
// use this to decide whether to retry, escalate, or accept. This is
// distinct from Error/Cancelled/BudgetExceeded (all of which also set
// it false): OutputComplete focuses specifically on "did the subagent
// actually say something useful?"
OutputComplete bool
// FileChanges is the manifest of writes/edits this subagent performed,
// captured via its own ChangeTracker. nil when tracking wasn't
// initialized for this run.
FileChanges []TrackedFileChange
// ProgressLog is a per-run timeline of notable subagent events
// (spawn, output, complete). Surfaced to the primary's LLM via the
// SubagentReturn envelope so the model can reason about *what* the
// subagent did, not just the final assistant message. Capped to
// subagentProgressLogCap entries.
ProgressLog []SubagentProgressEntry
}
SubagentResult is the structured output from a subagent
type SubagentReturn ¶
type SubagentReturn struct {
// Output is the subagent's final assistant message (was: "stdout").
Output string `json:"stdout"`
// Stderr carries the subagent's terminal error message if any.
Stderr string `json:"stderr"`
// ExitCode is "0" on success, "1" otherwise. Kept as string for
// shape-compat with the legacy resultMap.
ExitCode string `json:"exit_code"`
// Completed is "true" on natural completion, "false" if cancelled.
Completed string `json:"completed"`
// TimedOut is "true" if the run hit its timeout.
TimedOut string `json:"timed_out"`
// BudgetExceeded is "true" if the run hit its token budget.
BudgetExceeded string `json:"budget_exceeded"`
// ElapsedSeconds is the wall-clock duration, formatted "%.1f".
ElapsedSeconds string `json:"elapsed_seconds"`
// TokensUsed is the rolled-up token count (string for shape-compat).
TokensUsed string `json:"tokens_used"`
// Cost is the rolled-up dollar cost (string for shape-compat).
Cost string `json:"cost"`
// ToolCallCount is the number of tool calls the subagent made.
ToolCallCount string `json:"tool_calls"`
// Summary is JSON-stringified human-readable highlights (file ops,
// build/test status, errors). Kept for shape-compat.
Summary string `json:"summary,omitempty"`
// ContextUsed is "true" / "false" reflecting whether the subagent
// received the parent's context bundle.
ContextUsed string `json:"context_used,omitempty"`
// FilesUsed is the parent-provided files-of-interest list.
FilesUsed string `json:"files_used,omitempty"`
// WorkingDir is the directory the subagent executed under.
WorkingDir string `json:"working_dir,omitempty"`
// Status is the terminal state. Always populated, even on success.
Status SubagentStatus `json:"status"`
// ErrorReason carries free-form context when Status != completed.
ErrorReason string `json:"error_reason,omitempty"`
// FilesModified is the change-tracker-sourced manifest. nil when
// change tracking is disabled (caller treats nil as "not reported").
FilesModified []FileChange `json:"files_modified,omitempty"`
// Metrics is the structured token/cost rollup. Mirror of the
// TokensUsed/Cost/ToolCallCount string fields above for callers
// that prefer typed access.
Metrics SubagentRunMetrics `json:"metrics"`
// ProgressLog is a capped timeline of subagent activity events
// (spawn / output / complete) so the primary's LLM can reason about
// what the subagent actually did, not just its final assistant
// message. nil when no events were captured.
ProgressLog []ProgressEntry `json:"progress_log,omitempty"`
}
SubagentReturn is the typed envelope a subagent tool call returns to the primary's LLM. It marshals to JSON with backward-compatible keys for the old map[string]string shape so existing LLM behavior keeps working, plus new typed fields (status, files_modified, metrics) for callers that want them.
func (*SubagentReturn) MarshalJSONIndent ¶
func (r *SubagentReturn) MarshalJSONIndent() (string, error)
MarshalJSONIndent renders the envelope as a 2-space-indented JSON string for the tool result.
type SubagentRunMetrics ¶
type SubagentRunMetrics struct {
TokensUsed int `json:"tokens_used"`
Cost float64 `json:"cost"`
ToolCalls int `json:"tool_calls"`
Iterations int `json:"iterations"`
}
SubagentRunMetrics is the structured token/cost accounting for a subagent run. Sourced directly from SubagentResult (subagent_runner.go), not by regex-scraping stdout. Iterations is the assistant-turn count, exposed so the primary's LLM can reason about how much budget a delegated task burned.
type SubagentRunner ¶
type SubagentRunner struct {
// contains filtered or unexported fields
}
SubagentRunner manages in-process subagent execution
func NewSubagentRunner ¶
func NewSubagentRunner(parent *Agent, shared *SharedState) *SubagentRunner
NewSubagentRunner creates a new SubagentRunner
func (*SubagentRunner) CancelAll ¶
func (r *SubagentRunner) CancelAll()
CancelAll cancels all running subagents. Called when the user clicks Stop on the primary — without this, the primary's TriggerInterrupt returns but subagent work continues until self-completion.
func (*SubagentRunner) CancelSubagent ¶
func (r *SubagentRunner) CancelSubagent(id string) bool
CancelSubagent cancels a specific running subagent by ID. Cancels both the run context (truncates pending work) and the subagent agent's interrupt signal (preempts the in-flight ProcessQuery loop, which doesn't observe runCtx).
func (*SubagentRunner) GetActiveSubagents ¶
func (r *SubagentRunner) GetActiveSubagents() []*runningSubagent
GetActiveSubagents returns information about currently running subagents
func (*SubagentRunner) InjectInputIntoActive ¶
func (r *SubagentRunner) InjectInputIntoActive(input string) (string, bool)
InjectInputIntoActive delivers a steering message to the PRIMARY agent first. Only if the primary's channel is full or unavailable does it fall back to the deepest (most-recently-started) running subagent.
The primary agent is what reads user steer messages and decides whether to abort subagents, redirect them, or fold the steer into its own plan. Routing to the subagent bypasses this decision loop — the parent never sees "yes, commit and push" until the subagent finishes, by which point the subagent may have already taken destructive action.
Returns the target ID ("primary" or subagent ID) when delivery succeeds, or ("", false) when no target is available.
func (*SubagentRunner) Metrics ¶
func (r *SubagentRunner) Metrics() SubagentMetrics
Metrics returns a snapshot of the subagent runner's operational metrics.
func (*SubagentRunner) Run ¶
func (r *SubagentRunner) Run(ctx context.Context, prompt string, opts SubagentOptions) *SubagentResult
Run spawns an in-process subagent and waits for completion
func (*SubagentRunner) RunParallel ¶
func (r *SubagentRunner) RunParallel(ctx context.Context, tasks []SubagentTask, opts SubagentOptions) []*SubagentResult
RunParallel spawns multiple subagents concurrently. If the parent context is cancelled, remaining subagents are cancelled and their results are set to cancellation errors.
type SubagentStatus ¶
type SubagentStatus string
SubagentStatus enumerates terminal states of a subagent run. Replaces the legacy SUBAGENT_SECURITY_ERROR / SUBAGENT_TOKEN_BUDGET_EXCEEDED / SUBAGENT_FAILED sentinel string prefixes — those literals are retained in the human-readable Output so any LLM behavior keyed on the legacy shape still works, but in-process callers should switch to Status.
const ( SubagentStatusCompleted SubagentStatus = "completed" SubagentStatusCancelled SubagentStatus = "cancelled" SubagentStatusTimedOut SubagentStatus = "timed_out" SubagentStatusBudgetExceeded SubagentStatus = "budget_exceeded" SubagentStatusSecurityBlocked SubagentStatus = "security_blocked" SubagentStatusFailed SubagentStatus = "failed" )
type SubagentTask ¶
type SubagentTask struct {
ID string
Prompt string
Model string
Provider string
Persona string
WorkingDir string // optional: override workspace root
}
SubagentTask represents a single parallel subagent task
type SummaryStore ¶ added in v0.16.25
SummaryStore manages the previous conversation summary.
type SyncOp ¶
type SyncOp struct {
OpType string `json:"op_type"` // "write", "delete", or "rename"
Path string `json:"path"` // Target file path (relative to workspace root)
Content string `json:"content"` // For write ops: the file content
NewPath string `json:"new_path"` // For rename ops: the destination path
BrowserSeq int64 `json:"browser_seq"` // Monotonically increasing browser-side seq number
Timestamp int64 `json:"timestamp"` // Unix milliseconds when the op was created
}
SyncOp represents a single file operation sent from the browser to the container as part of the workspace sync protocol.
type SyncOpResult ¶
type SyncOpResult struct {
Accepted bool `json:"accepted"` // Whether the op was applied
ConflictPath string `json:"conflict_path"` // Set if there's a container-side conflict (path to .theirs file)
ContainerSeq int64 `json:"container_seq"` // Current container sequence after applying
Error string `json:"error,omitempty"` // Error message if not accepted
}
SyncOpResult is the server response to a SyncOp application.
type TaskAction ¶
type TaskAction struct {
Type string // "file_created", "file_modified", "command_executed", "file_read"
Description string // Human-readable description
Details string // Additional details like file path, command, etc.
}
TaskAction represents a completed action during task execution
type TaskActionStore ¶ added in v0.16.25
type TaskActionStore interface {
GetTaskActions() []TaskAction
SetTaskActions([]TaskAction)
AddTaskAction(TaskAction)
GetTaskActionsMutex() *sync.RWMutex
}
TaskActionStore manages task actions and their associated mutex.
type TerminationStore ¶ added in v0.16.25
type TerminationStore interface {
GetLastRunTerminationReason() string
SetLastRunTerminationReason(string)
}
TerminationStore manages the last run termination reason.
type Theme ¶
type Theme struct {
Name string `json:"name"`
Description string `json:"description"`
Colors struct {
Success string `json:"success"`
Warning string `json:"warning"`
Error string `json:"error"`
Info string `json:"info"`
Primary string `json:"primary"`
Secondary string `json:"secondary"`
Accent string `json:"accent"`
} `json:"colors"`
}
Theme represents a color theme configuration
type ThemeManager ¶
type ThemeManager struct {
// contains filtered or unexported fields
}
ThemeManager manages color themes
func NewThemeManager ¶
func NewThemeManager() *ThemeManager
NewThemeManager creates a new theme manager with default theme
func (*ThemeManager) GetColor ¶
func (tm *ThemeManager) GetColor(name string) string
GetColor returns a color by name
func (*ThemeManager) GetTheme ¶
func (tm *ThemeManager) GetTheme() Theme
GetTheme returns the current theme
func (*ThemeManager) LoadDefaultTheme ¶
func (tm *ThemeManager) LoadDefaultTheme()
LoadDefaultTheme loads the default theme
func (*ThemeManager) LoadThemeFromFile ¶
func (tm *ThemeManager) LoadThemeFromFile(themePath string) error
LoadThemeFromFile loads a theme from a JSON file
type TokenCounter ¶ added in v0.16.25
type TokenCounter interface {
GetTotalTokens() int
SetTotalTokens(int)
GetPromptTokens() int
SetPromptTokens(int)
GetCompletionTokens() int
SetCompletionTokens(int)
}
TokenCounter manages prompt and completion token counts.
type TokenUsage ¶
type TokenUsage struct {
PromptTokens int
CompletionTokens int
TotalTokens int
EstimatedCost float64
}
TokenUsage captures key token metrics for each turn
type ToolCallTracker ¶ added in v0.16.25
type ToolCallTracker interface {
GetTotalToolCalls() int
SetTotalToolCalls(int)
IncrementTotalToolCalls()
}
ToolCallTracker manages tool call count tracking.
type ToolGuidanceStore ¶ added in v0.16.25
ToolGuidanceStore manages tool call guidance state.
type TraceStore ¶ added in v0.16.25
type TraceStore interface {
GetTraceSession() interface{}
SetTraceSession(interface{})
}
TraceStore manages the trace session.
type TrackedBulkItem ¶ added in v0.16.2
type TrackedBulkItem struct {
FilePath string `json:"file_path"`
OriginalCode string `json:"original_code"`
NewCode string `json:"new_code"`
Operation string `json:"operation"` // "create" | "edit" | "delete"
}
TrackedBulkItem is the per-file payload packed inside a bulk TrackedFileChange.
type TrackedFileChange ¶
type TrackedFileChange struct {
FilePath string `json:"file_path"`
OriginalCode string `json:"original_code"`
NewCode string `json:"new_code"`
Operation string `json:"operation"` // "write", "edit", "create", "delete", "bulk"
Timestamp time.Time `json:"timestamp"`
ToolCall string `json:"tool_call"`
// Source attributes a change to its origin. Empty for direct
// primary-agent edits; "subagent:<persona>" for subagent changes.
Source string `json:"source,omitempty"`
// BulkCount is set on a rollup entry when a single shell command
// churns more than the bulk threshold. FilePath names the directory
// or command label and Operation is "bulk".
BulkCount int `json:"bulk_count,omitempty"`
// BulkItems carries the per-file recovery payload for bulk entries.
BulkItems []TrackedBulkItem `json:"bulk_items,omitempty"`
}
TrackedFileChange represents a file change made during agent execution
type TranscriptDiff ¶ added in v0.16.4
type TranscriptDiff struct {
OlderPath string `json:"older_path"`
NewerPath string `json:"newer_path"`
OlderTimestamp time.Time `json:"older_timestamp"`
NewerTimestamp time.Time `json:"newer_timestamp"`
OlderMessageCount int `json:"older_message_count"`
NewerMessageCount int `json:"newer_message_count"`
OlderCheckpointCount int `json:"older_checkpoint_count"`
NewerCheckpointCount int `json:"newer_checkpoint_count"`
OlderTotalTokens int `json:"older_total_tokens"`
NewerTotalTokens int `json:"newer_total_tokens"`
OlderFileChangeCount int `json:"older_file_change_count"`
NewerFileChangeCount int `json:"newer_file_change_count"`
NewFileChanges []TranscriptFileChange `json:"new_file_changes,omitempty"`
MessagesDroppedAtTail int `json:"messages_dropped_at_tail"`
MessagesReplacedByRole map[string]int `json:"messages_replaced_by_role,omitempty"`
ChangedIndices []TranscriptDiffEntry `json:"changed_indices,omitempty"`
Notes []string `json:"notes,omitempty"`
}
TranscriptDiff is a compact, human-friendly comparison of two snapshots. Used by `/transcript diff` to expose what compaction (or some other state mutation) changed between snapshots.
func DiffTranscriptSnapshots ¶ added in v0.16.4
func DiffTranscriptSnapshots(older, newer *TranscriptSnapshot) *TranscriptDiff
DiffTranscriptSnapshots compares two snapshots and returns a human-readable diff structure. Older should be the chronologically earlier snapshot; the function does not re-sort.
type TranscriptDiffEntry ¶ added in v0.16.4
type TranscriptDiffEntry struct {
Index int `json:"index"`
OlderRole string `json:"older_role,omitempty"`
NewerRole string `json:"newer_role,omitempty"`
OlderSource string `json:"older_source,omitempty"`
NewerSource string `json:"newer_source,omitempty"`
OlderFirstLine string `json:"older_first_line,omitempty"`
NewerFirstLine string `json:"newer_first_line,omitempty"`
}
TranscriptDiffEntry is a single divergence in the per-index walk. Truncated content makes diffs scannable; full text is in the raw JSON.
type TranscriptFileChange ¶ added in v0.16.4
type TranscriptFileChange struct {
Path string `json:"path"`
Operation string `json:"operation"`
Source string `json:"source"`
ToolCall string `json:"tool_call,omitempty"`
Timestamp time.Time `json:"timestamp,omitempty"`
BulkCount int `json:"bulk_count,omitempty"`
}
TranscriptFileChange is the slim per-file projection embedded in a snapshot's top-level FileChanges field. It deliberately omits the full original/new file bodies that the ChangeTracker keeps for recovery — those can be multi-megabyte per file and would blow up snapshot size. The path, operation, and tool-call identifier give a reader enough to answer "what files were touched between snapshot A and snapshot B" without loading the bytes themselves.
Source distinguishes changes the primary agent made directly ("primary") from rollups parsed out of subagent tool results ("subagent"). The subagent's [subagent files modified] block is the authoritative per-call manifest, so the parser is a deterministic text scan rather than heuristic prose extraction.
func ExtractFileChangesFromMessages ¶ added in v0.16.4
func ExtractFileChangesFromMessages(messages []api.Message) []TranscriptFileChange
ExtractFileChangesFromMessages walks the supplied message slice and returns a deduped manifest of files touched, drawn from three authoritative sources: (1) tool_calls on assistant messages whose function name is a known file-write tool, (2) `[subagent files modified]` blocks embedded by tool_handlers_subagent in subagent tool results, and (3) `Files modified during compacted segment:` blocks that this package writes when /compact substitutes a summary for prior turns. The third source is what carries the manifest forward across successive compactions.
type TranscriptSnapshot ¶ added in v0.16.4
type TranscriptSnapshot struct {
Format string `json:"format"`
Timestamp time.Time `json:"timestamp"`
Label string `json:"label"`
SessionID string `json:"session_id"`
WorkingDirectory string `json:"working_directory"`
State *ConversationState `json:"state"`
MessageAnnotations []MessageAnnotation `json:"message_annotations"`
FileChanges []TranscriptFileChange `json:"file_changes,omitempty"`
ChangeTrackerRev string `json:"change_tracker_revision,omitempty"`
CompactPreview *CompactPreview `json:"compact_preview,omitempty"`
}
TranscriptSnapshot is the file shape written by /transcript and by the auto-capture path on compaction events. It is intentionally a superset of ConversationState so a reader can diff message lists, inspect checkpoint summaries, and compare snapshots across time.
func LoadTranscriptSnapshot ¶ added in v0.16.4
func LoadTranscriptSnapshot(path string) (*TranscriptSnapshot, error)
LoadTranscriptSnapshot reads a snapshot file back into memory.
type TurnCheckpoint ¶
type TurnCheckpoint struct {
StartIndex int `json:"start_index"`
EndIndex int `json:"end_index"`
Summary string `json:"summary"`
ActionableSummary string `json:"actionable_summary,omitempty"`
// FileChanges is the git-style manifest (M/A/D/R) of files touched
// during this turn. Populated from the agent's ChangeTracker at
// checkpoint-record time. Empty when tracking is disabled or the turn
// didn't write any files. For rollups (Level>0), this is the union of
// the source checkpoints' file changes so the manifest doesn't get
// lost as rollups stack.
FileChanges []CheckpointFileChange `json:"file_changes,omitempty"`
// RevisionID is the ChangeTracker revision that was active when this
// turn ran. When set, the summary text references it so the model can
// call the view_history tool to recover the exact diff. Empty when
// tracking is disabled. For rollups, this is the most recent
// revision_id from the source set.
RevisionID string `json:"revision_id,omitempty"`
// ID is a stable identifier for this checkpoint, independent of its
// position in the TurnCheckpoints slice. Used by rollups to reference
// their source checkpoints via SourceCheckpointIDs.
ID string `json:"id,omitempty"`
// Level is the rollup depth. 0 = per-turn (existing behavior).
// 1 = rollup of per-turn checkpoints. 2 = rollup of rollups. Etc.
Level int `json:"level,omitempty"`
// CoveredTurns is the count of original per-turn checkpoints this
// entry effectively replaces. For Level=0 this is 1 (or omitted).
// For rollups this is the sum of CoveredTurns from the source set.
CoveredTurns int `json:"covered_turns,omitempty"`
// SourceCheckpointIDs lists the checkpoint IDs this rollup consumed.
// Lets the UI drill down and lets a re-roll-up operate on the right
// source. Empty for Level=0.
SourceCheckpointIDs []string `json:"source_checkpoint_ids,omitempty"`
}
TurnCheckpoint stores a compact summary for a completed user turn while preserving the original full messages for cache-efficient reuse until needed.
A Level=0 entry is a per-turn checkpoint (the historical default). A Level>0 entry is a "rollup" that folds many lower-level checkpoints into one coarser summary. Both kinds substitute identically through seed's BuildCheckpointCompactedMessages — the rollup is just a checkpoint whose StartIndex/EndIndex span a wider historical range.
type TurnEvaluation ¶
type TurnEvaluation struct {
Iteration int
Timestamp time.Time
UserInput string
AssistantContent string
ToolCalls []api.ToolCall
ToolResults []api.Message
TokenUsage TokenUsage
CompletionReached bool
FinishReason string
ReasoningSnippet string
GuardrailTrigger string
}
TurnEvaluation captures the inputs, outputs, and tool activity for each iteration
type TurnJournal ¶ added in v0.17.17
type TurnJournal struct {
// contains filtered or unexported fields
}
func OpenTurnJournal ¶ added in v0.17.17
func OpenTurnJournal(sessionID, workingDir string) (*TurnJournal, error)
func (*TurnJournal) AppendTurnEvent ¶ added in v0.17.17
func (j *TurnJournal) AppendTurnEvent(ev TurnJournalEvent) error
func (*TurnJournal) CloseTurnJournal ¶ added in v0.17.17
func (j *TurnJournal) CloseTurnJournal() error
type TurnJournalEvent ¶ added in v0.17.17
type TurnJournalEvent struct {
V int `json:"v"`
Type string `json:"type"`
Ts time.Time `json:"ts"`
Query string `json:"query,omitempty"`
Base int `json:"base,omitempty"`
Msgs []api.Message `json:"msgs,omitempty"`
Checkpoint *TurnCheckpoint `json:"checkpoint,omitempty"`
TokenTotals *TurnJournalTokens `json:"token_totals,omitempty"`
}
type TurnJournalTokens ¶ added in v0.17.17
type UI ¶
type UI interface {
// ShowDropdown displays a dropdown selection UI
ShowDropdown(ctx context.Context, items interface{}, options DropdownOptions) (interface{}, error)
// ShowQuickPrompt shows a small prompt with quick choices
ShowQuickPrompt(ctx context.Context, prompt string, options []QuickOption, horizontal bool) (QuickOption, error)
// IsInteractive returns true if UI is available
IsInteractive() bool
}
UI provides UI capabilities to the agent
type WebUIPasswordPrompter ¶ added in v0.16.18
type WebUIPasswordPrompter struct {
// contains filtered or unexported fields
}
WebUIPasswordPrompter implements PasswordPrompter for WebUI sessions. Publishes a password_request event and blocks for the response.
func NewWebUIPasswordPrompter ¶ added in v0.16.18
func NewWebUIPasswordPrompter(agent *Agent) *WebUIPasswordPrompter
NewWebUIPasswordPrompter creates a WebUI-backed password prompter.
type WorkflowBudgetConfig ¶ added in v0.16.19
type WorkflowBudgetConfig struct {
USD float64 `json:"usd,omitempty"`
WarnAt []float64 `json:"warn_at,omitempty"`
}
WorkflowBudgetConfig is parsed from the "budget" section of a workflow JSON.
type WorkflowLoopConfig ¶ added in v0.16.19
type WorkflowLoopConfig struct {
TodoFile string `json:"todo_file,omitempty"`
GatePromptFile string `json:"gate_prompt_file,omitempty"`
MaxRetries int `json:"max_retries,omitempty"`
MaxIterations int `json:"max_iterations,omitempty"`
BuildCommand string `json:"build_command,omitempty"`
}
WorkflowLoopConfig is parsed from the "loop" section of a workflow JSON file. Only the fields relevant to the in-process runner are included.
type WorkflowProgressConfig ¶ added in v0.16.19
type WorkflowProgressConfig struct {
HeartbeatSeconds int `json:"heartbeat_seconds,omitempty"`
}
WorkflowProgressConfig is parsed from the "progress" section.
type WorkflowResult ¶ added in v0.16.19
WorkflowResult is returned when the workflow completes.
func RunWorkflowLoopInProcess ¶ added in v0.16.19
func RunWorkflowLoopInProcess(ctx context.Context, parentAgent *Agent, configPath string, eventBus *events.EventBus) (*WorkflowResult, error)
RunWorkflowLoopInProcess creates a fresh agent and runs the TODO loop workflow in the calling goroutine (blocking). For non-blocking use, call it from a goroutine.
The fresh agent is created using the same pattern as subagents: new client from factory, new state managers, proper interrupt context, full tool wiring via the seed tool registry, and budget tracking.
configPath is the path to the workflow JSON file. The file is parsed for the "loop" section; if no loop section is found, an error is returned.
type WorkspaceFileMetadata ¶
type WorkspaceFileMetadata struct {
// BrowserSeq counts user-driven edits to the file from the browser side.
// Bumped each time the user types and the change flushes to OPFS.
BrowserSeq int64 `json:"browser_seq"`
// ContainerSeq counts agent-driven writes to the file via the agent's
// tool handlers. Bumped each time writeFileContent succeeds.
ContainerSeq int64 `json:"container_seq"`
// LastSyncedBrowser is the BrowserSeq value the container has
// acknowledged. BrowserSeq > LastSyncedBrowser means the browser has
// unsynced edits — see the conflict rule.
LastSyncedBrowser int64 `json:"last_synced_browser"`
// LastSyncedContainer is the ContainerSeq value the browser has
// acknowledged.
LastSyncedContainer int64 `json:"last_synced_container"`
// ModifiedAt is the wall-clock time of the most recent write to the
// file from any source. Used by the staleness rule's "recent
// modification" check.
ModifiedAt time.Time `json:"modified_at"`
}
WorkspaceFileMetadata describes the per-file sync state for enforcing consistency between the browser-side OPFS replica and the container FS. On native sprout (single-replica), only ModifiedAt and the agent's turn-scoped read tracking matter; sequence fields are placeholders for the eventual WS-based sync layer.
func (WorkspaceFileMetadata) HasUnsyncedBrowserEdits ¶
func (m WorkspaceFileMetadata) HasUnsyncedBrowserEdits() bool
HasUnsyncedBrowserEdits reports whether the browser side has writes the container hasn't applied yet. The agent's write_file tool wrapper refuses to overwrite such files without explicit user confirmation.
Source Files
¶
- access_mode.go
- agent.go
- agent_accessors.go
- agent_change_methods.go
- agent_creation.go
- agent_debug.go
- agent_embedding.go
- agent_events.go
- agent_getters.go
- agent_helpers.go
- agent_helpers_ansi.go
- agent_history.go
- agent_lifecycle.go
- agent_logger.go
- agent_prompt.go
- agent_provider.go
- agent_query_guard.go
- agent_risk.go
- agent_runtime.go
- agent_security.go
- agent_shell.go
- agent_state.go
- agent_test_factory.go
- agent_test_helpers.go
- agent_tool_wiring.go
- agent_tool_wiring_nonjs.go
- agent_vision_probe.go
- api_client_types.go
- approval_allowlist.go
- approval_broker.go
- ask_user_service.go
- atomic_write.go
- background_cleanup_desktop.go
- change_tracking.go
- change_tracking_autoskip.go
- change_tracking_checkpoint.go
- change_tracking_helpers.go
- change_tracking_history_adapter.go
- change_tracking_mutations.go
- change_tracking_paths.go
- change_tracking_shell.go
- change_tracking_shell_persist.go
- change_tracking_snapshot.go
- change_tracking_summary.go
- clarification_manager.go
- command_policy.go
- computer_use_active_agent.go
- computer_use_registration.go
- context_budget.go
- context_discovery.go
- conversation.go
- conversation_optimizer.go
- conversation_pruner.go
- conversation_turn.go
- conversation_types.go
- conversation_utils.go
- cost_model.go
- debug_log.go
- destructive_app_prompter.go
- diff.go
- drift_detection.go
- drift_notification.go
- edit_approval.go
- embedded_prompts.go
- errors.go
- fleet_usd_budget.go
- force_save.go
- github_url_router.go
- helpers_test_util.go
- input.go
- llm_summarizer.go
- local_provider_hook.go
- mcp.go
- memory.go
- memory_embedding.go
- memory_gate.go
- memory_handlers.go
- memory_manage.go
- memory_search_handler.go
- metrics.go
- mock_provider.go
- mock_provider_init.go
- models.go
- notifications.go
- oom_watchdog.go
- oom_watchdog_proc_linux.go
- ordered_json.go
- ordered_map.go
- ordered_serialize.go
- ordered_yaml.go
- output_buffer.go
- output_router.go
- password_prompter_broker.go
- password_prompter_cli.go
- password_prompter_mux.go
- password_prompter_test_helpers.go
- password_prompter_webui.go
- path_tier.go
- pause.go
- persistence_index.go
- persistence_message.go
- persistence_session.go
- persona.go
- proactive_context.go
- project_discovery.go
- provider_syntax.go
- pruning_config.go
- resource_capture.go
- retry.go
- rewind.go
- risk_assessment.go
- risk_prompt.go
- rollup.go
- rollup_boundary.go
- rollup_embedding.go
- runtime_config_refresh.go
- scripted_assert.go
- scripted_dsl.go
- scripted_record.go
- scripted_response_builder.go
- search_engine_adapter.go
- secret_prompter.go
- security_analyzer.go
- security_analyzer_cache.go
- security_circuit_breaker.go
- seed_conversions.go
- seed_integration.go
- seed_provider.go
- seed_provider_token_anchor.go
- seed_query.go
- seed_special_token_guard.go
- seed_tool_event_publisher.go
- seed_tool_execution.go
- seed_tool_payload_helpers.go
- seed_tool_registry.go
- seed_tool_security.go
- semantic_recall.go
- semantic_recall_instrumentation.go
- session_info.go
- session_recovery.go
- settings_defs.go
- settings_handler.go
- shell.go
- shell_approval.go
- shell_approval_broker.go
- shell_approval_test_helpers.go
- shell_cwd.go
- shell_destructive.go
- shell_readonly.go
- simple_ui.go
- skill_loader_adapter.go
- skills.go
- state.go
- state_interfaces.go
- state_test_helpers.go
- steer_boundary.go
- steer_staging.go
- streaming.go
- subagent_creation.go
- subagent_display.go
- subagent_lifecycle.go
- subagent_monitoring.go
- subagent_runner.go
- subagent_runners.go
- subagent_task.go
- subagent_types.go
- submanager_mcp.go
- submanager_output.go
- submanager_security.go
- submanager_session.go
- submanager_state.go
- submanager_state_metrics.go
- submanager_state_persona.go
- submanager_state_security.go
- summary.go
- testing_state_isolation.go
- theme.go
- token_utils.go
- tool_call_format.go
- tool_definitions.go
- tool_definitions_from_registry.go
- tool_definitions_handler.go
- tool_direct_execute.go
- tool_duplicates.go
- tool_execution_context.go
- tool_execution_helpers.go
- tool_handlers.go
- tool_handlers_analysis.go
- tool_handlers_automate.go
- tool_handlers_automate_msgs.go
- tool_handlers_browse.go
- tool_handlers_changes.go
- tool_handlers_file.go
- tool_handlers_history.go
- tool_handlers_interaction.go
- tool_handlers_mcp.go
- tool_handlers_recover.go
- tool_handlers_repo_map.go
- tool_handlers_request_clarification.go
- tool_handlers_respond_clarification.go
- tool_handlers_search.go
- tool_handlers_shell.go
- tool_handlers_structured.go
- tool_handlers_subagent.go
- tool_handlers_subagent_events.go
- tool_handlers_subagent_result.go
- tool_handlers_subagent_spawn.go
- tool_handlers_subagent_spawn_cleanup.go
- tool_handlers_subagent_spawn_helpers.go
- tool_handlers_subagent_spawn_lifecycle.go
- tool_handlers_subagent_spawn_worktree.go
- tool_handlers_todo.go
- tool_json_repair.go
- tool_registry.go
- tool_result_constraint.go
- tool_security.go
- tool_security_audit.go
- tool_security_paths.go
- tool_security_policy.go
- tool_security_prompter.go
- tool_subagent_classify.go
- tool_visibility.go
- tools.go
- tools_approval_adapter.go
- training_hook.go
- transcript_snapshot.go
- turn_checkpoint_summary.go
- turn_checkpoints.go
- turn_embedding.go
- turn_journal.go
- turn_journal_wiring.go
- types.go
- ui.go
- ui_choice.go
- ui_types.go
- utils.go
- vision_batch_split.go
- workflow_runner.go
- workspace_sync.go