agent

package
v0.32.2 Latest Latest
Warning

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

Go to latest
Published: Oct 18, 2026 License: Apache-2.0 Imports: 88 Imported by: 0

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.

Package agent: approval broker forwarders (SP-141 phase 3, increment 5). The broker implementation (RequestApproval) and EvaluateCommandPolicy live in pkg/agent/approvals; these keep the *Agent method surface used by the tool-security gates, the seed-time security checks, and the destructive-approval prompter.

Package agent: ApprovalAgent seam accessors (SP-141 phase 3, increment 5). These exported methods expose the private surface the approval broker needs so it can live in pkg/agent/approvals behind the ApprovalAgent interface (the changes.AgentView / workflow.LoopAgent pattern). Each wrapper delegates to the existing private implementation unchanged; the broker (approvals.RequestApproval) is the only consumer.

SP-141 phase 2 wiring: the seam between pkg/agent and the extracted pkg/agent/changes package. The tracker's logic moved to changes; the Agent-facing construction half stays here (the unexported changeTracker field, the unexported config-stamping path, and Agent identity make it agent-internal), mirroring phase 1's workflow.LoopAgent shape: pkg/agent imports changes, never the reverse.

Package agent provides error definitions for the agent package.

final_message_guard.go — the final-message language guard. The final (completed) assistant message of a turn is judged against the user's language (the user-language resolution plus the configured language fallback); on a mismatch the message is not displayed: it is regenerated ONCE with an explicit instruction to answer in the user's language, and if the regeneration still mismatches (or fails) a short templated notice in the user's language is shown with the option to view the original. Images, screenshots and rendered previews pass through unchanged — the judgment is over extracted prose only (ExtractProse), so non-prose content is never affected.

langguard_metrics.go — the per-model language-guard metric. Every final message the guard judges is counted as a check; a reliable language mismatch is counted as a mismatch. The per-model mismatch rate (mismatches / checks) is the diagnostic signal: a high rate for a given model means that model frequently replies in the wrong language. The role dimension buckets each check under the agent's role, so the metric keys by (model, role): an empty model or role is bucketed under "unknown".

Package agent: forwarders for the path-tier / access-mode foundation, moved to the approvals subpackage (SP-141 phase 3).

The classifier and its helpers live in pkg/agent/approvals so they are reusable without a *Agent dependency. The aliases below keep every existing call site (risk_assessment.go, tool_security_paths.go, security_circuit_breaker.go, agent_security.go, computer_use_registration.go, submanager_security.go) working unchanged.

detectHomeDir is a test-override hook: it delegates to the approvals implementation so that overriding it in a test keeps working for the agent-side callers (risk_assessment.go, tool_security_paths.go).

Package agent — plan-context injection.

When a structured plan (.sprout/plan.json) exists for the project, the agent reads it at the start of a turn and injects a compact plan summary — the goal plus each scope item (id + title) with a status — into the turn's context so the model works scope item by scope item. When there is no plan, or the plan cannot be read or validated, nothing is injected and the turn is never failed: an absent or corrupt plan is "no plan", not an error.

The per-scope status is deliberately self-contained. Completion tracking must not depend on the todo scope-ID work nor on scope write-back, so the plan carries no completion data and every scope item is reported as "pending" (not yet confirmed done) until a later change tracks progress.

repetition_guard.go — the streaming degenerate-repetition guard. A model can occasionally degenerate mid-reply into a repetition loop: the same short line ("Let me run." / "Let me do it.") over and over with no tool call, until it breaks out on its own. Such a reply is a dead turn: nothing is acted on and the user waits out the loop. The guard watches the streamed assistant text, recognizes the degenerate run as it forms, and signals so the streaming layer can cut the attempt and retry once with a nudge.

The component is pure and fully unit-testable: it wraps a sink (the client-facing delivery, the same seam the language hold-back uses) and exposes Write / Finish / Reset / Looping / Dropped. It reconstructs lines from the chunk stream and holds back only the REPEATED occurrences of a short line — the first occurrence is legitimate prose and streams through per chunk, so live streaming is unchanged for ordinary replies. When a run of the same short line reaches the configured threshold the held duplicates are discarded (the degenerate text does not reach the client) and Looping() turns true; every later chunk is captured but not delivered.

False positives are the hazard, so the guard ignores fenced code blocks (repeated lines are normal there), counts only SHORT lines (a repeated long paragraph is prose, not degeneration), counts only near-verbatim consecutive identical lines (similar-but-different list items do not form a run), and treats blank lines as neutral. A progress log whose lines differ by a counter or path never accumulates a run.

