cmd

package
v0.16.1 Latest Latest
Warning

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

Go to latest
Published: Jun 1, 2026 License: MIT Imports: 58 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.

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 TryDirectExecution

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

TryDirectExecution attempts to execute simple commands directly using static pattern matching. Returns true if command was executed directly, false if normal agent flow should proceed.

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

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
	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
	Provider       string  `json:"provider"`   // LLM provider name (e.g., "openai", "anthropic")
	Model          string  `json:"model"`      // Model identifier (e.g., "gpt-4o")
}

AgentResultMetrics holds execution metrics for structured output.

type AgentWorkflowConfig

type AgentWorkflowConfig struct {
	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"`
}

AgentWorkflowConfig defines non-interactive workflow orchestration.

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 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 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"`
	When          string   `json:"when,omitempty"`
	FileExists    []string `json:"file_exists,omitempty"`
	FileNotExists []string `json:"file_not_exists,omitempty"`
	AgentWorkflowRuntime
}

AgentWorkflowStep is a single prompt step executed after the initial query.

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

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 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) DrainUnsentBuffer added in v0.16.1

func (c *SteerCoordinator) DrainUnsentBuffer() string

DrainUnsentBuffer returns any text the user typed into the steer panel during the last turn but did not submit. The REPL loop calls this after EndTurn and carries the text into the next ReadLine via InputReader.SetInitialContent. The steer buffer is reset after drain.

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

Jump to

Keyboard shortcuts

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