agent

package
v1.0.9 Latest Latest
Warning

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

Go to latest
Published: Oct 29, 2026 License: MIT Imports: 23 Imported by: 1 module, 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

Turn loop that streams the model, gates and runs its tool calls and repeats until it stops

Context management hooks that summarize old turns and drop stale thinking before a request

Index

Constants

View Source
const Omitted = "(reasoning omitted)"

Text left where an assistant turn held nothing but thinking

View Source
const SubagentTool = "Agent"

Name the parent model calls to delegate

Variables

View Source
var ErrInterrupted = errors.New("agent: interrupted")

Error a run ends with after Interrupt was called

Every event a configuration may name

Functions

func NextSeq

func NextSeq() int64

Next event sequence number shared by every agent in the process

func Observe

func Observe(ctx context.Context, ev Event)

Reports an event to the observer of the run the context belongs to, if any

func WithLineage

func WithLineage(ctx context.Context, parent string, depth int) context.Context

Carries the parent and depth a child agent runs under

func WithObserver

func WithObserver(ctx context.Context, observe func(Event)) context.Context

Carries an observer so tools and hooks can report events into the run that called them

Types

type Advice

type Advice struct {
	Call     protocol.ToolCall
	Decision policy.Decision
	// Text appended to the tool result for the model
	Context string
}

What a hook asks for a tool call before it runs

type Agent

type Agent struct {
	Name    string
	Model   Model
	ModelID string
	System  string
	Tools   *tool.Registry
	Gate    policy.Gate
	Session *session.Session
	// Request options copied onto every turn, the output budget left to the model when zero
	MaxTokens   int
	Temperature *float64
	Extra       map[string]json.RawMessage
	// Tool rounds one Run may take before the model must answer, unlimited when zero
	MaxRounds int
	Hooks     []Hook
	// contains filtered or unexported fields
}

Model, tools, policy and transcript wired into one loop

func (*Agent) Interrupt

func (a *Agent) Interrupt()

Asks the run to stop after the current turn or tool round finishes

func (*Agent) Run

func (a *Agent) Run(ctx context.Context, input []protocol.Part, observe func(Event)) (protocol.Response, error)

Appends the user input, then loops model turns and tool rounds until the model stops

func (*Agent) Running

func (a *Agent) Running() bool

Reports whether a run is in progress

func (*Agent) Steer

func (a *Agent) Steer(parts ...protocol.Part)

Queues input the model sees at the next turn boundary, or as a new turn once it has stopped

type Approval

type Approval struct {
	Request policy.Request
	Answer  policy.Answer
	Err     error
	Pending bool
}

Approval asked of the gate, pending until the answer or error is filled in

type Child

type Child struct {
	Name        string
	Description string
	Parent      string
	Depth       int
	CallID      string
	Agent       *Agent
	Started     time.Time
	Finished    time.Time
	Running     bool
	Err         error
	Answer      string
	// contains filtered or unexported fields
}

One child the tool spawned, live or finished

type Dedup

type Dedup struct {
	Hooks
	Session *session.Session
	Tools   *tool.Registry
}

Hook that answers a repeated read only call whose result did not change by pointing at the earlier result

func (*Dedup) AfterTool

func (d *Dedup) AfterTool(ctx context.Context, call protocol.ToolCall, result protocol.ToolResult) (protocol.ToolResult, error)

type Event

type Event struct {
	// Position across every agent in the process
	Seq  int64
	Time time.Time
	Type EventType
	// Name of the agent that produced the event
	Agent string
	// Name of the agent that spawned the producer, empty at the root
	Parent string
	Depth  int
	// Model turn the event belongs to, counted from one within a run
	Round    int
	Model    protocol.Event
	Call     protocol.ToolCall
	Result   protocol.ToolResult
	Data     any
	Duration time.Duration
	// Why the call was refused before it ran, or why the run ended
	Err      error
	Approval *Approval
	Parts    []protocol.Part
	Text     string
	// Completed turn on turn end and the final response on run end
	Response *protocol.Response
	// Turn usage on turn end and run total on run end
	Usage protocol.Usage
}

Progress of a run, stamped with its order, time and the agent lineage that produced it

type EventType

type EventType string
const (
	EventRunStart      EventType = "run_start"
	EventRunEnd        EventType = "run_end"
	EventTurnStart     EventType = "turn_start"
	EventTurnEnd       EventType = "turn_end"
	EventModel         EventType = "model"
	EventToolStart     EventType = "tool_start"
	EventToolEnd       EventType = "tool_end"
	EventApproval      EventType = "approval"
	EventSteer         EventType = "steer"
	EventNote          EventType = "note"
	EventCompactStart  EventType = "compact_start"
	EventCompactEnd    EventType = "compact_end"
	EventHook          EventType = "hook"
	EventSubagentStart EventType = "subagent_start"
	EventSubagentEnd   EventType = "subagent_end"
	EventInterrupt     EventType = "interrupt"
)

