cmd

package
v0.16.25 Latest Latest
Warning

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

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

Documentation

Overview

Agent command for sprout

Agent execution utilities: command execution, formatting, and helper functions

Simple enhanced agent command with web UI support Flag variables for web UI configuration (used by agent_modes.go)

Agent modes: handles interactive and direct execution modes

Agent query processing: handles query execution and detection

daemon_logging.go — Daemon log rotation via lumberjack.

When sprout runs as a daemon (SPROUT_SERVICE=1), this module redirects os.Stdout and os.Stderr to lumberjack.Logger instances so that log files are automatically rotated. This replaces the approach of letting launchd / systemd / nohup write to fixed files and provides uniform rotation on every platform.

Package cmd provides the `sprout explain` subcommand (SP-068 Phase 3) for human-readable risk assessment of commands and tool calls.

Export training data command for sprout

GitHub MCP setup prompt for interactive mode

Plan command for sprout - Seamless planning and execution using agent framework

Shell command for sprout

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

func ConfirmPrompt

func ConfirmPrompt(msg string) bool

ConfirmPrompt displays a confirmation prompt to the user and reads their response from stdin. It returns true only if the user types "y" or "yes" (case-insensitive). Any other input (including empty) returns false. If reading from stdin fails (e.g., not a TTY), it returns false. The prompt is written to stderr so it doesn't interfere with stdout capture. The msg should NOT include the y/N suffix — it is appended automatically with the default letter bolded when stderr is a terminal.

func Execute

func Execute() error

Execute adds all child commands to the root command and sets flags appropriately. This is called by main.main(). It only needs to happen once to the rootCmd.

func ExecuteCommand

func ExecuteCommand(cmd string) (string, error)

ExecuteCommand runs a shell command and streams its output in real-time. Returns the combined output (for error messages) and any error that occurred.

func FormatDuration

func FormatDuration(d time.Duration) string

FormatDuration formats duration in human readable format

func GetCompletions

func GetCompletions(input string, chatAgent *agent.Agent) []string

GetCompletions provides tab completion for commands and files

func GetTerminalWidth

func GetTerminalWidth() int

GetTerminalWidth attempts to get the terminal width for separators Returns a conservative width to avoid wrapping

func IsCI

func IsCI() bool

IsCI checks if running in CI environment

func ProcessQuery

func ProcessQuery(ctx context.Context, chatAgent *agent.Agent, eventBus *events.EventBus, query string) error

ProcessQuery processes a single query

func RunAgent

func RunAgent(chatAgent *agent.Agent, isInteractive bool, args []string) (err error)

RunAgent runs the agent in interactive or direct mode

func SetupAgentEvents

func SetupAgentEvents(chatAgent *agent.Agent, eventBus *events.EventBus, indicator *console.ActivityIndicator)

SetupAgentEvents configures the agent for event-driven output routing. The OutputRouter handles dual-path delivery (EventBus + terminal) so no separate streaming callback is needed here. This function ensures the agent's output router is wired to the event bus for WebUI subscribers.

When indicator is non-nil, the streaming callback also stops it on the first chunk so any "Thinking…" spinner is cleared before tokens appear.

func StdinIsTerminal

func StdinIsTerminal() bool

StdinIsTerminal returns true if os.Stdin is connected to a terminal. Used by command handlers to decide whether to show interactive prompts. If testIsTerminal is set (in tests), it delegates to that function.

func TryZshCommandExecution

func TryZshCommandExecution(ctx context.Context, chatAgent *agent.Agent, query string) (bool, error)

tryZshCommandExecution attempts to detect and execute zsh commands directly Returns true if command was executed, false if normal flow should proceed

func WriteTestSession added in v0.16.18

func WriteTestSession(stateDir, sessionID, workingDir string, cs agent.ConversationState) (string, error)

WriteTestSession creates a valid session JSON file in the scoped sessions directory for a given session ID and working directory. Returns the absolute path of the written file.

Types

type AgentAdapter

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

AgentAdapter wraps *agent.Agent to implement GitHubSetupAgentInterface

func NewAgentAdapter

func NewAgentAdapter(agent *agent.Agent) *AgentAdapter

NewAgentAdapter creates a new AgentAdapter wrapping the given agent

