Documentation
¶
Overview ¶
Package agentrun runs a coding agent in the background, for Autopilot: one scriptrun.Spec of KindAgent from a finished plan, each agent's stream parser into the one event model (runevent), how a run came out, the Verifier that picks a run up after a restart, and the run view's reads.
It takes its own plain input, Plan, which core builds from the launcher's background plan: the argv, the environment, the worktree, the prompt, and the fence. It never plans a launch itself, so a background run has no more access than the launcher gave it. It never imports Autopilot, the launcher, the inbox, the settings, the desktop shell, or core.
Index ¶
- Constants
- Variables
- func FolderFor(root, sessionID string) string
- type Config
- type End
- type Fence
- type Folder
- type Git
- type Intent
- type Limit
- type LimitReader
- type Liveness
- type Outcome
- type Plan
- type ProcSweeper
- type Report
- type Result
- type Review
- type ReviewComment
- type Runner
- func (r *Runner) Alive(ctx context.Context, runID int64) (Liveness, error)
- func (r *Runner) Diff(ctx context.Context, runID int64) (runevent.Diff, error)
- func (r *Runner) Events(ctx context.Context, runID, after int64) (runevent.Page, error)
- func (r *Runner) EventsBefore(ctx context.Context, runID, before int64) (runevent.Page, error)
- func (r *Runner) Folders() []Folder
- func (r *Runner) Progress(runID int64) (runevent.Progress, bool)
- func (r *Runner) ScriptRun(ctx context.Context, runID int64) (int64, bool)
- func (r *Runner) Start(ctx context.Context, plan Plan) (int64, error)
- func (r *Runner) Stop(ctx context.Context, runID int64) error
- func (r *Runner) StopAll(ctx context.Context) error
- func (r *Runner) TakenOf(ctx context.Context, id int64) (Taken, bool)
- func (r *Runner) Verify(rec scriptrun.Record) scriptrun.Verification
- func (r *Runner) Wait(ctx context.Context, runID int64) error
- type Session
- type SessionState
- type SessionUpdate
- type Sessions
- type StartedSession
- type Status
- type Sweeper
- type Taken
- type Usage
Constants ¶
const ReportSchema = `{"type":"object","required":["outcome","summary","pushed","needsPerson"],` +
`"properties":{"outcome":{"enum":["fixed","nothing_to_do","partial","blocked","failed"]},` +
`"summary":{"type":"string","maxLength":2000},"pushed":{"type":"boolean"},` +
`"pushedCommit":{"type":"string","pattern":"^[0-9a-f]{40}$"},"needsPerson":{"type":"boolean"},` +
`"reason":{"type":"string","maxLength":500},` +
`"review":{"type":"object","required":["verdict","body"],"properties":{` +
`"verdict":{"enum":["approve","request_changes","comment"]},"body":{"type":"string","maxLength":20000},` +
`"comments":{"type":"array","maxItems":50,"items":{"type":"object","required":["path","line","body"],` +
`"properties":{"path":{"type":"string"},"line":{"type":"integer","minimum":1},` +
`"startLine":{"type":"integer","minimum":1},"side":{"enum":["LEFT","RIGHT"]},` +
`"body":{"type":"string","maxLength":4000}}}}}}}}`
ReportSchema is the JSON schema of the report every background run returns, on one line, as the agent's structured output: how it came out, a summary, whether it pushed and which commit, whether a person is needed, and, for a run that reviews a pull request, its review: a verdict, its text, and its line comments, which the app itself posts as the routine's Post the agent's review says, never the agent. The agent's report is shown as the agent's; the app's own verdict comes only from GitHub.
const UnattendedNote = "You are running unattended, in the background: nobody can answer a question or approve " +
"anything, so don't ask; work it out or report that a person is needed. Work only in this folder. Never " +
"merge, approve, or close anything, and never force-push. When you are done, give your report in the " +
"structured output asked for."
UnattendedNote is the system note every background run gets beside its prompt: nobody watches it, so it asks no one, works in its worktree alone, and leaves every decision that changes what others see to a person.
const ( // UsageEvery is how often, at most, a run's tokens so far are written to its record. UsageEvery = 30 * time.Second )
Variables ¶
var ( // ErrNoGit is returned for a run's Diff by a runner given no Git. ErrNoGit = errors.New("the runner reads no git") // ErrNoHead is returned for the Diff of a run whose record names no head it started on, // or no worktree, as one from an older build. ErrNoHead = errors.New("the run names no head it started on") )
var ErrInvalidPlan = errors.New("invalid background run")
ErrInvalidPlan is returned for a plan a run can't start from.
var ErrNoRun = errors.New("no such agent run")
ErrNoRun is returned for a run the runner doesn't know.
Functions ¶
Types ¶
type Config ¶
type Config struct {
// Engine runs the runs, and Runs reads their history and logs.
Engine *scriptrun.Engine
Runs *scriptrun.Service
// Git reads the worktree's commit as a run ends, and the files its commits changed.
// Without it, neither is read.
Git Git
// Sessions records each run as a session. Optional.
Sessions Sessions
// Ended hears each run's end once its record holds it, once, on the goroutine that
// recorded it: it must return promptly. Autopilot's engine hears it (RunEnded).
Ended func(ctx context.Context, end End)
// Changed hears, with the ledger's run, that a run's events changed, as its stream
// grows; core tells the window, a few times a second at most. It must return promptly.
Changed func(runID int64)
// Usage hears a run's tokens so far, at most every UsageEvery. Optional.
Usage func(ctx context.Context, u Usage)
// KeepAwake reports whether to keep the Mac from idle sleep while a run goes, through
// Caffeinate (/usr/bin/caffeinate), started beside each run. Either nil or "" keeps
// nothing awake.
KeepAwake func(ctx context.Context) bool
Caffeinate string
// Sweeper ends what a run left in its worktree after SIGKILL. Optional.
Sweeper Sweeper
// Limits reads which usage limit refused a run, and when it resets, from the agent's
// own record of it, as the run ends in error. Optional.
Limits LimitReader
Clock clock.Clock
Logger *slog.Logger
}
Config holds a Runner's dependencies. Engine and Runs are required.
type End ¶
type End struct {
// ScriptRunID is the run in the history, and Intent what it set out to do.
ScriptRunID int64
Intent Intent
Outcome Outcome
EndedAt time.Time
}
End is how a run ended, once its record holds it.
type Fence ¶
type Fence struct {
// Preset is the tools preset, in the catalog's words ("readOnly").
Preset string `json:"preset"`
// Timeout is its time limit, on Go's timers, which don't count a sleeping Mac.
Timeout time.Duration `json:"timeout"`
// BudgetUSD is its budget in dollars, which the agent keeps to itself, or 0; and
// BudgetTokens its budget in tokens, which the runner stops it at, or 0.
BudgetUSD float64 `json:"budgetUsd"`
BudgetTokens int64 `json:"budgetTokens"`
// ReadOnly reports the preset that changes nothing, whose final message is its notes.
ReadOnly bool `json:"readOnly"`
}
Fence is what holds a background run in, as its routine's step set it.
type Folder ¶
type Folder struct {
// RunID is the run in the history, or 0 while it starts, and LedgerRunID the ledger's;
// Title is the run's, and Agent the agent it runs.
RunID int64
LedgerRunID int64
Title string
Agent agent.ID
// Dir is the worktree, and PID the agent's process, or 0 while it starts.
Dir string
PID int
}
Folder is a worktree an agent's run works in now.
type Git ¶
type Git interface {
Head(ctx context.Context, dir string) (string, error)
ChangedFiles(ctx context.Context, dir, from, to string) ([]string, error)
WorktreeDiff(ctx context.Context, dir, from string) (gitread.WorktreeDiff, error)
}
Git reads what a run left in its worktree, read-only: *gitread.Git.
type Intent ¶
type Intent struct {
RunID int64 `json:"runId"`
MatchID int64 `json:"matchId"`
RoutineID int64 `json:"routineId"`
Agent agent.ID `json:"agent"`
SessionID string `json:"sessionId"`
HeadBefore string `json:"headBefore"`
Fence Fence `json:"fence"`
// ItemID is the item the run's session is about, and Folder the run's own folder,
// where its fence's policy is read from as it ends.
ItemID int64 `json:"itemId"`
Folder string `json:"folder,omitempty"`
// Dir is the worktree it works in, whose changes the run view's Diff reads.
Dir string `json:"dir,omitempty"`
// ConfigDir is the agent profile's config folder, "" for the default profile's, where
// a LimitReader finds the agent's own record of the run.
ConfigDir string `json:"configDir,omitempty"`
}
Intent is what a run sets out to do, written into its record as it starts, so a run picked up after a restart is read and told of as one the runner started.
type Limit ¶
type Limit struct {
// Status is allowed, allowed_warning, or rejected; Type is which window
// ("five_hour", "seven_day", ...); ResetsAt is when it resets, in Unix seconds.
Status string `json:"status"`
Type string `json:"type"`
ResetsAt int64 `json:"resetsAt"`
}
Limit is the provider's usage limit, as the agent last reported it.
type LimitReader ¶
type LimitReader interface {
Limit(ctx context.Context, id agent.ID, configDir, agentSessionID string) (Limit, bool)
}
LimitReader reads the provider's usage limit from an agent's own record of a run, for an agent whose stream says it was refused for usage but not which limit, or when it resets (Codex's rollout of the thread): the agent, the profile's config folder ("" for the default profile's), and the agent's ID of the conversation. It reports the limit the record last holds, its Status "rejected" when the record says it was reached.
type Liveness ¶
type Liveness string
Liveness is what the runner knows of a run the ledger records as going.
type Outcome ¶
type Outcome struct {
Status Status `json:"status"`
// Summary says it in a sentence: "Finished: nothing to do.", "Out of budget ($0.50).",
// "Stopped after 30 minutes.".
Summary string `json:"summary"`
// Result is the agent's own end, nil when it never reported one.
Result *Result `json:"result"`
// Report is its structured report, nil when it gave none, and NoReport says so in the
// window's words with the last of its narration.
Report *Report `json:"report"`
NoReport string `json:"noReport"`
// Limit is the usage limit that refused it, for a run out of usage.
Limit *Limit `json:"limit"`
// TokensIn and TokensOut are what it used, its result's or, with none, what its
// stream counted.
TokensIn int64 `json:"tokensIn"`
TokensOut int64 `json:"tokensOut"`
CacheRead int64 `json:"cacheRead"`
// Commit is the worktree's commit as the run ended, and Changed the files its commits
// changed since the head before it.
Commit string `json:"commit"`
Changed []string `json:"changed"`
// Unknown counts the messages the parser didn't know.
Unknown int64 `json:"unknown"`
// Todos are its todo list as it last wrote it, which the run view keeps showing once
// the run has ended.
Todos []runevent.Todo `json:"todos"`
// Sandbox is what a sandboxed run's sandbox check left in its folder (fence.Sandboxed):
// held, leaked, or unchecked, none for a run with no sandbox, and "" for one whose
// policy couldn't be read.
Sandbox fence.SandboxState `json:"sandbox,omitempty"`
// Refused counts the calls its fence hook refused, as the hook's log in the run's folder
// keeps them (an agent's stream may show none), and Refusals are the last of them.
Refused int `json:"refused"`
Refusals []fence.Denial `json:"refusals"`
}
Outcome is how a run came out, as its record keeps it (the run's result's Outcome).
type Plan ¶
type Plan struct {
// RunID is the ledger's run, which the run's end is told for; MatchID and RoutineID
// name its match and routine.
RunID int64
MatchID int64
RoutineID int64
// Title and Source are the run's: "Fix checks · acme-org/api #212",
// "autopilot:<routine id>".
Title string
Source string
// Agent is the agent it runs, and SessionID the session's ID minted for it, which
// names its own folder.
Agent agent.ID
SessionID string
// Repo is the item's repository, and Dir the item's worktree, where it runs and whose
// lock it holds.
Repo repo.Name
Dir string
// Argv is the agent's command, its binary's absolute path first; the prompt is never on
// it. Env is the run's whole environment.
Argv []string
Env []string
// Command is Argv as the window shows it, "" to write it out.
Command string
// Folder is the run's own folder, <data>/agent-runs/<session id>, which holds its
// fence's files and its prompt, and which goes with its log.
Folder string
// Prompt is the filled-in prompt, read on stdin.
Prompt string
// HeadBefore is the item's head the run starts on, which its commits are read from.
HeadBefore string
// Fence is what holds it in.
Fence Fence
// Session is how the run is recorded as a session.
Session Session
// Before checks, under the worktree's lock and a slot, that the run may still start:
// the worktree is still clean with nothing unpushed, and no session runs there. Its
// error ends the start, as it is. nil checks nothing.
Before func(ctx context.Context) error
}
Plan is a background run, worked out and checked: core builds it from the launcher's background plan, and the runner only starts it.
func (Plan) PromptPath ¶
PromptPath returns the file the run reads its prompt from.
type ProcSweeper ¶
ProcSweeper ends the processes working in a run's worktree once the run's group got SIGKILL (Sweeper): an agent's background shell calls setsid and so leaves the group, and SIGKILL, unlike SIGINT, leaves it alive, with the worktree as its folder (S1). The app and its own children are left alone, and so is every process outside the worktree.
type Report ¶
type Report struct {
Outcome string `json:"outcome"`
Summary string `json:"summary"`
Pushed bool `json:"pushed"`
PushedCommit string `json:"pushedCommit"`
NeedsPerson bool `json:"needsPerson"`
Reason string `json:"reason"`
// Review is its review of the pull request, nil when it wrote none.
Review *Review `json:"review,omitempty"`
}
Report is the agent's structured report, as ReportSchema asks for it.
type Result ¶
type Result struct {
// Subtype is the agent's word for how it ended ("success", "error_max_budget_usd",
// "error_during_execution"), and IsError whether it ended in error.
Subtype string `json:"subtype"`
IsError bool `json:"isError"`
// Message is its final message, at most 50 KB: a read-only run's notes.
Message string `json:"message"`
// Report is its structured output, as it gave it, or nil.
Report json.RawMessage `json:"report"`
// Cost is what it reports the run cost, in dollars, nil when it reports none, and
// Estimated says it is an estimate of what the API would have charged, as for a run
// signed in with the user's plan rather than an API key.
Cost *float64 `json:"cost"`
Estimated bool `json:"estimated"`
// TokensIn, TokensOut, and CacheRead are the tokens it used, Turns its turns, and
// DurationMS how long it ran.
TokensIn int64 `json:"tokensIn"`
TokensOut int64 `json:"tokensOut"`
CacheRead int64 `json:"cacheRead"`
Turns int64 `json:"turns"`
DurationMS int64 `json:"durationMs"`
// Models are the models it actually used: plan mode runs on another model than asked.
Models []string `json:"models"`
// TerminalReason and Errors say why it ended, as the agent does, and Denials counts
// the tool uses its permissions denied.
TerminalReason string `json:"terminalReason"`
Errors []string `json:"errors"`
Denials int `json:"denials"`
}
Result is the agent's own end of a run, from its result line.
type Review ¶
type Review struct {
Verdict string `json:"verdict"`
Body string `json:"body"`
Comments []ReviewComment `json:"comments,omitempty"`
}
Review is the review a run wrote of a pull request: its verdict ("approve", "request_changes", or "comment"), its text, and its line comments.
type ReviewComment ¶
type ReviewComment struct {
Path string `json:"path"`
Line int `json:"line"`
StartLine int `json:"startLine,omitempty"`
Side string `json:"side,omitempty"`
Body string `json:"body"`
}
ReviewComment is one of a review's line comments: a line of a file's diff, or a range ending at it, on a side ("LEFT" is the base version, "RIGHT", or "", the head's).
type Runner ¶
type Runner struct {
// contains filtered or unexported fields
}
Runner starts agents' background runs, follows their streams, and tells how each ended. It is the runs' Verifier too, registered for KindAgent.
func (*Runner) Alive ¶
Alive says what the runner knows of the ledger's run: alive while it starts, goes, or its end hasn't been told; gone once it ended; never when the history holds no run of it.
func (*Runner) Diff ¶
Diff returns the ledger's run's worktree's changes since the head it started on, committed or not, and the files git doesn't track there, read-only.
func (*Runner) Events ¶
Events returns the ledger's run's events after the one numbered after: from memory while the runner follows it, with how far it has got; else its log's last page, with how it came out, which Earlier and Before read back from.
func (*Runner) EventsBefore ¶
EventsBefore returns the page of the ledger's run's events read from its log, of the lines before the offset before (a line's start, as Page.Before gives it), or its log's last page for 0: a chunk at a time back from there until it holds about pageLines lines, or pageBytes, or reaches the log's start. A run that ended says how it came out.
func (*Runner) Folders ¶
Folders returns the worktrees the agents' runs work in now, those still starting and those from before the app restarted included: the process list leaves both the app's own children and an orphan out, so the worktrees, the launcher, and the engine read these.
func (*Runner) Progress ¶
Progress returns how far the ledger's run has got, while the runner follows it.
func (*Runner) ScriptRun ¶
ScriptRun returns the history's ID of the ledger's run, if the history holds it.
func (*Runner) Start ¶
Start starts plan's run and returns its ID in the history. In order, under the worktree's lock and a slot: the plan's own Before (the worktree is still clean, and no session runs there), then the run's folder, 0700, with its prompt and settings, 0600; then it is recorded and started, its prompt on stdin. Once it starts, it is recorded as a session. An error from Before comes back as it is; one once the engine stopped matches scriptrun.ErrClosed.
func (*Runner) Stop ¶
Stop stops the ledger's run, as the run's Stop does; one still starting is called off.
func (*Runner) StopAll ¶
StopAll stops every agent's run, and calls off every one still starting, leaving the engine open for later starts; no script's run is touched.
func (*Runner) TakenOf ¶
TakenOf returns the background run id in the run history is, for Take over, and whether the history holds it as an agent's run.
func (*Runner) Verify ¶
func (r *Runner) Verify(rec scriptrun.Record) scriptrun.Verification
Verify gives a run from before the app restarted its callbacks again, from its intent: its log is read from the start, and its end judged as a run the runner started.
type Session ¶
type Session struct {
Agent agent.ID
Profile string
ConfigDir string
// Prompt is the prompt's nickname.
Prompt string
ItemID int64
Repo repo.Name
Kind item.Kind
Number int
Title string
URL string
// Clone and Worktree are the clone and the item's worktree the run works in.
Clone string
Worktree string
// WorktreeAction is what making the worktree did, and Permission summarizes the
// fence's access.
WorktreeAction string
Permission string
}
Session is the session a background run is recorded as, so the item's row and its panel follow it as they follow any session.
type SessionState ¶
type SessionState string
SessionState is what a run's session does, as its run says.
const ( SessionWorking SessionState = "working" SessionEnded SessionState = "ended" SessionFailed SessionState = "failed" )
The states a run gives its session.
type SessionUpdate ¶
type SessionUpdate struct {
State SessionState
LastMessage string
AgentSessionID string
}
SessionUpdate is what a run says of its session. AgentSessionID links it to the agent's own ID of the conversation once the agent's stream names it, "" to keep the one stored; a session is linked once, and Take over resumes that conversation.
type Sessions ¶
type Sessions interface {
Started(ctx context.Context, s StartedSession) error
State(ctx context.Context, sessionID string, u SessionUpdate) error
}
Sessions records each run as a session, which the item's row follows (core adapts the sessions ledger).
type StartedSession ¶
type StartedSession struct {
Session
// ID is the session's ID, and RunID the run's in the history.
ID string
RunID int64
// AgentSessionID is the agent's own ID of the conversation: the session's ID for an
// agent that takes the app's (Claude Code), the one its stream named for an agent that
// picks its own (Codex's thread), or "" until that comes (SessionUpdate).
AgentSessionID string
// Dir is the worktree it runs in, PromptHead the start of its prompt, and LaunchedAt
// when it started.
Dir string
PromptHead string
LaunchedAt time.Time
}
StartedSession is a run's session, as it is recorded once the run starts.
type Status ¶
type Status string
Status is how a run came out, as the app judges it from the agent's result line and how its program ended, never its exit code alone.
const ( // StatusDone is a run the agent finished. StatusDone Status = "done" // StatusFailed is one that ended in error, or crashed without a word. StatusFailed Status = "failed" // StatusOutOfBudget is one that reached its budget, in dollars or tokens. StatusOutOfBudget Status = "outOfBudget" // StatusOutOfUsage is one the provider refused for the profile's usage limit. StatusOutOfUsage Status = "outOfUsage" // StatusTimedOut is one stopped at its time limit. StatusTimedOut Status = "timedOut" // StatusStopped is one the user stopped, or that was stopped as its item closed or the // app quit. StatusStopped Status = "stopped" // StatusInterrupted is one whose end the app couldn't see, as when the Mac shut down: // it keeps what its log shows, and counts as no try. StatusInterrupted Status = "interrupted" )
The ways a run comes out.
type Sweeper ¶
Sweeper ends what a run left running in its worktree after its group got SIGKILL: an agent's background shell leaves the group, and SIGKILL leaves it alive.
type Taken ¶
type Taken struct {
// RunID is the ledger's run.
RunID int64
// Preset is its tools preset, in the catalog's words, and Folder its own folder, which
// holds its fence's settings.
Preset string
Folder string
}
Taken is a background run as Take over needs it: the ledger's run, and the fence its conversation resumes under.
Source Files
¶
Directories
¶
| Path | Synopsis |
|---|---|
|
Package runevent is the event model of an agent's background run: what the run view, the Activity's Working list, and the tray show of a run, whichever agent runs it.
|
Package runevent is the event model of an agent's background run: what the run view, the Activity's Working list, and the tray show of a run, whichever agent runs it. |