type Factory

type Factory func(ctx context.Context, kind, model string) (*Agent, error)

Builds a fresh child agent for one task, of the named kind or the default one when the name is empty

type Hook

type Hook interface {
	// Runs before the first turn and may rewrite the user input
	BeforeRun(ctx context.Context, input []protocol.Part) ([]protocol.Part, error)
	// Runs before every model turn and may rewrite the request
	BeforeTurn(ctx context.Context, req *protocol.Request) error
	// Runs after the assistant turn was appended to the session
	AfterTurn(ctx context.Context, resp protocol.Response) error
	// Runs before a tool call and may rewrite it, settle its permission, add context or refuse it with an error
	BeforeTool(ctx context.Context, call protocol.ToolCall) (Advice, error)
	// Runs after a tool call and may rewrite its result
	AfterTool(ctx context.Context, call protocol.ToolCall, result protocol.ToolResult) (protocol.ToolResult, error)
	// Runs when the model stops and may hand back parts that continue the run, again reporting an earlier continuation
	OnStop(ctx context.Context, resp protocol.Response, again bool) ([]protocol.Part, error)
}

Steps of a run that outside code may observe and rewrite

type HookBlocked

type HookBlocked struct {
	HookEvent HookEvent
	Reason    string
}

Refusal raised by a hook

func (*HookBlocked) Error

func (b *HookBlocked) Error() string

type HookCommand

type HookCommand struct {
	Type    string `json:"type,omitempty"`
	Command string `json:"command"`
	Timeout int    `json:"timeout,omitempty"`
}

One command to run

type HookConfig

type HookConfig map[HookEvent][]HookGroup

func LoadHooks

func LoadHooks(r io.Reader) (HookConfig, error)

Reads a hooks block from JSON, nested under hooks or at the top level, and checks every entry

func LoadHooksFile

func LoadHooksFile(path string) (HookConfig, error)

func (HookConfig) Validate

func (c HookConfig) Validate() error

Checks event names, command kinds and matcher patterns, compiling the patterns

type HookEvent

type HookEvent string

Moment in a run a hook can attach to

const (
	UserPromptSubmit HookEvent = "UserPromptSubmit"
	PreToolUse       HookEvent = "PreToolUse"
	PostToolUse      HookEvent = "PostToolUse"
	Stop             HookEvent = "Stop"
	PreCompact       HookEvent = "PreCompact"
	SessionStart     HookEvent = "SessionStart"
	SessionEnd       HookEvent = "SessionEnd"
	SubagentStop     HookEvent = "SubagentStop"
	Notification     HookEvent = "Notification"
)

type HookExecution

type HookExecution struct {
	HookEvent HookEvent
	Command   string
	Tool      string
	ExitCode  int
	Duration  time.Duration
	Stdout    string
	Stderr    string
	Blocked   bool
}

What one hook execution produced, published as the data of a hook event

type HookGroup

type HookGroup struct {
	Matcher string        `json:"matcher,omitempty"`
	Hooks   []HookCommand `json:"hooks"`
	// contains filtered or unexported fields
}

Commands run for tools whose name matches the pattern, every tool when empty

type HookRunner

type HookRunner struct {
	Config HookConfig
	// Working directory of hook commands, the process directory when empty
	Dir string
	// KEY=VALUE pairs layered over the process environment
	Env []string
	// Passed to hooks as session_id and ICEBATH_SESSION_ID
	SessionID string
	// Path of the stored session log, passed to hooks as transcript_path
	Transcript string
	// Receives hook standard error and any standard hookOutput that is not JSON, discarded when nil
	Log io.Writer
}

Runs configured hooks as an agent hook

func (HookRunner) AfterTool

Runs PostToolUse hooks, an updated response replacing the result and a block marking it as failed with the reason

func (HookRunner) AfterTurn

func (HookRunner) BeforeRun

func (r HookRunner) BeforeRun(ctx context.Context, input []protocol.Part) ([]protocol.Part, error)

func (HookRunner) BeforeTool

func (r HookRunner) BeforeTool(ctx context.Context, call protocol.ToolCall) (Advice, error)

Runs PreToolUse hooks, carrying their rewritten input, settled permission and context back as advice

func (HookRunner) BeforeTurn

func (HookRunner) Fire

func (r HookRunner) Fire(ctx context.Context, event HookEvent, fields map[string]any) (string, error)

Runs the hooks of any event with extra top level fields, returning the context they added

func (HookRunner) OnStop

func (r HookRunner) OnStop(ctx context.Context, resp protocol.Response, again bool) ([]protocol.Part, error)

Runs Stop hooks, a block continuing the run with the reason and any context as the next user message

type Hooks