func (*AgentAdapter) GetConfigManager

func (a *AgentAdapter) GetConfigManager() interface {
	GetConfig() *configuration.Config
	UpdateConfig(func(c *configuration.Config) error) error
}

func (*AgentAdapter) RefreshMCPTools

func (a *AgentAdapter) RefreshMCPTools() error

type AgentResult

type AgentResult struct {
	Status         string             `json:"status"`                     // "success" or "error"
	Error          string             `json:"error,omitempty"`            // error message if status=="error"
	Query          string             `json:"query"`                      // the original prompt
	FilesModified  []string           `json:"files_modified,omitempty"`   // files changed during execution
	GitDiff        string             `json:"git_diff,omitempty"`         // unified diff of all changes
	PullRequestURL string             `json:"pull_request_url,omitempty"` // URL of PR created during execution
	Metrics        AgentResultMetrics `json:"metrics"`
}

AgentResult is the structured output produced when --output-format=json is used. It captures everything a SaaS wrapper (e.g. Sprout Foundry) needs from a non-interactive sprout run.

type AgentResultMetrics

type AgentResultMetrics struct {
	ElapsedSeconds float64 `json:"elapsed_seconds"`
	TokensIn       int     `json:"tokens_in"`  // Total prompt/input tokens
	TokensOut      int     `json:"tokens_out"` // Total completion/output tokens
	LLMCalls       int     `json:"llm_calls"`  // Number of LLM API calls made
	Cost           float64 `json:"cost"`       // Total estimated USD cost
	Provider       string  `json:"provider"`   // LLM provider name (e.g., "openai", "anthropic")
	Model          string  `json:"model"`      // Model identifier (e.g., "gpt-4o")

	// Security telemetry — track post-caution LLM behavior so external tools
	// can measure SECURITY_CAUTION_REQUIRED signal effectiveness.
	SecurityCautionsIssued      int64 `json:"security_cautions_issued"`       // Times a SECURITY_CAUTION_REQUIRED was produced
	SecurityRetriesAfterCaution int64 `json:"security_retries_after_caution"` // Times the LLM retried the same blocked op after a caution
	SecurityLoopsDetected       int64 `json:"security_loops_detected"`        // Times loop-detection fired (3+ identical blocks)
}

AgentResultMetrics holds execution metrics for structured output.

type AgentWorkflowBudgetConfig added in v0.16.4

type AgentWorkflowBudgetConfig struct {
	// USD is the hard cap on cumulative cost across the workflow.
	// <= 0 means no cap.
	USD float64 `json:"usd,omitempty"`
	// WarnAt is a list of fractional thresholds (0.0–1.0). When the
	// cumulative spend first crosses each threshold, a single warning
	// is emitted to stdout and (when wired) the event bus.
	// Empty defaults to [0.50, 0.80].
	WarnAt []float64 `json:"warn_at,omitempty"`
	// OnExceed controls what happens when USD is reached.
	// "truncate" (default) sets the truncation flag so the run finishes
	// the current LLM response and stops gracefully. "stop" is reserved
	// for future hard-kill behavior; today it's treated like truncate.
	OnExceed string `json:"on_exceed,omitempty"`
}

AgentWorkflowBudgetConfig caps the total USD spend of a workflow run (primary agent + every subagent it spawns share the same budget).

USD-denominated rather than tokens because mixed-provider workflows route different personas to different price tiers — a token cap that covers an Opus orchestrator would let a DeepSeek coder consume 50× the work for the same budget, defeating the cap.

type AgentWorkflowConfig

