Help us shape the future of Go! Take the 2026 Go Developer Survey

agent

package
v0.15.0 Latest Latest
Warning

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

Go to latest
Published: Oct 31, 2026 License: MIT Imports: 34 Imported by: 0

Documentation

Overview

Package agent runs the step loop: query the model, execute tool calls, repeat.

Index

Constants

View Source
const (
	StatusSubmitted   = "Submitted"
	StatusCompleted   = "Completed" // model stopped calling tools without the submit marker
	StatusStepLimit   = "StepLimitExceeded"
	StatusCostLimit   = "CostLimitExceeded"
	StatusTimeLimit   = "TimeLimitExceeded"
	StatusInterrupted = "Interrupted"
	StatusError       = "Error"
	// StatusInvalidOutput ends an --output-schema run that produced no valid
	// submit_result within MaxInvalidOutputs consecutive attempts.
	StatusInvalidOutput = "InvalidOutput"
	// StatusFormatError: too many consecutive steps of malformed tool calls.
	StatusFormatError = "RepeatedFormatError"
	// StatusVerificationFailed: stop hooks were still rejecting the result
	// when the max_stop_continuations cap was reached.
	StatusVerificationFailed = "VerificationFailed"
	// StatusOutputTruncated: too many consecutive responses were cut off at
	// the output-token limit.
	StatusOutputTruncated = "OutputTruncated"
	// StatusNeedsInput: the model asked the user a question with ask_user;
	// a resume with the answer continues the run.
	StatusNeedsInput = trajectory.StatusNeedsInput
)
View Source
const BudgetWarnFraction = 0.8

BudgetWarnFraction is the share of a token or cost budget at which the model is told, once, to wrap up.

View Source
const MaxInvalidOutputs = 3

MaxInvalidOutputs is how many consecutive invalid result attempts (an invalid or mixed submit_result call, or a turn with no tool calls) end an --output-schema run as InvalidOutput.

View Source
const StatusTokenLimit = "TokenLimitExceeded"

StatusTokenLimit ends a run whose provider-reported tokens (input plus output, delegates and workers included) reached the token limit.

View Source
const SubmitMarker = "COMPLETE_TASK_AND_SUBMIT_FINAL_OUTPUT"
View Source
const SubmitToolName = "submit_result"

SubmitToolName is the built-in tool an --output-schema run ends with. It contains no "__", so it cannot collide with MCP tools (<alias>__<name>).

Variables

View Source
var ErrMCPResume = errors.New("MCP-enabled runs cannot be resumed; start a fresh task")

ErrMCPResume rejects resuming a loaded checkpoint whose run used MCP or plugin tools. Run's checkpoint validation refuses the same checkpoints; New reports it before anything is built.

Functions

func AdditionalDirsInfo added in v0.5.0

func AdditionalDirsInfo(dirs []tools.ExtraDir, readOnly bool) []trajectory.AdditionalDir

AdditionalDirsInfo records dirs, with their effective modes, for trajectories and run.started; nil when there are none.

func ApplyPatchToolSignature added in v0.5.0

func ApplyPatchToolSignature(readOnly, plan, images, applyPatch bool) string

ApplyPatchToolSignature is ImagesToolSignature with apply_patch enabled or not. Without apply_patch it equals ImagesToolSignature.

func CommandEnvInfo added in v0.5.0

func CommandEnvInfo(c *tools.CommandEnv) *trajectory.CommandEnvInfo

CommandEnvInfo summarizes c by name for trajectories and run.started; nil when no policy is active.

func CommandToolsInfo added in v0.5.0

func CommandToolsInfo(e *tools.Executor) []trajectory.CommandToolInfo

CommandToolsInfo records the command tools e offers for trajectories; nil when it offers none.

func FileAccessInfo added in v0.5.0

func FileAccessInfo(f *tools.FileAccess) *trajectory.FileAccessInfo

FileAccessInfo records f's rules for trajectories and run.started; nil when f is nil.

func ImagesToolSignature added in v0.5.0

func ImagesToolSignature(readOnly, plan, images bool) string

ImagesToolSignature is ToolSignature with update_plan and view_image enabled or not. Without images it equals PlanToolSignature.

func LSPToolSignature added in v0.5.0

func LSPToolSignature(readOnly, plan, images, applyPatch, delegate, webFetch, lsp bool) string

LSPToolSignature is the signature with every opt-in tool flag, lsp last.

func MemoryLoadedFields added in v0.9.0

func MemoryLoadedFields(m *ProjectMemory) map[string]any

MemoryLoadedFields returns the memory.loaded event fields for m: the store path, the loaded entry ids (newest first) and how many active entries were omitted. Entry text is never included.