type Hooks struct {
	BeforeRunFn  func(ctx context.Context, input []protocol.Part) ([]protocol.Part, error)
	BeforeTurnFn func(ctx context.Context, req *protocol.Request) error
	AfterTurnFn  func(ctx context.Context, resp protocol.Response) error
	BeforeToolFn func(ctx context.Context, call protocol.ToolCall) (Advice, error)
	AfterToolFn  func(ctx context.Context, call protocol.ToolCall, result protocol.ToolResult) (protocol.ToolResult, error)
	OnStopFn     func(ctx context.Context, resp protocol.Response, again bool) ([]protocol.Part, error)
}

Hook assembled from optional functions, unset ones passing through

func (Hooks) AfterTool

func (h Hooks) AfterTool(ctx context.Context, call protocol.ToolCall, result protocol.ToolResult) (protocol.ToolResult, error)

func (Hooks) AfterTurn

func (h Hooks) AfterTurn(ctx context.Context, resp protocol.Response) error

func (Hooks) BeforeRun

func (h Hooks) BeforeRun(ctx context.Context, input []protocol.Part) ([]protocol.Part, error)

func (Hooks) BeforeTool

func (h Hooks) BeforeTool(ctx context.Context, call protocol.ToolCall) (Advice, error)

func (Hooks) BeforeTurn

func (h Hooks) BeforeTurn(ctx context.Context, req *protocol.Request) error

func (Hooks) OnStop

func (h Hooks) OnStop(ctx context.Context, resp protocol.Response, again bool) ([]protocol.Part, error)

type Kind

type Kind struct {
	Name        string
	Description string
}

Kind of agent the tool may spawn, as the model hears it

type Lineage

type Lineage struct {
	Parent string
	Depth  int
}

Who spawned an agent and how deep it sits

func LineageFrom

func LineageFrom(ctx context.Context) Lineage

Lineage carried by the context, the root lineage when none was set

type Model

type Model interface {
	Stream(ctx context.Context, req protocol.Request) iter.Seq2[protocol.Event, error]
}

Streams one turn, satisfied by a provider

type Pruner

type Pruner struct {
	Hooks
	Session *session.Session
	After   int
}

Hook that swaps tool results older than After assistant turns for one line stubs in the request

func (*Pruner) BeforeTurn

func (p *Pruner) BeforeTurn(ctx context.Context, req *protocol.Request) error

type StripThinking

type StripThinking struct {
	Hooks
	// contains filtered or unexported fields
}

Hook that keeps thinking only on the newest turn of the run and only while the request before it is unchanged

func (*StripThinking) AfterTurn

func (s *StripThinking) AfterTurn(ctx context.Context, resp protocol.Response) error

func (*StripThinking) BeforeRun

func (s *StripThinking) BeforeRun(ctx context.Context, input []protocol.Part) ([]protocol.Part, error)

func (*StripThinking) BeforeTurn

func (s *StripThinking) BeforeTurn(ctx context.Context, req *protocol.Request) error

type Subagents

type Subagents struct {
	Factory Factory
	// Levels of children allowed below the root, unlimited when zero
	MaxDepth int
	// Budget for one child run, unlimited when zero
	Timeout time.Duration
	// Lets several children of one round run at the same time
	Parallel bool
	// Kinds the model may name, none when nil
	Kinds func() []Kind
	// contains filtered or unexported fields
}

Tool that runs a child agent to completion and returns its final text

func (*Subagents) Annotations

func (t *Subagents) Annotations() tool.Annotations

Destructive and open world always, and read only when children may run side by side

func (*Subagents) Cancel

func (t *Subagents) Cancel(name string) error

Stops a running child

func (*Subagents) Child

func (t *Subagents) Child(name string) (Child, bool)

Child by name

func (*Subagents) Children

func (t *Subagents) Children() []Child

Every child spawned so far, oldest first

func (*Subagents) Definition

func (t *Subagents) Definition() protocol.Tool

func (*Subagents) Run

func (t *Subagents) Run(ctx context.Context, args json.RawMessage) (tool.Result, error)

func (*Subagents) Steer

func (t *Subagents) Steer(name string, parts ...protocol.Part) error

Queues input for a running child

type Summarizer

type Summarizer struct {
	Hooks
	Model   Model
	ModelID string
	Session *session.Session
	// Context tokens, as measured by the last response plus what was added since, at which a summary is made
	Threshold int
	// Messages kept verbatim after the summary, none when zero
	Keep int
	// Extra guidance appended to the summary instructions
	Instructions string
	// Runs before a summary is made, such as external PreCompact hooks
	Before func(ctx context.Context) error
}

Hook that replaces the oldest turns with a model written summary once the context grows past a threshold

func (*Summarizer) BeforeTurn

func (s *Summarizer) BeforeTurn(ctx context.Context, req *protocol.Request) error

Summarizes and compacts the session when the pending request would grow past the threshold

func (*Summarizer) Summarize

func (s *Summarizer) Summarize(ctx context.Context) (string, error)

Asks the model for a summary of the turns compaction drops, in parts when they are too long for one call

Jump to

Keyboard shortcuts

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