type AgentWorkflowConfig struct {
	Description             string                            `json:"description,omitempty"`
	Initial                 *AgentWorkflowInitial             `json:"initial,omitempty"`
	Steps                   []AgentWorkflowStep               `json:"steps"`
	ContinueOnError         bool                              `json:"continue_on_error,omitempty"`
	PersistRuntimeOverrides *bool                             `json:"persist_runtime_overrides,omitempty"`
	Orchestration           *AgentWorkflowOrchestrationConfig `json:"orchestration,omitempty"`
	NoWebUI                 *bool                             `json:"no_web_ui,omitempty"`
	WebPort                 *int                              `json:"web_port,omitempty"`
	Daemon                  *bool                             `json:"daemon,omitempty"`
	Budget                  *AgentWorkflowBudgetConfig        `json:"budget,omitempty"`
	Progress                *AgentWorkflowProgressConfig      `json:"progress,omitempty"`

	// SubagentTimeoutSeconds overrides the per-run_subagent tool timeout
	// (default 1800 = 30 minutes). Set higher for very large refactors.
	SubagentTimeoutSeconds *int `json:"subagent_timeout_seconds,omitempty"`

	// RequiresApproval controls whether the run_automate agent tool must
	// surface an intent-confirmation prompt to the user before launching
	// this workflow. Pointer so we can distinguish "unset" (default: true)
	// from explicit false. Set to false for workflows that exist
	// specifically so an agent can invoke them mid-task — e.g. a
	// validation workflow referenced from AGENTS.md that the model must
	// run before considering work done. Anyone with workflow-file access
	// can flip this, so the security implication should be obvious to a
	// reader of the JSON.
	//
	// Only affects the agent tool path. The CLI (`sprout automate run`)
	// always prompts unless --yes is passed, because a human at the
	// keyboard might still fat-finger the wrong workflow.
	RequiresApproval *bool `json:"requires_approval,omitempty"`

	// Loop configures the workflow to iterate over a TODO file, processing
	// each unchecked item independently with a fresh agent context.
	// When Loop is set, Steps are ignored — the loop IS the execution plan.
	Loop *AgentWorkflowLoopConfig `json:"loop,omitempty"`
}

AgentWorkflowConfig defines non-interactive workflow orchestration.

func (*AgentWorkflowConfig) IsApprovalRequired added in v0.16.4

func (c *AgentWorkflowConfig) IsApprovalRequired() bool

IsApprovalRequired reports whether the run_automate tool path should surface an intent-confirmation prompt before launching this workflow. Defaults to true when unset.

type AgentWorkflowInitial

type AgentWorkflowInitial struct {
	Prompt     string `json:"prompt,omitempty"`
	PromptFile string `json:"prompt_file,omitempty"`
	AgentWorkflowRuntime
}

AgentWorkflowInitial is the first run definition (can replace CLI prompt).

type AgentWorkflowLoopConfig added in v0.16.19

type AgentWorkflowLoopConfig struct {
	// TodoFile is the markdown file to scan for [ ] items. Default: TODO.md.
	TodoFile string `json:"todo_file,omitempty"`
	// GatePromptFile is the system prompt for the gate LLM call that
	// parses each TODO section into a structured delegation prompt.
	// Required. The gate call uses the agent's existing client.
	GatePromptFile string `json:"gate_prompt_file,omitempty"`
	// MaxRetries is the number of retry attempts on build failure
	// before skipping an item. Default: 2.
	MaxRetries int `json:"max_retries,omitempty"`
	// MaxIterations caps the agent iterations per item. Default: 50.
	MaxIterations int `json:"max_iterations,omitempty"`
	// BuildCommand is run after each item to verify. Default: "go build ./...".
	BuildCommand string `json:"build_command,omitempty"`
}

AgentWorkflowLoopConfig configures the workflow to iterate over a TODO file, processing each unchecked item independently with a fresh agent context. When Loop is set, Steps are ignored — the loop IS the execution plan.

type AgentWorkflowOrchestrationConfig

type AgentWorkflowOrchestrationConfig struct {
	Enabled                bool   `json:"enabled,omitempty"`
	Resume                 *bool  `json:"resume,omitempty"`
	YieldOnProviderHandoff *bool  `json:"yield_on_provider_handoff,omitempty"`
	StateFile              string `json:"state_file,omitempty"`
	EventsFile             string `json:"events_file,omitempty"`
	ConversationSessionID  string `json:"conversation_session_id,omitempty"`
}

AgentWorkflowOrchestrationConfig enables external orchestration integration.

type AgentWorkflowProgressConfig added in v0.16.4

type AgentWorkflowProgressConfig struct {
	// HeartbeatSeconds is the interval at which the workflow prints a
	// progress line ([budget] $X of $Y · iter N · elapsed Tm).
	// <= 0 disables the heartbeat. Default 600 (10 min) when Budget is set.
	HeartbeatSeconds int `json:"heartbeat_seconds,omitempty"`
}