func MemoryToolsOffered added in v0.9.0

func MemoryToolsOffered(t *trajectory.Trajectory) bool

MemoryToolsOffered reports whether a resumed checkpoint offered the read-only memory_search and memory_list tools (checkpoints from before they existed resume without them).

func PermissionsInfo added in v0.8.0

func PermissionsInfo(p *permissions.Policy) *trajectory.PermissionsInfo

PermissionsInfo records p's policy for trajectories and run.started; nil when p is nil.

func PlanToolSignature added in v0.5.0

func PlanToolSignature(readOnly, plan bool) string

PlanToolSignature is ToolSignature with update_plan enabled or not.

func RememberOffered added in v0.9.0

func RememberOffered(t *trajectory.Trajectory) bool

RememberOffered reports whether a resumed checkpoint offered the remember tool, so the resumed run offers the same tool set. Checkpoints written before the tool existed resume without it.

func ResumeLockdown added in v0.9.0

func ResumeLockdown(t *trajectory.Trajectory) ([]lockdown.Source, []lockdown.Denial)

ResumeLockdown returns the taint sources and lockdown denials a checkpoint recorded, for lockdown.State.Restore.

func ResumeMemoryLoadedFields added in v0.9.0

func ResumeMemoryLoadedFields(t *trajectory.Trajectory, path string) map[string]any

ResumeMemoryLoadedFields returns the memory.loaded event fields for a resumed or follow-up run of checkpoint t, which replays the checkpoint's memory snapshot instead of reading the store: the same fields as a fresh run, with path set to path (the store the snapshot came from, or "" when it can't be resolved) and from_checkpoint true. It returns nil when the checkpoint ran with memory off.

func ResumeUntrusted added in v0.9.0

func ResumeUntrusted(t *trajectory.Trajectory) bool

ResumeUntrusted reports whether a checkpoint's conversation already holds untrusted external content (a review diff, a web_fetch result, an external tool result, or a taint the lockdown recorded), so a resumed run's memory writes stay pending.

func ScopedAgentsMDDelivered added in v0.5.0

func ScopedAgentsMDDelivered(t *trajectory.Trajectory) []string

ScopedAgentsMDDelivered returns the scoped AGENTS.md paths of checkpoint t whose delivering results are still in context, for run.started; nil when there are none.

func SubmitToolSpec added in v0.5.0

func SubmitToolSpec(s *outschema.Schema) model.ToolSpec

SubmitToolSpec returns the submit_result tool for s.

func SystemPrompt added in v0.4.0

func SystemPrompt(cfg config.AgentConfig, root string, skipAgentsMD bool, readOnly ...bool) string

SystemPrompt returns the effective system prompt a run rooted at root would use, given cfg and whether AGENTS.md is skipped. It is exported so callers can validate a checkpoint against the current configuration.

func ToolSignature added in v0.4.0

func ToolSignature(readOnly ...bool) string

ToolSignature fingerprints the definitions plus an execution contract version (see tools.Selection.Signature). The opt-in tools are off, so checkpoints from earlier builds still resume.

func ValidateResume added in v0.4.0

func ValidateResume(t *trajectory.Trajectory, cfg config.AgentConfig, root string) error

ValidateResume runs before provider setup, using only the explicit execution root and current config. Checkpoint paths and credentials are never executed or loaded from metadata.

func WebFetchToolSignature added in v0.5.0

func WebFetchToolSignature(readOnly, plan, images, applyPatch, delegate, webFetch bool) string

WebFetchToolSignature is the signature with every opt-in tool flag, web_fetch last.

Types

type Agent

