agent

package
v0.2.0 Latest Latest
Warning

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

Go to latest
Published: Oct 4, 2026 License: MIT Imports: 20 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 agent runs the native agent loop over narrow ports implemented by core.

Index

Constants

View Source
const CompactStopReason = "compact"

CompactStopReason marks summary generations in run_steps; they use no budget step.

View Source
const ProgressFlushInterval = 750 * time.Millisecond

ProgressFlushInterval is how often a streaming reply is written to the journal.

Variables

View Source
var ErrCanceled = errors.New("run canceled by user")

ErrCanceled is the cause of a run's context when the user canceled the run; a context stopped for any other cause interrupts the run.

View Source
var ErrContextExhausted = errors.New("context_exhausted: the conversation no longer fits the model's context window")

ErrContextExhausted fails a run whose conversation no longer fits the model's window even after summarising it.

Functions

func ContextLimit

func ContextLimit(model Model, windowTokens int, outputLimit int) int

ContextLimit is the prompt room of model in a window of windowTokens: the window without a reserve and the output limit its requests send, outputLimit when set, else the model's own.

func DenialResult

func DenialResult(reason string) tools.Result

DenialResult is the result the model reads for a call the user denied.

func ImageInputAllowed

func ImageInputAllowed(model Model) bool

ImageInputAllowed reports whether the model accepts inline images.

func ToolCallMessage

func ToolCallMessage(id, sessionID, runID, name string, args []byte, finished bool, at time.Time) transcript.Message

ToolCallMessage is the transcript message of one requested tool call.

func ToolResultMessage

func ToolResultMessage(id, sessionID, runID, callID, name string, result tools.Result, at time.Time) (transcript.Message, error)

ToolResultMessage is the transcript message carrying a tool result.

func ToolResultStatus

func ToolResultStatus(result tools.Result) tools.ResultStatus

ToolResultStatus is the stored status of a tool result.

func ToolUseAllowed

func ToolUseAllowed(model Model) bool

ToolUseAllowed reports whether the model can receive tool definitions.

Types

type Approvals

type Approvals interface {
	Request(ctx context.Context, p Pending) error
	Pending(ctx context.Context, runID string) (bool, error)
}

Approvals records approval requests and reports whether any are still open.

type Budget

type Budget struct {
	Steps      int
	ActiveTime time.Duration
	Tokens     int64
}

Budget limits one run; a zero field is unlimited.

type Config

type Config struct {
	Journal     Journal
	Tools       Tools
	Approvals   Approvals
	Inbox       Inbox
	Sink        Sink
	Prompts     Prompts
	Todos       Todos
	Attachments agentcontext.AttachmentReader
	Now         func() time.Time
	NewID       func(prefix string) string
	// Sleep waits d or until ctx stops; nil uses a real timer.
	Sleep func(ctx context.Context, d time.Duration) error
	// ModelSlots bounds the model requests of every run sharing it; nil is unbounded.
	ModelSlots *toolsched.Semaphore
	// Locks serialises tool calls sharing a concurrency key across every run
	// using it; nil gives the engine locks of its own.
	Locks *toolsched.Locks
}

Config wires the ports of one run.

type Counters

type Counters struct {
	Steps         int           `json:"steps,omitempty"`
	Tokens        int64         `json:"tokens,omitempty"`
	Active        time.Duration `json:"active,omitempty"`
	WrapUpSent    bool          `json:"wrap_up_sent,omitempty"`
	LoopRecent    string        `json:"loop_recent,omitempty"`
	LoopTool      string        `json:"loop_tool,omitempty"`
	LoopRepeats   int           `json:"loop_repeats,omitempty"`
	LoopWarned    bool          `json:"loop_warned,omitempty"`
	Continuations int           `json:"continuations,omitempty"`
	OutputLimit   int           `json:"output_limit,omitempty"`
	LowYield      int           `json:"low_yield,omitempty"`
	ElidedResults int64         `json:"elided_results,omitempty"`
	ElidedImages  int64         `json:"elided_images,omitempty"`
	HistoryEdit   int64         `json:"history_edit,omitempty"`
	LearnedLimit  int           `json:"learned_limit,omitempty"`
	TodoNudged    bool          `json:"todo_nudged,omitempty"`
	// Await is set while the run waits for what an await call asked for.
	Await *tools.Await `json:"await,omitempty"`
}

steps: no-progress streak, output limit, low-yield summaries, elision, last history edit, learned prompt room, whether open todo items were pointed out and what the run awaits. It is checkpointed so a parked or restarted run continues from it.

func (Counters) Carried

func (c Counters) Carried() Counters

Carried is what the session's next run starts from: what the requests elide and the last history edit, so its first request looks like the last one.

type Decision

type Decision struct {
	Allowed   bool
	Reason    string
	Barrier   bool
	Key       string
	Delegated bool
}