AgentWorkflowProgressConfig controls runtime visibility of the workflow.

type AgentWorkflowRuntime

type AgentWorkflowRuntime struct {
	SkipPrompt        *bool                     `json:"skip_prompt,omitempty"`
	Provider          string                    `json:"provider,omitempty"`
	Model             string                    `json:"model,omitempty"`
	Persona           string                    `json:"persona,omitempty"`
	DryRun            *bool                     `json:"dry_run,omitempty"`
	MaxIterations     *int                      `json:"max_iterations,omitempty"`
	NoStream          *bool                     `json:"no_stream,omitempty"`
	SystemPrompt      string                    `json:"system_prompt,omitempty"`
	SystemPromptFile  string                    `json:"system_prompt_file,omitempty"`
	Unsafe            *bool                     `json:"unsafe,omitempty"`
	NoSubagents       *bool                     `json:"no_subagents,omitempty"`
	ResourceDirectory string                    `json:"resource_directory,omitempty"`
	ReasoningEffort   string                    `json:"reasoning_effort,omitempty"`
	SubagentOverrides WorkflowSubagentOverrides `json:"subagent_overrides,omitempty"`
	// RiskProfile selects a named shell-command risk cascade preset
	// for this step / initial run (SP-058). One of: readonly,
	// cautious, default, permissive, unrestricted. Per-step values
	// override the workflow-level initial setting and the global
	// config. Unknown values fall through to the agent's default
	// resolution chain (override > config > "default").
	RiskProfile string `json:"risk_profile,omitempty"`
}

AgentWorkflowRuntime contains runtime options aligned with agent CLI flags.

type AgentWorkflowStep

type AgentWorkflowStep struct {
	Name          string   `json:"name,omitempty"`
	Prompt        string   `json:"prompt,omitempty"`
	PromptFile    string   `json:"prompt_file,omitempty"`
	Command       string   `json:"command,omitempty"`
	CommandFile   string   `json:"command_file,omitempty"`
	When          string   `json:"when,omitempty"`
	FileExists    []string `json:"file_exists,omitempty"`
	FileNotExists []string `json:"file_not_exists,omitempty"`
	AgentWorkflowRuntime
}

AgentWorkflowStep is a single step executed after the initial query.

A step is either an agent step (Prompt or PromptFile) or a shell step (Command or CommandFile). The two kinds are mutually exclusive — validation fails if both are set or neither is set.

Shell steps run the command via the user's $SHELL (or /bin/sh) with the workflow's working directory and inherit stdout/stderr. They do NOT trigger model inference; they are useful for cheap, deterministic steps like `make build`, `git status`, or invoking a custom script that prepares state for the next agent step.

func (AgentWorkflowStep) IsShellStep added in v0.16.4

func (s AgentWorkflowStep) IsShellStep() bool

IsShellStep reports whether the step is configured to run a shell command instead of triggering model inference.

type BaseCommand

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

BaseCommand provides common functionality for all CLI commands

func NewBaseCommand

func NewBaseCommand(use, short, long string) *BaseCommand

NewBaseCommand creates a new base command with common functionality

func (*BaseCommand) AddCustomFlag

func (b *BaseCommand) AddCustomFlag(name, shorthand, defaultValue, description string) *string

AddCustomFlag adds a custom flag to the command

func (*BaseCommand) GetCommand

func (b *BaseCommand) GetCommand() *cobra.Command

GetCommand returns the underlying cobra command

func (*BaseCommand) Initialize

func (b *BaseCommand) Initialize() error

Initialize sets up common command infrastructure

func (*BaseCommand) SetRunFunc

func (b *BaseCommand) SetRunFunc(fn func(*CommandConfig, []string) error)

SetRunFunc sets the command's run function with common initialization. CLI-G-1: errors surface via console.GlyphError.Fprintln so they hit the terminal stderr (with NO_COLOR / FORCE_COLOR honored) instead of being routed through log.Printf to ~/.sprout/workspace.log, which was the bug class behind "silent exit on broken config".

type CommandConfig

