Documentation
¶
Overview ¶
Package cli is the shell of the spec command: one positional input, one JSON envelope on stdout, progress on stderr, the shared flags, and the checks that refuse a run before a token is spent.
Index ¶
- Constants
- Variables
- func Emit(w io.Writer, env Envelope) int
- func EmitWithOutput(w io.Writer, outPath string, env Envelope) int
- func EncodeJSON(v any) ([]byte, error)
- func ExitCodeFor(category string) int
- func FormatDuration(d time.Duration) string
- func FormatTokens(n int64) string
- func IsTerminal(w io.Writer) bool
- func PhaseSummary(res agentrun.Result) string
- func RenderThread(ref issuex.IssueRef, t issuex.IssueThread) string
- func ResumePlaceholder(in Input) string
- func RetryableFor(category string) bool
- func SetProvider(p core.ProviderClient) (restore func())
- func SplitArgs(fs *flag.FlagSet, argv []string) (positional string, err error)
- func StatusFor(code int) string
- func Truncate(s string) (string, bool)
- func Usagef(format string, args ...any) error
- func WarnStage(code WarnCode) (string, bool)
- func WarningMessages(ws []Warning) []string
- func WriteAtomic(path string, data []byte) error
- type App
- type Artifact
- type ArtifactKind
- type ArtifactsProvider
- type Common
- func (c *Common) Bounds(defaults agentrun.Bounds, singlePhase bool) agentrun.Bounds
- func (c *Common) ContextBlock() string
- func (c *Common) ModelSpec() string
- func (c *Common) Register(fs *flag.FlagSet)
- func (c *Common) ResolveModels() (agentrun.Plan, error)
- func (c *Common) ResolveOutput() (string, error)
- func (c *Common) Validate() error
- func (c *Common) Workspace() (*workspace.Workspace, error)
- type Deps
- type DetailedResult
- type Envelope
- type ErrorInfo
- type Estimate
- type FixHint
- type Input
- type InputInfo
- type ModelInfo
- type Next
- type NextProvider
- type PhaseInfo
- type PhaseModelInfo
- type PreflightCheck
- type Progress
- func (p *Progress) Begin(format string, args ...any) func(summary string)
- func (p *Progress) Detail(format string, args ...any)
- func (p *Progress) PhaseEnd(phase, stopReason string, turns int, costUSD float64, elapsed time.Duration)
- func (p *Progress) PhaseStart(phase, model string, maxTurns int, budgetUSD float64)
- func (p *Progress) Raw(s string)
- func (p *Progress) Step(stage, format string, args ...any)
- func (p *Progress) Turn(phase string, turn int, costUSD float64)
- type Resumabler
- type Run
- func (r *Run) AddPhase(p PhaseInfo)
- func (r *Run) CostUSD() float64
- func (r *Run) Envelope(code int, result any, failure *ErrorInfo) Envelope
- func (r *Run) RecordSideEffect(action, kind, target, url string, ok bool, warn WarnCode)
- func (r *Run) SetBounds(b agentrun.Bounds)
- func (r *Run) SetInput(in Input)
- func (r *Run) SetModels(plan agentrun.Plan)
- func (r *Run) SideEffects() []SideEffect
- func (r *Run) Warn(code WarnCode, severity string, format string, args ...any)
- func (r *Run) Warnings() []Warning
- type SchemaField
- type SchemaObject
- type SchemaProvider
- type SideEffect
- type SourceKind
- type StageError
- type Summarizable
- type Summarizer
- type UsageError
- type UsageInfo
- type WarnCode
- type Warning
Constants ¶
const ( // ModelEnv selects the model. AGENTKIT_MODEL is honoured as a fallback. ModelEnv = "AF_MODEL" ModelEnvFallback = "AGENTKIT_MODEL" // EffortEnv supplies the effort when --effort is not given. EffortEnv = "AF_MODEL_EFFORT" )
Environment variables the shared flags read when they are not given.
const ( WarnInputTruncated = envelope.WarnInputTruncated WarnInputLooksLikePath = envelope.WarnInputLooksLikePath WarnCommentsUnreadable = envelope.WarnCommentsUnreadable WarnCommentsTruncated = envelope.WarnCommentsTruncated WarnEffortClamped = envelope.WarnEffortClamped WarnSpecsDirUnreadable = envelope.WarnSpecsDirUnreadable WarnProjectLanguageUnknown = envelope.WarnProjectLanguageUnknown WarnSteeringMalformed = envelope.WarnSteeringMalformed WarnNameFlagIgnored = envelope.WarnNameFlagIgnored WarnRepoMapBuildFailed = envelope.WarnRepoMapBuildFailed WarnScopeRenamed = envelope.WarnScopeRenamed WarnScopeCountMismatch = envelope.WarnScopeCountMismatch WarnToolErrors = envelope.WarnToolErrors WarnSplitPlanForeign = envelope.WarnSplitPlanForeign WarnSplitPlanUnreadable = envelope.WarnSplitPlanUnreadable WarnSplitPlanStale = envelope.WarnSplitPlanStale WarnSplitPlanUpdateFailed = envelope.WarnSplitPlanUpdateFailed WarnSplitPlanNotRemoved = envelope.WarnSplitPlanNotRemoved WarnArchitectureNotWritten = envelope.WarnArchitectureNotWritten WarnActivationFailed = envelope.WarnActivationFailed WarnCommentNotPosted = envelope.WarnCommentNotPosted WarnOutputNotWritten = envelope.WarnOutputNotWritten WarnPRDReviewIncomplete = envelope.WarnPRDReviewIncomplete WarnPlanReviewSkipped = envelope.WarnPlanReviewSkipped WarnPlanReviewIncomplete = envelope.WarnPlanReviewIncomplete WarnSpecInvalid = envelope.WarnSpecInvalid WarnSectionAbsent = envelope.WarnSectionAbsent WarnOverBudget = envelope.WarnOverBudget WarnTaskNotReady = envelope.WarnTaskNotReady WarnTaskStateForced = envelope.WarnTaskStateForced WarnTasksOpen = envelope.WarnTasksOpen WarnSupersedesNotRecorded = envelope.WarnSupersedesNotRecorded )
The declared warning codes, which are defined in package envelope so that a program reading the output can name them. Every declared code has exactly one stage in warnStages, so a code cannot be used without a stage, and cannot be recorded against two different stages by accident. A call site that fits none of them gets a new constant in package envelope and in warnStages, never a bare string.
const ( ExitOK = envelope.ExitOK ExitFailed = envelope.ExitFailed ExitUsage = envelope.ExitUsage )
Exit codes. Something other than a human reads them.
const ( ArtifactSpecPackage = envelope.ArtifactSpecPackage ArtifactComment = envelope.ArtifactComment ArtifactMarkdownFile = envelope.ArtifactMarkdownFile )
The artifact kinds the commands produce.
const DefaultModel = "STANDARD"
DefaultModel is the tier a run uses unless told otherwise. It is a tier rather than a model id so that spec keeps working when a model is retired.
const DefaultRepoMapTokens = 6000
DefaultRepoMapTokens is the default token budget of the repository map.
const DescriptionTag = "description"
DescriptionTag is the struct tag a field's schema description is read from, beside its json tag. A doc comment is not visible to reflection, and a side table drifts from the field it describes; a tag sits on the field.
const MaxInputBytes = 256 << 10
MaxInputBytes bounds what one input can contribute to a prompt. A 40MB log pasted at a coding agent is a bill, not an input, and truncating here — deterministically, at a line boundary, with a visible marker — is better than discovering the context window at request time.
const NoInputMessage = "no input: give a report, a file path, a GitHub or GitLab issue URL, or - to read stdin"
NoInputMessage names the four accepted input shapes for an empty or missing input.
const SameInputPlaceholder = envelope.SameInputPlaceholder
SameInputPlaceholder stands for the original input in a suggested invocation whose input may be arbitrarily large (raw text, stdin).
const SchemaDialect = "https://json-schema.org/draft/2020-12/schema"
SchemaDialect is the JSON Schema dialect every generated document declares.
const SiblingCommands = "spec writes a package from an idea, specr renders one, speca reports and changes its state."
SiblingCommands is the sentence that names the three commands, so that an agent that finds one of them learns from it what the other two are for. Each command's help and each --schema description carry it, and this is the one place it is written. It is an untyped constant so that a help text, which is a raw-string constant, can be built with it.
const ToolErrorWarnThreshold = 5
ToolErrorWarnThreshold is how many failed tool calls in one phase make the run say so.
Variables ¶
var ErrNoInput = errors.New("no input given")
ErrNoInput is an empty or missing input. A program cannot block on a conversational turn waiting for one: it exits with a usage error before a token is spent.
Functions ¶
func Emit ¶
Emit writes the envelope as one indented JSON document and a newline, and returns the exit code.
func EmitWithOutput ¶
EmitWithOutput is Emit with a durable second copy: when outPath is not empty, the very bytes about to be written to w are first written atomically to outPath, so the file is complete before any byte reaches stdout. That includes Emit's own marshal-failure fallback: the same minimal envelope goes to both. A failure to write outPath never changes what is written to w or the exit code returned; here it is ignored, since on the fallback path there is no further envelope left to carry a warning about it. It returns the exit code, as Emit does.
func EncodeJSON ¶
EncodeJSON renders v as indented JSON and a trailing newline, the way every document on stdout is written. It does not escape <, > and & the way encoding/json does by default: the output is read by programs and models, never embedded in HTML, and Markdown in a string is full of them.
func ExitCodeFor ¶
ExitCodeFor maps an error category onto the exit table.
func FormatDuration ¶
FormatDuration renders a duration the way a run summary should read: sub-second precision below a second, whole units above it.
func FormatTokens ¶
FormatTokens abbreviates a token count for a one-line summary.
func IsTerminal ¶
IsTerminal reports whether w is a terminal: a person is reading it, not a program.
func PhaseSummary ¶
PhaseSummary is the footer a phase prints when it ends: turns, tokens in and out, and the cached tokens when there were any.
func RenderThread ¶
func RenderThread(ref issuex.IssueRef, t issuex.IssueThread) string
RenderThread flattens an issue and its comments into the text a model reads. It is a pure function so two runs on the same thread produce the same prompt, which is what lets a provider's cache prefix survive.
func ResumePlaceholder ¶
ResumePlaceholder is how a next[] entry names in to re-run it: the literal origin (a file path or an issue URL) when the input had a small, stable one, and SameInputPlaceholder when it was raw text or stdin.
func RetryableFor ¶
RetryableFor reports whether an error of the given category can succeed if re-run unchanged.
func SetProvider ¶
func SetProvider(p core.ProviderClient) (restore func())
SetProvider makes every run use p instead of an Anthropic client, for a test. It returns the function that puts the previous value back.
func SplitArgs ¶
SplitArgs separates the one positional argument from the flags, allowing flags on either side of it. Anything after the first non-flag token that itself starts with "-" is still parsed as a flag, except the bare "-", which means stdin.
func Truncate ¶
Truncate cuts at a line boundary and says so, because an input that ends mid-stack-trace with no marker reads to a model as a complete stack trace that simply had no more frames.
func WarnStage ¶
WarnStage returns the stage a code is recorded against, and whether the code is declared.
func WarningMessages ¶
WarningMessages returns the message text of each warning, in order.
func WriteAtomic ¶
WriteAtomic writes data to path the way --output is written: a reader sees nothing or the whole document. See writeAtomic.
Types ¶
type App ¶
type App struct {
Name string
Version string
// Usage is the help text printed above the flag list.
Usage string
// Flags registers the command's own flags.
Flags func(*flag.FlagSet)
// DefaultBounds are the per-phase ceilings before the flags override
// them.
DefaultBounds agentrun.Bounds
// SinglePhase folds --total-budget into the per-phase ceiling.
SinglePhase bool
// PreCheck runs after flag parsing and before anything is fetched.
PreCheck func(*Common) error
// CheckInput runs after the input is read and before the model is
// resolved.
CheckInput func(Input) error
// Exec is the work: the exit code, the result, and the error object when
// there is one.
Exec func(context.Context, Deps) (int, any, *ErrorInfo)
// PreflightExec runs every check Exec would make before its first model
// call, and stops.
PreflightExec func(context.Context, Deps) (int, any, *ErrorInfo)
}
App is the command: its name, help, own flags, default ceilings, and the function that does the work.
func (App) Main ¶
func (a App) Main(ctx context.Context, argv []string, stdin io.Reader, stdout, stderr io.Writer) int
Main parses, resolves and runs. It returns the process exit code.
It writes exactly one JSON object to stdout on every program-driven path. Two paths are for a person and print text instead: --version, and -h/--help or a bare invocation, which print the help to stderr. A bare invocation also writes a usage envelope when stdout is not a terminal, so a program piping stdout still gets one object to parse.
type ArtifactKind ¶
type ArtifactKind = envelope.ArtifactKind
type ArtifactsProvider ¶
type ArtifactsProvider interface {
Artifacts() []Artifact
}
ArtifactsProvider is implemented by a result that lists what the run produced. Every entry is read off a fact the result holds, never off the model's account of its own work.
type Common ¶
type Common struct {
Dir string
Model string
Effort string
MaxTurns int
MaxTokens int
Budget float64
Timeout time.Duration
TotalBudgetUSD float64
TrustProject bool
Verbose bool
Quiet bool
ShowText bool
Version bool
Context []string
// Detail selects the result view on stdout: "summary" (the default) or
// "full".
Detail string
// InputKind forces how the argument is classified: "file", "text",
// "issue" or "stdin". Empty means guess.
InputKind string
// DryRun makes no change on disk or on a forge.
DryRun bool
// Output is where a second, atomic copy of the stdout envelope is
// written, resolved against the process's working directory.
Output string
// RepoMapTokens is the token budget of the repository map in every
// phase's prompt; 0 disables the map.
RepoMapTokens int
// Preflight runs every check that would refuse the run, then stops
// before any model phase.
Preflight bool
// PhaseModels are the --phase-model values, in the order given.
PhaseModels []agentrun.PhaseChoice
}
Common is the flag set every run shares: where to work, which model, the ceilings, the input and how the result is printed.
func (*Common) Bounds ¶
Bounds are the per-phase ceilings: the flags over the tool's defaults. A single-phase run folds --total-budget in, since the two then bound the same spend and the lower one is the phase's ceiling.
func (*Common) ContextBlock ¶
ContextBlock renders the --context values into one labelled block, or "" when none were given.
func (*Common) ResolveModels ¶
ResolveModels resolves the model and effort of every phase: --model (or its environment) for all of them, --effort (then $AF_MODEL_EFFORT, then each phase's tier effort) for all of them, and each --phase-model for its own phase. An invalid environment value is a usage error, like an invalid flag value.
func (*Common) ResolveOutput ¶
ResolveOutput validates --output and returns the absolute path it names, or "" when none was given. "-" (stdin, for the input) and an existing directory are usage errors. A missing parent is created when the envelope is written.
type Deps ¶
type Deps struct {
Common *Common
Input Input
Workspace *workspace.Workspace
Runner *agentrun.Runner
// Forge is the forge client — GitHub or GitLab, chosen from the input URL
// or the origin remote — and is always non-nil. Whether it can write is
// Forge.Authenticated().
Forge issuex.Client
Run *Run
Progress *Progress
// Models is the model and effort of every phase.
Models agentrun.Plan
// Index is the run's code-search index; nil when it could not be built,
// and IndexUnavailable then says why.
Index tools.Index
}
Deps are what an App's Exec receives: everything the shell has already resolved and checked.
type DetailedResult ¶
type DetailedResult interface {
SetDetail(string)
}
DetailedResult is implemented by a result that records which view ("summary" or "full") was emitted.
type Envelope ¶
Envelope is the object a command writes, with its result of whatever type the command produces.
type FixHint ¶
func FixHintFor ¶
FixHintFor computes a machine-usable remedy for a failure: the flag to raise for a ceiling, the environment variables for a missing credential, the legal values for an unknown model. It returns nil when no mechanical remedy is known.
type Input ¶
type Input struct {
Kind SourceKind
// Origin is the path, the URL, or "argument"/"stdin".
Origin string
// Body is the text the tool works from, already truncated to
// MaxInputBytes.
Body string
// Context is the rendered additional context block from --context flags.
Context string
// Truncated reports that Body is shorter than the source.
Truncated bool
// CommentsTruncated reports that an issue has more comments than the
// forge client read.
CommentsTruncated bool
// Issue is set for KindIssue: the reference and the thread it was read
// from. It is what lets a tool comment back on the issue it was given.
Issue *issuex.IssueRef
Thread *issuex.IssueThread
}
Input is the classified argument: the text, plus where it came from.
func Resolve ¶
func Resolve(ctx context.Context, arg string, stdin io.Reader, forge issuex.Client, run *Run) (Input, error)
Resolve classifies arg and loads it.
The order is deliberate. "-" is stdin, unambiguously. An issue URL is recognized before the filesystem is touched, so a URL is never stat'ed. A path that exists and is a regular file is read. Everything else is text — including a path that does not exist, because "the widget/ package panics" is a plausible thing to say and refusing it as a missing file would be wrong. A text argument that is shaped like a path, though, is called out with a high-severity input_looks_like_path warning on run; a nil run records nothing.
func ResolveForced ¶
func ResolveForced(ctx context.Context, kind, arg string, stdin io.Reader, forge issuex.Client) (Input, error)
ResolveForced loads arg as the given kind instead of guessing, for --input-kind. It skips Resolve's auto-classification entirely rather than running it and checking the outcome, so nothing is fetched or read on the way to a refusal. Every mismatch is a *UsageError, which the shell turns into exit 2 before a model is resolved.
- file: the argument must stat as a regular file; a missing path and a directory are refused by name, before Resolve's file-vs-text fallback.
- text: the argument is the body, verbatim: no file, URL or path-shape check, and no warning.
- issue: the argument must parse as a forge issue or pull-request URL, checked before any HTTP request.
- stdin: the argument must be exactly "-".
type NextProvider ¶
type NextProvider interface {
Next() []Next
}
NextProvider is implemented by a result that suggests the invocations a caller would plausibly make next.
type PhaseModelInfo ¶
type PhaseModelInfo = envelope.PhaseModelInfo
type PreflightCheck ¶
type PreflightCheck = envelope.PreflightCheck
type Progress ¶
type Progress struct {
// contains filtered or unexported fields
}
Progress writes human-readable progress to stderr.
It is on stderr and never stdout, without an option to change that: stdout carries exactly one JSON object, and a tool that interleaves progress into it is a tool whose output cannot be parsed. A caller that wants silence passes --quiet; a caller that wants detail passes --verbose.
func NewProgress ¶
NewProgress returns a Progress writing to w, prefixing each line with the tool's name. A nil w means os.Stderr.
func (*Progress) Begin ¶
Begin starts a step that will take a while, returning the function that ends it. On a terminal, without --verbose, a spinner runs so an operator can tell a ten-minute model call from a hang; only one step owns the spinner at a time.
func (*Progress) Detail ¶
Detail prints one line only under --verbose. It is indented, because a detail line belongs to the step above it.
func (*Progress) PhaseEnd ¶
func (p *Progress) PhaseEnd(phase, stopReason string, turns int, costUSD float64, elapsed time.Duration)
PhaseEnd traces how a phase ended, under --verbose.
func (*Progress) PhaseStart ¶
PhaseStart traces the model and the ceilings a phase runs under, under --verbose.
type Resumabler ¶
type Resumabler interface {
Resumable() bool
}
Resumabler is implemented by a result that reports whether re-running the same input continues rather than restarts the work.
type Run ¶
type Run struct {
// contains filtered or unexported fields
}
Run is the accumulating state of one invocation: what the pipeline reports into and what the envelope is built from. It is safe for concurrent use.
func (*Run) AddPhase ¶
AddPhase records one model-facing step's cost. Five or more failed tool calls in one phase raise a tool_errors warning.
func (*Run) CostUSD ¶
CostUSD is the cumulative spend of every phase recorded so far: what --total-budget is checked against between phases.
func (*Run) Envelope ¶
Envelope assembles the object to print from the full result. code decides OK: only ExitOK is a success, so ok can never be true beside a non-zero exit code or an error object.
func (*Run) RecordSideEffect ¶
RecordSideEffect records one write to a forge, at the one place it happens, beside the Warn the same site makes on failure. An ok entry never carries a warning, and a failed one never a URL.
func (*Run) SideEffects ¶
func (r *Run) SideEffects() []SideEffect
SideEffects returns a copy of the forge writes recorded so far, in order.
type SchemaField ¶
SchemaField is one key of a SchemaObject.
type SchemaObject ¶
type SchemaObject []SchemaField
SchemaObject is a JSON object whose keys keep the order they were set in. A map would sort them, and in a schema a model reads, property order is visible: what a field is comes before what is inside it.
func EnvelopeDocument ¶
func EnvelopeDocument(result any, omit ...string) SchemaObject
EnvelopeDocument is the standalone JSON Schema document of the envelope a command writes: Envelope with its result property replaced by the schema of result's type, and the named properties a command never sets left out. result is used for its type only, so a zero value does.
func FlagsDocument ¶
func FlagsDocument(fs *flag.FlagSet, enums map[string][]string) SchemaObject
FlagsDocument describes every flag on fs as a standalone JSON Schema document, in flag-name order, so a framework can use it as a tool's input schema. enums names the flags with a closed set of values. --schema and --version are left out: both return before any work is done. Nothing is required, since every flag has a default.
func SchemaFor ¶
func SchemaFor(t reflect.Type) SchemaObject
SchemaFor describes a Go type as a JSON Schema node, reading it the way encoding/json does: a struct's properties in declaration order, named by their json tags, required unless omitempty or omitzero; a slice as an array of its element; a pointer as its pointee; a map as an object of its values. Each property's description is read from its description tag.
func (SchemaObject) Get ¶
func (o SchemaObject) Get(key string) (any, bool)
Get returns the value of key, and whether it is set.
func (SchemaObject) MarshalJSON ¶
func (o SchemaObject) MarshalJSON() ([]byte, error)
MarshalJSON writes the keys in order.
func (*SchemaObject) Set ¶
func (o *SchemaObject) Set(key string, value any)
Set replaces the value of key in place, or appends it.
type SchemaProvider ¶
type SchemaProvider interface {
JSONSchema() SchemaObject
}
SchemaProvider is implemented by a type whose JSON form comes from its own MarshalJSON, so reflecting over its Go fields would describe the wrong document. It returns the schema of what it marshals to.
type SideEffect ¶
type SideEffect = envelope.SideEffect
type SourceKind ¶
type SourceKind string
SourceKind is what the single argument turned out to be.
spec takes exactly one input and it is one of these four. The classification is done here, in Go, and never delegated to a model: it decides whether a network call happens at all, which is a decision an operator must be able to audit without reading a transcript; a wrong guess costs a round trip and a spec written about the wrong thing; and the rules are dull — "does this path exist on disk" is not a judgement call.
const ( // KindText is literal text given on the command line. KindText SourceKind = "text" // KindFile is a readable regular file whose contents are the input. KindFile SourceKind = "file" // KindStdin is the input piped in, selected with the argument "-". KindStdin SourceKind = "stdin" // KindIssue is an issue or pull/merge request on any supported forge. KindIssue SourceKind = "issue" )
func (SourceKind) String ¶
func (k SourceKind) String() string
type StageError ¶
StageError is a pipeline failure carrying a stage and a category.
type Summarizable ¶
type Summarizable interface {
SummaryView() any
}
Summarizable is implemented by a result that supplies a trimmed view of itself, the one printed under --detail summary.
type Summarizer ¶
type Summarizer interface {
Summary() string
}
Summarizer is implemented by a result that supplies a one-sentence summary of the run.
type UsageError ¶
type UsageError struct {
// contains filtered or unexported fields
}
UsageError is a wrong invocation: nothing was fetched and nothing was written.
func (*UsageError) Category ¶
func (e *UsageError) Category() string
Category is "usage", so a UsageError is classified, and exits, as one.
func (*UsageError) Error ¶
func (e *UsageError) Error() string