agentrun

package
v1.5.0 Latest Latest
Warning

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

Go to latest
Published: Nov 6, 2026 License: Apache-2.0 Imports: 27 Imported by: 0 modules, 0 packages

The first number is the count of modules that contain a package that imports this one. The module count is a better indicator of popularity than the package count. A module with 100 importing packages is counted only once instead of 100 times, reflecting the fact that the choice to use the package was likely made only once, not 100 times.
A '?' means that the value hasn't been computed yet.

Documentation

Overview

Package agentrun runs one model phase of the spec pipeline on AgentKit's driver.

A phase is a system prompt, a user prompt, the read-only file tools and one terminating tool whose arguments are the phase's result. Each phase is its own agentkit.Agent: sharing a transcript would carry one phase's reasoning into the next, and the next phase is meant to start from the first one's conclusion rather than from how it got there.

The package is deliberately small. AgentKit owns the loop, the retries of a request that fails before its response starts (the Anthropic SDK's), the prompt cache breakpoints and the pruning of old tool results; this package owns what is specific to a spec phase: the per-phase ceilings, the tool grant, the repeat of a call that fails mid-stream, the project context, the error vocabulary the envelope reports and the progress a person watches.

Index

Constants

View Source
const (
	CategoryAuth     = envelope.CategoryAuth
	CategoryModel    = envelope.CategoryModel
	CategoryBudget   = envelope.CategoryBudget
	CategoryMaxTurns = envelope.CategoryMaxTurns
	CategoryAPI      = envelope.CategoryAPI
	CategoryAborted  = envelope.CategoryAborted
	CategoryRefusal  = envelope.CategoryRefusal
	CategoryNoResult = envelope.CategoryNoResult
	CategoryInternal = envelope.CategoryInternal
)

Error categories. They are the vocabulary the CLI's JSON envelope reports, and they exist so a caller can decide whether re-running could help without pattern-matching a message. They are defined in package envelope, which documents each one.

View Source
const (
	PhasePRD = "prd"
	// PhasePRDReview and PhasePRDRevision are the adversarial review of a
	// PRD and its answer (--adversarial). No tier lists them, so they run on
	// the tier's base entry: the PRD phase's model and effort.
	PhasePRDReview    = "prd_review"
	PhasePRDRevision  = "prd_revision"
	PhaseRequirements = "requirements"
	PhaseTestSpec     = "test_spec"
	PhaseTasks        = "tasks"
	PhaseArchitecture = "architecture"
)

The phases of a run a model and an effort can be chosen for.

View Source
const (
	// DefaultMaxTurns is generous because a phase spends most of its turns
	// reading, and stingy enough that a model looping on a validation error
	// it cannot fix stops costing money.
	DefaultMaxTurns = 60
	// DefaultMaxBudgetUSD bounds one phase, not a whole run.
	DefaultMaxBudgetUSD = 5.00
)

Defaults applied when Bounds leaves a field at zero.

View Source
const (
	SymbolBackendTreeSitter = "tree-sitter"
	SymbolBackendGoOnly     = "go-only"
)

The two names DetectSymbolBackend reports, which are the Detail of a preflight "symbol_backend" check.

View Source
const EffortOff = "off"

EffortOff is the --effort value that sends no effort at all, leaving the model's own default.

View Source
const ToolCodeSearch = "code_search"

ToolCodeSearch names the indexed search tool. It is granted only when the run has an index, so it is not part of ReadOnlyFileTools.

Variables

View Source
var DefaultRetryDelays = []time.Duration{2 * time.Second, 8 * time.Second, 30 * time.Second}

DefaultRetryDelays are the waits before each repeat of a model call that failed on the way: three repeats, about forty seconds in all.

The SDK retries a request that fails before its response starts. Nothing below this package retries one that fails after: AgentKit's loop ends the run on the first failed turn, so one dropped connection twenty turns into a phase threw the phase away, and with it every package of a split still being generated on the same connection.

View Source
var DetectSymbolBackend = detectSymbolBackend

DetectSymbolBackend reports which backend file_outline and find_symbol will use for languages other than Go: SymbolBackendTreeSitter when AgentKit was built with cgo and parses them in-process, SymbolBackendGoOnly when it was not and only Go files (go/ast) have an outline.

AgentKit exposes no detection function, so the probe builds the tools the way grantedTools does, confirms file_outline is among them, and outlines a small Python source with AgentKit's own outline package (the one file_outline uses), reading the backend it reports, so the decision cannot diverge from AgentKit's. An error means the detection itself failed: no workspace, or the file tools could not be built.

It is a variable so a test can simulate a failing detection.

Efforts are the efforts a model can be asked for, lowest first.

View Source
var NewIndex = func(ws *workspace.Workspace) (tools.Index, error) {
	return codesearch.New(ws, codesearch.Options{})
}

NewIndex builds the run's code-search index. Creating it does not read the tree: AgentKit indexes it on the first code_search call. It is a variable so a test can stand in for codesearch.New.

Phases are the phases a model can be chosen for, in the order a package is built.

View Source
var ProjectContextFiles = []string{"AGENTS.md", "CLAUDE.md"}

ProjectContextFiles are the repository's own instructions to agents, read from the workspace root into the system prompt under --trust-project.

View Source
var ReadOnlyFileTools = []string{
	"read_file", "list_files", "find_files", "search_files",
	"file_outline", "find_symbol", "find_references",
}

ReadOnlyFileTools are the built-in tools a spec phase may be granted. Every one of them only reads; none runs a program. file_outline, find_symbol and find_references navigate by declaration.

Tiers is the declaration order of the tiers, cheapest first.

Functions

func CategoryOf

func CategoryOf(err error) string

CategoryOf reports the category of err, or CategoryInternal when err carries none.

func EffortValues

func EffortValues() []string

EffortValues are the accepted --effort values: off, then Efforts.

func NoResultError

func NoResultError(phase, terminator string, res Result) error

NoResultError is the error a caller reports when a phase finished but its terminator never accepted a submission. It is separated from a transport failure because the remedy is different: raise a bound, lower the effort, or narrow the task.

func OpenIndex

func OpenIndex(ws *workspace.Workspace) (idx tools.Index, unavailable string, closeFn func())

OpenIndex builds the run's one code-search index and returns it with the function that closes it. When it cannot be built it returns a nil index, why, and a no-op closer: navigation never fails a run, and without an index the phases search with search_files.

func ParseEffort

func ParseEffort(raw string) (core.Effort, error)

ParseEffort reads an --effort value, case-insensitively. "off" is the empty Effort, which sends no effort.

func WithCodeSearch

func WithCodeSearch(grant []string, on bool) []string

WithCodeSearch returns the grant with code_search appended when the run has an index, and the grant itself when it has none. The result is a copy, so the shared read-only list is never grown.

Types

type Bounds

type Bounds struct {
	// MaxTurns bounds one phase. Zero means DefaultMaxTurns.
	//
	// It is also the repair budget. A schema or rule violation is a tool
	// error the loop hands back, so "how many attempts does the model get"
	// and "how many turns may this phase take" are the same number.
	MaxTurns int
	// MaxBudgetUSD bounds one phase's spend. Zero means DefaultMaxBudgetUSD.
	MaxBudgetUSD float64
	// MaxTokens caps one model response of every phase, the thinking and the
	// reply together, in place of the cap the phase asks for in
	// Phase.MaxTokens. Zero keeps each phase's own. It is the operator's lever
	// for a phase whose response ran out of room before it reached its tool
	// call; the model's own output ceiling still applies.
	MaxTokens int
	// Timeout is the wall-clock ceiling on one phase. Zero means no ceiling
	// beyond the caller's context.
	Timeout time.Duration
}

Bounds are the ceilings on one phase. They are not the model's to choose, and they fail differently: turns catch a model looping cheaply, the budget catches one reading large files a few expensive times, and the timeout catches a provider that never answers.

func (Bounds) ResolvedMaxBudget

func (b Bounds) ResolvedMaxBudget() float64

ResolvedMaxBudget is the spend ceiling after defaulting.

func (Bounds) ResolvedMaxTokens

func (b Bounds) ResolvedMaxTokens(phaseCap int) int

ResolvedMaxTokens is the response cap of a phase that asks for phaseCap: the bound when there is one, else the phase's own. Zero, from a phase with none either, leaves AgentKit's default.

func (Bounds) ResolvedMaxTurns

func (b Bounds) ResolvedMaxTurns() int

ResolvedMaxTurns is the turn ceiling after defaulting.

type Config

type Config struct {
	// Model is the resolved default model. Required.
	Model Model
	// PhaseModels holds the model of each phase kind that runs on another
	// one than Model (see Phases). A kind it does not hold runs on Model.
	PhaseModels map[string]Model
	// Client is the Anthropic SDK client every phase sends through. Required
	// unless Provider is set.
	Client *sdk.Client
	// Provider replaces Client: a test passes provider/faux here and needs no
	// network and no key.
	Provider core.ProviderClient
	// Workspace roots the file tools. Every path a tool is handed is
	// resolved against it, symlinks included, so a path that escapes is
	// refused by the tool rather than by a paragraph in a prompt.
	Workspace *workspace.Workspace
	// Index is the code-search index shared by every phase of the run. When
	// set, phases that grant ToolCodeSearch get code_search. The caller
	// closes it.
	Index tools.Index
	// TrustProject admits the repository's AGENTS.md and CLAUDE.md into the
	// system prompt. It is off by default because a repository that is merely
	// the current directory would otherwise author part of the prompt that
	// reads it.
	TrustProject bool
	// Bounds are the per-phase ceilings.
	Bounds Bounds
	// RetryDelays are the waits before each repeat of a model call that
	// failed on the way, once the SDK's own retries are spent or no longer
	// apply; their number is the number of repeats. Nil means
	// DefaultRetryDelays, an empty slice no repeats.
	RetryDelays []time.Duration
	// Observer receives progress. May be nil.
	Observer Observer
	// ShowText streams the model's own prose to the observer.
	ShowText bool
}

Config is what a Runner is built with: everything that is the same for every phase of one run.

type Error

type Error struct {
	Phase      string
	Detail     string
	Cat        string
	Cause      error
	StopReason core.RunStopReason
}

Error is one failure with a category attached.

func (*Error) Category

func (e *Error) Category() string

Category reports the failure class.

func (*Error) Error

func (e *Error) Error() string

func (*Error) RunStopReason

func (e *Error) RunStopReason() core.RunStopReason

RunStopReason reports the stop reason if this error was caused by a loop termination.

func (*Error) Unwrap

func (e *Error) Unwrap() error

Unwrap exposes the underlying cause to errors.Is and errors.As.

type Model

type Model struct {
	// Spec is what was asked for: a tier name or a model id.
	Spec string
	// Row is the catalog row.
	Row core.Model
	// Effort is the effort the run sends; empty sends none.
	Effort core.Effort
	// Clamped is set when the asked-for effort was lowered to one the model
	// takes: the effort asked for, for the warning.
	Clamped core.Effort
}

Model is a resolved model: the catalog row and the effort the run asks for.

func ResolveModel

func ResolveModel(spec string, effort core.Effort, explicit bool) (Model, error)

ResolveModel resolves a tier name or a model id to its catalog row and an effort: the run's default, the model a phase runs on when nothing chooses another for it. ResolvePlan resolves every phase.

A tier name (case-insensitive) carries the tier's base model and effort. Anything else must be a model the catalog lists, with or without an "anthropic/" prefix: an unlisted id would run with no price, so no budget could ever stop it. effort, when set (explicit is true), replaces the tier's; an empty explicit effort sends none. An effort the model does not take is lowered to the highest one it does, and Clamped records what was asked for; a model that takes no effort at or below it gets none.

func (Model) ID

func (m Model) ID() string

ID is the catalog id of the model.

func (Model) String

func (m Model) String() string

String is the model and its effort, as "id/effort", or "id" with none.

type ModelTier

type ModelTier string

ModelTier classifies models by capability level. A tier is what a spec author actually chooses between — cheap, balanced, best — and keeping it is the point: the alternative is asking whoever runs spec to know which model id is current this month.

const (
	// TierSimple represents lightweight, cost-effective models.
	TierSimple ModelTier = "SIMPLE"
	// TierStandard represents balanced capability models.
	TierStandard ModelTier = "STANDARD"
	// TierAdvanced represents the most capable models.
	TierAdvanced ModelTier = "ADVANCED"
)

type Observer

type Observer interface {
	// Detail reports one line of tracing, shown only under --verbose.
	Detail(format string, args ...any)
	// Raw writes model prose verbatim, shown only under --show-text.
	Raw(s string)
	// PhaseStart reports that a model phase begins, with the model and effort
	// it runs on and its ceilings.
	PhaseStart(phase, model string, maxTurns int, budgetUSD float64)
	// PhaseEnd reports that the phase ended.
	PhaseEnd(phase, stopReason string, turns int, costUSD float64, elapsed time.Duration)
	// Turn reports one finished model turn and the phase's spend so far.
	Turn(phase string, turn int, costUSD float64)
}

Observer receives a phase's progress. The CLI's progress writer satisfies it; a test passes nil.

type Phase

type Phase struct {
	// Name identifies the step in errors, progress and the cost report.
	Name string
	// Kind is the phase's entry in Phases, which picks its model. Empty runs
	// on the default model.
	Kind string
	// System and User are the two prompts.
	System string
	User   string
	// Prefix is context sent before User, as the same user turn, with a
	// prompt-cache breakpoint of its own after it. Phases that share their
	// system prompt, their tools and this text share the cached prefix too,
	// so the context several phases read is paid for at the cache-read rate
	// after the first.
	Prefix string
	// RepoMap is the repository map the caller put into User. The runner
	// never injects it; the field exists so its size can be logged.
	RepoMap string
	// Terminator is the name of the tool that ends the phase by producing
	// its result. A run that ends without it is a failure, not a partial
	// success.
	Terminator string
	// Custom are the phase's own tools, the terminator included.
	Custom []core.Tool
	// BuiltinTools names the read-only built-in tools to grant: a subset of
	// ReadOnlyFileTools, plus ToolCodeSearch.
	BuiltinTools []string
	// MaxTokens caps one response, unless Bounds.MaxTokens replaces it. Zero
	// leaves AgentKit's default.
	MaxTokens int
	// LoadProjectContext admits the project context files under
	// Config.TrustProject.
	LoadProjectContext bool
}

Phase is one model-facing step.

type PhaseChoice

type PhaseChoice struct {
	Phase string
	// Model is a tier name or a catalog model id.
	Model string
	// Effort is the effort asked for; HasEffort says one was, "off" included.
	Effort    core.Effort
	HasEffort bool
}

PhaseChoice is one --phase-model value: PHASE=MODEL[:EFFORT].

func ParsePhaseChoice

func ParsePhaseChoice(raw string) (PhaseChoice, error)

ParsePhaseChoice reads PHASE=MODEL[:EFFORT]. The effort suffix is split off only when it names an effort, so a model id is never cut in two.

type Plan

type Plan struct {
	// Default is what --model resolved to.
	Default Model
	// Phases holds every phase of Phases, resolved.
	Phases map[string]Model
}

Plan is the model and effort of every phase of a run.

func ResolvePlan

func ResolvePlan(spec string, effort core.Effort, explicit bool, choices []PhaseChoice) (Plan, error)

ResolvePlan resolves the model and effort of every phase.

spec (a tier or a model id) decides every phase: a tier through its entry for that phase, a model id the same for all. effort, when explicit, replaces every phase's. A PhaseChoice then decides its phase alone: its model (again a tier or an id), at its own effort when it names one, else at the explicit effort, else at its tier's. A later choice for the same phase wins.

func (Plan) For

func (p Plan) For(phase string) Model

For is the model the phase runs on: its own, or the default.

type Result

type Result struct {
	Name string
	// Model is the model and effort the phase ran on.
	Model      Model
	Turns      int
	StopReason core.RunStopReason
	// LastReason is why the phase's last model response stopped. The run's
	// StopReason cannot say a response was cut off at the output limit: the
	// loop goes on only while a response holds a tool call, so one that ran
	// out of room while thinking ends the run as an end_turn.
	LastReason core.StopReason
	Usage      core.Usage
	Elapsed    time.Duration
	// ToolErrors counts the tool calls that came back as errors, keyed "tool"
	// or "tool/code" when the error carries a code. Each one cost the model a
	// turn.
	ToolErrors map[string]int
	// ToolCalls counts the calls to each tool by name. Nil when there were
	// none.
	ToolCalls map[string]int
}

Result is what a finished phase reports.

type Runner

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

Runner builds and drives one agent per phase.

func NewRunner

func NewRunner(cfg Config) (*Runner, error)

NewRunner returns a Runner. The model must already be resolved and the client built: both happen before any prompt is, so an operator learns about a missing key in the first second.

func (*Runner) Index

func (r *Runner) Index() tools.Index

Index reports the run's code-search index, nil when there is none.

func (*Runner) Model

func (r *Runner) Model() Model

Model reports the default model: the one a phase with no model of its own runs on.

func (*Runner) ModelFor

func (r *Runner) ModelFor(kind string) Model

ModelFor reports the model a phase of the given kind runs on.

func (*Runner) ResolvedBounds

func (r *Runner) ResolvedBounds() (maxTurns int, maxBudgetUSD float64)

ResolvedBounds reports the per-phase ceilings this Runner applies, for a caller that reports them before any phase runs.

func (*Runner) Run

func (r *Runner) Run(ctx context.Context, p Phase) (Result, error)

Run drives one phase to its terminating tool.

The (Result, error) pair is the honest return: a run can end without a result — budget, turn limit, a model that answered in prose — and the caller has to be able to tell that apart from a finished phase. Whether the terminator accepted a submission is the caller's sink to say; the error names a stop the phase could not get past.

Directories

Path Synopsis
Package indextest holds a recording tools.Index double: a test checks that a run builds one code-search index, hands the same instance to its Runner and to specgen's Options, and closes it once on every exit path.
Package indextest holds a recording tools.Index double: a test checks that a run builds one code-search index, hands the same instance to its Runner and to specgen's Options, and closes it once on every exit path.

Jump to

Keyboard shortcuts

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