repetition_metrics.go — the per-(provider, model) streamed-repetition metric. Every time the repetition guard cuts a degenerate run it records one loop for that (provider, model) pair, so a model that degenerates frequently is visible in the metrics. The counter is process-wide and safe for concurrent use (the guard runs on the agent's streaming path, which can be concurrent across chats); it mirrors the language-guard metric's shape.

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

Package agent: unified risk assessment — the *Agent forwarder (SP-141 phase 3, increment 6). The resolver implementation (approvals.ResolveToolRisk) and the RiskAgent seam live in pkg/agent/approvals (risk_resolver.go, risk_agent.go); this file keeps the *Agent method used by the tool-security gates, the seed-time security checks, and the shell handler.

Behavior preservation: the pre-move body was nil-*Agent-safe (it skipped every agent-coupled input and returned the classifier-only assessment). A nil *Agent boxed into the RiskAgent interface is non-nil, so that guard stays here.

Package agent: risk-assessment vocabulary + pure decision helpers — aliases and forwarders into pkg/agent/approvals (SP-141 phase 3, increment 4). The implementation (RiskSource, RiskAssessment, the Combine/Explain/decision helpers, and the git-command gate detectors) lives in approvals; these keep the historical pkg/agent identifiers working for ResolveToolRisk, the tool-handler gates, and the seed/tool-security call sites.

Package agent: RiskAgent seam accessors (SP-141 phase 3, increment 6). These exported methods expose the private surface the risk resolver needs so it can live in pkg/agent/approvals behind the RiskAgent interface (the ApprovalAgent / changes.AgentView / workflow.LoopAgent pattern). Each wrapper delegates to the existing implementation unchanged; the resolver (approvals.ResolveToolRisk) is the only consumer. EffectiveCwd, DebugEnabled, and DebugLogf come from approval_seam_accessors.go (same package).

Package agent — plan-scope milestone events.

When a todo_write changes the status of todos linked to a plan scope item (the todo "scope" field), the runtime emits a progress_milestone event for that scope item: phase "started" when one of its todos first goes in_progress, phase "finished" when all of its todos reach a terminal status (completed/cancelled). The finished event carries the files-touched count (change-tracker delta since the scope started) and the scope item's elapsed wall time. Every event carries the stable run id (the session id), the plan revision, and the scope id so consumers can de-duplicate and correlate the started/finished pair ("stable IDs (run, plan revision, scope item)").

The plan snapshot behind the payload is not frozen at the first load: the milestone path re-reads .sprout/plan.json and refreshes the cached revision and titles whenever the stored revision differs, so a scope write-back that bumps the plan mid-run is reflected by the very next milestone instead of every event reporting the revision first seen. And a scope whose todos go from open straight to all-terminal inside one todo_write — never observed in_progress — emits its whole lifecycle, started then finished, in that order.

An absent or corrupt plan never fails a todo_write: it means "no plan" (revision 0, no titles) and milestones still fire for the scope ids the todos carry.

Security audit logger lifecycle: resolving its path, opening it at agent start, and closing it on shutdown.

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 — stack-skill auto-activation.

When a project's starter manifest (.sprout/starter.json, loaded through pkg/starterstore) names a starter, the starter's own stack skill — the skill under pkg/skills/library/<starter>/ that carries the stack's conventions (formatter/linter, test conventions, the commands declared in the manifest) — activates automatically at the start of a turn, so the model works with the starter's defaults from the first turn.

Auto-activation is best-effort context enrichment: a missing or invalid manifest, or a starter with no skill, is a no-op and never fails a turn. Activation is idempotent — the skill is activated once and stays active for the rest of the session — so the per-turn cost is one manifest read and one registry lookup.

The upgrade-note half (the agent may propose an upgrade, never apply it silently) arrives later; this file is the auto-activation mechanism only.

Package agent — starter upgrade proposals.

When a project's starter manifest (.sprout/starter.json, loaded through pkg/starterstore) names an older version of its starter than the embedded starter tree (pkg/starters), the agent is told about the upgrade at the start of a turn: an advisory notice is appended to the turn's system prompt. The notice names the starter and both versions, points at the starter's stack-skill upgrade note (the "## Upgrade note" section of the skill auto-activated alongside), and carries the load-bearing instruction — the agent may PROPOSE the upgrade, but it never applies one silently; the upgrade is applied only when the user explicitly approves it.

The turn-start hook (prepareQueryRun, seed_query.go) calls starterUpgradeNotice once per turn — after the stack-skill auto-activation — and appends the notice to the composed system prompt, exactly like the plan summary. A missing or stale-free manifest changes nothing: the method returns "" in every case where there is no verifiable upgrade to propose.

The mechanism is a pure reader with respect to the project: it reads the manifest and the embedded starter catalogue and never writes a file. That purity is what guarantees the contract — this mechanism can propose, but it cannot apply; applying an upgrade is a deliberate, user-approved action.

stream_holdback.go — the streaming language-guard hold-back. A reply streams token by token, so a wrong-language reply would be visible to the client before a whole-message check could run. The guard holds back the start of each streamed reply until it has enough prose to judge (a few dozen words, code excluded via langguard.ExtractProse), checks it against the user's language, and then either releases the buffer and streams the rest live (pass / undetermined) or keeps the whole reply held (a reliable mismatch), so the wrong-language content never reaches the client.

A reply that never reaches the prose threshold — a short or code-only stream, which the guard does not judge — is released on Finish: it is never held. Only a judged, reliably-mismatched stream is held.

A reply that switches language mid-stream is re-checked at completion: the hold-back only judges the START of the stream (and releases it once the start passes), so a later switch is already streamed to the client and cannot be un-streamed. The hold-back therefore also accumulates the FULL content of the reply (Full), and the agent re-checks it at completion — replacing the already-streamed message with a server event when it fails.

The component is pure and fully unit-testable: it wraps a sink (the client-facing delivery) and exposes Write / Finish / State / Held. The agent wiring (seed_provider_chat.go) gates assistant-text delivery through it and, when a stream is held, delivers the localized notice instead of the wrong-language stream.

Package agent: subagents forwarders (SP-141 phase 4, increment 1). The subagent data types and their pure helpers (display, preamble, lifecycle counter, prefix builder) live in pkg/agent/subagents; these aliases and one-line forwarders keep the existing pkg/agent call sites (the tool handlers, the task runner, workflow wiring) unchanged. The SubagentRunner and its methods stay here until the runner seam.

Package agent: SubagentRunner construction and metrics (SP-141 phase 4, increment 2). The prefix builder and the process-wide active counter moved to pkg/agent/subagents in increment 1 (forwarded via subagent_forwarders.go); the lifecycle-event emission moved in increment 2. These thin wrappers resolve the runner's shared EventBus and delegate.

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: the SubagentRunner execution machinery (SP-141 phase 4, increment 1). The data types and pure helpers moved to pkg/agent/subagents (see subagent_forwarders.go for the aliases); the runner and the running-subagent tracker stay here until the runner seam lands, because they hold *Agent references (parentAgent, the child Agent) directly.

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. (12 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.

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.

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

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 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: which tools spawn subagents (and so are gated by subagent depth) and how the seed event publisher labels them for the UI.

Package agent: attached-image fallback resolution for vision tool inputs. Moved here from tool_handlers_analysis.go when the dead legacy handlers were removed (SP-137 B4). The interface-based handlers in pkg/agent_tools are the only execution path; this helper is used by the WebUI bridge to resolve image references to the latest attached user image when the referenced file is missing.

SP-141 phase 1 wiring: the workflow runner's construction half. The fresh loop Agent is built here (unexported Agent fields make construction agent-internal), then handed to the loop in pkg/agent/workflow via the LoopAgent seam — pkg/agent imports workflow, never the reverse.

Index

Constants

View Source
const (
	QuerySourceCLI        = "cli"
	QuerySourceWebUI      = "webui"
	QuerySourceAutoResume = "auto-resume"
	QuerySourceUnknown    = "unknown"
)

Query source constants used for QueryGuardOwner.Source.

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

View Source
const (
	BillingPayPerToken  = providers.BillingPayPerToken
	BillingSubscription = providers.BillingSubscription
	BillingFree         = providers.BillingFree
)

Billing type constants (re-exported for convenience within the agent package).

View Source
const (
	TaskTypeReadSearch = "read/search"
	TaskTypeSummarise  = "summarise"
	TaskTypeEdit       = "edit"
	TaskTypeTest       = "test"
	TaskTypeOther      = "other"
)

Task-type categories a delegated task is classified into. The order is the one classifyTaskType checks a matching word against, so a word that names several kinds of work takes the earlier category.

View Source
const (
	OutcomeVerified  = "verified"
	OutcomeEscalated = "escalated"
	OutcomeFailed    = "failed"
)

Verification outcomes a delegated task can finish with. "verified" means the worker's result passed the pre-reliance checks (or the task is a non-worker task that completed normally); "escalated" means the task was retried once on the coder model and that retry held; "failed" means it did not hold up.

View Source
const (
	DefaultMinMemoryBytes = 8 * 1024 * 1024 * 1024  // 8 GB
	DefaultRetryMinBytes  = 16 * 1024 * 1024 * 1024 // 16 GB
	DefaultRetrySleep     = 30 * time.Second
	DefaultMaxRetries     = 5
)

Default thresholds.

View Source
const (
	RunTerminationCompleted           = "completed"
	RunTerminationMaxIterations       = "max_iterations"
	RunTerminationInterrupted         = "interrupted"
	RunTerminationFleetBudgetExceeded = "fleet_budget_exceeded"
)
View Source
const (
	PathTierUnknown   = approvals.PathTierUnknown
	PathTierWorkspace = approvals.PathTierWorkspace
	PathTierExternal  = approvals.PathTierExternal
	PathTierSensitive = approvals.PathTierSensitive
)
View Source
const (
	RiskSourceClassifier        = approvals.RiskSourceClassifier
	RiskSourcePersonaCascade    = approvals.RiskSourcePersonaCascade
	RiskSourceCriticalOp        = approvals.RiskSourceCriticalOp
	RiskSourceGitHistoryRewrite = approvals.RiskSourceGitHistoryRewrite
	RiskSourceGitRebase         = approvals.RiskSourceGitRebase
	RiskSourceGitWrite          = approvals.RiskSourceGitWrite
	RiskSourceFSTier            = approvals.RiskSourceFSTier
	RiskSourceWorkspacePolicy   = approvals.RiskSourceWorkspacePolicy
	RiskSourceHandler           = approvals.RiskSourceHandler
	RiskSourcePasswordPrompter  = approvals.RiskSourcePasswordPrompter
)

The RiskSource taxonomy, aliased so existing references are unchanged.

View Source
const (
	SubagentStatusCompleted       = subagents.SubagentStatusCompleted
	SubagentStatusCancelled       = subagents.SubagentStatusCancelled
	SubagentStatusTimedOut        = subagents.SubagentStatusTimedOut
	SubagentStatusBudgetExceeded  = subagents.SubagentStatusBudgetExceeded
	SubagentStatusSecurityBlocked = subagents.SubagentStatusSecurityBlocked
	SubagentStatusFailed          = subagents.SubagentStatusFailed
)
View Source
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
)
View Source
const (
	MessageSourceOriginal      = changes.MessageSourceOriginal
	MessageSourceLLMCheckpoint = changes.MessageSourceLLMCheckpoint
)
View Source
const CompactedFilesHeader = changes.CompactedFilesHeader

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. Defined in pkg/agent/changes (with the parser); aliased above for the pkg/agent surface.

View Source
const DefaultClarificationTimeout = 60 * time.Second

DefaultClarificationTimeout is the default timeout for clarification requests.

View Source
const MaxChainSubcommandsForBatchPrompt = approvals.MaxChainSubcommandsForBatchPrompt
View Source
const ProgressLogCap = subagents.ProgressLogCap

ProgressLogCap bounds the per-run progress log (implementation in pkg/agent/subagents).

View Source
const RedactedContentMarker = changes.RedactedContentMarker

RedactedContentMarker aliases history.RedactedContentMarker (kept stable across the phase-2 move; the canonical definition lives in pkg/agent/changes next to its primary consumer).

View Source
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.

View Source
const TranscriptSnapshotFormat = "sprout-transcript/v1"

TranscriptSnapshotFormat identifies snapshot file shape. Bump when breaking shape changes land so older readers don't silently misparse.

View Source
const WakeupBatchPrefix = "[wakeup] "

WakeupBatchPrefix marks formatted wakeup batches. The REPL uses it to distinguish auto-resume turns from user-queued steer messages so the echo line and query source can be specialized.

Variables

View Source
var (
	ErrUINotAvailable = errors.New("UI not available")
	ErrCancelled      = errors.New("user cancelled")
)

UI errors

View Source
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.

View Source
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.

View Source
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.

View Source
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.

View Source
var ErrRunInterrupted = errors.New("query interrupted")

ErrRunInterrupted reports a query stopped by an interrupt (Stop, stale connection, shutdown) rather than one that failed.

View Source
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.

View Source
var MILESTONE_PHASES = []string{"spawn", "complete", "step"}

MILESTONE_PHASES defines phases that trigger immediate publish without batching

View Source
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.

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

func ApplyHunks(original string, hunks []Hunk, acceptedIDs []string) string

ApplyHunks reconstructs file content by applying only the accepted hunks.

func AssertNoStateLeak added in v0.16.6

func AssertNoStateLeak(realDir string, before map[string]time.Time) int

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

func BuildScopedSessionPathForTesting(stateDir, sessionID, workingDir string) (string, error)

BuildScopedSessionPathForTesting constructs the scoped session file path for test setup.

func BuildToolDefinitions added in v0.16.4

func BuildToolDefinitions() []api.Tool

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

func BuildToolDefinitionsForAgent(_ *Agent) []api.Tool

BuildToolDefinitionsForAgent returns the tool roster offered to the given agent's model.

func ChainCacheKey added in v0.17.7

func ChainCacheKey(input string) string

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

func ContextWithSproutDir(ctx context.Context, dir string) context.Context

ContextWithSproutDir returns a context that carries the sprout directory.

func DecrementActiveSubagents

func DecrementActiveSubagents()

DecrementActiveSubagents lowers the active-subagent counter when a subagent finishes (implementation in pkg/agent/subagents).

func DeleteMemory

func DeleteMemory(name string) error

DeleteMemory deletes a memory file by name (with .md extension)

func DeleteSession

func DeleteSession(sessionID string) error

DeleteSession removes a session state file

func DeleteSessionScoped

func DeleteSessionScoped(sessionID, workingDir string) error

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

func DeliverShellDecision(requestID string, decisions map[string]bool) bool

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 DetectLanguages(dir string) []string

func EstimateTokens

func EstimateTokens(text string) int

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 (implementation in pkg/agent/approvals).

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 FormatFileChangesForSummary added in v0.16.4

func FormatFileChangesForSummary(changesManifest []TranscriptFileChange) string

FormatFileChangesForSummary renders a manifest into the canonical text block appended to a /compact summary. SP-141 phase 2 forwarder — the implementation lives in pkg/agent/changes.

func FormatWakeupBatch added in v0.16.19

func FormatWakeupBatch(notifications []Notification) string

func FormatWakeupDisplay added in v0.17.24

func FormatWakeupDisplay(notifications []Notification) string

FormatWakeupDisplay renders the chat bubble shown to the user while the agent works on completed background tasks. It never exposes session IDs or tool mechanics — just the task name the user saw when the command started.

func GenerateUnifiedDiff added in v0.16.12

func GenerateUnifiedDiff(path, original, proposed string) (string, error)

GenerateUnifiedDiff produces a standard unified-diff string from original and proposed content.

func GetActiveSubagents

func GetActiveSubagents() int

GetActiveSubagents returns the number of running subagents (implementation in pkg/agent/subagents).

func GetEmbeddedPlanningPrompt

func GetEmbeddedPlanningPrompt(createTodos bool) (string, error)

GetEmbeddedPlanningPrompt returns the embedded planning prompt

func GetEmbeddedRollupPrompt added in v0.16.4

func GetEmbeddedRollupPrompt() string

GetEmbeddedRollupPrompt returns the rollup summarizer prompt.

func GetEmbeddedSystemPrompt

func GetEmbeddedSystemPrompt() (string, error)

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

func GetEmbeddedSystemPromptWithProvider(provider string) (string, error)

GetEmbeddedSystemPromptWithProvider returns the embedded system prompt

func GetSessionName

func GetSessionName(sessionID string) string

GetSessionName returns the name of a session

func GetSessionNameScoped

func GetSessionNameScoped(sessionID, workingDir string) string

func GetSessionPreview

func GetSessionPreview(sessionID string) string

GetSessionPreview returns the first 50 characters of the first user message

func GetSessionPreviewScoped

func GetSessionPreviewScoped(sessionID, workingDir string) string

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 GetSkillManifest

func GetSkillManifest(content string) (map[string]string, string, error)

func GetStateDir

func GetStateDir() (string, error)

GetStateDir returns the directory for storing conversation state

func GetStructuredPlanningPrompt added in v0.23.0

func GetStructuredPlanningPrompt(createTodos bool) (string, error)

GetStructuredPlanningPrompt returns the planning prompt with the structured-plan schema section appended after the base prompt body and before the todo-integration suffix. The schema section describes the .sprout/plan.json document the write_plan tool persists, including the rule that every scope item needs at least one acceptance item. It is advertised to the model only in structured planning mode (`sprout plan --structured`); the base GetEmbeddedPlanningPrompt never includes it.

func IncrementActiveSubagents

func IncrementActiveSubagents()

IncrementActiveSubagents bumps the process-wide active-subagent counter (implementation in pkg/agent/subagents).

func InjectUserMessageTimestamp added in v0.17.7

func InjectUserMessageTimestamp(userMessage string) string

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 stamp is applied once at injection — prepareQueryRun stamps the query before it enters the conversation state, and steer messages are stamped at delivery — so the stamped bytes are part of the prefix every later request replays byte-identically. The provider-boundary net (stampTurnTimestamp) only catches messages that somehow arrive unstamped. Persisted state is stripped (ExportState), so restored sessions re-stamp on their first turn. 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

func InjectUserMessageTimestampAt(userMessage string, at time.Time) string

InjectUserMessageTimestampAt prepends a timestamp fixed at at. Providers use it to keep one turn's prompt byte-identical across iterations and retries.

func IsApplicationCodePath added in v0.23.0

func IsApplicationCodePath(path string) bool

IsApplicationCodePath reports whether a changed workspace path counts as application code for the verification gate. It is a pure path-string predicate: it never touches the filesystem, and it classifies whatever form the caller passes (relative or absolute; separators normalized for the platform it runs on).

A path is NOT application code when either of these holds:

  • Documentation: a markdown file (a `.md` extension, any case), or any file under a `docs` directory segment at any depth (`docs/`, `foo/docs/`; the directory name compares case-insensitively). That covers the obvious README.md, CHANGELOG.md, and docs/** cases wherever they live. The rule matches the directory, not a file of that name: a file literally named `docs` (a final path element with no extension, e.g. `pkg/docs`) is application code. Other prose extensions (.txt, .rst) are deliberately not filtered — they may be fixtures or data.

  • Sprout bookkeeping: a path with a `.sprout` path segment (the plan/starter-manifest/session directory: `.sprout/plan.json`, `.sprout/starter.json`, ...), at any depth — including a final element named `.sprout` (a file of that name is bookkeeping too, unlike the docs rule above, which matches directories only). Segment equality only — `.sprout` as a substring of a segment (`mysprout/`, `x.sprout/`) is an ordinary name and stays application code.

Everything else is application code: sources (.go, .ts, .py, .rs, ...), markup and styles (.html, .css), build configuration (go.mod, package.json, Makefile), data, and unknown extensions. The gate exists to skip obvious no-build turns, so an unfamiliar path must fail open (count as application code and run verification), never silently skip it.

func IsInteractiveTool

func IsInteractiveTool(name string) bool

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

func IsMemoryIntensiveCommand(cmd string) bool

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 LanguageMismatchNotice added in v0.23.0

func LanguageMismatchNotice(user langguard.Language) string

LanguageMismatchNotice returns the templated notice in the user's language (the table's English entry for any code without a dedicated entry, including the zero language).

func LastLanguageGuardOriginal added in v0.23.0

func LastLanguageGuardOriginal(messages []api.Message) string

LastLanguageGuardOriginal returns the most recent "view original" payload the language guard stored (langGuardOriginalMetaKey on an assistant message), scanning the conversation from the end. It returns "" when no message carries one. Exported so the CLI's /original command reads the same key the guard writes — the string literal lives here and in the write sites above, nowhere else.

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

func ListChangesPersistedOnly(args map[string]interface{}) (string, error)

ListChangesPersistedOnly returns a session manifest from the persisted history store.

func ListSessions

func ListSessions() ([]string, error)

ListSessions returns all available session IDs

func ListTranscriptSnapshots added in v0.16.4

func ListTranscriptSnapshots(sessionID, workingDir string) ([]string, error)

ListTranscriptSnapshots returns snapshot file paths for the given session within the current workspace scope, sorted oldest-first.

func LoadContextFiles

func LoadContextFiles() (string, error)

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

func LoadMemoryContent(name string) (string, error)

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

func NewSproutProvider(agent *Agent, client api.ClientInterface) (core.Provider, error)

NewSproutProvider creates a Provider that wraps a sprout ClientInterface.

func NewTestStateDir added in v0.16.6

func NewTestStateDir(t *testing.T) func()

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/ until we caught it. See the `cleanup` body below for the Layer-5 detector that fails any future test that bypasses this isolation.

Returns a cleanup func that:

  1. Restores the original getStateDirFunc (mirrors t.Setenv unwind semantics but for our package-level function var).
  2. 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

func NormalizeChain(chain Chain) string

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 ParseAgentsMd(path string) (name string, description string)

func ParseJSONOrderedAny added in v0.16.8

func ParseJSONOrderedAny(content string) (interface{}, error)

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

func RegisterPasswordRequestForTest(requestID string) chan string

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 RemoveTurnJournal(sessionID, workingDir string) error

func RenameSession

func RenameSession(sessionID string, newName string) error

RenameSession renames a session by updating the name field in the state file

func RenameSessionScoped

func RenameSessionScoped(sessionID, newName, workingDir string) error

func RunWorkflowLoopInProcess added in v0.16.19

func RunWorkflowLoopInProcess(ctx context.Context, parentAgent *Agent, configPath string, eventBus *events.EventBus) (*workflow.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. (SP-141: entry lives in pkg/agent; the loop itself is pkg/agent/workflow.RunTodoLoop.)

func SaveMemory

func SaveMemory(name string, content string) error

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

func SerializeJSONOrdered(data interface{}) (string, error)

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

func SerializeYAMLOrdered(data interface{}) (string, error)

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 SetBackgroundHost added in v0.21.5

func SetBackgroundHost(active bool)

SetBackgroundHost marks whether a wakeup poller is running in this process. Pollers call it with true on start and false on exit.

func SetEditApprovalTimeout added in v0.16.17

func SetEditApprovalTimeout(d time.Duration)

SetEditApprovalTimeout overrides the default WebUI response timeout.

func SetGetStateDirForTest

func SetGetStateDirForTest(dir string) func() (string, error)

SetGetStateDirForTest is a convenience helper that sets getStateDirFunc to return a fixed directory for testing.

func SetGetStateDirForTestError

func SetGetStateDirForTestError(msg string) func() (string, error)

SetGetStateDirForTestError is a convenience helper that sets getStateDirFunc to return an error for testing error handling.

func SetGetStateDirFunc

func SetGetStateDirFunc(fn func() (string, error)) func() (string, error)

SetGetStateDirFunc sets the getStateDirFunc for testing purposes. Returns the previous function so it can be restored after the test.

func SetGlobalLanguageGuardMetricsForTest added in v0.23.0

func SetGlobalLanguageGuardMetricsForTest(r *LanguageGuardMetrics) func()

SetGlobalLanguageGuardMetricsForTest installs a recorder for the duration of a test. It returns a cleanup func that restores the previous recorder.

func SetGlobalRepetitionMetricsForTest added in v0.24.0

func SetGlobalRepetitionMetricsForTest(r *RepetitionMetrics) func()

SetGlobalRepetitionMetricsForTest installs a recorder for the duration of a test. It returns a cleanup func that restores the previous recorder.

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 package-level helpers 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

func SetStateDirFuncForTesting(fn func() (string, error)) func()

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

func SettingEnumValues(key string) []string

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

func SettingIsListType(key string) bool

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 ShortCommandLabel added in v0.17.24

func ShortCommandLabel(command string) string

ShortCommandLabel builds a user-facing task name from a shell command: first line only, whitespace-collapsed, capped to maxLabelRunes.

func SnapshotRealStateDir added in v0.16.6

func SnapshotRealStateDir() (realDir string, before map[string]time.Time)

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

func SproutDirFromContext(ctx context.Context) string

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

func StripUserMessageTimestamp(userMessage string) string

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

func TestShellApprovalRegister(requestID string) chan map[string]bool

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

func TestShellApprovalRespond(requestID string, decisions map[string]bool) bool

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

func WorkflowRequiresApproval(workflowName string) bool

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

func WorkflowRequiresApprovalIn(dir, workflowName string) bool

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 NewAgent

func NewAgent() (*Agent, error)

NewAgent creates a new agent with auto-detected provider

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

func NewAgentWithConfigDir(configDir, model string) (*Agent, error)

NewAgentWithConfigDir creates a new agent using a per-client config directory for WebUI isolation.

func NewAgentWithLayers

func NewAgentWithLayers(globalDir, workspaceDir, model string) (*Agent, error)

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

func NewAgentWithModel(model string) (*Agent, error)

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 NewTestAgentWithConfigManager added in v0.23.0

func NewTestAgentWithConfigManager(mgr *configuration.Manager) *Agent

NewTestAgentWithConfigManager is NewTestAgent with the configuration manager wired in, for tests that exercise config-gated behavior (e.g. the verification flag) without a full NewAgent.

func (*Agent) AddMessage

func (a *Agent) AddMessage(message api.Message)

AddMessage adds a single message to the conversation history

func (*Agent) AddSessionAllowedFolder

func (a *Agent) AddSessionAllowedFolder(folder string)

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

func (a *Agent) AddTaskAction(actionType, description, details string)

AddTaskAction records a completed task action for continuity

func (*Agent) AddToHistory

func (a *Agent) AddToHistory(command string)

AddToHistory adds a command to the history buffer

func (*Agent) AllowAppForComputerUse added in v0.16.19

func (a *Agent) AllowAppForComputerUse(key string)

AllowAppForComputerUse adds the given app key to the per-session allowlist. Guarded by computerUseMu.

func (*Agent) ApplyApprovalDecision added in v0.21.5

func (a *Agent) ApplyApprovalDecision(decision security.ApprovalDecision, command string)

ApplyApprovalDecision performs the side-effects of the user's approval choice (ApproveAlways persists the command; Elevate bumps the session risk profile).

func (*Agent) ApplyPersona

func (a *Agent) ApplyPersona(personaID string) error

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) ApproveShellCommandParts added in v0.21.5

func (a *Agent) ApproveShellCommandParts(ctx context.Context, command string) (map[string]bool, []string, error)

ApproveShellCommandParts splits `command` into a classified ShellProposal and runs the per-part approval picker, returning the per-part decisions and the proposal's part IDs (in order). Callers verify that every part was approved; any missing or denied part denies the whole command.

func (*Agent) AttributeCommitMessage added in v0.30.0

func (a *Agent) AttributeCommitMessage(message string, extra ...git.Assistant) string

AttributeCommitMessage appends the opt-in Assisted-by trailer (commit_attribution: "trailer") to a commit message sprout is about to create on this agent's behalf. The agent's own provider/model — the one that made the changes in this session — is always listed; extra lists further tool+model pairs that contributed, such as the model that wrote the commit message. Duplicates collapse to one line. With the setting off (the default) the message is returned unchanged.

func (*Agent) BackgroundTaskDetail added in v0.21.5

func (a *Agent) BackgroundTaskDetail(id string) (string, error)

BackgroundTaskDetail reports one task's progress or result for display. Unlike check_subagent it leaves the task's pending notification queued: the user looking at a result doesn't mean the agent has seen it.

func (*Agent) BackgroundTasksSummary added in v0.21.5

func (a *Agent) BackgroundTasksSummary() string

BackgroundTasksSummary lists background subagent tasks for display.

func (*Agent) BookRoleUsage added in v0.23.0

func (a *Agent) BookRoleUsage(role string, promptTokens, completionTokens int, cost float64)

BookRoleUsage attributes an external model call's usage to a role in the agent's per-role metrics. It records a cost entry under role — feeding both the per-role bucket and the overall cost totals — and advances the overall prompt/completion/total token counters, exactly as a first-party LLM call would, so the per-role totals keep summing to the overall totals. Used by a role-serving capability that runs its own model client outside the main loop (the progress summarizer), so that spend is visible in /cost-style views under its role. A no-op for a nil agent/state or a fully-zero usage.

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 (a *Agent) BuildCheckpointCompactedMessages(messages []api.Message) ([]api.Message, []TurnCheckpoint)

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

func (a *Agent) CanSpawnSubagents() bool

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

func (a *Agent) CaptureTranscriptSnapshot(label string, includePreview bool) (string, error)

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) CaptureVerificationCheckpoint added in v0.23.0

func (a *Agent) CaptureVerificationCheckpoint(res *verify.Result)

CaptureVerificationCheckpoint creates a checkpoint of the project's current state after the agent's verification run passed. It is the seam the automatic trigger goes through: the turn-end hook calls it on a passing run (res.Passed()), so a passing verification leaves a restorable marker on the timeline.

The checkpoint captures the agent's current revision (the change set the turn produced), not whichever revision happens to be most recent in the process history store: the marker must identify the state verification passed on.

It is a no-op for a nil or non-passing result. A capture failure is logged and swallowed: the checkpoint is a convenience over a run that already passed, and a store failure must never turn a good turn into an error.

func (*Agent) CheckFileContentSecurity

func (a *Agent) CheckFileContentSecurity(filePath string, content string)

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

func (a *Agent) CheckForInterrupt() bool

CheckForInterrupt checks if an interrupt was requested

func (*Agent) CheckPatchConflict

func (a *Agent) CheckPatchConflict(path string) (bool, string)

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

func (a *Agent) ClassifyFileAccess(ctx context.Context, filePath, resolvedPath, mode string) string

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) Client added in v0.21.5

func (a *Agent) Client() api.ClientInterface

Client returns the agent's provider client under the client lock.

func (*Agent) CommitChanges

func (a *Agent) CommitChanges(llmResponse string) error

CommitChanges commits all tracked changes to the change tracker

func (*Agent) ConsumePendingStrictSwitchNotice

func (a *Agent) ConsumePendingStrictSwitchNotice() string

func (*Agent) DebugEnabled added in v0.21.5

func (a *Agent) DebugEnabled() bool

DebugEnabled reports whether verbose debug logging is on.

func (*Agent) DebugLogf added in v0.21.5

func (a *Agent) DebugLogf(format string, args ...interface{})

DebugLogf writes a structured debug-log line (a no-op when debug is off).

func (*Agent) DebugLogger added in v0.21.5

func (a *Agent) DebugLogger() changes.DebugLogger

DebugLogger exposes the agent's logger as the narrow changes.DebugLogger interface so *Agent structurally satisfies changes.ChangeAgent without pkg/agent/changes importing pkg/agent (a concrete *AgentLogger return type in the interface would create an import cycle). Nil-safe.

func (*Agent) DeferredMessageCount

func (a *Agent) DeferredMessageCount() int

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

func (a *Agent) DisableStreaming()

DisableStreaming disables response streaming

func (*Agent) DisableWakeup added in v0.16.19

func (a *Agent) DisableWakeup()

func (*Agent) DrainDeferredMessages

func (a *Agent) DrainDeferredMessages() []string

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) DrainWakeupForREPL added in v0.17.21

func (a *Agent) DrainWakeupForREPL() []string

DrainWakeupForREPL returns and clears stashed wakeup batches destined for the REPL loop. Called by the REPL after ReadLine returns ErrWakeupPending (or at the top of each loop iteration) so the resume turn runs as an auto-queued turn through the normal machinery.

func (*Agent) EconomyDescription added in v0.32.1

func (a *Agent) EconomyDescription() string

EconomyDescription is the human-readable effect of the current mode, for the session info surfaces (the UI shows the mode and its effect plainly).

func (*Agent) EffectiveCwd added in v0.21.5

func (a *Agent) EffectiveCwd() string

EffectiveCwd returns the shell working directory the broker uses for LLM security analysis.

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

func (a *Agent) EnableChangeTracking(instructions string)

EnableChangeTracking enables change tracking for this agent session.

func (*Agent) EnableStreaming

func (a *Agent) EnableStreaming(callback func(string))

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 (a *Agent) EnqueueDeferredMessage(text string)

func (*Agent) EnsureLocalServer added in v0.17.17

func (a *Agent) EnsureLocalServer() error

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

func (a *Agent) ExportState() ([]byte, error)

ExportState exports the current agent state for persistence

func (*Agent) FleetBudgetExceeded

func (a *Agent) FleetBudgetExceeded() bool

FleetBudgetExceeded reports whether the fleet budget was exceeded (mid-run truncation).

func (*Agent) FlushState added in v0.32.0

func (a *Agent) FlushState()

FlushState synchronously writes the conversation to its session file. The web daemon calls it before the workspace stops so the transcript on disk matches what the user last saw. Agents with no messages are skipped so an idle chat does not leave an empty session file behind.

func (*Agent) ForceSaveAndExit added in v0.17.17

func (a *Agent) ForceSaveAndExit(code int)

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

func (a *Agent) ForkAtBreakpoint(breakpointIndex int) (string, error)

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) FormatCacheSavings added in v0.23.0

func (a *Agent) FormatCacheSavings() string

FormatCacheSavings renders the session's cache savings for display. When savings are known it is the USD amount; when any cached response had no determinable savings (no actual cost, no catalog rate) and nothing was determined, it is "unknown" — never a misleading "$0.000000".

func (*Agent) GenerateActionSummary

func (a *Agent) GenerateActionSummary() string

GenerateActionSummary creates a summary of completed actions for continuity

func (*Agent) GenerateCompactSummary

func (a *Agent) GenerateCompactSummary() string

GenerateCompactSummary creates a compact summary for session continuity (max 5K context)

func (*Agent) GenerateConversationSummary

func (a *Agent) GenerateConversationSummary() string

GenerateConversationSummary creates a comprehensive summary of the conversation including todos

func (*Agent) GenerateResponse

func (a *Agent) GenerateResponse(messages []api.Message) (string, error)

GenerateResponse generates a simple response using the current model without tool calls.

func (*Agent) GenerateSessionSummary

func (a *Agent) GenerateSessionSummary() string

GenerateSessionSummary creates a summary of previous actions for continuity

func (*Agent) GetActivePersona

func (a *Agent) GetActivePersona() string

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 (a *Agent) GetAvailablePersonaIDs() []string

func (*Agent) GetAvailableToolNames

func (a *Agent) GetAvailableToolNames() []string

func (*Agent) GetAverageTPS

func (a *Agent) GetAverageTPS() float64

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) GetCacheSavingsUnknown added in v0.23.0

func (a *Agent) GetCacheSavingsUnknown() bool

GetCacheSavingsUnknown reports whether any cached response in this session had no determinable savings. When true and no savings were determined, the cost views render "unknown" rather than a misleading $0.

func (*Agent) GetCacheWriteTokens added in v0.16.17

func (a *Agent) GetCacheWriteTokens() int

GetCacheWriteTokens returns the total tokens written to the provider cache

func (*Agent) GetCachedCostSavings

func (a *Agent) GetCachedCostSavings() float64

GetCachedCostSavings returns the cost savings from cached tokens

func (*Agent) GetCachedTokens

func (a *Agent) GetCachedTokens() int

GetCachedTokens returns the total cached/reused tokens

func (*Agent) GetChangeCount

func (a *Agent) GetChangeCount() int

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

func (a *Agent) GetChangesSummary() string

GetChangesSummary returns a summary of tracked changes

func (*Agent) GetChargedCostTotal added in v0.16.19

func (a *Agent) GetChargedCostTotal() float64

GetChargedCostTotal returns the total charged cost

func (*Agent) GetChatID added in v0.17.24

func (a *Agent) GetChatID() string

GetChatID returns the chat session this agent is bound to (WebUI event metadata "chat_id"), or "". Shell tools use it to scope hidden and background PTY sessions per conversation so multi-chat daemons don't share one shell. Nil-safe for bare Agents constructed in tests.

func (*Agent) GetCompletionTokens

func (a *Agent) GetCompletionTokens() int

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

func (a *Agent) GetConfigOverrides() map[string]interface{}

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

func (a *Agent) GetContextTokens() (used, limit int)

GetContextTokens returns the current and max token counts for the active model's context window.

func (*Agent) GetContextWarningIssued

func (a *Agent) GetContextWarningIssued() bool

GetContextWarningIssued returns whether a context warning has been issued

func (*Agent) GetContinuationNudges added in v0.17.18

func (a *Agent) GetContinuationNudges() int

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

func (a *Agent) GetCurrentContextTokens() int

GetCurrentContextTokens returns the current context token count

func (*Agent) GetCurrentIteration

func (a *Agent) GetCurrentIteration() int

GetCurrentIteration returns the current iteration number

func (*Agent) GetCurrentTPS

func (a *Agent) GetCurrentTPS() float64

GetCurrentTPS returns the current TPS value (alias for GetLastTPS)

func (*Agent) GetDebugLogPath

func (a *Agent) GetDebugLogPath() string

GetDebugLogPath returns the path to the current debug log file (if any)

func (*Agent) GetDelegatedTaskOutcomes added in v0.32.1

func (a *Agent) GetDelegatedTaskOutcomes() []DelegatedTaskOutcome

GetDelegatedTaskOutcomes returns a copy of the session's bounded delegated-task outcome records, most recent last. Nil-safe for a nil agent.

func (*Agent) GetDelegationSummary added in v0.32.1

func (a *Agent) GetDelegationSummary() DelegationSummary

GetDelegationSummary computes the session's delegation summary from the recorded outcomes: the share of the delegated work the worker model completed and the credits saved versus running it on the coder model. The savings are determined from the coder model's catalog rate; when that rate is unknown the savings are reported as unknown rather than a fabricated $0 (mirroring the cache-savings handling).

func (*Agent) GetEconomyMode added in v0.32.1

func (a *Agent) GetEconomyMode() bool

GetEconomyMode reports whether economy mode is currently on.

func (*Agent) GetEffectiveContextCap added in v0.17.7

func (a *Agent) GetEffectiveContextCap() int

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

func (a *Agent) GetEstimatedTokenResponses() int

GetEstimatedTokenResponses returns how many responses used estimated token usage.

func (*Agent) GetEventBus

func (a *Agent) GetEventBus() *events.EventBus

GetEventBus returns the current event bus

func (*Agent) GetEventChatID

func (a *Agent) GetEventChatID() string

GetEventChatID returns the bound chat_id from event metadata, if present.

func (*Agent) GetEventClientID

func (a *Agent) GetEventClientID() string

GetEventClientID returns the bound client_id from event metadata, if present.

func (*Agent) GetEventUserID

func (a *Agent) GetEventUserID() string

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

func (a *Agent) GetHistory() []string

GetHistory returns a defensive copy of the command history.

func (*Agent) GetHistoryCommand

func (a *Agent) GetHistoryCommand(index int) string

GetHistoryCommand returns the command at the given index from history

func (*Agent) GetHistorySize

func (a *Agent) GetHistorySize() int

GetHistorySize returns the number of commands in history

func (*Agent) GetImageTokens added in v0.17.5

func (a *Agent) GetImageTokens() int

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

func (a *Agent) GetInputInjectionContext() <-chan string

GetInputInjectionContext returns the input injection channel for the new system

func (*Agent) GetLLMCallCount

func (a *Agent) GetLLMCallCount() int

GetLLMCallCount returns the total number of LLM API calls made

func (*Agent) GetLastMessages

func (a *Agent) GetLastMessages(n int) []api.Message

GetLastMessages returns the last N messages for preview

func (*Agent) GetLastPreparedToolNames

func (a *Agent) GetLastPreparedToolNames() []string

GetLastPreparedToolNames returns the tool names sent in the most recent model request.

func (*Agent) GetLastRunTerminationReason

func (a *Agent) GetLastRunTerminationReason() string

func (*Agent) GetLastTPS

func (a *Agent) GetLastTPS() float64

GetLastTPS returns the most recent TPS value from the provider

func (*Agent) GetMainLoopEconomy added in v0.32.1

func (a *Agent) GetMainLoopEconomy() bool

GetMainLoopEconomy reports whether the main loop is running in economy mode for this session (the mode was on when the session started).

func (*Agent) GetMaxContextTokens

func (a *Agent) GetMaxContextTokens() int

GetMaxContextTokens returns the maximum context tokens for the current model

func (*Agent) GetMaxContextTokensCached added in v0.17.20

func (a *Agent) GetMaxContextTokensCached() int

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

func (a *Agent) GetMaxIterations() int

GetMaxIterations returns the maximum iterations allowed (0 means unlimited)

func (*Agent) GetMessages

func (a *Agent) GetMessages() []api.Message

GetMessages returns the current conversation messages

func (*Agent) GetModel

func (a *Agent) GetModel() string

GetModel gets the current model being used by the agent

func (*Agent) GetOptimizationStats

func (a *Agent) GetOptimizationStats() map[string]interface{}

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 (a *Agent) GetPersonaProviderModel(personaID string) (string, string, error)

func (*Agent) GetPreviousSummary

func (a *Agent) GetPreviousSummary() string

GetPreviousSummary returns the summary of previous actions

func (*Agent) GetPromptTokens

func (a *Agent) GetPromptTokens() int

GetPromptTokens returns the total prompt tokens used

func (*Agent) GetProvider

func (a *Agent) GetProvider() string

GetProvider returns the current provider name

func (*Agent) GetProviderType

func (a *Agent) GetProviderType() api.ClientType

GetProviderType returns the current provider type

func (*Agent) GetPruningStats

func (a *Agent) GetPruningStats() map[string]interface{}

GetPruningStats returns information about the current pruning configuration

func (*Agent) GetRevisionID

func (a *Agent) GetRevisionID() string

GetRevisionID returns the current revision ID (if change tracking is enabled)

func (*Agent) GetRole added in v0.23.0

func (a *Agent) GetRole() string

GetRole returns the role whose model selection this agent's usage is attributed to (a configuration.Role* constant, "coder" for the primary agent). Empty when the agent was built before role stamping (callers bucket it under "unknown").

func (*Agent) GetRoleUsage added in v0.23.0

func (a *Agent) GetRoleUsage() []RoleUsage

GetRoleUsage returns the per-role token/cost totals accumulated for this agent, sorted by role. Nil when no cost entry carried a role yet.

func (*Agent) GetSecurityAnalysisCache added in v0.21.5

func (a *Agent) GetSecurityAnalysisCache() *SecurityAnalysisCache

GetSecurityAnalysisCache returns the lazily-created LLM security-analysis cache (the nil-agent guard is preserved by the underlying getter).

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

func (a *Agent) GetSecurityCautionsIssued() int64

GetSecurityCautionsIssued returns the number of SECURITY_CAUTION_REQUIRED errors produced this session.

func (*Agent) GetSecurityLoopsDetected added in v0.16.12

func (a *Agent) GetSecurityLoopsDetected() int64

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

func (a *Agent) GetSecurityRetriesAfterCaution() int64

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

func (a *Agent) GetSessionID() string

GetSessionID returns the session identifier

func (*Agent) GetSessionName added in v0.16.18

func (a *Agent) GetSessionName() string

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

func (a *Agent) GetShellCwd() string

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

func (a *Agent) GetSystemPrompt() string

GetSystemPrompt returns the current system prompt

func (*Agent) GetTPSStats

func (a *Agent) GetTPSStats() map[string]float64

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

func (a *Agent) GetTokenCostTotal() float64

GetTokenCostTotal returns the total token-based cost

func (*Agent) GetTotalCost

func (a *Agent) GetTotalCost() float64

GetTotalCost returns the total cost of the conversation

func (*Agent) GetTotalTokens

func (a *Agent) GetTotalTokens() int

GetTotalTokens returns the total tokens used across all requests

func (*Agent) GetTrackedFiles

func (a *Agent) GetTrackedFiles() []string

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

func (a *Agent) GetUnsafeMode() bool

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

func (a *Agent) GetUnsafeShellMode() bool

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

func (a *Agent) GetWorkspaceRoot() string

GetWorkspaceRoot returns the logical workspace root for this agent instance.

func (*Agent) HandleInterrupt

func (a *Agent) HandleInterrupt() string

HandleInterrupt processes an interrupt request. Deterministic: any interrupt stops the current task immediately.

func (*Agent) HasActiveWebUIClients

func (a *Agent) HasActiveWebUIClients() bool

func (*Agent) HasPasswordPrompter added in v0.16.18

func (a *Agent) HasPasswordPrompter() bool

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 (a *Agent) HasPendingNotifications() bool

func (*Agent) HasSessionOverrides

func (a *Agent) HasSessionOverrides() bool

HasSessionOverrides returns true if there are session-scoped provider/model overrides

func (*Agent) HasTurnCheckpoints

func (a *Agent) HasTurnCheckpoints() bool

func (*Agent) HomeDir added in v0.21.5

func (a *Agent) HomeDir() string

HomeDir returns the user's home directory through the detectHomeDir test-override hook, or "" if unresolved. Routing through the hook (rather than os.UserHomeDir directly) keeps the pre-move test overrides working.

func (*Agent) ImportState

func (a *Agent) ImportState(data []byte) error

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

func (a *Agent) InjectInputContext(input string) error

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

func (a *Agent) InterruptCtx() context.Context

InterruptCtx returns the agent's interrupt context so child operations (e.g., tool execution) can derive from it and respect user cancellations.

When the stored context is stale-canceled (a previous turn was interrupted and no query is running to reset it) this returns a fresh context instead — see ensureLiveInterruptCtx. Snapshotting the dead context here made every post-interrupt slash command that takes a context (/compact, /review, /review-deep, /shell) fail instantly with "context canceled".

Healing is not sticky: a between-turns call clears the interrupted state, so a later CheckForInterrupt() no longer observes the earlier interrupt. Callers that must remember an interrupt should capture it at the point it happens, not re-read it between turns.

func (*Agent) IsAppAllowedForComputerUse added in v0.16.19

func (a *Agent) IsAppAllowedForComputerUse(key string) bool

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

func (a *Agent) IsCdTargetAllowed(target string) bool

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

func (a *Agent) IsChangeTrackingEnabled() bool

IsChangeTrackingEnabled returns whether change tracking is enabled

func (*Agent) IsDebugMode

func (a *Agent) IsDebugMode() bool

IsDebugMode returns whether debug mode is enabled

func (*Agent) IsFolderSessionAllowed

func (a *Agent) IsFolderSessionAllowed(absPath string) bool

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

func (a *Agent) IsFolderSessionWriteAllowed(absPath string) bool

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) IsGitWriteAllowed added in v0.21.5

func (a *Agent) IsGitWriteAllowed() bool

IsGitWriteAllowed reports whether the active persona carries the git-write capability (the persona gate the risk resolver folds into the assessment).

func (*Agent) IsInteractiveMode

func (a *Agent) IsInteractiveMode() bool

IsInteractiveMode returns true if running in interactive mode

func (*Agent) IsInterrupted

func (a *Agent) IsInterrupted() bool

IsInterrupted returns true if an interrupt has been requested

func (*Agent) IsLocalMode

func (a *Agent) IsLocalMode() bool

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) IsNonInteractive added in v0.21.5

func (a *Agent) IsNonInteractive() bool

IsNonInteractive reports whether the agent runs without an interactive approval surface.

func (*Agent) IsPathOutsideWorkspace added in v0.16.12

func (a *Agent) IsPathOutsideWorkspace(path string) bool

IsPathOutsideWorkspace reports whether the resolved absolute path falls outside the agent's workspace root.

func (*Agent) IsQueryInProgress added in v0.16.17

func (a *Agent) IsQueryInProgress() bool

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

func (a *Agent) IsReadOnlyAllowedFolder(absPath string) bool

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

func (a *Agent) IsSecurityBypassApproved() bool

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

func (a *Agent) IsSessionElevated() bool

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

func (a *Agent) IsShellCommandAllowlisted(command string) bool

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

func (a *Agent) IsShutdown() bool

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, stopped MCP servers — have to be able to observe it.

func (*Agent) IsStreamingEnabled

func (a *Agent) IsStreamingEnabled() bool

IsStreamingEnabled returns whether streaming is enabled

func (*Agent) IsSubagent

func (a *Agent) IsSubagent() bool

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

func (a *Agent) IsUnderWorkspaceRoot(absPath string) bool

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 (a *Agent) IsWakeupDisabled() bool

func (*Agent) IsWorkflowApprovedInSession added in v0.16.4

func (a *Agent) IsWorkflowApprovedInSession(workflow string) bool

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) IsWorkflowRun added in v0.23.0

func (a *Agent) IsWorkflowRun() bool

IsWorkflowRun reports whether this agent is executing a workflow/automate run, which is non-interactive for approval purposes even when launched from a terminal.

func (*Agent) LanguageGuardStats added in v0.23.0

func (a *Agent) LanguageGuardStats() []LanguageGuardModelStat

LanguageGuardStats is the Agent's diagnostic accessor for the language-guard metric: it returns the process-wide per-(model, role) snapshot — for each (model, role), how many final messages the guard judged and how many were mismatches, with a mismatch rate per (model, role). A high rate for a model means it frequently replies in the wrong language. It is pure Go (no cgo), so it works in the native daemon, the CLI, and the WASM build alike.

func (*Agent) LastQualityResult added in v0.23.0

func (a *Agent) LastQualityResult() *verify.QualityResult

LastQualityResult returns the turn's last quality-after-edits run, or nil when the hook never ran for the turn (quality disabled, no code change, a subagent turn, or a runner setup error).

func (*Agent) LastTurnVerification added in v0.23.0

func (a *Agent) LastTurnVerification() *TurnVerification

LastTurnVerification returns the turn's stored end-verification state (stored by the turn-end hook on every verification run), or nil when the hook never ran for the turn (verification disabled, the turn changed no code, a subagent turn, or a runner setup error) — including on a nil receiver. Attempts is a copy: mutating it never affects the agent's stored state.

func (*Agent) LastVerificationResult added in v0.23.0

func (a *Agent) LastVerificationResult() *verify.Result

LastVerificationResult returns the last turn-end verification result, stored on every verification run (pass, fail, or stop-rule), or nil when the turn-end hook never ran for this agent (verification disabled, the turn changed no code, a subagent turn, or a runner setup error). The final-reply contract and the verification event report from it.

func (*Agent) LifetimeCtx added in v0.17.14

func (a *Agent) LifetimeCtx() context.Context

LifetimeCtx returns a lazily-initialized, process-scoped context for background goroutines.

func (*Agent) ListAllowedCdTargets added in v0.17.7

func (a *Agent) ListAllowedCdTargets() []string

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

func (a *Agent) ListChanges(args map[string]interface{}) (string, error)

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

func (a *Agent) LoadStateFromFile(filename string) error

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

func (a *Agent) LoadSummaryFromFile(filename string) error

LoadSummaryFromFile loads ONLY the compact summary from a state file for minimal continuity

func (*Agent) LogSecurityDecision added in v0.21.5

func (a *Agent) LogSecurityDecision(tool string, args map[string]interface{}, assessment RiskAssessment, action string)

LogSecurityDecision records an approval outcome in the audit logger.

func (*Agent) LogToolCall

func (a *Agent) LogToolCall(tc api.ToolCall, phase string)

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) MarkSessionStarted added in v0.32.1

func (a *Agent) MarkSessionStarted()

MarkSessionStarted is the exported form of markSessionStarted, for a caller that has loaded a prior conversation (a resumed session) before the first turn: it tells the agent the session is already under way, so a subsequent SetEconomyMode is a mid-session change that re-routes subagents without switching the main-loop model the resumed prompt cache was built on.

func (*Agent) MarkWorkflowApprovedInSession added in v0.16.4

func (a *Agent) MarkWorkflowApprovedInSession(workflow string)

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

func (a *Agent) MaxSubagentDepth() int

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

func (a *Agent) MergeEventMetadata(extras map[string]interface{})

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

func (a *Agent) MyRecentChanges(since string) (string, error)

MyRecentChanges returns the cross-session timeline. Thin wrapper around list_changes(include_persisted=true, include_cross_session=true, since=…).

func (*Agent) NavigateHistory

func (a *Agent) NavigateHistory(direction int, currentIndex int) (string, int)

NavigateHistory navigates through command history direction: 1 for up (older), -1 for down (newer) currentIndex: current position in the input line

func (*Agent) NotVerifiedReason added in v0.24.1

func (a *Agent) NotVerifiedReason() string

NotVerifiedReason states why the agent's current turn has no verification result (Agent.LastVerificationResult == nil), reusing the same reasons the turn-completion event carries (progress_complete.not_verified_reason). It is the accessor consumers outside pkg/agent use — the benchmark report records it on a run whose verification never produced a result, so a failed run always carries the reason instead of reading as a silent failure.

The values are:

  • "" — verification is disabled for this agent (no configuration manager, or the configuration does not enable verification);
  • "no code changes this turn" — verification is enabled but the turn changed no application code (the hook's change gate);
  • "verification setup error" — the turn changed application code and the hook entered, but its verify runner hit a setup error and stored nothing;
  • "verification did not run this turn" — verification is enabled and code changed, but the hook still did not run (a subagent turn, or the reason was not otherwise recorded).

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 (a *Agent) NotifyCompletion(sessionID, kind, content string)

NotifyCompletion queues a background-task notification without a label. Satisfies the agent_tools.BackgroundNotifier interface.

func (*Agent) NotifyCompletionLabeled added in v0.17.24

func (a *Agent) NotifyCompletionLabeled(sessionID, kind, content, label string)

NotifyCompletionLabeled queues a background-task notification with a short user-facing task name shown in the WebUI wakeup bubble.

func (*Agent) ObserveRead added in v0.24.1

func (a *Agent) ObserveRead(path string, startLine, endLine int) int

ObserveRead implements tools.ReadCallGuard. It records an identical read_file call (same path + same effective range) and returns how many times that exact call has been made this turn, including this one. The read_file handler uses a count of 3 or more to return a short note instead of re-emitting content the model already has. State is per-agent and reset at each turn boundary by ResetFileReadsForNewTurn.

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

func (a *Agent) PendingSteerCount() int

PendingSteerCount returns the number of staged entries not currently in flight (the retractable set, plus any rejected-then-released ones).

func (*Agent) PersistShellCommandAllowlist

func (a *Agent) PersistShellCommandAllowlist(command string) error

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

func (a *Agent) PersistShellCommandAskPolicy(command string) error

PersistShellCommandAskPolicy adds a "always ask" command policy rule for the given command.

func (*Agent) PersistShellCommandPattern added in v0.16.12

func (a *Agent) PersistShellCommandPattern(pattern string) error

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) PrepareShellCommand added in v0.21.5

func (a *Agent) PrepareShellCommand(command string)

PrepareShellCommand primes the shell-mutation baseline before a command that may change files runs. Agents that skip the eager prime (subagents, so read-only ones never pay for a workspace walk) otherwise primed after their first mutating command, losing that command's changes.

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

func (a *Agent) PrintConversationSummary(forceFull bool)

PrintConversationSummary displays a comprehensive conversation summary with formatting

func (*Agent) PrintLine

func (a *Agent) PrintLine(text string)

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

func (a *Agent) PrintLineAsync(text string)

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

func (a *Agent) PrintTerminalOnly(text string)

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

func (a *Agent) ProcessQuery(userQuery string) (string, error)

ProcessQuery handles the main conversation loop with the LLM

func (*Agent) ProcessQueryAs added in v0.17.20

func (a *Agent) ProcessQueryAs(source, userQuery string) (string, error)

ProcessQueryAs is ProcessQuery with an explicit caller source recorded on the query guard for accurate busy-state messaging.

func (*Agent) ProcessQueryWithContinuity

func (a *Agent) ProcessQueryWithContinuity(userQuery string) (string, error)

func (*Agent) ProcessQueryWithContinuityAs added in v0.17.20

func (a *Agent) ProcessQueryWithContinuityAs(source, userQuery string) (string, error)

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

func (a *Agent) PublishAgentMessage(category, message string, extra map[string]interface{})

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

func (a *Agent) PublishCompactStarted(source string, messageCount, checkpointCount int)

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

func (a *Agent) PublishEvent(eventType string, data interface{})

PublishEvent publishes an event through the agent's event bus with metadata decoration.

func (*Agent) PublishFileChange

func (a *Agent) PublishFileChange(filePath, action, content string)

PublishFileChange emits a file_changed event for ChangeTracker-detected mutations.

func (*Agent) PublishQueryProgress

func (a *Agent) PublishQueryProgress(message string, iteration int, tokensUsed int)

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) PublishRawEvent added in v0.21.5

func (a *Agent) PublishRawEvent(eventType string, data interface{})

PublishRawEvent publishes eventType/data on the event bus WITHOUT the event-metadata decoration that publishEvent adds. The change-tracking shell-bulk rollup (pkg/agent/changes) uses it so the seam preserves the pre-seam publish semantics exactly. Nil-safe.

func (*Agent) PublishStreamChunk

func (a *Agent) PublishStreamChunk(chunk string, contentType string)

PublishStreamChunk publishes a streaming chunk for real-time updates

func (*Agent) PublishTodoUpdate

func (a *Agent) PublishTodoUpdate(todos []map[string]interface{})

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) 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) PublishTurnProgressComplete added in v0.23.0

func (a *Agent) PublishTurnProgressComplete()

PublishTurnProgressComplete exposes the turn-completion progress emit — the progress_verification / progress_complete pair built from the stored turn-end verification result — for cross-package tests and embedding turn loops. It is the same path handleQueryResult calls on the success path; a no-op when no event bus is wired or the turn is a subagent turn.

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

func (a *Agent) ReadFileContent(path string) (string, error)

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) RecordErrorCategory added in v0.16.19

func (a *Agent) RecordErrorCategory(err error)

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

func (a *Agent) RecordFileReadThisTurn(path string)

RecordFileReadThisTurn marks `path` as read by the agent during the current turn. Called from the read_file tool handler.

func (*Agent) RecordTurnCheckpoint

func (a *Agent) RecordTurnCheckpoint(startIndex, endIndex int)

func (*Agent) RecordTurnCheckpointAsync

func (a *Agent) RecordTurnCheckpointAsync(startIndex, endIndex int)

func (*Agent) RecordWakeupTokens added in v0.16.19

func (a *Agent) RecordWakeupTokens(tokens int, cfg configuration.WakeupConfig)

func (*Agent) RecoverFile

func (a *Agent) RecoverFile(path string) (string, error)

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

func (a *Agent) RefreshMCPTools() error

RefreshMCPTools refreshes the MCP tools cache

func (*Agent) RefreshRuntimeConfig added in v0.16.19

func (a *Agent) RefreshRuntimeConfig(ctx context.Context) error

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

func (a *Agent) RefreshSkills() error

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

func (a *Agent) RemoveSessionAllowedFolder(folder string) error

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) RepetitionLoopStats added in v0.24.0

func (a *Agent) RepetitionLoopStats() []RepetitionLoopStat

RepetitionLoopStats is the Agent's diagnostic accessor for the repetition metric: it returns the process-wide per-(provider, model) snapshot — how many degenerate repetition loops the guard cut for each pair. It is pure Go (no cgo), so it works in the native daemon, the CLI, and the WASM build alike.

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

func (a *Agent) RequestShellApproval(ctx context.Context, p ShellProposal) (map[string]bool, error)

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:

  1. If no parts, returns empty map and nil error.
  2. If the WebUI has an active surface, dispatch via the security approval manager (the real WebUI per-part dialog is implemented in requestShellApprovalViaWebUI).
  3. 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) ResetWakeupBudget added in v0.17.24

func (a *Agent) ResetWakeupBudget()

ResetWakeupBudget clears the wakeup disable flag and both budget counters. Called when a real user query arrives: budget exhaustion should pause auto-resume until the user re-engages, not silence it for the rest of the session — otherwise background completions sit in the queue and only show up prepended to the user's next message.

func (*Agent) ResolveBillingType added in v0.17.5

func (a *Agent) ResolveBillingType() string

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

func (a *Agent) RespondToPasswordRequest(requestID string, password string) bool

RespondToPasswordRequest delivers a user password to a pending password request. Called by the WebUI handler.

func (*Agent) RespondToShellApproval added in v0.17.10

func (a *Agent) RespondToShellApproval(requestID string, decisions map[string]bool) bool

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) RetractLatestDeferredMessage added in v0.17.18

func (a *Agent) RetractLatestDeferredMessage() (string, bool)

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

func (a *Agent) RetractLatestSteer() (string, bool)

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

func (a *Agent) RevertMyChanges(scope, file, since string) (string, error)

RevertMyChanges performs a bulk revert. With a non-empty `file` it reverts that one path; the single-path recover result is translated into the same {restored, failed, summary, entries} envelope the bulk path returns, so every caller (WebUI/API) sees one shape — a per-file revert used to return {recovered, path, action, message}, which the UI summary helper could not read.

func (*Agent) ReviewChanges added in v0.21.5

func (a *Agent) ReviewChanges(ctx context.Context, opts ReviewChangesOptions) (*ReviewChangesResult, error)

ReviewChanges reviews a change with one or more reviewer subagents. It owns the parts that shouldn't depend on the calling model: building each reviewer's pre-loaded context, deciding whether to split the change across parallel reviewers, and merging their findings into one result.

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) RollupSubagentUsage added in v0.23.0

func (a *Agent) RollupSubagentUsage(r *subagents.SubagentResult)

RollupSubagentUsage folds a completed subagent/reviewer's usage into this agent's totals, attributed to the role that drove the subagent's model choice with the subagent's actual prompt/completion token split. It records a cost entry under the subagent's role (feeding both the per-role bucket and the overall cost totals) and advances the overall prompt/completion/total token counters — exactly as a first-party LLM call would — so the per-role totals keep summing to the overall totals. The subagent's own metrics manager is left untouched; this is the parent-side attribution.

func (*Agent) RotateSession added in v0.16.25

func (a *Agent) RotateSession() (string, error)

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

func (a *Agent) RunAutomateWorkflow(ctx context.Context, workflow string) (string, error)

RunAutomateWorkflow executes a named workflow and returns the JSON result. This is the public entry point for the WebUI automate API.

func (*Agent) RunForcedTurnEndVerification added in v0.24.1

func (a *Agent) RunForcedTurnEndVerification(ctx context.Context) (*verify.Result, error)

RunForcedTurnEndVerification runs the turn-end verification without consulting the turn's change window, and stores the result as the turn's verification state. It is the escape hatch for a caller that has independent evidence the turn changed the workspace (the benchmark runner's git baseline) but whose changes never reached Agent.TurnChangedPaths.

It shares the hook's inputs and storage: a snapshot of the starter manifest and the active plan is taken if the turn has none (getTurnVerifySnapshot), the runner's commands come only from the manifest and the explicit project configuration (verify.ConfigurationCommands), and the stored state is the same turnVerification the hook writes — so LastVerificationResult, LastTurnVerification, and the per-turn repair metrics see this result exactly as they see a hook-run one.

Unlike the hook it runs once: it does not feed a failing check back to the model for repair (the turn is already over). The result is stored and returned.

It no-ops (returns nil, nil) when verification is disabled for this turn's configuration, or the agent has no configuration: the forced seam still honors the verification switch — a benchmark run forces the switch on, but the seam is general and a disabled run must never verify. A setup error (no executor, empty root) is returned so the caller can record why no result was produced; nothing is stored in that case.

func (*Agent) SaveConversationSummary

func (a *Agent) SaveConversationSummary() error

SaveConversationSummary saves the conversation summary to the state file

func (*Agent) SaveState

func (a *Agent) SaveState(sessionID string) error

SaveState saves the current conversation state

func (*Agent) SaveStateScoped

func (a *Agent) SaveStateScoped(sessionID, workingDir string) error

SaveStateScoped saves conversation state under a directory-scoped session namespace.

func (*Agent) SaveStateToFile

func (a *Agent) SaveStateToFile(filename string) error

SaveStateToFile saves agent state to a file

func (*Agent) SelectProvider

func (a *Agent) SelectProvider() error

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

func (a *Agent) SetBaseSystemPrompt(prompt string)

SetBaseSystemPrompt updates the baseline prompt used when persona overrides are cleared.

func (*Agent) SetBudgetExceededCallback added in v0.16.4

func (a *Agent) SetBudgetExceededCallback(fn func(spent, limit float64))

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

func (a *Agent) SetBudgetWarningCallback(fn func(threshold, spent, limit float64))

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

func (a *Agent) SetConfigOverrides(overrides map[string]interface{})

SetConfigOverrides stores session-scoped config overrides on the agent. These are applied in-memory and persisted with the session state.

func (*Agent) SetConversationOptimization

func (a *Agent) SetConversationOptimization(enabled bool)

func (*Agent) SetEconomyMode added in v0.32.1

func (a *Agent) SetEconomyMode(enabled bool)

SetEconomyMode enables or disables economy mode for this session. Called before the first turn it also starts the main loop in economy mode (for a new session); called mid-session it changes only which subagents get the worker model, leaving the main-loop model where it is.

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

func (a *Agent) SetEventBus(eventBus *events.EventBus)

SetEventBus sets the event bus for real-time UI updates and initializes the validator

func (*Agent) SetEventMetadata

func (a *Agent) SetEventMetadata(metadata map[string]interface{})

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

func (a *Agent) SetFleetBudget(tracker *atomic.Int64, limit int64)

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

func (a *Agent) SetHasActiveWebUIClients(fn func() bool)

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

func (a *Agent) SetLastPreparedToolNames(tools []api.Tool)

SetLastPreparedToolNames records the exact tool names prepared for the most recent model request.

func (*Agent) SetMaxIterations

func (a *Agent) SetMaxIterations(max int)

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

func (a *Agent) SetMessages(messages []api.Message)

SetMessages sets the conversation messages (for restore)

func (*Agent) SetModel

func (a *Agent) SetModel(model string) error

SetModel changes the current model for the session (session-scoped, not persisted).

func (*Agent) SetModelPersisted

func (a *Agent) SetModelPersisted(model string) error

SetModelPersisted changes the current model and persists the choice to config.

func (*Agent) SetOutputMutex

func (a *Agent) SetOutputMutex(mutex *sync.Mutex)

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

func (a *Agent) SetPreviousSummary(summary string)

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

func (a *Agent) SetPruningSlidingWindowSize(size int)

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

func (a *Agent) SetPruningThreshold(threshold float64)

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

func (a *Agent) SetRecentMessagesToKeep(count int)

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) SetRole added in v0.23.0

func (a *Agent) SetRole(role string)

SetRole sets the role the agent's model calls are attributed to. The primary constructor stamps the coder role (the main conversation loop is the coder's); entry points whose loop serves a different purpose re-stamp it here — e.g. the planning entry point stamps the planner role so the plan agent's metering is attributed to the planner, not the coder.

func (*Agent) SetSessionAllowedFolderMode added in v0.17.7

func (a *Agent) SetSessionAllowedFolderMode(folder, mode string)

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

func (a *Agent) SetSessionID(sessionID string)

SetSessionID sets the session identifier for continuity

func (*Agent) SetSessionName

func (a *Agent) SetSessionName(name string)

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

func (a *Agent) SetShellCwd(dir string)

SetShellCwd sets the logical shell working directory and records the previous.

func (*Agent) SetSlashCommands added in v0.17.5

func (a *Agent) SetSlashCommands(registry any)

SetSlashCommands stores the command registry on the agent. Called after the registry is created in cmd/agent_mode_interactive.go.

func (*Agent) SetStatsUpdateCallback

func (a *Agent) SetStatsUpdateCallback(callback func(int, float64))

SetStatsUpdateCallback sets a callback for token/cost updates

func (*Agent) SetStreamingCallback

func (a *Agent) SetStreamingCallback(callback func(string))

SetStreamingCallback sets a custom callback for streaming output

func (*Agent) SetStreamingEnabled

func (a *Agent) SetStreamingEnabled(enabled bool)

SetStreamingEnabled enables or disables streaming responses

func (*Agent) SetSystemPrompt

func (a *Agent) SetSystemPrompt(prompt string)

SetSystemPrompt sets the system prompt for the agent

func (*Agent) SetSystemPromptFromFile

func (a *Agent) SetSystemPromptFromFile(filePath string) error

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

func (a *Agent) SetUI(ui UI)

SetUI sets the UI provider for the agent

func (*Agent) SetUnsafeMode

func (a *Agent) SetUnsafeMode(unsafe bool)

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

func (a *Agent) SetUnsafeShellMode(unsafe bool)

SetUnsafeShellMode sets the unsafe shell mode flag. No-op when the security submanager is unset.

func (*Agent) SetWakeupDoneFn added in v0.20.0

func (a *Agent) SetWakeupDoneFn(fn func(err error))

SetWakeupDoneFn registers fn to run after each background resume turn, with the turn's error. nil clears it.

func (*Agent) SetWakeupWakeFn added in v0.17.21

func (a *Agent) SetWakeupWakeFn(fn func())

SetWakeupWakeFn registers the REPL wake callback used by TryAutoResume (interactive CLI). Pass nil to revert to the background-goroutine path.

func (*Agent) SetWorkflowRun added in v0.23.0

func (a *Agent) SetWorkflowRun(v bool)

SetWorkflowRun marks the agent as executing a workflow/automate run, which is non-interactive for approval purposes regardless of the console's interactivity. Safe to call before any turn runs.

The flag is process-scoped for the life of the run: a workflow run is a distinct, direct-mode invocation (cmd/agent_modes.go forces isInteractive false when a workflow config drives the run and returns when it ends), so the agent instance is not reused for a later interactive session. If that ever changes, call SetWorkflowRun(false) when the run ends.

func (*Agent) SetWorkspaceMode added in v0.22.0

func (a *Agent) SetWorkspaceMode(mode string)

SetWorkspaceMode records the workspace mode the next query was sent from. Hosts (the web UI server, the WASM shell) call it before each query; the mode's skills activate at turn start.

func (*Agent) SetWorkspaceRoot

func (a *Agent) SetWorkspaceRoot(workspaceRoot string)

SetWorkspaceRoot records the logical workspace root for this agent instance.

func (*Agent) ShouldGateEdit added in v0.16.12

func (a *Agent) ShouldGateEdit(path string) bool

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

func (a *Agent) ShowColoredDiff(oldContent, newContent string, maxLines int)

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

func (a *Agent) ShowMyChange(path string) (string, error)

ShowMyChange returns a unified diff JSON envelope for `path`. Shape matches the frontend's ChangeDiffResponse: {found, path, op, tool, diff}. The diff is computed from the in-memory session buffer when the path was touched this session; otherwise it falls back to the persisted history store so previous-session entries in the timeline tab still render a diff.

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

func (a *Agent) SlashCommands() any

SlashCommands returns the agent's command registry, or nil if not set.

func (*Agent) SnapshotSessionAllowedFolderModes added in v0.17.7

func (a *Agent) SnapshotSessionAllowedFolderModes() map[string]string

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

func (a *Agent) SnapshotSessionAllowedFolders() []string

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

func (a *Agent) StageSteerInput(text string) error

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

func (a *Agent) SteeringChannel() <-chan string

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) StopBackgroundTask added in v0.21.5

func (a *Agent) StopBackgroundTask(id string) (string, error)

StopBackgroundTask stops a running background task.

func (*Agent) SubagentDepth

func (a *Agent) SubagentDepth() int

SubagentDepth returns the nesting depth of this agent. 0 = primary agent (EA), 1 = orchestrator, 2 = coder/tester, etc.

func (*Agent) SummarizeMySession

func (a *Agent) SummarizeMySession() (string, error)

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) TakeUnbookedUsage added in v0.20.0

func (a *Agent) TakeUnbookedUsage() Usage

TakeUnbookedUsage returns the usage accrued since the previous call (or since the conversation was restored) and marks it booked. The running totals only grow within a conversation; a total below its mark means they were reset, and everything since the reset is new.

func (*Agent) TakeUnbookedUsageByRole added in v0.23.0

func (a *Agent) TakeUnbookedUsageByRole() map[string]Usage

TakeUnbookedUsageByRole returns the per-role usage accrued since the previous call and marks each role booked. The delta for each role is computed against that role's own mark, with the same reset detection as the overall view (a per-role total below its mark means it was reset, so everything since the reset is new). The values are Usage with Role set.

The overall and per-role views agree: because the per-role totals feed the overall totals, the sum of the per-role deltas equals TakeUnbookedUsage's delta (each LLM call records one cost entry that lands in exactly one role's bucket and in the overall totals).

func (*Agent) ToolLog

func (a *Agent) ToolLog(action string, target string)

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

func (a *Agent) TrackFileEdit(filePath string, originalContent string, newContent string) error

TrackFileEdit is called by the EditFile tool to track file edits

func (*Agent) TrackFileWrite

func (a *Agent) TrackFileWrite(filePath string, originalContent string, content string) error

TrackFileWrite is called by the WriteFile tool to track file writes. originalContent is the file's pre-write state captured by the handler before the write (empty for a create).

func (*Agent) TrackFileWriteState added in v0.21.5

func (a *Agent) TrackFileWriteState(filePath string, originalContent string, content string, existed bool) error

TrackFileWriteState is TrackFileWrite for callers that know whether the file existed before the write (so an existing empty file isn't recorded as a create, which revert would delete).

func (*Agent) TrackMetricsFromResponse

func (a *Agent) TrackMetricsFromResponse(promptTokens, completionTokens, totalTokens int, estimatedCost float64, cachedTokens, cacheWriteTokens, imageTokens int, actualCost float64)

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). actualCost is the provider-reported cost for this request (OpenRouter `usage.cost`); 0 when the provider does not report one.

func (*Agent) TrackShellCommand added in v0.17.26

func (a *Agent) TrackShellCommand(command string) error

TrackShellCommand is called by the shell_command tool to capture filesystem mutations made outside the file tools (scripts, rm, git checkout, ...). It skips commands the read-only classifier can prove change nothing, then diffs the workspace — which records both writes and deletes. Best-effort: callers treat this as fire-and-forget.

func (*Agent) TriggerInterrupt

func (a *Agent) TriggerInterrupt()

TriggerInterrupt manually triggers an interrupt for testing purposes

func (*Agent) TryAutoResume added in v0.17.14

func (a *Agent) TryAutoResume() bool

TryAutoResume checks whether there are pending background-task notifications that warrant an automatic agent resume. If so, it drains them and re-invokes the agent so it can act on the completed background tasks.

Routing depends on the host surface:

  • Interactive CLI: a wake function is registered (SetWakeupWakeFn) that interrupts the idle REPL prompt and runs the resume turn through the loop's full turn machinery — assistant renderer, spinner, steer panel, turn summary. Running the turn on a side goroutine instead left currentTurnRenderer nil, so every stream chunk fell through the PrintExternal fallback, which appends a newline per chunk — prose rendered one token per line.
  • WebUI / headless: no wake function; the resume runs inline on a background goroutine (events publish to the bus, WebUI renders).

Returns true if a resume was scheduled, 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

func (a *Agent) TryBeginQuery() error

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

func (a *Agent) TryBeginQueryAs(source string) error

TryBeginQueryAs marks this Agent as "query in progress" and records the caller source so busy-state messages can name the actual holder.

func (*Agent) TurnChangedApplicationPaths added in v0.23.0

func (a *Agent) TurnChangedApplicationPaths() []string

TurnChangedApplicationPaths returns the distinct workspace paths the current turn changed that count as application code (IsApplicationCodePath), in TurnChangedPaths' first-seen order — or nil when change tracking is off, the turn changed no files, or every changed path is documentation or .sprout bookkeeping. The turn-end verification gate and the not-verified reason read this filtered window, not the raw one: a docs-only or bookkeeping-only turn reports "no code changes" and never starts a build.

func (*Agent) TurnChangedPaths added in v0.23.0

func (a *Agent) TurnChangedPaths() []string

TurnChangedPaths returns the distinct workspace paths this agent's current turn changed (the gate for the turn-end verification run), or nil when change tracking is off or the turn changed no files. The window opens at the turn's EnableChangeTracking (MarkTurnStart) and is read without consuming it.

func (*Agent) WaitWakeupGoroutines added in v0.17.25

func (a *Agent) WaitWakeupGoroutines()

WaitWakeupGoroutines blocks until every auto-resume goroutine spawned by TryAutoResume's headless path has finished.

The query guard is NOT a teardown boundary for these turns: the resume's deferred auto-save runs AFTER EndQuery (defer LIFO across ProcessQueryWithContinuityAs and processQueryWithSeed), so session state can be written while IsQueryInProgress() already reports false. Callers that tear down the agent's state dir — test cleanup above all, but also Shutdown mid-flight — must wait on this instead, or the save lands in the temp dir mid-cleanup ("TempDir cleanup: directory not empty" / the [state-leak] CI failure).

func (*Agent) WebUIAttached added in v0.21.10

func (a *Agent) WebUIAttached() bool

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). WebUIAttached reports whether a web UI server is attached to this agent.

func (*Agent) WorkspaceMode added in v0.22.0

func (a *Agent) WorkspaceMode() string

WorkspaceMode returns the mode recorded by SetWorkspaceMode, or "".

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) GetCacheSavingsUnknown added in v0.23.0

func (m *AgentMetricsManager) GetCacheSavingsUnknown() bool

GetCacheSavingsUnknown reports whether any cached response had no determinable savings (missing actual cost and missing catalog rate).

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) GetRoleUsage added in v0.23.0

func (m *AgentMetricsManager) GetRoleUsage() []RoleUsage

GetRoleUsage returns the per-role token/cost totals, sorted by role for stable output. A nil receiver returns nil. The per-role ChargedCost/ TokenCost sums agree with the aggregate chargedCostTotal/tokenCostTotal because both are accumulated with the same guards.

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) SetCacheSavingsUnknown added in v0.23.0

func (m *AgentMetricsManager) SetCacheSavingsUnknown(unknown bool)

SetCacheSavingsUnknown records that a cached response had no determinable savings. Monotonic within a session — once unknown, the session's savings display stays "unknown" until a determined value is set.

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) SetRoleUsage added in v0.23.0

func (m *AgentMetricsManager) SetRoleUsage(usages []RoleUsage)

SetRoleUsage replaces the per-role usage map. Used by state restore to rehydrate the per-role totals so they keep summing to the restored overall totals. An empty/nil slice clears the map.

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) GetEventMetadataUnlocked added in v0.26.1

func (m *AgentOutputManager) GetEventMetadataUnlocked() map[string]interface{}

GetEventMetadataUnlocked returns metadata without acquiring the mutex. Caller must hold m.eventMetadataMu (read or write). Callers that already hold the read lock must use this instead of GetEventMetadata: RWMutex read locks are not reentrant, and a second RLock queued behind a pending writer deadlocks both the reader and the writer.

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

func (*AgentSecurityManager) WebUIAttached added in v0.21.10

func (m *AgentSecurityManager) WebUIAttached() bool

WebUIAttached reports whether a web UI server is attached that could answer an approval request, now or once a browser connects.

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 (12 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) 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) 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"`
	// QueryDisplays maps a user message to the chat bubble shown for it when
	// the two differ — a background-task wakeup the model reads as a status
	// batch, the user as "Looking into '…'…".
	QueryDisplays   map[string]string `json:"query_displays,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"`
	// CacheSavingsUnknown records that at least one cached response had no
	// determinable savings (no actual cost and no usable catalog rate), so the
	// cost views render "unknown" rather than a misleading $0 after a restore.
	CacheSavingsUnknown bool `json:"cache_savings_unknown,omitempty"`
	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"`

	// Per-role token/cost totals. Persisted so a
	// restored conversation keeps its per-role attribution and the per-role
	// totals keep summing to the restored overall totals.
	RoleUsage []RoleUsage `json:"role_usage,omitempty"`

	// PendingBackgroundNotifications are background-task completion notices
	// that were queued but not yet delivered to the model. They survive
	// agent teardown/restore (idle eviction in the daemon re-creates
	// agents from this snapshot) so a task finishing while its chat was
	// away still wakes the conversation later.
	PendingBackgroundNotifications []Notification `json:"pending_background_notifications,omitempty"`
}

AgentState represents the state of an agent that can be persisted

type AgentStateManager

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 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 = approvals.BrokerDecision

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.

func (*CLIPasswordPrompter) Prompt added in v0.16.18

func (cli *CLIPasswordPrompter) Prompt(ctx context.Context, reason string) (string, error)

Prompt asks the user to type a password on the terminal. Returns ErrNoInteractiveSurface if stdin is not a TTY. SuspendIndicator/PauseSteer/SuspendStreaming ensure the prompt isn't clobbered.

type CacheStats added in v0.16.25

type CacheStats interface {
	GetCachedTokens() int
	SetCachedTokens(int)
	GetCacheWriteTokens() int
	SetCacheWriteTokens(int)
	GetCachedCostSavings() float64
	SetCachedCostSavings(float64)
	GetCacheSavingsUnknown() bool
	SetCacheSavingsUnknown(bool)
	GetImageTokens() int
	SetImageTokens(int)
}

CacheStats manages prompt cache statistics.

type Chain added in v0.17.7

type Chain = approvals.Chain

func ParseChain added in v0.17.7

func ParseChain(s string) Chain

type ChangeTracker

type ChangeTracker = changes.ChangeTracker

ChangeTracker manages change tracking for the agent workflow. SP-141 phase 2 moved the implementation to pkg/agent/changes; this alias keeps every pkg/agent (and external) reference to agent.ChangeTracker valid with no behavior change.

func NewChangeTracker

func NewChangeTracker(view changes.AgentView, instructions string) *ChangeTracker

NewChangeTracker creates a new change tracker for an agent session. Thin forwarder to changes.NewChangeTracker through the AgentView seam.

type CheckpointFileChange

type CheckpointFileChange = changes.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). SP-141 phase 2: alias to pkg/agent/changes, where the tracker that produces these entries now lives.

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

type ChoiceOption struct {
	Label string
	Value string
}

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

type ContextFileInfo struct {
	Path        string
	Content     string
	Description string
	Priority    int
}

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

type ContinuationNudgeStore interface {
	RecordContinuationNudges(int)
	GetContinuationNudges() int
}

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

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"`
	CacheSavingsUnknown     bool             `json:"cache_savings_unknown,omitempty"`
	ImageTokens             int              `json:"image_tokens,omitempty"`
	// Per-role token/cost totals. Persisted so a
	// restored session keeps its per-role attribution and the per-role
	// totals keep summing to the restored overall totals.
	RoleUsage            []RoleUsage `json:"role_usage,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"`
	// QueryDisplays: see AgentState.QueryDisplays.
	QueryDisplays map[string]string `json:"query_displays,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"`

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

func (*ConversationState) DisplayMessages added in v0.20.0

func (s *ConversationState) DisplayMessages() []api.Message

DisplayMessages returns the messages as the chat showed them: user messages without the timestamp envelope the model was sent, or as their recorded bubble text where one differs.

type CostEntry added in v0.16.19

type CostEntry struct {
	BillingType      string  `json:"billing_type"`
	Provider         string  `json:"provider"`
	Model            string  `json:"model"`
	Role             string  `json:"role,omitempty"`
	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

Role is the role name (a configuration.Role* constant such as "coder" or "reviewer") whose model selection drove this call. The metrics manager aggregates per-role usage keyed by this field; an empty Role is bucketed under "unknown" (consistent with the language-guard metric), so a call that never resolved a role never drops its usage.

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)
	// GetRoleUsage returns the per-role token/cost totals,
	// sorted by role. Nil/empty when no cost entry carried a
	// role yet.
	GetRoleUsage() []RoleUsage
	// SetRoleUsage replaces the per-role token/cost totals.
	// Used by state restore to rehydrate the per-role totals so
	// they keep summing to the restored overall totals.
	SetRoleUsage([]RoleUsage)
}

CostTracker manages billing costs, token costs, and subscription/free token counts.

type DelegatedTaskOutcome added in v0.32.1

type DelegatedTaskOutcome struct {
	Model            string  `json:"model"`
	Provider         string  `json:"provider"`
	Role             string  `json:"role"`
	TaskType         string  `json:"task_type"`
	Outcome          string  `json:"outcome"`
	Tokens           int     `json:"tokens"`
	PromptTokens     int     `json:"prompt_tokens"`
	CompletionTokens int     `json:"completion_tokens"`
	Cost             float64 `json:"cost"`
	// At is the record time (RFC3339 UTC).
	At string `json:"at"`
}

DelegatedTaskOutcome is the record of one completed delegated task. Model and Provider name the model that produced the FINAL result (the coder model when a worker task was escalated), Role the role that model was resolved through, TaskType the prompt's work kind, Outcome the verification result, and Tokens/Cost what the final result consumed. No prompt text is carried.

type DelegationSummary added in v0.32.1

type DelegationSummary struct {
	// TaskCount is the number of recorded delegated tasks.
	TaskCount int `json:"task_count"`
	// WorkerTaskCount is the number of tasks whose final result the worker
	// model produced (verified without escalation).
	WorkerTaskCount int `json:"worker_task_count"`
	// TotalTokens / WorkerTokens are the delegated token totals, overall and
	// for the worker-model-completed tasks.
	TotalTokens  int `json:"total_tokens"`
	WorkerTokens int `json:"worker_tokens"`
	// WorkerTokenShare is WorkerTokens/TotalTokens (0 when there is no
	// delegated work): the share of delegated work the worker model handled.
	WorkerTokenShare float64 `json:"worker_token_share"`
	// CoderProvider/CoderModel and WorkerProvider/WorkerModel are the two
	// models the savings comparison is made between.
	CoderProvider  string `json:"coder_provider"`
	CoderModel     string `json:"coder_model"`
	WorkerProvider string `json:"worker_provider"`
	WorkerModel    string `json:"worker_model"`
	// CreditsSaved is the USD saved by running the worker-model tasks on the
	// worker model instead of the coder model.
	CreditsSaved float64 `json:"credits_saved"`
	// CreditsSavedKnown is false when the savings could not be determined
	// (the coder model's rate is unknown) — render "unknown", not $0.
	CreditsSavedKnown bool `json:"credits_saved_known"`
}

DelegationSummary aggregates a session's delegated-task outcomes: the share of the delegated work the worker model actually completed, and the credits saved versus running that work on the coder model.

type DiffChange

type DiffChange struct {
	OldStart  int
	OldLength int
	NewStart  int
	NewLength int
}

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 DropdownItem struct {
	Label string
	Value string
}

DropdownItem represents an item in a dropdown selection

type DropdownOptions struct {
	Prompt       string
	SearchPrompt string
	ShowCounts   bool
}

DropdownOptions provides options for dropdown display

type EditDecision added in v0.16.12

type EditDecision struct {
	Approved      bool
	AcceptedHunks []string
}

EditDecision captures the user's per-hunk accept/reject choices.

type EditProposal added in v0.16.12

type EditProposal struct {
	Path     string
	Original string
	Proposed string
	Hunks    []Hunk
}

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 = subagents.FileChange

Type aliases — the canonical definitions are in pkg/agent/subagents.

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 GuardOutcome added in v0.23.0

type GuardOutcome struct {
	// Display is what the user sees: the final text (no mismatch, or a
	// successful regeneration) or the localized templated notice (a
	// mismatch the single regeneration could not repair).
	Display string
	// Original is the mismatched message — the "view original" payload.
	// "" when there was no mismatch.
	Original string
	// Regenerated reports the regeneration's role in the outcome: true on
	// the display path (the displayed text came from the regeneration
	// call); on the notice path, true only when the regeneration produced
	// text that still failed the check, false when it errored or
	// produced nothing.
	Regenerated bool
	// Mismatched reports whether a language mismatch was detected in the
	// final message.
	Mismatched bool
}

GuardOutcome is the result of running the final assistant message through the final-message guard.

func FinalMessageGuard added in v0.23.0

func FinalMessageGuard(ctx context.Context, finalText string, user langguard.Language, regenerate Regenerator) GuardOutcome

FinalMessageGuard checks finalText against the user's language and repairs a mismatch exactly once. Behavior matrix:

  • user language undetermined (user.Code == ""): Display is finalText unchanged (byte-identical passthrough), no mismatch, regenerate is not called.
  • CheckLanguage(finalText, user) is pass or undetermined (too short, code-heavy, detector unsure): Display is finalText unchanged, no mismatch, regenerate is not called.
  • mismatch: regenerate is called EXACTLY ONCE and its result is re-checked:
  • regenerated text that is not a mismatch is displayed (Regenerated=true, Original=finalText);
  • a regenerated text that is still a mismatch, or a regeneration error / empty result, shows the templated notice in the user's language (Mismatched=true, Original=finalText, Regenerated only when the regeneration produced text).

An empty regeneration result counts as a failed regeneration — the notice is shown, never a blank display.

type HoldbackState added in v0.23.0

type HoldbackState int

HoldbackState is the lifecycle of a StreamHoldback over one streamed reply.

const (
	// HoldbackBuffering: chunks are accumulating; the prose has not yet
	// reached the judgable threshold (or the user language is still being
	// judged). Nothing has been delivered to the sink.
	HoldbackBuffering HoldbackState = iota
	// HoldbackLive: the buffer has been released (or the hold-back is
	// inactive); subsequent chunks pass straight through to the sink.
	HoldbackLive
	// HoldbackHeld: the accumulated prose is a reliable mismatch; the whole
	// reply is held and never delivered to the sink.
	HoldbackHeld
)

The hold-back states.

type Hunk added in v0.16.12

type Hunk struct {
	ID       string
	OldStart int
	OldLines int
	NewStart int
	NewLines int
	Lines    []DiffLine
}

Hunk represents a discrete change region in a unified diff.

func SplitIntoHunks added in v0.16.12

func SplitIntoHunks(original, proposed string) []Hunk

SplitIntoHunks computes the unified diff and splits it into discrete hunks with stable IDs.

type IterationStore added in v0.16.25

type IterationStore interface {
	GetCurrentIteration() int
	SetCurrentIteration(int)
}

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 LanguageGuardMetrics added in v0.23.0

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

LanguageGuardMetrics aggregates per-(model, role) language-guard observations into a per-(model, role) mismatch rate. It is process-wide and safe for concurrent use from any goroutine (the guard runs on the agent's query path, which can be concurrent across chats). The process-wide instance is exposed via GlobalLanguageGuardMetrics; tests build their own with NewLanguageGuardMetrics for isolation.

func GlobalLanguageGuardMetrics added in v0.23.0

func GlobalLanguageGuardMetrics() *LanguageGuardMetrics

GlobalLanguageGuardMetrics returns the process-wide recorder, creating one if init hasn't run yet (defensive — init above normally sets it).

func NewLanguageGuardMetrics added in v0.23.0

func NewLanguageGuardMetrics() *LanguageGuardMetrics

NewLanguageGuardMetrics constructs an empty recorder.

func (*LanguageGuardMetrics) OverallRate added in v0.23.0

func (m *LanguageGuardMetrics) OverallRate() float64

OverallRate returns the aggregate mismatch rate across all (model, role) cells (total mismatches / total checks; 0 when no checks have been recorded).

func (*LanguageGuardMetrics) Record added in v0.23.0

func (m *LanguageGuardMetrics) Record(modelID, role string, mismatched bool)

Record counts one guarded judgment of a final message for a (model, role) pair. A check is always counted; a mismatch is counted additionally when mismatched is true. This keeps the invariant Mismatches <= Checks per (model, role). A nil receiver is a no-op. An empty model ID or role is bucketed under "unknown" so a missing value never drops the observation.

func (*LanguageGuardMetrics) Snapshot added in v0.23.0

Snapshot returns a copy of every per-(model, role) stat, sorted by ModelID then Role for stable output. A nil receiver returns nil.

type LanguageGuardModelStat added in v0.23.0

type LanguageGuardModelStat struct {
	ModelID    string
	Role       string
	Checks     int64
	Mismatches int64
}

LanguageGuardModelStat is one (model, role) cell of the language-guard metric: how many final messages the guard judged for that model under that role (Checks) and how many of those were a reliable mismatch (Mismatches).

func (LanguageGuardModelStat) Rate added in v0.23.0

Rate returns this model's mismatch rate: mismatches / checks. It is 0 when no checks have been recorded (a model never judged has no measurable rate).

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

type MemoryGateError struct {
	AvailableBytes int64
	RequiredBytes  int64
	Retried        bool
}

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 = changes.MessageAnnotation

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 = changes.MessageSource

MessageSource tags how a message arrived in the live conversation. The type and its values moved to pkg/agent/changes; these aliases keep the pkg/agent surface byte-compatible.

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

func (m *MockLLMProvider) ListModels(ctx context.Context) ([]api.ModelInfo, error)

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) 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
	Label     string           // short user-facing task name (e.g. "make build")
	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"
	NotifSubagent       NotificationKind = "subagent"
)

type OOMProbeResult added in v0.16.19

type OOMProbeResult struct {
	NodeCount     int
	TotalRSSBytes uint64
	Timestamp     time.Time
}

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

func (ob *OutputBuffer) Clear()

Clear clears the 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{}
	GetEventMetadataUnlocked() 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 = approvals.PathTier

PathTier is the approval-tier classification of a filesystem path.

func ClassifyPathAccess

func ClassifyPathAccess(path, workspaceRoot, homeDir, cwd string) PathTier

ClassifyPathAccess decides which approval tier a path falls into.

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 ProgressEntry

type ProgressEntry = subagents.ProgressEntry

Type aliases — the canonical definitions are in pkg/agent/subagents.

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

type QuickOption struct {
	Label string
	Value string
}

QuickOption represents a quick choice option

type RateLimitExceededError

type RateLimitExceededError struct {
	Attempts  int
	LastError error
}

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 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 Regenerator added in v0.23.0

type Regenerator func(ctx context.Context) (string, error)

Regenerator performs the single regeneration model call: "regenerate once". Implementations issue exactly one model call — a focused prompt, not a re-run of the tool loop. The guard calls it at most once, never in a retry loop.

type RepairReport added in v0.17.17

type RepairReport struct {
	DroppedToolResults         int
	StrippedAssistantToolCalls int
}

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 RepetitionGuard added in v0.24.0

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

RepetitionGuard observes streamed assistant text and detects a degenerate repetition run. It wraps a sink that receives content that is not held back as a candidate repeated line.

func NewRepetitionGuard added in v0.24.0

func NewRepetitionGuard(cfg RepetitionGuardConfig, sink func(content string)) *RepetitionGuard

NewRepetitionGuard constructs a guard that delivers non-degenerate content to sink. A disabled config still constructs a usable guard; when disabled it is a pure passthrough.

func (*RepetitionGuard) Dropped added in v0.24.0

func (g *RepetitionGuard) Dropped() string

Dropped returns the degenerate text that never reached the sink (empty when the guard never flagged).

func (*RepetitionGuard) Enabled added in v0.24.0

func (g *RepetitionGuard) Enabled() bool

Enabled reports whether the guard is active. A disabled guard never flags and delivers every chunk eagerly.

func (*RepetitionGuard) Finish added in v0.24.0

func (g *RepetitionGuard) Finish()

Finish flushes the incomplete trailing line and any held (legitimate) duplicates, then releases the guard. A finished guard that never degenerated has delivered the whole reply; a looping guard delivers nothing further.

func (*RepetitionGuard) Looping added in v0.24.0

func (g *RepetitionGuard) Looping() bool

Looping reports whether a degenerate repetition run has been confirmed.

func (*RepetitionGuard) NoteToolCall added in v0.24.0

func (g *RepetitionGuard) NoteToolCall()

NoteToolCall records that the response has emitted a tool call: a reply that acts is never a degenerate loop, so a noted tool call suppresses flagging. The streaming callback cannot see tool-call deltas mid-stream, so the provider checks the completed response (see repetitionAttempt): a reply that carries tool calls is kept for the turn to act on instead of being cut.

func (*RepetitionGuard) Reset added in v0.24.0

func (g *RepetitionGuard) Reset()

Reset returns the guard to its initial state for a fresh stream (the retry-once attempt), dropping any held, captured, or looping state so the discarded attempt never leaks into the next one.

func (*RepetitionGuard) RunLength added in v0.24.0

func (g *RepetitionGuard) RunLength() int

RunLength returns the length of the current consecutive identical-line run.

func (*RepetitionGuard) Write added in v0.24.0

func (g *RepetitionGuard) Write(chunk string)

Write feeds one chunk of the streamed assistant text. Complete lines are evaluated for a degenerate run: the first occurrence of a line streams through, repeated occurrences are held back (flushed on a break, discarded on degeneration). A disabled guard delivers the chunk eagerly.

type RepetitionGuardConfig added in v0.24.0

type RepetitionGuardConfig struct {
	// Enabled gates the guard. When false the guard is a pure passthrough
	// and never flags.
	Enabled bool
	// MinRepetitions is how many consecutive identical short lines form a
	// degenerate run. A value below 2 is clamped to the default.
	MinRepetitions int
	// MaxLineChars is the longest a line may be to count toward a run.
	// Longer lines are prose, not degenerate tokens, and are skipped
	// (delivered and never counted).
	MaxLineChars int
}

RepetitionGuardConfig parameterizes the guard. The zero value is the enabled default set; the configured thresholds come from the repetition guard section (see pkg/configuration).

type RepetitionLoopStat added in v0.24.0

type RepetitionLoopStat struct {
	Provider string
	Model    string
	Loops    int64
}

RepetitionLoopStat is one (provider, model) cell of the repetition metric: how many degenerate repetition loops the guard cut for that pair.

type RepetitionMetrics added in v0.24.0

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

RepetitionMetrics aggregates per-(provider, model) repetition-loop counts. The process-wide instance is exposed via GlobalRepetitionMetrics; tests build their own with NewRepetitionMetrics for isolation.

func GlobalRepetitionMetrics added in v0.24.0

func GlobalRepetitionMetrics() *RepetitionMetrics

GlobalRepetitionMetrics returns the process-wide recorder, creating one if init hasn't run yet (defensive — init above normally sets it).

func NewRepetitionMetrics added in v0.24.0

func NewRepetitionMetrics() *RepetitionMetrics

NewRepetitionMetrics constructs an empty recorder.

func (*RepetitionMetrics) Record added in v0.24.0

func (m *RepetitionMetrics) Record(provider, model string)

Record counts one cut repetition loop for a (provider, model) pair. A nil receiver is a no-op. An empty provider or model is bucketed under "unknown" so a missing value never drops the observation.

func (*RepetitionMetrics) Snapshot added in v0.24.0

func (m *RepetitionMetrics) Snapshot() []RepetitionLoopStat

Snapshot returns a copy of every per-(provider, model) stat, sorted by Provider then Model for stable output. A nil receiver returns nil.

func (*RepetitionMetrics) Total added in v0.24.0

func (m *RepetitionMetrics) Total() int64

Total returns the aggregate loop count across every (provider, model) cell.

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 ReviewChangesOptions added in v0.21.5

type ReviewChangesOptions struct {
	// Scope is "working_tree" (default), "staged", or "range".
	Scope string
	// Range is the git revision range for Scope "range".
	Range string
	// Focus is optional guidance passed to every reviewer.
	Focus string
	// Dir overrides the directory whose repository is reviewed; empty uses
	// the agent's workspace root.
	Dir string
	// contains filtered or unexported fields
}

ReviewChangesOptions selects what review_changes reviews.

type ReviewChangesResult added in v0.21.5

type ReviewChangesResult struct {
	// Verdict is "APPROVE", "CHANGES_REQUIRED", or "INCONCLUSIVE" (a
	// reviewer failed or returned no structured verdict, and no MUST_FIX
	// was found elsewhere).
	Verdict string `json:"verdict"`
	// Branch identifies the tree the review ran in: the absolute repo root
	// plus the short HEAD it resolved when the review started. Multi-
	// worktree setups make a range like <sha>..HEAD meaningless without
	// knowing which HEAD — the caller checks this before trusting the
	// findings.
	RepoRoot  string          `json:"repo_root,omitempty"`
	Branch    string          `json:"branch,omitempty"`
	Findings  []ReviewFinding `json:"findings"`
	Reviewers []ReviewerRun   `json:"reviewers"`
	Elapsed   time.Duration   `json:"elapsed"`
}

ReviewChangesResult is the merged outcome of a review.

func (*ReviewChangesResult) GuidanceJSON added in v0.21.5

func (r *ReviewChangesResult) GuidanceJSON() string

GuidanceJSON renders findings as {"MUST_FIX": [...], "VERIFY": [...], "NOTE": [...]} with issue/evidence/suggestion/file entries — the shape the web UI review tab's fix picker parses.

func (*ReviewChangesResult) Markdown added in v0.21.5

func (r *ReviewChangesResult) Markdown() string

Markdown renders the result compactly for the calling model and for display.

func (*ReviewChangesResult) Summary added in v0.21.5

func (r *ReviewChangesResult) Summary() string

Summary is the one-line verdict and finding counts.

type ReviewFinding added in v0.21.5

type ReviewFinding struct {
	Severity string `json:"severity"` // MUST_FIX | VERIFY | NOTE
	File     string `json:"file,omitempty"`
	Line     int    `json:"line,omitempty"`
	Issue    string `json:"issue"`
	Evidence string `json:"evidence,omitempty"`
	Fix      string `json:"fix,omitempty"`
}

ReviewFinding is one issue reported by a reviewer.

type ReviewerRun added in v0.21.5

type ReviewerRun struct {
	ID         string        `json:"id"`
	Files      []string      `json:"files,omitempty"`
	Elapsed    time.Duration `json:"elapsed"`
	Iterations int           `json:"iterations"`
	TokensUsed int           `json:"tokens_used"`
	Error      string        `json:"error,omitempty"`
	// Unstructured holds the reviewer's report when it ended without a
	// parseable findings block, so nothing it found is lost.
	Unstructured string `json:"unstructured,omitempty"`
}

ReviewerRun summarizes one reviewer subagent within a review.

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 = approvals.RiskAssessment

type RiskSource added in v0.16.7

type RiskSource = approvals.RiskSource

RiskSource and RiskAssessment are aliases to the moved types.

type RoleUsage added in v0.23.0

type RoleUsage struct {
	Role             string  `json:"role"`
	PromptTokens     int     `json:"prompt_tokens"`
	CompletionTokens int     `json:"completion_tokens"`
	Tokens           int     `json:"tokens"`
	ChargedCost      float64 `json:"charged_cost"`
	TokenCost        float64 `json:"token_cost"`
	Calls            int     `json:"calls"`
}

RoleUsage is the per-role token/cost aggregate for one role: the tokens the agent's model calls attributed to that role consumed and what they cost. Tokens is PromptTokens+CompletionTokens. Exposed via AgentMetricsManager.GetRoleUsage and Agent.GetRoleUsage so /usage-style views and embedding surfaces can attribute spend per role.

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

func (c *ScriptedClient) ListModels(ctx context.Context) ([]api.ModelInfo, error)

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

Build returns the constructed ScriptedResponse

func (*ScriptedResponseBuilder) Content

Content sets the message content

func (*ScriptedResponseBuilder) Delay

Delay sets the delay before returning the response

func (*ScriptedResponseBuilder) Error

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

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

StreamConfig sets streaming configuration

func (*ScriptedResponseBuilder) ToolCall

ToolCall adds a single tool call

func (*ScriptedResponseBuilder) ToolCalls

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

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 = approvals.SecurityAnalysis

func AnalyzeChain added in v0.17.7

func AnalyzeChain(ctx context.Context, a *Agent, chain Chain, classifications []agenttools.ChainedClassification, cwd string) (*SecurityAnalysis, error)

AnalyzeChain analyzes a command chain using the agent's LLM.

func AnalyzeChainFallback added in v0.17.7

func AnalyzeChainFallback(ctx context.Context, a *Agent, chain Chain, classifications []agenttools.ChainedClassification, cwd string) (*SecurityAnalysis, error)

AnalyzeChainFallback analyzes long chains per-subcommand and synthesizes.

func AnalyzeShellCommand added in v0.17.7

func AnalyzeShellCommand(ctx context.Context, a *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 = approvals.SecurityAnalysisCache

func NewSecurityAnalysisCache added in v0.17.7

func NewSecurityAnalysisCache() *SecurityAnalysisCache

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
	WebUIAttached() 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 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

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

type SessionStore interface {
	GetSessionID() string
	SetSessionID(string)
}

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 = subagents.SharedState

Type aliases — the canonical definitions are in pkg/agent/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

func SplitShellIntoParts(cmd string) []ShellPart

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 NewSimpleUI

func NewSimpleUI() *SimpleUI

NewSimpleUI creates a new simple UI instance

func (*SimpleUI) IsInteractive

func (s *SimpleUI) IsInteractive() bool

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 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 StreamHoldback added in v0.23.0

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

StreamHoldback holds back the start of a streamed reply until enough prose has accumulated to judge its language, then releases the buffer and streams the rest live (pass/undetermined) or keeps the whole reply held (a reliable mismatch). It wraps a sink that receives released content.

func NewStreamHoldback added in v0.23.0

func NewStreamHoldback(user langguard.Language, sink func(content string)) *StreamHoldback

NewStreamHoldback constructs a hold-back that judges a streamed reply against user's language and delivers released content to sink. An undetermined user language (Code == "") makes the hold-back a no-op passthrough (constructed inactive): it never holds and every chunk reaches sink directly.

func (*StreamHoldback) Deliver added in v0.23.0

func (h *StreamHoldback) Deliver(content string)

Deliver writes content through the hold-back's sink — the same client-facing delivery as released content — so the user sees the regenerated text instead of the held wrong-language stream. It bypasses the hold-back state: the reply is already judged and held, and the regenerated text must reach the client regardless of which delivery mechanisms the sink wires up.

func (*StreamHoldback) DeliverNotice added in v0.23.0

func (h *StreamHoldback) DeliverNotice(notice string)

DeliverNotice writes notice through the hold-back's sink — the same client-facing delivery as released content — so the user sees the notice instead of the held wrong-language stream. It is a thin wrapper over Deliver for the templated-notice case.

func (*StreamHoldback) Finish added in v0.23.0

func (h *StreamHoldback) Finish()

Finish is called at the end of the stream. A reply that never reached the prose threshold (short or code-only — not judged) is released here. A held stream stays held (the agent replaces it with the notice).

func (*StreamHoldback) Full added in v0.23.0

func (h *StreamHoldback) Full() string

Full returns the entire content written for this response — every chunk, including those delivered live after the buffer was released, not just the held/buffered prefix. It is the completion re-check's input: a reply whose start passed the hold-back but which switched language later in the stream is re-judged on its full content. Empty when nothing was written.

func (*StreamHoldback) Held added in v0.23.0

func (h *StreamHoldback) Held() string

Held returns the held (wrong-language) content — the whole reply, including chunks that arrived after the mismatch was detected — or "" when the stream is not held.

func (*StreamHoldback) RawLen added in v0.23.0

func (h *StreamHoldback) RawLen() int

RawLen reports the number of bytes buffered so far (raw assistant-text, before the prose threshold is evaluated). It lets the reasoning-model fallback (which runs when no assistant-text was delivered) distinguish "the hold-back already holds this response's content" (RawLen > 0 — the finalize releases or holds it) from "the model streamed it as reasoning and the hold-back holds nothing" (RawLen == 0 — route the content through the hold-back so it is language-gated). A released hold-back has an empty buffer too, so callers must also confirm the streaming buffer is empty.

func (*StreamHoldback) Reset added in v0.23.0

func (h *StreamHoldback) Reset()

Reset returns the hold-back to its initial state for a fresh stream (a provider retry). Any buffered, held, or fully-accumulated content from the discarded attempt is dropped so it never leaks into the next attempt.

func (*StreamHoldback) State added in v0.23.0

func (h *StreamHoldback) State() HoldbackState

State returns the current lifecycle stage.

func (*StreamHoldback) User added in v0.23.0

func (h *StreamHoldback) User() langguard.Language

User returns the user language the hold-back judges against.

func (*StreamHoldback) Write added in v0.23.0

func (h *StreamHoldback) Write(chunk string)

Write feeds one chunk of the streamed reply. While buffering, chunks accumulate; once the extracted prose reaches the judgable threshold the language check runs and the hold-back either releases the buffer (pass or undetermined) and goes live, or holds the reply (a reliable mismatch). Live chunks pass straight through; held chunks are captured (not delivered). Every chunk is also recorded into full (the completion re-check's input).

type SubagentError

type SubagentError = subagents.SubagentError

Type aliases — the canonical definitions are in pkg/agent/subagents.

type SubagentMetrics

type SubagentMetrics = subagents.SubagentMetrics

Type aliases — the canonical definitions are in pkg/agent/subagents.

type SubagentOptions

type SubagentOptions = subagents.SubagentOptions

Type aliases — the canonical definitions are in pkg/agent/subagents.

type SubagentProgressEntry

type SubagentProgressEntry = subagents.SubagentProgressEntry

Type aliases — the canonical definitions are in pkg/agent/subagents.

type SubagentResult

type SubagentResult = subagents.SubagentResult

Type aliases — the canonical definitions are in pkg/agent/subagents.

type SubagentReturn

type SubagentReturn = subagents.SubagentReturn

Type aliases — the canonical definitions are in pkg/agent/subagents.

type SubagentRunMetrics

type SubagentRunMetrics = subagents.SubagentRunMetrics

Type aliases — the canonical definitions are in pkg/agent/subagents.

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

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.

func (*SubagentRunner) SetSubagentClientFactoryForTest added in v0.24.1

func (r *SubagentRunner) SetSubagentClientFactoryForTest(factory func(clientType agent_api.ClientType, model string) (agent_api.ClientInterface, error))

SetSubagentClientFactoryForTest installs a client factory the runner uses instead of factory.CreateProviderClient when building a subagent. It is the exported form of the unexported testClientFactory field so tests outside pkg/agent (e.g. pkg/benchmark) can drive a scripted subagent without a real provider. Never called in production.

type SubagentStatus

type SubagentStatus = subagents.SubagentStatus

Type aliases — the canonical definitions are in pkg/agent/subagents.

type SubagentTask

type SubagentTask = subagents.SubagentTask

Type aliases — the canonical definitions are in pkg/agent/subagents.

type SummaryStore added in v0.16.25

type SummaryStore interface {
	GetPreviousSummary() string
	SetPreviousSummary(string)
}

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

type ToolGuidanceStore interface {
	IsToolCallGuidanceAdded() bool
	SetToolCallGuidanceAdded(bool)
}

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 = changes.TrackedBulkItem

TrackedBulkItem is the per-file payload packed inside a bulk TrackedFileChange.

type TrackedFileChange

type TrackedFileChange = changes.TrackedFileChange

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 = changes.TranscriptFileChange

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. SP-141 phase 2 forwarder — the implementation lives in pkg/agent/changes.

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"`
	// CompactionShrink carries the full post-compaction message list on a
	// "compaction" event: a mid-turn compaction persist REPLACED the state
	// list (shrinking it below the journal's high-water mark), so replay
	// must replace, not append. Nil on all other event types.
	CompactionShrink []api.Message `json:"compaction_shrink,omitempty"`
}

type TurnJournalTokens added in v0.17.17

type TurnJournalTokens struct {
	TotalTokens      int     `json:"total_tokens,omitempty"`
	PromptTokens     int     `json:"prompt_tokens,omitempty"`
	CompletionTokens int     `json:"completion_tokens,omitempty"`
	TotalCost        float64 `json:"total_cost,omitempty"`
}

type TurnVerification added in v0.23.0

type TurnVerification struct {
	// Result is the turn's last verification run (the hook stores a
	// state on every run, pass, fail, or stop-rule; a non-nil
	// LastTurnVerification always carries a non-nil Result).
	Result *verify.Result
	// Attempts is the per-check repair attempts the hook consumed
	// against the stopping rule before its last verification run,
	// keyed like the hook's per-check counters (checkAttemptKey). It
	// is a copy: mutating it does not affect the agent's stored
	// state. Empty (nil) when the last run saw no repair rounds yet
	// (a passing run, or the first run of a failing sequence).
	Attempts map[string]int
	// Limit is the stopping-rule limit that was in effect for the
	// turn (stored on every run, pass or fail).
	Limit int
	// Rounds is how many repair rounds the hook ran within the turn
	// (0 for a turn that verified once and passed; a turn where the
	// hook never ran reports LastTurnVerification == nil, not
	// Rounds == 0).
	Rounds int
}

TurnVerification is one turn's end-verification state for consumers outside pkg/agent (the benchmark metrics, and the verification event later): the run's result, the per-check repair attempts consumed against the stopping rule, the configured limit, and how many repair rounds the hook ran.

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 Usage added in v0.20.0

type Usage struct {
	Role             string
	PromptTokens     int
	CompletionTokens int
	ChargedCost      float64
	TokenCost        float64
}

Usage is an amount of model usage: tokens and what they cost. Role is the role the usage is attributed to; it is empty on the overall ledger view (TakeUnbookedUsage) and set on the per-role view.

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.

func (*WebUIPasswordPrompter) Prompt added in v0.16.18

func (wp *WebUIPasswordPrompter) Prompt(ctx context.Context, reason string) (string, error)

Prompt asks the WebUI to collect a password from the user. Returns ErrNoInteractiveSurface if no event bus or active WebUI clients.

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

Directories

Path Synopsis
Package approvals: the ApprovalAgent seam (SP-141 phase 3, increment 5).
Package approvals: the ApprovalAgent seam (SP-141 phase 3, increment 5).
Auto-skip learning for ChangeTracker shell-mutation tracking.
Auto-skip learning for ChangeTracker shell-mutation tracking.
Package subagents: the process-wide active-subagent counter and the terminal display-prefix builder (SP-141 phase 4, increment 1).
Package subagents: the process-wide active-subagent counter and the terminal display-prefix builder (SP-141 phase 4, increment 1).
Package workflow provides the in-process workflow runner for TODO-loop workflows.
Package workflow provides the in-process workflow runner for TODO-loop workflows.

Jump to

Keyboard shortcuts

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