type Agent struct {
	Model     model.Model
	ModelName string
	// FallbackModels is the fallback chain recorded in the trajectory and
	// run.started. Model must then be a *model.Fallback over ModelName
	// followed by these specs; empty means no fallback.
	FallbackModels []string
	// ReasoningEffort is recorded in new trajectories; the Model sends it.
	ReasoningEffort string
	// OpenAIAPI is the openai provider's resolved transport, recorded in
	// trajectories and run.started; the Model uses it.
	OpenAIAPI string
	// Profile is the config profile selected with --profile, recorded in
	// the trajectory and run.started; "" when none.
	Profile string
	// ProviderAPI and ProviderBaseURL describe a config-defined provider,
	// recorded in trajectories and run.started; empty for built-ins.
	ProviderAPI     string
	ProviderBaseURL string
	Tools           *tools.Executor
	// RedactSecrets describes Tools.Redactor by name for the trajectory
	// and run.started; nil when redact_secrets is off.
	RedactSecrets *trajectory.RedactSecretsInfo
	Config        config.AgentConfig
	Out           io.Writer // progress log; nil discards
	Err           io.Writer // warnings; nil discards
	Verbose       bool
	// Streamed means the model already wrote its text to Out as it arrived.
	Streamed bool
	// CompactFirst compacts the conversation before the run's first model
	// request, whatever its size (chat's /compact). NoCompact wins.
	CompactFirst bool
	// SkipAgentsMD stops Run from appending the nearest AGENTS.md at or above
	// <root> to the system prompt.
	SkipAgentsMD bool
	// ScopedAgentsMD delivers AGENTS.md files in directories below <root>
	// with the results of the built-in file tools that touch paths there
	// (--scoped-agents-md). SkipAgentsMD turns it off.
	ScopedAgentsMD bool
	// SkillsEnabled records that skills discovery was on for this run; the
	// discovered skills are Tools.Skills.
	SkillsEnabled bool
	// Plugins records the loaded plugins for trajectories and run.started.
	Plugins []trajectory.PluginInfo
	// Memory is the project memory loaded at run start (memory.enabled);
	// nil means memory is off. Its section follows AGENTS.md.
	Memory *ProjectMemory
	// Ratchet is the Project rules section (issue #249) placed after the
	// project memory section; "" adds nothing.
	Ratchet string
	// TaskPreamble is placed before the task in a fresh run's first user
	// message (the session handoff, issue #251); t.Task stays the task.
	TaskPreamble string
	// NoCompact turns off context compaction: the full history is always
	// sent, and a context-overflow error ends the run.
	NoCompact bool
	// Hooks run around tool calls the executor permits, and stop hooks
	// before a successful finish; nil runs none.
	Hooks *hooks.Runner
	// Policy is the compiled tool permission policy; nil enforces nothing.
	// It is applied between the executor's Permits check and the hooks, so a
	// denial reuses the error-result path and hooks never override it.
	Policy *permissions.Policy
	// Lockdown is the run's untrusted-content taint state (#171); nil is
	// off. Children share their parent's.
	Lockdown *lockdown.State
	// PermissionApprover answers a policy "ask" through the channel the run
	// has (a terminal prompt, ACP session/request_permission, ...). nil
	// resolves asks with the policy's non-interactive decision.
	PermissionApprover func(ctx context.Context, req permissions.Request) permissions.Answer

	// OnStep is called after every step, e.g. to save the trajectory. A
	// non-nil error stops the run.
	OnStep func(*trajectory.Trajectory) error
	// OnEvent receives machine-readable progress events when configured.
	OnEvent func(string, map[string]any)
	// Resume, when non-nil, continues that trajectory instead of starting a
	// fresh run: its messages, accounting totals, and steps are the starting
	// state, and a continuation notice is appended before the first request.
	Resume       *trajectory.Trajectory
	ResumeSource string // audit-only input path for resume provenance
	// FollowUp, with Resume, continues a finished (Submitted or Completed)
	// checkpoint with this new user instruction, or answers a NeedsInput
	// checkpoint's question. It must be empty for an unfinished checkpoint
	// and set for the others.
	FollowUp string
	// Continue marks Resume as the trajectory this process's previous Run
	// returned (an ACP session's earlier turn), not a loaded checkpoint:
	// the checks against changes between invocations are skipped, and
	// FollowUp continues it whatever status that turn ended with.
	Continue bool
	// TaskImages (--image) are attached to the task message of a fresh run,
	// or to the follow-up message with FollowUp. The message text gets one
	// label line per image.
	TaskImages []model.Image
	// OutputSchema, when non-nil, adds the submit_result tool and makes the
	// run succeed only with a result that validates against it.
	OutputSchema *outschema.Schema
	// Snapshots, when non-nil, captures the workspace: a baseline before
	// the first request, before every tool batch that can change files, and
	// at the end of the run (--snapshots).
	Snapshots Snapshotter
	// Worktree, when non-nil, records the --worktree checkout a fresh run
	// works in; it is copied into the new trajectory.
	Worktree *trajectory.WorktreeInfo
	// Review, when non-nil, records the change set a fresh review run was
	// given; it is copied into the new trajectory.
	Review *trajectory.ReviewInfo

	// Subagents runs the opt-in delegate tool's children; Tools.Delegate
	// offers the tool. nil leaves delegate calls failing with an error.
	Subagents *Subagents

	// Workers runs the opt-in worker tool's children; Tools.Workers
	// offers the tool. nil leaves worker calls failing with an error.
	Workers *Workers
	// Routes are the resolved model routes (main, delegated tasks) this
	// run uses, reported in run.started; informational only.
	Routes []routing.Route
	// Helpers maps an auxiliary task (routing.TaskCompaction,
	// routing.TaskReview) to the model serving it; a task without an
	// entry uses Model.
	Helpers map[string]model.Model
	// UsageRole and UsageTask label this agent's own requests in
	// usage_by_role and model.request; empty means main/main.
	UsageRole, UsageTask string
	// contains filtered or unexported fields
}