Decision says whether a requested tool call may run; Reason goes back to the model. A Barrier call that waits for approval holds back the calls after it in its batch. Calls sharing a non-empty Key run one at a time, across runs too. A Delegated call runs another agent, whose time is not this run's.

type Engine

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

Engine runs the native agent loop over its ports.

func New

func New(cfg Config) *Engine

New returns an engine over the given ports.

func (*Engine) Run

func (e *Engine) Run(ctx context.Context, task Task) (outcome Outcome, err error)

Run executes steps until the run completes, parks, fails or ctx stops. The error is reserved for failures that must leave the run's status untouched.

type Event

type Event struct {
	Kind            EventKind
	SessionID       string
	RunID           string
	Message         transcript.Message
	ToolCallID      string
	ToolName        string
	ResultMessageID string
	Result          tools.Result
	ContextTokens   int
	WindowTokens    int
}

Event is live progress for clients.

type EventKind

type EventKind string

EventKind names what Sink receives.

const (
	EventMessageCreated EventKind = "message.created"
	EventMessageUpdated EventKind = "message.updated"
	EventToolRequested  EventKind = "tool.requested"
	EventToolFinished   EventKind = "tool.finished"
	// EventContextMeasured carries ContextTokens and WindowTokens after a step.
	EventContextMeasured EventKind = "context.measured"
)

type Inbox

type Inbox interface {
	Peek(ctx context.Context, runID string, kind InputKind) ([]Input, error)
	Consume(ctx context.Context, runID string, ids []string) error
	Finished(ctx context.Context, taskIDs []string) (bool, error)
}

Inbox delivers outside input. Peek never consumes: steers and events stay pending until the engine consumes their IDs, and InputDecided returns decided approvals whose call has no result yet. Finished reports whether any of the background tasks ended, even if its event went elsewhere.

type Input

type Input struct {
	Kind       InputKind
	ID         string
	Text       string
	Images     []transcript.MessagePart
	ToolCallID string
	ToolName   string
	WorkingDir string
	Args       json.RawMessage
	Denied     bool
	Reason     string
}

Input arrives from outside the engine: steer Text with the Images sent with it, a decided approval, or an event such as a finished background task, whose Text the model reads. Denied approvals carry the user's Reason.

type InputKind

type InputKind string

InputKind selects what Inbox.Peek returns.

const (
	InputSteer   InputKind = "steer"
	InputDecided InputKind = "decided"
	InputEvent   InputKind = "event"
)

type InterruptedCall

type InterruptedCall struct {
	ToolCallID string
	Settle     Settle
	Request    tools.ApprovalRequest
	Result     tools.Result
}

InterruptedCall is a call of the run a restart left without a result.

type Journal

type Journal interface {
	Load(ctx context.Context, sessionID string) (Window, error)
	Append(ctx context.Context, msg transcript.Message) (seq int64, err error)
	BeginStreaming(ctx context.Context, msg transcript.Message) (seq int64, err error)
	Stream(ctx context.Context, msg transcript.Message) error
	FinishStreaming(ctx context.Context, msg transcript.Message) error
	Checkpoint(ctx context.Context, state State) error
	RecordStep(ctx context.Context, step Step) error
}

Journal persists one session's transcript; during a run the engine is its only writer. BeginStreaming/Stream use the fast progress path; FinishStreaming is the durable update of an in-flight assistant message and the only update of a written message.

type Model

type Model interface {
	Generate(ctx context.Context, req providers.Request) (providers.Response, error)
}

Model generates one assistant turn; providers.Runtime satisfies it.

type Outcome

type Outcome struct {
	Status         Status
	StopReason     StopReason
	Assistant      *transcript.Message
	AssistantSaved bool
	Err            error
	MarkErrored    bool
	Reached        Status
	Counters       Counters
}

Outcome is applied by core. Assistant is the final reply (completed), the reply to seal (canceled, interrupted) or the errored reply (failed with MarkErrored). Reached is what the last step produced before an interruption; StopReason is set whenever the run completed or reached completion, and for a context-exhausted failure. Counters are the run's counters when it stopped.

type Pending

type Pending struct {
	RunID      string
	SessionID  string
	ToolCallID string
	ToolName   string
	Request    tools.ApprovalRequest
}

Pending is a tool call that waits for a user decision.

type Phase

type Phase string

Phase is the durable execution boundary a run last reached.

const (
	PhaseModel     Phase = "model"
	PhaseToolBatch Phase = "tool_batch"
)

type Prompts

type Prompts interface {
	System(ctx context.Context, history []transcript.Message) (system, custom string)
	Context(ctx context.Context) string
}

Prompts supplies the core-owned parts of every request: the system prompt and custom instructions, fixed for a run, and the changing state the engine sends as a context note whenever it changes.

type Settle

type Settle string

Settle is how a resumed run settles a call a restart left without a result.