type CommandConfig struct {
	SkipPrompt      bool
	Model           string
	DryRun          bool
	Logger          *utils.Logger
	Config          *configuration.Config
	TraceSession    *trace.TraceSession
	TraceDatasetDir string
}

CommandConfig represents the common configuration shared across commands

type CommandFlags

type CommandFlags struct {
	SkipPrompt      *bool
	Model           *string
	DryRun          *bool
	TraceDatasetDir *string
}

CommandFlags defines common flags used across commands

type GitHubSetupAgentInterface

type GitHubSetupAgentInterface interface {
	GetConfigManager() interface {
		GetConfig() *configuration.Config
		UpdateConfig(func(c *configuration.Config) error) error
	}
	RefreshMCPTools() error
}

GitHubSetupAgentInterface defines the interface needed from an agent for GitHub MCP setup

type InstanceInfo

type InstanceInfo struct {
	ID         string    `json:"id"`
	Port       int       `json:"port"`
	PID        int       `json:"pid"`
	StartTime  time.Time `json:"start_time"`
	WorkingDir string    `json:"working_dir"`
	LastPing   time.Time `json:"last_ping"`
	SessionID  string    `json:"session_id,omitempty"`
}

InstanceInfo represents a running sprout instance

type PendingInput added in v0.16.17

type PendingInput struct {
	// InitialContent is text to pre-fill in the next prompt (unsent
	// steer text the user may want to edit before submitting).
	InitialContent string

	// QueuedPrefix is the formatted block of deferred messages to
	// prepend to the user's next submitted query. Empty when no
	// messages are queued.
	QueuedPrefix string

	// QueuedCount is how many deferred messages were drained (for
	// footer badge clearing and logging).
	QueuedCount int
}

PendingInput captures all text that should carry over from one turn to the next: unsent steer text (typed but not submitted) and queued messages (submitted via Tab+Enter QUEUE mode). The REPL loop drains both in a single call to DrainPendingInput after EndTurn, eliminating the two-channel confusion where unsent text and queued messages followed different code paths.

type PricingRow added in v0.16.4

type PricingRow struct {
	Provider      string
	Model         string
	InputUsdPerM  float64
	OutputUsdPerM float64
	HasPricing    bool
}

PricingRow is a single model's per-million-token rates.

type PromptIntent added in v0.16.2

type PromptIntent string

PromptIntent labels a piece of submitted text by which of the main REPL's pre-LLM interception classes it would fall into. The empty string means freeform text destined for the model.

Used by the steer / queue submit handlers (cmd/steer_coordinator.go) to reject submissions that would silently lose their command meaning if injected mid-turn or wrapped into the deferred-queue blockquote.

const (
	IntentNone       PromptIntent = ""
	IntentSlash      PromptIntent = "slash command"
	IntentBangShell  PromptIntent = "shell command (! prefix)"
	IntentDetectedSh PromptIntent = "shell command"
)

func ClassifyPromptIntent added in v0.16.2

func ClassifyPromptIntent(chatAgent *agent.Agent, text string) PromptIntent

ClassifyPromptIntent mirrors the dispatch decisions the main REPL makes BEFORE handing a query to the LLM. The classifier returns the first matching category in the same precedence order the REPL uses:

  1. Slash / bang prefix → registry.IsSlashCommand
  2. Zsh-detected command (config-gated) → zsh.IsCommand

Returns IntentNone for plain text. The chatAgent argument may be nil in tests; in that case the config-gated checks are skipped.

Keep this in lockstep with cmd/agent_modes.go's main-prompt dispatch (the IsSlashCommand check and the TryZshCommandExecution fast-path block). If a new pre-LLM interception lands at the prompt, add it here too — otherwise the steer/queue panels will diverge from the prompt's behavior.

type SteerCoordinator

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

SteerCoordinator owns the lifecycle of the pinned steer-input panel across an interactive session (SP-055). It wires the SteerInputReader's submit and interrupt callbacks to the agent's InjectInputContext / TriggerInterrupt once, and toggles the reader on/off around each ProcessQuery call via StartTurn / EndTurn.

Lifecycle:

c := NewSteerCoordinator(chatAgent, footer)
for {
    query := inputReader.ReadLine()
    c.StartTurn()
    ProcessQuery(...)
    c.EndTurn()
}

