Documentation
¶
Overview ¶
Package runner orchestrates agent execution workflows and model calls.
Index ¶
- Constants
- Variables
- func ExecuteRun(cmd *cobra.Command, args []string, opts *RunOptions) error
- func FindAgentDir(agentName, explicitDir string, cfg *config.Config) (string, error)
- func InvokeModel(ctx context.Context, opts *RunOptions, bundle *agent.Bundle) (string, *metrics.Metrics, error)
- func ManifestToPipeline(m *agent.Manifest) (*pl.Pipeline, error)
- func ResolveGitToplevel(dir string) string
- func ResolveModelPrecedence(ctx context.Context, opts *RunOptions, bundle *agent.Bundle) (string, error)
- type Isolation
- type IsolationMode
- type RunOptions
Constants ¶
const DefaultMaxTokensLeaf = 4096
DefaultMaxTokensLeaf is the output-token floor for leaf agents (no Task tool). Leaf agents mostly emit Edit/Write/Bash tool calls whose arguments are modest, but 4096 gives comfortable headroom for long file-write operations.
const DefaultMaxTokensWithTask = 16384
DefaultMaxTokensWithTask is the output-token floor for agents that have access to the Task tool. Task prompts embed file lists, prior-agent context, and hard constraints, easily requiring 4K+ tokens in a single tool-call argument. langchaingo's default of 2048 silently truncates these arguments, causing the child dispatch to fail with "prompt is required".
Variables ¶
var ComposedFlags = []string{
"system",
"print-bundle",
"bundle-out",
"apply",
"apply-fallback",
"stream",
}
ComposedFlags lists flags that are incompatible with composed agents. `require-actionable` is deliberately omitted: it is leaf-only and a no-op on the pipeline path, so it is tolerated rather than rejected.
Functions ¶
func ExecuteRun ¶
func ExecuteRun(cmd *cobra.Command, args []string, opts *RunOptions) error
ExecuteRun contains the full run command logic, parameterized by RunOptions.
func FindAgentDir ¶
FindAgentDir locates an agent by name using the source manager. It returns the path to the agent directory (containing agent.yaml).
func InvokeModel ¶
func InvokeModel(ctx context.Context, opts *RunOptions, bundle *agent.Bundle) (string, *metrics.Metrics, error)
InvokeModel resolves provider settings and calls the appropriate model backend. It is exported so the pipeline runner can call it directly.
The returned *metrics.Metrics is always non-nil so callers can report partial cost even when the run is interrupted (e.g. ctrl+c during MCP server initialization).
func ManifestToPipeline ¶
ManifestToPipeline converts a composed agent manifest into a Pipeline. The manifest's stages and gates are mapped to their pipeline equivalents.
func ResolveGitToplevel ¶ added in v0.2.0
ResolveGitToplevel returns the canonical repository root for dir by asking git for its toplevel. It falls back to dir unchanged when dir is not inside a git repository, so callers always get a usable canonical path. This must be called before worktree isolation rewrites the working directory so sessions are keyed to the real repo, not an ephemeral worktree.
func ResolveModelPrecedence ¶
func ResolveModelPrecedence(ctx context.Context, opts *RunOptions, bundle *agent.Bundle) (string, error)
ResolveModelPrecedence selects the model/provider for this run by walking, in order:
- Explicit caller intent (opts.Model from a CLI flag or routine field). Always wins.
- Config default (opts.ConfigModel / opts.ConfigProvider) when the user has credentials for that provider. The config model may sit outside the agent manifest's models: list — that earns a warning, but the user's explicit intent is honoured because credentials, cost ceilings, and provider routing only live in the user's config.
- Manifest models walked in ranked order: the first entry with credentials wins. Skipping the top-ranked entry due to a missing key also earns a warning so the user knows they fell off the preferred path.
- As a last resort, the config default is used without credentials (with a strong warning that the call will likely fail). If even that is unavailable, a non-nil error is returned listing the env vars that would unblock the run.
Returns (warning, error). Callers should display the warning on stderr when non-empty and abort on a non-nil error.
Types ¶
type Isolation ¶
type Isolation struct {
Mode IsolationMode
Original string // user-facing working directory (cwd or --working-dir)
Effective string // path the agent actually operates in
Branch string // branch name created by branch/worktree modes; empty otherwise
// contains filtered or unexported fields
}
Isolation describes the resolved working environment for a run. When Mode is IsolationNone, Effective == Original and Teardown is a no-op.
func PrepareIsolation ¶
func PrepareIsolation(ctx context.Context, originalDir string, mode IsolationMode, agentName string) (*Isolation, error)
PrepareIsolation sets up the run environment for the requested mode.
IsolationWorktree creates `.squad/worktrees/<agent>-<stamp>` on a new branch `squad/<agent>-<stamp>` rooted at HEAD of the original repo. If the original directory is not a git repository, it logs a warning and downgrades to IsolationNone instead of failing the run.
IsolationBranch, IsolationCommit, and IsolationStaged perform their git operations in the original directory and require it to be a git repo; otherwise an error is returned.
IsolationNone and IsolationUnstaged perform no git operations.
func (*Isolation) Teardown ¶
Teardown applies the cleanup policy for the resolved mode:
- worktree: prune the worktree when it has no changes; keep it otherwise.
- staged: restore the previously stashed unstaged changes (always, even on agent failure, so the user's working tree isn't silently lost).
- none, branch, commit, unstaged: no-op.
Idempotent. Returns whether the worktree was kept and its filesystem path (worktree mode only).
type IsolationMode ¶
type IsolationMode string
IsolationMode controls how the agent's run interacts with the working tree and git history before, during, and after the run.
const ( // IsolationNone runs the agent in the working directory directly with no // git operations. IsolationNone IsolationMode = "none" // IsolationWorktree runs the agent in a fresh git worktree on a new // branch derived from the agent name and a timestamp. IsolationWorktree IsolationMode = "worktree" // IsolationBranch checks out a new branch `squad-<id>` from the current // state (including uncommitted changes) before the run. The branch is // left checked out afterwards. IsolationBranch IsolationMode = "branch" // IsolationCommit commits everything in the working tree as // `squad: snapshot before <agent>` before the run. No-op when the tree // is clean. IsolationCommit IsolationMode = "commit" // IsolationStaged stashes unstaged changes, commits the index as // `squad: staged snapshot before <agent>`, then restores the unstaged // changes on completion. No-op when nothing is staged. IsolationStaged IsolationMode = "staged" // IsolationUnstaged runs the agent against the working tree as-is. No // git operations occur before or after the run. Distinct from // IsolationNone only as user intent. IsolationUnstaged IsolationMode = "unstaged" )
func ResolveIsolationMode ¶
func ResolveIsolationMode(cliFlag, manifestVal, configVal string) (IsolationMode, error)
ResolveIsolationMode picks an effective IsolationMode using precedence: CLI flag > agent manifest > config default > IsolationNone. Empty strings at any layer mean "not specified, fall through".
type RunOptions ¶
type RunOptions struct {
// Agent is the name of the agent to run (must exist under AgentsDir).
Agent string
// AgentsDir is the directory containing agent sub-directories.
AgentsDir string
// WorkingDir is the directory the agent operates in.
WorkingDir string
// APIKey is the provider API key (overrides config/env).
APIKey string
// BaseURL overrides the provider's default API endpoint.
BaseURL string
// Org is the OpenAI organization ID.
Org string
// APIVersion is used by Azure OpenAI and other versioned APIs.
APIVersion string
// APIType selects the API variant (e.g., "azure").
APIType string
// OpenAICompatMax enforces max_tokens for OpenAI-compatible providers.
OpenAICompatMax bool
// Provider is the explicitly requested model provider (from a CLI flag
// or routine definition). Highest precedence; empty falls through to
// manifest then ConfigProvider.
Provider string
// Model is the explicitly requested model identifier (from a CLI flag
// or routine definition). Highest precedence; empty falls through to
// manifest then ConfigModel.
Model string
// ConfigProvider holds the provider default from the loaded config
// file. Used only when neither the CLI/routine nor the agent manifest
// specifies a provider. Kept separate from Provider so manifest
// preferences can win over config defaults.
ConfigProvider string
// ConfigModel holds the model default from the loaded config file.
// Used only when neither the CLI/routine nor the agent manifest
// specifies a model. Kept separate from Model so manifest preferences
// can win over config defaults.
ConfigModel string
// Temperature controls sampling randomness.
Temperature float64
// MaxTokens is the per-request output token budget.
MaxTokens int
// System overrides the agent's assembled system prompt.
System string
// Output is the file path for writing the model's final response.
Output string
// Print reports whether to write the response to stdout.
Print bool
// BundleOut is the file path for writing the assembled prompt bundle.
BundleOut string
// PrintBundle reports whether to print the bundle to stdout.
PrintBundle bool
// DryRun reports whether to estimate cost and exit without running.
DryRun bool
// RequireActionable reports whether the run must produce file edits.
RequireActionable bool
// Apply reports whether to apply a unified diff from the response.
Apply bool
// ApplyFallback reports whether to attempt diff parsing as a fallback.
ApplyFallback bool
// NumCtx is the context window size for Ollama models.
NumCtx int
// MaxIterations caps the number of model iterations (0 = unlimited).
MaxIterations int
// MaxIterationsExplicit reports whether MaxIterations came from an
// explicit --max-iterations flag. When true the value is used verbatim;
// when false the runner derives the effective cap from the agent's base
// budget and the per-model iteration factor (see resolveIterationBudget).
MaxIterationsExplicit bool
// MaxCost is the total cost budget in USD (0 = unlimited).
MaxCost float64
// MaxRetries overrides the per-call LLM retry count for transient
// errors. Zero or negative falls back to tools.DefaultMaxRetries.
MaxRetries int
// Mode is the run mode passed to prompt templates (e.g., "edit").
Mode string
// Vars holds template variables passed to prompt templates.
Vars map[string]string
// ConfigAvailable reports whether a config file was loaded.
ConfigAvailable bool
// Config is the loaded squad configuration.
Config *config.Config
// Findings is a shared findings store set by the pipeline runner.
Findings *tools.FindingsStore
// AgentName is the current agent name used for finding attribution.
AgentName string
// MCPServers lists MCP servers declared via --mcp-server flags.
MCPServers []mcp.ServerConfig
// Stream reports whether to stream response tokens to stderr.
Stream bool
// MaxConcurrentTasks is the maximum number of concurrent background
// child tasks (0 = default).
MaxConcurrentTasks int
// ResumeID is the session ID to resume; empty starts a new session.
ResumeID string
// ResumeResponseID is the OpenAI response ID to chain from, set by
// openSession when resuming an existing session.
ResumeResponseID string
// NoSession disables session logging (e.g., for tests).
NoSession bool
// Isolation overrides the agent manifest's isolation preference.
// Empty falls through to manifest, then config, then IsolationNone.
Isolation string
// RoutineID, when set, is stamped onto the session's meta.json so
// `squad routine history` can filter by exact provenance. Qualified
// form: "global:nightly" / "repo:audit".
RoutineID string
// LastSessionID is an OUTPUT field populated by ExecuteRun with the
// session id it created (or resumed). Empty when NoSession is true or
// session creation failed. Callers like the routines daemon read this
// after ExecuteRun returns to record which session a fire produced.
LastSessionID string
// SkillOverrides applies per-run adjustments to the agent's skill
// catalog (--allow-skill / --deny-skill / --skills-enabled flags).
// nil means "use agent.yaml defaults".
SkillOverrides *agent.SkillOverrides
// AutoConfirm is the resolution policy for the Confirm tool in
// non-TTY runs. Empty (the default) means "abort" so unattended runs
// fail loudly when a skill needs a human checkpoint.
AutoConfirm tools.AutoConfirmMode
// CanonicalRepoPath is the pre-isolation git toplevel of the working dir.
CanonicalRepoPath string
// WorktreePath is the ephemeral worktree path (if isolation is used).
WorktreePath string
}
RunOptions holds the resolved configuration for a single run invocation.