const (
	// SettleRerun runs the call again through Authorize once nothing is pending.
	SettleRerun Settle = "rerun"
	// SettleAsk asks the user with Request before the call runs again.
	SettleAsk Settle = "ask"
	// SettleAnswer journals Result as the call's result.
	SettleAnswer Settle = "answer"
)

type Sink

type Sink interface {
	Emit(event Event)
}

Sink fans engine events out to clients.

type State

type State struct {
	RunID    string
	Phase    Phase
	Batch    *ToolBatch
	Counters Counters
}

State is the checkpoint the engine writes before each model call, when it starts calls of a tool batch and when the run parks; its Counters let a parked or restarted run keep its budget.

type Status

type Status string

Status is how a Run call ended.

const (
	StatusCompleted       Status = "completed"
	StatusWaitingApproval Status = "waiting_approval"
	StatusWaitingEvents   Status = "waiting_events"
	StatusInterrupted     Status = "interrupted"
	StatusCanceled        Status = "canceled"
	StatusFailed          Status = "failed"
)

type Step

type Step struct {
	RunID      string
	Model      string
	Provider   string
	Usage      providers.Usage
	StopReason string
	Latency    time.Duration
	ToolCalls  int
}

Step is one successful model generation (a run_steps row). StopReason is a provider stop reason or "compact" for a summary generation.

type StopReason

type StopReason string

StopReason says why a completed run stopped.

const (
	StopDone             StopReason = "done"
	StopBudgetExhausted  StopReason = "budget_exhausted"
	StopLoopDetected     StopReason = "loop_detected"
	StopContextExhausted StopReason = "context_exhausted"
)

func (StopReason) Continuable

func (r StopReason) Continuable() bool

Continuable reports whether a run stopped before its work was done.

type Task

type Task struct {
	RunID       string
	SessionID   string
	Client      string
	ExternalKey string
	WorkingDir  string
	Model       Model
	// WindowTokens is the model's context window; 0 means unknown.
	WindowTokens int
	// CompactModel writes the run's summaries instead of Model when set;
	// CompactWindowTokens is its context window, 0 when unknown.
	CompactModel        Model
	CompactWindowTokens int
	Budget              Budget
	Resume              Counters
	// Continues lists the runs this one continues, nearest first; what they keep
	// verbatim past a summary stays kept.
	Continues []string
	// Recovering is set when a restart or an interruption stopped the run's
	// previous execution; Interrupted settles the calls it left without a result.
	Recovering  bool
	Interrupted []InterruptedCall
}

Task is one native run to execute. Resume holds the counters the run had reached before it was parked or interrupted; a new run starts from what the session's previous run carried over.

type Todos

type Todos interface {
	// Open lists the unfinished items of the session's todo list when a run of
	// chain (a run and the runs it continues) wrote it, and none otherwise.
	Open(ctx context.Context, sessionID string, chain []string) ([]todo.Item, error)
}

type ToolBatch

type ToolBatch struct {
	CallIDs     []string `json:"call_ids"`
	DeferredIDs []string `json:"deferred_ids,omitempty"`
}

ToolBatch names the calls of the batch being run, in call order, and those of them held back (deferred) when the checkpoint was written; crash recovery defers those again.

type Tools

type Tools interface {
	Specs(ctx context.Context) []tools.Spec
	Authorize(ctx context.Context, name string, call tools.Call) (Decision, error)
	Execute(ctx context.Context, name string, call tools.Call) (tools.Result, *tools.ApprovalRequest, error)
}

Tools lists, authorizes and executes the tools of one run. Execute returns either a result or, for a call that waits for the user, its approval request. Execute errors are fatal; tool failures come back as error results. Execute runs on a goroutine of its own, concurrently with other calls of the batch; the other methods run on the engine goroutine.

type Window

type Window struct {
	Boundary *transcript.Message
	Messages []transcript.Message
}

Window is the transcript a run starts from: the session's newest context boundary, if any, and the messages after what it covers, ordered by seq.

func (Window) Compaction

func (w Window) Compaction() *transcript.Compaction

Compaction is the boundary's compaction; nil without a boundary.

Directories

Path Synopsis
Package agenttest provides a scripted model and in-memory fakes for the agent ports.
Package agenttest provides a scripted model and in-memory fakes for the agent ports.
Package agentcontext builds the model's view of a session: provider conversation, context boundaries and summaries, and token estimates.
Package agentcontext builds the model's view of a session: provider conversation, context boundaries and summaries, and token estimates.
Package prompt holds the fixed texts of the native agent's system prompt.
Package prompt holds the fixed texts of the native agent's system prompt.
Package todo is the agent's todo list: its items, their validation and how they are shown to the model.
Package todo is the agent's todo list: its items, their validation and how they are shown to the model.
Package toolsched holds the daemon-wide scheduling primitives of native runs: a semaphore for model requests and keyed locks and batches for tool calls.
Package toolsched holds the daemon-wide scheduling primitives of native runs: a semaphore for model requests and keyed locks and batches for tool calls.

Jump to

Keyboard shortcuts

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