Non-TTY runs construct a coordinator whose reader is a no-op, so callers don't need to gate the calls.

Future polish (SP-055 Phase 3) hooks here: mode-indicator glyphs, steer history recall, "done queue" mode. Keeping the coordinator behind a single small surface (StartTurn / EndTurn) means those features can land without touching the REPL loop.

func NewSteerCoordinator

func NewSteerCoordinator(chatAgent *agent.Agent, footer *console.StatusFooter) *SteerCoordinator

NewSteerCoordinator constructs the coordinator with the SteerInputReader's callbacks already bound to the agent. The reader is created once and reused for every turn; SteerInputReader.Start/Stop reset its internal buffer between cycles.

chatAgent and footer may be nil for tests; in that case StartTurn and EndTurn are no-ops.

func (*SteerCoordinator) DrainPendingInput added in v0.16.17

func (c *SteerCoordinator) DrainPendingInput() PendingInput

DrainPendingInput consolidates the two carry-over paths (unsent steer buffer + deferred queue messages) into a single drain. The REPL loop calls this once after EndTurn instead of separately calling DrainUnsentBuffer and DrainDeferredMessages.

When both paths have content, the unsent text becomes the initial content (pre-filled for editing) and the queued messages become the prefix. This is the correct priority: the user was actively composing the unsent text, so it goes into the editable buffer; the queued messages are context they already decided on, so they prepend silently as before.

func (*SteerCoordinator) EndTurn

func (c *SteerCoordinator) EndTurn()

EndTurn deactivates the steer reader and tears down the pinned line. Safe to call when already stopped.

func (*SteerCoordinator) SetCompleter added in v0.16.18

func (c *SteerCoordinator) SetCompleter(p console.CompletionProvider)

SetCompleter installs a slash-command completion provider on the steer reader (SP-078 Phase 2). Bound to Ctrl-] — Tab is reserved for the STEER ↔ QUEUE mode toggle. The same provider can be passed to both inputReader.SetCompleter (Tab, REPL prompt) and steerCoord.SetCompleter (Ctrl-], mid-turn) so completion works in both surfaces.

func (*SteerCoordinator) SetGroundTruth added in v0.16.1

func (c *SteerCoordinator) SetGroundTruth(gt *console.GroundTruthTermios)

SetGroundTruth installs the REPL's pristine termios snapshot into the steer reader so Stop() restores to a known-good state instead of a potentially-corrupted per-enter snapshot.

func (*SteerCoordinator) StartTurn

func (c *SteerCoordinator) StartTurn()

StartTurn activates the steer reader for the duration of a ProcessQuery call. Safe to call when the reader is already active (idempotent, the reader's own Start enforces this).

Also registers the pause/resume hooks so interactive prompts (e.g. security elevation in pkg/utils.AskForConfirmation) can hand stdin back to cooked mode without fighting the steer reader for bytes. Without this hook the prompt's bufio.Reader hits EOF immediately and auto-rejects with "stdin unavailable - rejecting for safety".

type WorkflowSubagentOverrides

type WorkflowSubagentOverrides map[string]workflowSubagentOverride

WorkflowSubagentOverrides maps persona IDs to their subagent routing overrides. Keys are normalized persona IDs (lowercase, hyphens→underscores). Values override provider/model for subagents with that persona.

Directories

Path Synopsis
Command enrich_registry annotates freshly-generated canonical model files with capability-probe results.
Command enrich_registry annotates freshly-generated canonical model files with capability-probe results.
Command model_probe runs the capability probe against a single provider/model and prints the result as JSON.
Command model_probe runs the capability probe against a single provider/model and prints the result as JSON.
Command model_registry_server runs a lightweight static file server for serving per-provider model JSON files.
Command model_registry_server runs a lightweight static file server for serving per-provider model JSON files.
Command sync_provider_configs updates the embedded provider config models.available_models field to match the canonical registry.
Command sync_provider_configs updates the embedded provider config models.available_models field to match the canonical registry.
Command validate_registry checks every providers/*.json against the runtime schema before the publish workflow uploads to GitHub Pages.
Command validate_registry checks every providers/*.json against the runtime schema before the publish workflow uploads to GitHub Pages.

Jump to

Keyboard shortcuts

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