func New added in v0.13.0

func New(o Options) (*Agent, error)

New validates o and returns the Agent it describes. An error names the invalid combination; nothing is started.

func (*Agent) Run

func (a *Agent) Run(ctx context.Context, task string) *trajectory.Trajectory

Run executes task until submission, a limit, or an error. It always returns a trajectory describing how the run ended.

func (*Agent) Step added in v0.5.0

func (a *Agent) Step() int

Step returns the current run's completed model calls, or 0 before Run starts. Event sinks call it from OnEvent to tag events with a step.

type ChildRoute added in v0.11.0

type ChildRoute struct {
	Match     []string
	Type      string
	Model     model.Model
	ModelName string
}

ChildRoute sends a delegated task whose brief contains any Match keyword (case-insensitive), or whose task_type equals Type, to Model.

type Options added in v0.13.0

type Options struct {
	// Identity: what runs and how it is recorded.
	Model           model.Model
	ModelName       string
	FallbackModels  []string
	ReasoningEffort string
	OpenAIAPI       string
	Profile         string
	ProviderAPI     string
	ProviderBaseURL string
	Routes          []routing.Route
	Helpers         map[string]model.Model

	// Tools and the limits, policy and hooks around them.
	Tools         *tools.Executor
	Config        config.AgentConfig
	RedactSecrets *trajectory.RedactSecretsInfo
	Hooks         *hooks.Runner
	Policy        *permissions.Policy
	Lockdown      *lockdown.State
	Subagents     *Subagents
	Workers       *Workers
	OutputSchema  *outschema.Schema
	Snapshots     Snapshotter

	// Output.
	Out      io.Writer
	Err      io.Writer
	Verbose  bool
	Streamed bool

	// Context and instructions.
	SkipAgentsMD   bool
	ScopedAgentsMD bool
	NoCompact      bool
	CompactFirst   bool
	TaskImages     []model.Image
	Worktree       *trajectory.WorktreeInfo
	Review         *trajectory.ReviewInfo

	// Resume: what this run continues.
	Resume       *trajectory.Trajectory
	ResumeSource string
	FollowUp     string
	Continue     bool
}

Options are the settings that define a run. New checks them together and builds the Agent from them; each field has the meaning of the Agent field with the same name. Per-run sinks wired after construction (OnStep, OnEvent, PermissionApprover, Plugins, Memory, ...) are still set on the returned Agent.

type ProjectMemory added in v0.9.0

type ProjectMemory struct {
	// Path is the store file the entries came from.
	Path string
	// Lines are the loaded entries, newest first.
	Lines []memory.Line
	// Omitted counts active entries left out to stay within max_bytes.
	Omitted int
}

ProjectMemory is the project memory a run loaded at start (issue #170): the active entries rendered into its system prompt. Writes during the run never change it, so the run that saves an entry never sees it.

type Snapshotter added in v0.5.0

type Snapshotter interface {
	Take(kind string, step int) (trajectory.Snapshot, error)
}

Snapshotter captures the working directory.

type Subagents added in v0.5.0

type Subagents struct {
	// Model and ModelName are the children's model; the caller builds it
	// (by default the parent's model spec, without streaming).
	Model     model.Model
	ModelName string
	// MaxSteps caps each child's model calls; 0 means
	// config.DefaultSubagentMaxSteps.
	MaxSteps int
	// Streamed reports whether Model writes text to the terminal itself.
	Streamed bool
	// Routes pick another model per task (models.delegated.routes).
	Routes []ChildRoute
}

Subagents configures the children the opt-in delegate tool runs.

type Workers added in v0.8.0

type Workers struct {
	// Model and ModelName are the workers' model (by default the parent's
	// model spec, without streaming).
	Model     model.Model
	ModelName string
	// MaxSteps caps each worker's model calls; 0 means
	// config.DefaultWorkerMaxSteps.
	MaxSteps int
	// Tools are the configured worker tools; nil means
	// config.DefaultWorkerTools. A worker gets only those the parent has.
	Tools []string
	// Routes pick another model per task (models.delegated.routes).
	Routes []ChildRoute
	// RunName prefixes worker branch and worktree names
	// (tinyagent/<RunName>-w<n>); "" generates one per process.
	RunName string
	// MaxConcurrent caps how many of one response's worker calls run at
	// once; 0 or 1 runs them one at a time.
	MaxConcurrent int
}

Workers configures the children the opt-in worker tool runs.

Jump to

Keyboard shortcuts

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